diff --git a/.github/workflows/fake-pr-tests.yml b/.github/workflows/fake-pr-tests.yml deleted file mode 100644 index 2274166..0000000 --- a/.github/workflows/fake-pr-tests.yml +++ /dev/null @@ -1,18 +0,0 @@ -name: PR tests -on: - pull_request: - types: [auto_merge_enabled] - workflow_dispatch: - -jobs: - skip: - name: Report fake success for PR tests - runs-on: ubuntu-latest - permissions: - checks: write - steps: - - uses: LouisBrunner/checks-action@v2.0.0 - with: - name: Run PR tests (Plugins) (Plugins) - conclusion: success - token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore deleted file mode 100644 index bf7460d..0000000 --- a/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.DS_Store -.vscode -.idea diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..449691b --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +save-exact=true \ No newline at end of file diff --git a/central_pane/dtdAbbreviation.json b/central_pane/dtdAbbreviation.json index bfbd503..685b3b8 100644 --- a/central_pane/dtdAbbreviation.json +++ b/central_pane/dtdAbbreviation.json @@ -6,4 +6,4 @@ "bool": "{0/1}", "bytes": "{BYTES}", "null": "{null}" -} \ No newline at end of file +} diff --git a/forward_engineering/alterScript/alterScriptBuilder.js b/forward_engineering/alterScript/alterScriptBuilder.js deleted file mode 100644 index f2609e1..0000000 --- a/forward_engineering/alterScript/alterScriptBuilder.js +++ /dev/null @@ -1,103 +0,0 @@ -const {getAlterScriptDtos} = require("./alterScriptFromDeltaHelper"); - -const {AlterScriptDto} = require('./types/AlterScriptDto'); - -/** - * @return {(dtos: AlterScriptDto[], shouldApplyDropStatements: boolean) => string} - * */ -const joinAlterScriptDtosIntoScript = (_) => (dtos, shouldApplyDropStatements) => { - const {commentIfDeactivated} = require('../utils/general')(_); - return dtos.map((dto) => { - if (dto.isActivated === false) { - return dto.scripts - .map((scriptDto) => commentIfDeactivated(scriptDto.script, { - isActivated: false, - isPartOfLine: false, - })); - } - if (!shouldApplyDropStatements) { - return dto.scripts - .map((scriptDto) => commentIfDeactivated(scriptDto.script, { - isActivated: !scriptDto.isDropScript, - isPartOfLine: false, - })); - } - return dto.scripts.map((scriptDto) => scriptDto.script); - }) - .flat() - .filter(Boolean) - .map((scriptLine) => scriptLine.trim()) - .filter(Boolean) - .join('\n\n'); -} - -/** - * @param data {CoreData} - * @param app {App} - * @return {string} - * */ -const buildEntityLevelAlterScript = (data, app) => { - const _ = app.require('lodash'); - const alterScriptDtos = getAlterScriptDtos(data, app); - const shouldApplyDropStatements = data.options?.additionalOptions?.some( - option => option.id === 'applyDropStatements' && option.value, - ); - - return joinAlterScriptDtosIntoScript(_)(alterScriptDtos, shouldApplyDropStatements); -} - -/** - * @param data {CoreData} - * @param app {App} - * @return { boolean} - * */ -const doesEntityLevelAlterScriptContainDropStatements = (data, app) => { - const alterScriptDtos = getAlterScriptDtos(data, app); - return alterScriptDtos - .some(alterScriptDto => alterScriptDto.isActivated && alterScriptDto - .scripts.some(scriptModificationDto => scriptModificationDto.isDropScript)); -} - -const mapCoreDataForContainerLevelScripts = (data) => { - return { - ...data, - jsonSchema: data.collections[0], - internalDefinitions: Object.values(data.internalDefinitions)[0], - } -} - -/** - * @param data {CoreData} - * @param app {App} - * @return {string} - * */ -const buildContainerLevelAlterScript = (data, app) => { - const preparedData = mapCoreDataForContainerLevelScripts(data); - const _ = app.require('lodash'); - const alterScriptDtos = getAlterScriptDtos(preparedData, app); - const shouldApplyDropStatements = preparedData.options?.additionalOptions?.some( - option => option.id === 'applyDropStatements' && option.value, - ); - - return joinAlterScriptDtosIntoScript(_)(alterScriptDtos, shouldApplyDropStatements); -} - -/** - * @param data {CoreData} - * @param app {App} - * @return { boolean} - * */ -const doesContainerLevelAlterScriptContainDropStatements = (data, app) => { - const preparedData = mapCoreDataForContainerLevelScripts(data); - const alterScriptDtos = getAlterScriptDtos(preparedData, app); - return alterScriptDtos - .some(alterScriptDto => alterScriptDto.isActivated && alterScriptDto - .scripts.some(scriptModificationDto => scriptModificationDto.isDropScript)); -} - -module.exports = { - buildEntityLevelAlterScript, - doesEntityLevelAlterScriptContainDropStatements, - buildContainerLevelAlterScript, - doesContainerLevelAlterScriptContainDropStatements -} diff --git a/forward_engineering/alterScript/alterScriptFromDeltaHelper.js b/forward_engineering/alterScript/alterScriptFromDeltaHelper.js deleted file mode 100644 index 7a1f9e5..0000000 --- a/forward_engineering/alterScript/alterScriptFromDeltaHelper.js +++ /dev/null @@ -1,354 +0,0 @@ -const { - getAddContainerScriptDto, - getDeleteContainerScriptDto, - getModifyContainerScriptDtos -} = require('./alterScriptHelpers/alterContainerHelper'); -const { - getAddCollectionScriptDto, - getDeleteCollectionScriptDto, - getAddColumnScriptDtos, - getDeleteColumnScriptDtos, - getModifyColumnScriptDtos, - getModifyCollectionScriptDtos, -} = require('./alterScriptHelpers/alterEntityHelper'); -const { - getDeleteUdtScriptDto, - getCreateUdtScriptDto, - getAddColumnToTypeScriptDtos, - getDeleteColumnFromTypeScriptDtos, - getModifyColumnOfTypeScriptDtos, -} = require('./alterScriptHelpers/alterUdtHelper'); -const { - getAddViewScriptDto, - getDeleteViewScriptDto, - getModifyViewScriptDtos -} = require('./alterScriptHelpers/alterViewHelper'); -const { - getModifyForeignKeyScriptDtos, - getDeleteForeignKeyScriptDtos, - getAddForeignKeyScriptDtos -} = require("./alterScriptHelpers/alterRelationshipsHelper"); -const {AlterScriptDto, ModificationScript} = require("./types/AlterScriptDto"); -const {App, CoreData} = require("../types/coreApplicationTypes"); -const {InternalDefinitions, ModelDefinitions, ExternalDefinitions} = require("../types/coreApplicationDataTypes"); - - -/** - * @param dto {{ - * collection: Object, - * app: App, - * }} - * @return {AlterScriptDto[]} - * */ -const getAlterContainersScriptDtos = ({collection, app}) => { - const addedContainers = collection.properties?.containers?.properties?.added?.items; - const deletedContainers = collection.properties?.containers?.properties?.deleted?.items; - const modifiedContainers = collection.properties?.containers?.properties?.modified?.items; - - const addContainersScriptDtos = [] - .concat(addedContainers) - .filter(Boolean) - .map(container => getAddContainerScriptDto(app)(Object.keys(container.properties)[0])); - const deleteContainersScriptDtos = [] - .concat(deletedContainers) - .filter(Boolean) - .map(container => getDeleteContainerScriptDto(app)(Object.keys(container.properties)[0])); - const modifyContainersScriptDtos = [] - .concat(modifiedContainers) - .filter(Boolean) - .map(containerWrapper => Object.values(containerWrapper.properties)[0]) - .flatMap(container => getModifyContainerScriptDtos(app)(container)) - - return [ - ...addContainersScriptDtos, - ...deleteContainersScriptDtos, - ...modifyContainersScriptDtos, - ].filter(Boolean); -}; - - -/** - * @param dto {{ - * collection: Object, - * app: App, - * dbVersion: string, - * modelDefinitions: ModelDefinitions, - * internalDefinitions: InternalDefinitions, - * externalDefinitions: ExternalDefinitions, - * }} - * @return {AlterScriptDto[]} - * */ -const getAlterCollectionsScriptDtos = ({ - collection, - app, - dbVersion, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }) => { - const createCollectionsScriptDtos = [] - .concat(collection.properties?.entities?.properties?.added?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(collection => collection.compMod?.created) - .map(getAddCollectionScriptDto({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions})); - const deleteCollectionScriptDtos = [] - .concat(collection.properties?.entities?.properties?.deleted?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(collection => collection.compMod?.deleted) - .map(getDeleteCollectionScriptDto(app)); - const modifyCollectionScriptDtos = [] - .concat(collection.properties?.entities?.properties?.modified?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .flatMap(getModifyCollectionScriptDtos(app)); - const addColumnScriptDtos = [] - .concat(collection.properties?.entities?.properties?.added?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(collection => !collection.compMod) - .flatMap(getAddColumnScriptDtos({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions})); - const deleteColumnScriptDtos = [] - .concat(collection.properties?.entities?.properties?.deleted?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(collection => !collection.compMod) - .flatMap(getDeleteColumnScriptDtos(app)); - const modifyColumnScriptDtos = [] - .concat(collection.properties?.entities?.properties?.modified?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(collection => !collection.compMod) - .flatMap(getModifyColumnScriptDtos({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions})); - - return [ - ...createCollectionsScriptDtos, - ...deleteCollectionScriptDtos, - ...modifyCollectionScriptDtos, - ...addColumnScriptDtos, - ...deleteColumnScriptDtos, - ...modifyColumnScriptDtos, - ].filter(Boolean); -}; - -/** - * @param collection {Object} - * @param app {App} - * @return {AlterScriptDto[]} - * */ -const getAlterViewScriptDtos = (collection, app) => { - const createViewsScriptDtos = [] - .concat(collection.properties?.views?.properties?.added?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .map(view => ({...view, ...(view.role || {})})) - .filter(view => view.compMod?.created && view.selectStatement) - .map(getAddViewScriptDto(app)); - - const deleteViewsScriptDtos = [] - .concat(collection.properties?.views?.properties?.deleted?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .map(view => ({...view, ...(view.role || {})})) - .map(getDeleteViewScriptDto(app)); - - const modifyViewsScriptDtos = [] - .concat(collection.properties?.views?.properties?.modified?.items) - .filter(Boolean) - .map(viewWrapper => Object.values(viewWrapper.properties)[0]) - .map(view => ({...view, ...(view.role || {})})) - .flatMap(view => getModifyViewScriptDtos(app)(view)); - - return [ - ...deleteViewsScriptDtos, - ...createViewsScriptDtos, - ...modifyViewsScriptDtos, - ].filter(Boolean); -}; - -/** - * @param dto {{ - * collection: Object, - * app: App, - * dbVersion: string, - * modelDefinitions: ModelDefinitions, - * internalDefinitions: InternalDefinitions, - * externalDefinitions: ExternalDefinitions, - * }} - * @return {AlterScriptDto[]} - * */ -const getAlterModelDefinitionsScriptDtos = ({ - collection, - app, - dbVersion, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }) => { - const createUdtScriptDtos = [] - .concat(collection.properties?.modelDefinitions?.properties?.added?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) - .filter(item => item.compMod?.created) - .map(getCreateUdtScriptDto({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions})); - const deleteUdtScriptDtos = [] - .concat(collection.properties?.modelDefinitions?.properties?.deleted?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) - .filter(collection => collection.compMod?.deleted) - .map(getDeleteUdtScriptDto(app)); - const addColumnScriptDtos = [] - .concat(collection.properties?.modelDefinitions?.properties?.added?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(item => !item.compMod) - .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) - .filter(item => item.childType === 'composite') - .flatMap( - getAddColumnToTypeScriptDtos({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}), - ); - const deleteColumnScriptDtos = [] - .concat(collection.properties?.modelDefinitions?.properties?.deleted?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(item => !item.compMod) - .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) - .filter(item => item.childType === 'composite') - .flatMap(getDeleteColumnFromTypeScriptDtos(app)); - - const modifyColumnScriptDtos = [] - .concat(collection.properties?.modelDefinitions?.properties?.modified?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(item => !item.compMod) - .map(item => ({...item, ...(app.require('lodash').omit(item.role, 'properties') || {})})) - .filter(item => item.childType === 'composite') - .flatMap(getModifyColumnOfTypeScriptDtos(app)); - - return [ - ...deleteUdtScriptDtos, - ...createUdtScriptDtos, - ...addColumnScriptDtos, - ...deleteColumnScriptDtos, - ...modifyColumnScriptDtos, - ].filter(Boolean); -}; - -/** - * @return Array - * */ -const getAlterRelationshipsScriptDtos = ({ - collection, - app, - }) => { - const _ = app.require('lodash'); - const ddlProvider = require('../ddlProvider/ddlProvider')(null, null, app); - - const addedRelationships = [] - .concat(collection.properties?.relationships?.properties?.added?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(relationship => relationship?.role?.compMod?.created); - const deletedRelationships = [] - .concat(collection.properties?.relationships?.properties?.deleted?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(relationship => relationship?.role?.compMod?.deleted); - const modifiedRelationships = [] - .concat(collection.properties?.relationships?.properties?.modified?.items) - .filter(Boolean) - .map(item => Object.values(item.properties)[0]) - .filter(relationship => relationship?.role?.compMod?.modified); - - const deleteFkScriptDtos = getDeleteForeignKeyScriptDtos(ddlProvider, _)(deletedRelationships); - const addFkScriptDtos = getAddForeignKeyScriptDtos(ddlProvider, _)(addedRelationships); - const modifiedFkScriptDtos = getModifyForeignKeyScriptDtos(ddlProvider, _)(modifiedRelationships); - - return [ - ...deleteFkScriptDtos, - ...addFkScriptDtos, - ...modifiedFkScriptDtos, - ].filter(Boolean); -} - -/** - * @param dto {AlterScriptDto} - * @return {AlterScriptDto | undefined} - */ -const prettifyAlterScriptDto = (dto) => { - if (!dto) { - return undefined; - } - /** - * @type {Array} - * */ - const nonEmptyScriptModificationDtos = dto.scripts - .map((scriptDto) => ({ - ...scriptDto, - script: (scriptDto.script || '').trim() - })) - .filter((scriptDto) => Boolean(scriptDto.script)); - if (!nonEmptyScriptModificationDtos.length) { - return undefined; - } - return { - ...dto, - scripts: nonEmptyScriptModificationDtos - } -} - -/** - * @param data {CoreData} - * @param app {App} - * @return {Array} - * */ -const getAlterScriptDtos = (data, app) => { - const collection = JSON.parse(data.jsonSchema); - if (!collection) { - throw new Error( - '"comparisonModelCollection" is not found. Alter script can be generated only from Delta model', - ); - } - - const modelDefinitions = JSON.parse(data.modelDefinitions); - const internalDefinitions = JSON.parse(data.internalDefinitions); - const externalDefinitions = JSON.parse(data.externalDefinitions); - const dbVersion = data.modelData[0]?.dbVersion; - const containersScriptDtos = getAlterContainersScriptDtos({collection, app}); - const collectionsScriptDtos = getAlterCollectionsScriptDtos({ - collection, - app, - dbVersion, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }); - const viewScriptDtos = getAlterViewScriptDtos(collection, app); - const modelDefinitionsScriptDtos = getAlterModelDefinitionsScriptDtos({ - collection, - app, - dbVersion, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }); - const relationshipScriptDtos = getAlterRelationshipsScriptDtos({collection, app}); - - return [ - ...containersScriptDtos, - ...modelDefinitionsScriptDtos, - ...collectionsScriptDtos, - ...viewScriptDtos, - ...relationshipScriptDtos, - ] - .filter(Boolean) - .map((dto) => prettifyAlterScriptDto(dto)) - .filter(Boolean); -}; - -module.exports = { - getAlterScriptDtos, -}; diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js deleted file mode 100644 index 1e11841..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/alterContainerHelper.js +++ /dev/null @@ -1,45 +0,0 @@ -const {getModifySchemaCommentsScriptDtos} = require("./containerHelpers/commentsHelper"); -const {AlterScriptDto} = require("../types/AlterScriptDto"); - -/** - * @return {(containerName: string) => AlterScriptDto | undefined} - * */ -const getAddContainerScriptDto = (app) => (containerName) => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const {wrapInQuotes} = require('../../utils/general')(_); - const script = ddlProvider.createSchemaOnly(wrapInQuotes(containerName)); - return AlterScriptDto.getInstance([script], true, false); -}; - -/** - * @return {(containerName: string) => AlterScriptDto | undefined} - * */ -const getDeleteContainerScriptDto = (app) => (containerName) => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const {wrapInQuotes} = require('../../utils/general')(_); - - const script = ddlProvider.dropSchema(wrapInQuotes(containerName)); - return AlterScriptDto.getInstance([script], true, true); -}; - -/** - * @return {(container: Object) => Array} - * */ -const getModifyContainerScriptDtos = (app) => (container) => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - - const modifyCommentScriptDtos = getModifySchemaCommentsScriptDtos(_, ddlProvider)(container); - - return [ - ...modifyCommentScriptDtos - ]; -} - -module.exports = { - getAddContainerScriptDto, - getDeleteContainerScriptDto, - getModifyContainerScriptDtos -}; diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js deleted file mode 100644 index fd85bdf..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/alterEntityHelper.js +++ /dev/null @@ -1,250 +0,0 @@ -const {getModifyCheckConstraintScriptDtos} = require("./entityHelpers/checkConstraintHelper"); -const {getModifyEntityCommentsScriptDtos} = require("./entityHelpers/commentsHelper"); -const {getUpdateTypesScriptDtos} = require("./columnHelpers/alterTypeHelper"); -const {getModifyNonNullColumnsScriptDtos} = require("./columnHelpers/nonNullConstraintHelper"); -const {getModifiedCommentOnColumnScriptDtos} = require("./columnHelpers/commentsHelper"); -const {getRenameColumnScriptDtos} = require("./columnHelpers/renameColumnHelper"); -const {AlterScriptDto} = require("../types/AlterScriptDto"); -const {AlterCollectionDto} = require('../types/AlterCollectionDto'); -const {getModifyPkConstraintsScriptDtos} = require("./entityHelpers/primaryKeyHelper"); - - -/** - * @return {(collection: AlterCollectionDto) => AlterScriptDto | undefined} - * */ -const getAddCollectionScriptDto = - ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => - collection => { - const _ = app.require('lodash'); - const {getEntityName} = require('../../utils/general')(_); - const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); - - const schemaName = collection.compMod.keyspaceName; - const schemaData = {schemaName, dbVersion}; - const jsonSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; - const columnDefinitions = _.toPairs(jsonSchema.properties).map(([name, column]) => { - const definitionJsonSchema = getDefinitionByReference({ - propertySchema: column, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }); - - return createColumnDefinitionBySchema({ - name, - jsonSchema: column, - parentJsonSchema: jsonSchema, - ddlProvider, - schemaData, - definitionJsonSchema, - }); - }); - const checkConstraints = (jsonSchema.chkConstr || []).map(check => - ddlProvider.createCheckConstraint(ddlProvider.hydrateCheckConstraint(check)), - ); - const tableData = { - name: getEntityName(jsonSchema), - columns: columnDefinitions.map(ddlProvider.convertColumnDefinition), - checkConstraints: checkConstraints, - foreignKeyConstraints: [], - schemaData, - columnDefinitions, - dbData: {dbVersion}, - }; - const hydratedTable = ddlProvider.hydrateTable({tableData, entityData: [jsonSchema], jsonSchema}); - - const script = ddlProvider.createTable(hydratedTable, jsonSchema.isActivated); - return AlterScriptDto.getInstance([script], true, false) - }; - -/** - * @return {(collection: AlterCollectionDto) => AlterScriptDto | undefined} - * */ -const getDeleteCollectionScriptDto = app => collection => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const {getFullTableName} = require('../../utils/general')(_); - - const fullName = getFullTableName(collection); - const script = ddlProvider.dropTable(fullName); - return AlterScriptDto.getInstance([script], true, true); -}; - -/** - * @return {(collection: AlterCollectionDto) => AlterScriptDto[]} - * */ -const getModifyCollectionScriptDtos = (app) => (collection) => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - - const modifyCheckConstraintScriptDtos = getModifyCheckConstraintScriptDtos(_, ddlProvider)(collection); - const modifyCommentScriptDtos = getModifyEntityCommentsScriptDtos(_, ddlProvider)(collection); - const modifyPKConstraintDtos = getModifyPkConstraintsScriptDtos(_, ddlProvider)(collection); - return [ - ...modifyCheckConstraintScriptDtos, - ...modifyCommentScriptDtos, - ...modifyPKConstraintDtos - ].filter(Boolean); -} - -/** - * @return {(collection: Object, predicate: ([name: string, jsonSchema: Object]) => boolean) => AlterScriptDto[]} - * */ -const getAddColumnsByConditionScriptDtos = ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => - (collection, predicate) => { - const _ = app.require('lodash'); - const {getEntityName, getNamePrefixedWithSchemaName} = require('../../utils/general')(_); - const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); - - const collectionSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; - const tableName = getEntityName(collectionSchema); - const schemaName = collectionSchema.compMod?.keyspaceName; - const fullName = getNamePrefixedWithSchemaName(tableName, schemaName); - const schemaData = {schemaName, dbVersion}; - - return _.toPairs(collection.properties) - .filter(([name, jsonSchema]) => predicate([name, jsonSchema])) - .map(([name, jsonSchema]) => { - const definitionJsonSchema = getDefinitionByReference({ - propertySchema: jsonSchema, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }); - - return createColumnDefinitionBySchema({ - name, - jsonSchema, - parentJsonSchema: collectionSchema, - ddlProvider, - schemaData, - definitionJsonSchema, - }); - }) - .map(ddlProvider.convertColumnDefinition) - .map(columnDefinition => ddlProvider.addColumn(fullName, columnDefinition)) - .map(addColumnScript => AlterScriptDto.getInstance([addColumnScript], true, false)) - .filter(Boolean); - }; - -/** - * @return {(collection: Object) => AlterScriptDto[]} - * */ -const getAddColumnScriptDtos = - ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => - collection => { - return getAddColumnsByConditionScriptDtos({ - app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions - })(collection, ([name, jsonSchema]) => !jsonSchema.compMod); - } - -/** - * @return {(collection: Object, predicate: ([name: string, jsonSchema: Object]) => boolean) => AlterScriptDto[]} - * */ -const getDeleteColumnsByConditionScriptDtos = app => (collection, predicate) => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const {getEntityName, getNamePrefixedWithSchemaName, wrapInQuotes} = require('../../utils/general')(_); - - const collectionSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; - const tableName = getEntityName(collectionSchema); - const schemaName = collectionSchema.compMod?.keyspaceName; - const fullTableName = getNamePrefixedWithSchemaName(tableName, schemaName); - - return _.toPairs(collection.properties) - .filter(([name, jsonSchema]) => predicate([name, jsonSchema])) - .map(([name]) => { - const columnNameForDDL = wrapInQuotes(name); - return ddlProvider.dropColumn(fullTableName, columnNameForDDL) - }) - .map(dropColumnScript => AlterScriptDto.getInstance([dropColumnScript], true, true)) - .filter(Boolean); -}; - -/** - * @return {(collection: Object) => AlterScriptDto[]} - * */ -const getDeleteColumnScriptDtos = app => collection => { - return getDeleteColumnsByConditionScriptDtos(app)(collection, ([name, jsonSchema]) => !jsonSchema.compMod) -}; - -/** - * @return {(collection: Object) => Array} - * */ -const getDropAndRecreateColumnsScriptDtos = ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => - (collection) => { - const _ = app.require('lodash'); - - return _.toPairs(collection.properties) - .filter(([name, jsonSchema]) => { - const oldName = jsonSchema.compMod.oldField.name; - const oldProperty = collection.role.properties[oldName]; - - const didGeneratedColumnChange = oldProperty.generatedColumn !== jsonSchema.generatedColumn - || oldProperty.columnGenerationExpression !== jsonSchema.columnGenerationExpression; - // all conditions that require drop-and-recreate go here - return didGeneratedColumnChange; - }) - .flatMap(([name, jsonSchema]) => { - const collectionWithJustThisProperty = { - ...collection, - properties: _.fromPairs([ - [name, jsonSchema] - ]), - } - const deleteColumnsScriptDtos = getDeleteColumnsByConditionScriptDtos(app)(collectionWithJustThisProperty, () => true); - const addColumnsScriptDtos = getAddColumnsByConditionScriptDtos({ - app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions - })(collectionWithJustThisProperty, () => true); - - return [ - ...deleteColumnsScriptDtos, - ...addColumnsScriptDtos, - ] - }) - .filter(Boolean); - } - -/** - * @return {(collection: Object) => AlterScriptDto[]} - * */ -const getModifyColumnScriptDtos = ( - {app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions} -) => collection => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - - const renameColumnScriptDtos = getRenameColumnScriptDtos(_, ddlProvider)(collection); - - const dropAndRecreateScriptDtos = getDropAndRecreateColumnsScriptDtos({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions})(collection); - if (dropAndRecreateScriptDtos.length) { - return [ - ...renameColumnScriptDtos, - ...dropAndRecreateScriptDtos, - ].filter(Boolean); - } - - const updateTypeScriptDtos = getUpdateTypesScriptDtos(_, ddlProvider)(collection); - const modifyNotNullScriptDtos = getModifyNonNullColumnsScriptDtos(_, ddlProvider)(collection); - const modifyCommentScriptDtos = getModifiedCommentOnColumnScriptDtos(_, ddlProvider)(collection); - - return [ - ...renameColumnScriptDtos, - ...updateTypeScriptDtos, - ...modifyNotNullScriptDtos, - ...modifyCommentScriptDtos, - ].filter(Boolean); -}; - -module.exports = { - getAddCollectionScriptDto, - getDeleteCollectionScriptDto, - getModifyCollectionScriptDtos, - getAddColumnScriptDtos, - getDeleteColumnScriptDtos, - getModifyColumnScriptDtos, -}; diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js deleted file mode 100644 index a86bbc9..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/alterRelationshipsHelper.js +++ /dev/null @@ -1,161 +0,0 @@ -const {AlterScriptDto} = require("../types/AlterScriptDto"); -const { - AlterRelationshipDto -} = require('../types/AlterRelationshipDto'); - - -/** - * @param relationship {AlterRelationshipDto} - * @return string - * */ -const getRelationshipName = (relationship) => { - return relationship.role.name; -} - -/** - * @return {(relationship: AlterRelationshipDto) => string} - * */ -const getFullChildTableName = (_) => (relationship) => { - const {getNamePrefixedWithSchemaName} = require('../../utils/general')(_); - const compMod = relationship.role.compMod; - - const childBucketName = compMod.child.bucket.name; - const childEntityName = compMod.child.collection.name; - return getNamePrefixedWithSchemaName(childEntityName, childBucketName); -} - -/** - * @return {(relationship: AlterRelationshipDto) => { - * isActivated: boolean, - * statement: string, - * }} - * */ -const getAddSingleForeignKeyStatementDto = (ddlProvider, _) => (relationship) => { - const compMod = relationship.role.compMod; - - const relationshipName = compMod.name?.new || getRelationshipName(relationship) || ''; - - return ddlProvider.createForeignKey({ - name: relationshipName, - foreignKey: compMod.child.collection.fkFields, - primaryKey: compMod.parent.collection.fkFields, - customProperties: compMod.customProperties?.new, - foreignTable: compMod.child.collection.name, - foreignSchemaName: compMod.child.bucket.name, - foreignTableActivated: compMod.child.collection.isActivated, - primaryTable: compMod.parent.collection.name, - primarySchemaName: compMod.parent.bucket.name, - primaryTableActivated: compMod.parent.collection.isActivated, - isActivated: Boolean(relationship.role?.compMod?.isActivated?.new), - }); -} - -/** - * @param relationship {AlterRelationshipDto} - * @return boolean - * */ -const canRelationshipBeAdded = (relationship) => { - const compMod = relationship.role.compMod; - if (!compMod) { - return false; - } - return [ - (compMod.name?.new || getRelationshipName(relationship)), - compMod.parent?.bucket, - compMod.parent?.collection, - compMod.parent?.collection?.fkFields?.length, - compMod.child?.bucket, - compMod.child?.collection, - compMod.child?.collection?.fkFields?.length, - ].every(property => Boolean(property)); -} - -/** - * @return {(addedRelationships: Array) => Array} - * */ -const getAddForeignKeyScriptDtos = (ddlProvider, _) => (addedRelationships) => { - return addedRelationships - .filter((relationship) => canRelationshipBeAdded(relationship)) - .map(relationship => { - const scriptDto = getAddSingleForeignKeyStatementDto(ddlProvider, _)(relationship); - return AlterScriptDto.getInstance([scriptDto.statement], scriptDto.isActivated, false); - }) - .filter(Boolean) - .filter(res => res.scripts.some(scriptDto => Boolean(scriptDto.script))); -} - -/** - * @return {(relationship: AlterRelationshipDto) => { - * isActivated: boolean, - * statement: string, - * }} - * */ -const getDeleteSingleForeignKeyStatementDto = (ddlProvider, _) => (relationship) => { - const {wrapInQuotes} = require('../../utils/general')(_); - const compMod = relationship.role.compMod; - - const ddlChildEntityName = getFullChildTableName(_)(relationship); - - const relationshipName = compMod.name?.old || getRelationshipName(relationship) || ''; - const ddlRelationshipName = wrapInQuotes(relationshipName); - const statement = ddlProvider.dropForeignKey(ddlChildEntityName, ddlRelationshipName); - - const isRelationshipActivated = Boolean(relationship.role?.compMod?.isActivated?.new); - const isChildTableActivated = compMod.child.collection.isActivated; - return { - statement, - isActivated: isRelationshipActivated && isChildTableActivated, - } -} - -/** - * @param relationship {AlterRelationshipDto} - * @return {boolean} - * */ -const canRelationshipBeDeleted = (relationship) => { - const compMod = relationship.role.compMod; - if (!compMod) { - return false; - } - return [ - (compMod.name?.old || getRelationshipName(relationship)), - compMod.child?.bucket, - compMod.child?.collection, - ].every(property => Boolean(property)); -} - -/** - * @return {(deletedRelationships: Array) => Array} - * */ -const getDeleteForeignKeyScriptDtos = (ddlProvider, _) => (deletedRelationships) => { - return deletedRelationships - .filter((relationship) => canRelationshipBeDeleted(relationship)) - .map(relationship => { - const scriptDto = getDeleteSingleForeignKeyStatementDto(ddlProvider, _)(relationship); - return AlterScriptDto.getInstance([scriptDto.statement], scriptDto.isActivated, true); - }) - .filter(Boolean) - .filter(res => res.scripts.some(scriptDto => Boolean(scriptDto.script))); -} - -/** - * @return {(modifiedRelationships: Array) => Array} - * */ -const getModifyForeignKeyScriptDtos = (ddlProvider, _) => (modifiedRelationships) => { - return modifiedRelationships - .filter(relationship => canRelationshipBeAdded(relationship) && canRelationshipBeDeleted(relationship)) - .map(relationship => { - const deleteScriptDto = getDeleteSingleForeignKeyStatementDto(ddlProvider, _)(relationship); - const addScriptDto = getAddSingleForeignKeyStatementDto(ddlProvider, _)(relationship); - const isActivated = addScriptDto.isActivated && deleteScriptDto.isActivated; - return AlterScriptDto.getDropAndRecreateInstance(deleteScriptDto.statement, addScriptDto.statement, isActivated); - }) - .filter(Boolean) - .filter(res => res.scripts.some(scriptDto => Boolean(scriptDto.script))); -} - -module.exports = { - getDeleteForeignKeyScriptDtos, - getModifyForeignKeyScriptDtos, - getAddForeignKeyScriptDtos, -} diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js deleted file mode 100644 index f316599..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/alterUdtHelper.js +++ /dev/null @@ -1,168 +0,0 @@ -const {AlterScriptDto} = require("../types/AlterScriptDto"); - -/** - * @return {(jsonSchema: Object) => AlterScriptDto | undefined} - * */ -const getCreateUdtScriptDto = - ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => - jsonSchema => { - const _ = app.require('lodash'); - const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); - - const schemaData = {dbVersion}; - - const columnDefinitions = _.toPairs(jsonSchema.properties || {}).map(([name, column]) => { - const definitionJsonSchema = getDefinitionByReference({ - propertySchema: column, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }); - - return createColumnDefinitionBySchema({ - name, - jsonSchema: column, - parentJsonSchema: jsonSchema, - ddlProvider, - schemaData, - definitionJsonSchema, - }); - }); - - const updatedUdt = createColumnDefinitionBySchema({ - name: jsonSchema.code || jsonSchema.name, - jsonSchema: jsonSchema, - parentJsonSchema: {required: []}, - definitionJsonSchema: {}, - ddlProvider, - schemaData, - }); - - const udt = {...updatedUdt, properties: columnDefinitions}; - - const script = ddlProvider.createUdt(udt); - return AlterScriptDto.getInstance([script], true, false); - }; - - -/** - * @return {(udt: Object) => AlterScriptDto | undefined} - * */ -const getDeleteUdtScriptDto = app => udt => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - - const {getUdtName, wrapInQuotes} = require('../../utils/general')(_); - - const ddlUdtName = wrapInQuotes(getUdtName(udt)); - if (udt.type === 'domain') { - const script = ddlProvider.dropDomain(ddlUdtName); - return AlterScriptDto.getInstance([script], true, true); - } else { - const script = ddlProvider.dropType(ddlUdtName); - return AlterScriptDto.getInstance([script], true, true); - } -}; - -/** - * @return {(udt: Object) => AlterScriptDto[]} - * */ -const getAddColumnToTypeScriptDtos = - ({app, dbVersion, modelDefinitions, internalDefinitions, externalDefinitions}) => - udt => { - const _ = app.require('lodash'); - const {createColumnDefinitionBySchema} = require('./createColumnDefinition')(app); - const {getUdtName, wrapInQuotes} = require('../../utils/general')(_); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const {getDefinitionByReference} = app.require('@hackolade/ddl-fe-utils'); - - const fullName = wrapInQuotes(getUdtName(udt)); - const schemaData = {dbVersion}; - - return _.toPairs(udt.properties) - .filter(([name, jsonSchema]) => !jsonSchema.compMod) - .map(([name, jsonSchema]) => { - const definitionJsonSchema = getDefinitionByReference({ - propertySchema: jsonSchema, - modelDefinitions, - internalDefinitions, - externalDefinitions, - }); - - return createColumnDefinitionBySchema({ - name, - jsonSchema, - parentJsonSchema: {required: []}, - ddlProvider, - schemaData, - definitionJsonSchema, - }); - }) - .map(ddlProvider.convertColumnDefinition) - .map(columnDefinition => ddlProvider.alterTypeAddAttribute(fullName, columnDefinition)) - .map(script => AlterScriptDto.getInstance([script], true, false)) - .filter(Boolean); - }; - -/** - * @return {(udt: Object) => AlterScriptDto[]} - * */ -const getDeleteColumnFromTypeScriptDtos = app => udt => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - - const {wrapInQuotes} = require('../../utils/general')(_); - - const fullName = wrapInQuotes(udt.code || udt.name); - - return _.toPairs(udt.properties) - .filter(([name, jsonSchema]) => !jsonSchema.compMod) - .map(([name]) => ddlProvider.alterTypeDropAttribute(fullName, wrapInQuotes(name))) - .map(script => AlterScriptDto.getInstance([script], true, true)) - .filter(Boolean); -}; - -/** - * @return {(udt: Object) => AlterScriptDto[]} - * */ -const getModifyColumnOfTypeScriptDtos = app => udt => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - - const {checkFieldPropertiesChanged, wrapInQuotes} = require('../../utils/general')(_); - - const fullName = wrapInQuotes(udt.code || udt.name); - - const renameColumnScripts = _.values(udt.properties) - .filter(jsonSchema => checkFieldPropertiesChanged(jsonSchema.compMod, ['name'])) - .map((jsonSchema) => { - const oldAttributeDDLName = wrapInQuotes(jsonSchema.compMod.oldField.name); - const newAttributeDDLName = wrapInQuotes(jsonSchema.compMod.newField.name); - return ddlProvider.alterTypeRenameAttribute(fullName, oldAttributeDDLName, newAttributeDDLName); - }) - .map(script => AlterScriptDto.getInstance([script], true, false)); - - const changeTypeScripts = _.toPairs(udt.properties) - .filter(([name, jsonSchema]) => checkFieldPropertiesChanged(jsonSchema.compMod, ['type', 'mode'])) - .map(([name, jsonSchema]) => { - const attributeDDLName = wrapInQuotes(name); - const newDataType = jsonSchema.compMod.newField.mode || jsonSchema.compMod.newField.type; - return ddlProvider.alterTypeChangeAttributeType(fullName, attributeDDLName, newDataType); - }) - .map(script => AlterScriptDto.getInstance([script], true, false)); - - return [ - ...renameColumnScripts, - ...changeTypeScripts - ].filter(Boolean); -}; - -module.exports = { - getCreateUdtScriptDto, - getDeleteUdtScriptDto, - getAddColumnToTypeScriptDtos, - getDeleteColumnFromTypeScriptDtos, - getModifyColumnOfTypeScriptDtos, -}; diff --git a/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js b/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js deleted file mode 100644 index 4d69fe4..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/alterViewHelper.js +++ /dev/null @@ -1,52 +0,0 @@ -const {getModifyViewCommentsScriptDtos} = require("./viewHelpers/commentsHelper"); -const {AlterScriptDto} = require("../types/AlterScriptDto"); - -/** - * @return {(view: Object) => AlterScriptDto | undefined} - * */ -const getAddViewScriptDto = app => view => { - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - - const viewData = { - name: view.code || view.name, - keys: [], - schemaData: { schemaName: '' }, - }; - const hydratedView = ddlProvider.hydrateView({ viewData, entityData: [view] }); - - const script = ddlProvider.createView(hydratedView, {}, view.isActivated); - return AlterScriptDto.getInstance([script], true, false); -}; - -/** - * @return {(view: Object) => AlterScriptDto | undefined} - * */ -const getDeleteViewScriptDto = app => view => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - const { wrapInQuotes } = require('../../utils/general')(_); - const viewName = wrapInQuotes(view.code || view.name); - - const script = ddlProvider.dropView(viewName); - return AlterScriptDto.getInstance([script], true, true); -}; - -/** - * @return {(view: Object) => AlterScriptDto[]} - * */ -const getModifyViewScriptDtos = (app) => (view) => { - const _ = app.require('lodash'); - const ddlProvider = require('../../ddlProvider/ddlProvider')(null, null, app); - - const modifyCommentsScriptDtos = getModifyViewCommentsScriptDtos(_, ddlProvider)(view); - - return [ - ...modifyCommentsScriptDtos, - ].filter(Boolean); -} - -module.exports = { - getAddViewScriptDto, - getDeleteViewScriptDto, - getModifyViewScriptDtos, -}; diff --git a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/alterTypeHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/alterTypeHelper.js deleted file mode 100644 index b3446ba..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/alterTypeHelper.js +++ /dev/null @@ -1,59 +0,0 @@ -const {AlterScriptDto} = require("../../types/AlterScriptDto"); - -/** - * @return {boolean} - * */ -const hasLengthChanged = (collection, oldFieldName, currentJsonSchema) => { - const oldProperty = collection.role.properties[oldFieldName]; - - const previousLength = oldProperty?.length; - const newLength = currentJsonSchema?.length; - return previousLength !== newLength; -} - -/** - * @return {boolean} - * */ -const hasPrecisionOrScaleChanged = (collection, oldFieldName, currentJsonSchema) => { - const oldProperty = collection.role.properties[oldFieldName]; - - const previousPrecision = oldProperty?.precision; - const newPrecision = currentJsonSchema?.precision; - const previousScale = oldProperty?.scale; - const newScale = currentJsonSchema?.scale; - - return previousPrecision !== newPrecision || previousScale !== newScale; -} - -/** - * @return {(collection: Object) => AlterScriptDto[]} - * */ -const getUpdateTypesScriptDtos = (_, ddlProvider) => (collection) => { - const {checkFieldPropertiesChanged, getFullTableName, wrapInQuotes} = require('../../../utils/general')(_); - const fullTableName = getFullTableName(collection); - - return _.toPairs(collection.properties) - .filter(([name, jsonSchema]) => { - const hasTypeChanged = checkFieldPropertiesChanged(jsonSchema.compMod, ['type', 'mode']); - if (!hasTypeChanged) { - const oldName = jsonSchema.compMod.oldField.name; - const isNewLength = hasLengthChanged(collection, oldName, jsonSchema); - const isNewPrecisionOrScale = hasPrecisionOrScaleChanged(collection, oldName, jsonSchema); - return isNewLength || isNewPrecisionOrScale; - } - return hasTypeChanged; - }) - .map( - ([name, jsonSchema]) => { - const typeName = jsonSchema.compMod.newField.mode || jsonSchema.compMod.newField.type; - const columnName = wrapInQuotes(name); - const typeConfig = _.pick(jsonSchema, ['length', 'precision', 'scale']); - return ddlProvider.alterColumnType(fullTableName, columnName, typeName, typeConfig); - } - ) - .map(script => AlterScriptDto.getInstance([script], true, false)); -} - -module.exports = { - getUpdateTypesScriptDtos -} diff --git a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/commentsHelper.js deleted file mode 100644 index 1b0cbde..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/commentsHelper.js +++ /dev/null @@ -1,55 +0,0 @@ -const {AlterScriptDto} = require("../../types/AlterScriptDto"); - -/** - * @return {(collection: Object) => AlterScriptDto[]} - * */ -const getUpdatedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => { - const {getFullColumnName, wrapComment} = require('../../../utils/general')(_); - return _.toPairs(collection.properties) - .filter(([name, jsonSchema]) => { - const newComment = jsonSchema.description; - const oldName = jsonSchema.compMod.oldField.name; - const oldComment = collection.role.properties[oldName]?.description; - return newComment && (!oldComment || newComment !== oldComment); - }) - .map(([name, jsonSchema]) => { - const newComment = jsonSchema.description; - const ddlComment = wrapComment(newComment); - const columnName = getFullColumnName(collection, name); - return ddlProvider.updateColumnComment(columnName, ddlComment); - }) - .map(script => AlterScriptDto.getInstance([script], true, false)); -} - -/** - * @return {(collection: Object) => AlterScriptDto[]} - * */ -const getDeletedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => { - const {getFullColumnName} = require('../../../utils/general')(_); - - return _.toPairs(collection.properties) - .filter(([name, jsonSchema]) => { - const newComment = jsonSchema.description; - const oldName = jsonSchema.compMod.oldField.name; - const oldComment = collection.role.properties[oldName]?.description; - return oldComment && !newComment; - }) - .map(([name, jsonSchema]) => { - const columnName = getFullColumnName(collection, name); - return ddlProvider.dropColumnComment(columnName); - }) - .map(script => AlterScriptDto.getInstance([script], true, true)); -} - -/** - * @return {(collection: Object) => AlterScriptDto[]} - * */ -const getModifiedCommentOnColumnScriptDtos = (_, ddlProvider) => (collection) => { - const updatedCommentScripts = getUpdatedCommentOnColumnScriptDtos(_, ddlProvider)(collection); - const deletedCommentScripts = getDeletedCommentOnColumnScriptDtos(_, ddlProvider)(collection); - return [...updatedCommentScripts, ...deletedCommentScripts]; -} - -module.exports = { - getModifiedCommentOnColumnScriptDtos -} diff --git a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js deleted file mode 100644 index 456bfaa..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/nonNullConstraintHelper.js +++ /dev/null @@ -1,41 +0,0 @@ -const {AlterScriptDto} = require("../../types/AlterScriptDto"); - -/** - * @return {(collection: Object) => AlterScriptDto[]} - * */ -const getModifyNonNullColumnsScriptDtos = (_, ddlProvider) => (collection) => { - const {getFullTableName, wrapInQuotes} = require('../../../utils/general')(_); - const fullTableName = getFullTableName(collection); - - const currentRequiredColumnNames = collection.required || []; - const previousRequiredColumnNames = collection.role.required || []; - - const columnNamesToAddNotNullConstraint = _.difference(currentRequiredColumnNames, previousRequiredColumnNames); - const columnNamesToRemoveNotNullConstraint = _.difference(previousRequiredColumnNames, currentRequiredColumnNames); - - const addNotNullConstraintsScript = _.toPairs(collection.properties) - .filter(([name, jsonSchema]) => { - const oldName = jsonSchema.compMod.oldField.name; - const shouldRemoveForOldName = columnNamesToRemoveNotNullConstraint.includes(oldName); - const shouldAddForNewName = columnNamesToAddNotNullConstraint.includes(name); - return shouldAddForNewName && !shouldRemoveForOldName; - }) - .map(([columnName]) => ddlProvider.setNotNullConstraint(fullTableName, wrapInQuotes(columnName))) - .map(script => AlterScriptDto.getInstance([script], true, false)); - - const removeNotNullConstraint = _.toPairs(collection.properties) - .filter(([name, jsonSchema]) => { - const oldName = jsonSchema.compMod.oldField.name; - const shouldRemoveForOldName = columnNamesToRemoveNotNullConstraint.includes(oldName); - const shouldAddForNewName = columnNamesToAddNotNullConstraint.includes(name); - return shouldRemoveForOldName && !shouldAddForNewName; - }) - .map(([name]) => ddlProvider.dropNotNullConstraint(fullTableName, wrapInQuotes(name))) - .map(script => AlterScriptDto.getInstance([script], true, true)); - - return [...addNotNullConstraintsScript, ...removeNotNullConstraint]; -} - -module.exports = { - getModifyNonNullColumnsScriptDtos -} diff --git a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/renameColumnHelper.js b/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/renameColumnHelper.js deleted file mode 100644 index 9d423e0..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/columnHelpers/renameColumnHelper.js +++ /dev/null @@ -1,24 +0,0 @@ -const {AlterScriptDto} = require("../../types/AlterScriptDto"); - -/** - * @return {(collection: Object) => AlterScriptDto[]} - * */ -const getRenameColumnScriptDtos = (_, ddlProvider) => (collection) => { - const {checkFieldPropertiesChanged, getFullTableName, wrapInQuotes} = require('../../../utils/general')(_); - const fullTableName = getFullTableName(collection); - - return _.values(collection.properties) - .filter(jsonSchema => checkFieldPropertiesChanged(jsonSchema.compMod, ['name'])) - .map( - jsonSchema => { - const oldColumnName = wrapInQuotes(jsonSchema.compMod.oldField.name); - const newColumnName = wrapInQuotes(jsonSchema.compMod.newField.name); - return ddlProvider.renameColumn(fullTableName, oldColumnName, newColumnName); - } - ) - .map(script => AlterScriptDto.getInstance([script], true, false)); -} - -module.exports = { - getRenameColumnScriptDtos -} diff --git a/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/commentsHelper.js deleted file mode 100644 index f6e75c3..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/containerHelpers/commentsHelper.js +++ /dev/null @@ -1,52 +0,0 @@ -const {AlterScriptDto} = require("../../types/AlterScriptDto"); - -const extractDescription = (container) => { - return container?.role?.compMod?.description || {}; -} - -/** - * @return {(collection: Object) => AlterScriptDto | undefined} - * */ -const getUpsertCommentsScriptDto = (_, ddlProvider) => (container) => { - const {wrapComment, wrapInQuotes} = require('../../../utils/general')(_); - - const description = extractDescription(container); - if (description.new && description.new !== description.old) { - const wrappedComment = wrapComment(description.new); - const wrappedSchemaName = wrapInQuotes(container.role.name); - const script = ddlProvider.updateSchemaComment(wrappedSchemaName, wrappedComment); - return AlterScriptDto.getInstance([script], true, false); - } - return undefined; -} - -/** - * @return {(collection: Object) => AlterScriptDto | undefined} - * */ -const getDropCommentsScriptDto = (_, ddlProvider) => (container) => { - const {wrapInQuotes} = require('../../../utils/general')(_); - - const description = extractDescription(container); - if (description.old && !description.new) { - const wrappedSchemaName = wrapInQuotes(container.role.name); - const script = ddlProvider.dropSchemaComment(wrappedSchemaName); - return AlterScriptDto.getInstance([script], true, true); - } - return undefined; -} - -/** - * @return {(collection: Object) => AlterScriptDto[]} - * */ -const getModifySchemaCommentsScriptDtos = (_, ddlProvider) => (container) => { - const upsertCommentScript = getUpsertCommentsScriptDto(_, ddlProvider)(container); - const dropCommentScript = getDropCommentsScriptDto(_, ddlProvider)(container); - return [ - upsertCommentScript, - dropCommentScript - ].filter(Boolean); -} - -module.exports = { - getModifySchemaCommentsScriptDtos -} diff --git a/forward_engineering/alterScript/alterScriptHelpers/createColumnDefinition.js b/forward_engineering/alterScript/alterScriptHelpers/createColumnDefinition.js deleted file mode 100644 index d4a6b06..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/createColumnDefinition.js +++ /dev/null @@ -1,34 +0,0 @@ -module.exports = app => { - const { createColumnDefinition } = app.require('@hackolade/ddl-fe-utils'); - - const getType = jsonSchema => { - if (jsonSchema.$ref) { - return jsonSchema.$ref.split('/').pop(); - } - - return jsonSchema.mode || jsonSchema.childType || jsonSchema.type; - }; - - const createColumnDefinitionBySchema = ({ - name, - jsonSchema, - parentJsonSchema, - ddlProvider, - schemaData, - definitionJsonSchema, - }) => { - return createColumnDefinition({ - name, - jsonSchema, - parentJsonSchema, - ddlProvider, - schemaData, - definitionJsonSchema, - getType, - }); - }; - - return { - createColumnDefinitionBySchema, - }; -}; diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js deleted file mode 100644 index cdc0601..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/checkConstraintHelper.js +++ /dev/null @@ -1,121 +0,0 @@ -const {AlterCollectionDto} = require('../../types/AlterCollectionDto'); -const {AlterScriptDto} = require("../../types/AlterScriptDto"); - -/** - * @typedef {{ - * id: string, - * chkConstrName: string, - * constrExpression: string, - * }} CheckConstraint - * - * @typedef {{ - * old?: CheckConstraint, - * new?: CheckConstraint - * }} CheckConstraintHistoryEntry - * */ - -/** - * @return {(collection: AlterCollectionDto) => Array} - * */ -const mapCheckConstraintNamesToChangeHistory = (_) => (collection) => { - const checkConstraintHistory = collection?.compMod?.chkConstr; - if (!checkConstraintHistory) { - return []; - } - const newConstraints = checkConstraintHistory.new || []; - const oldConstraints = checkConstraintHistory.old || []; - const constrNames = _.chain([ ...newConstraints, ...oldConstraints ]) - .map(constr => constr.chkConstrName) - .uniq() - .value(); - - return constrNames.map(chkConstrName => { - return { - old: _.find(oldConstraints, { chkConstrName }), - new: _.find(newConstraints, { chkConstrName }), - }; - }) -} - -/** - * @return {(constraintHistory: Array, fullTableName: string) => Array} - * */ -const getDropCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistory, fullTableName) => { - const {wrapInQuotes} = require('../../../utils/general')(_); - - return constraintHistory - .filter(historyEntry => historyEntry.old && !historyEntry.new) - .map(historyEntry => { - const wrappedConstraintName = wrapInQuotes(historyEntry.old.chkConstrName); - return ddlProvider.dropConstraint(fullTableName, wrappedConstraintName); - }) - .map(script => AlterScriptDto.getInstance([script], true, true)); -} - -/** - * @return {(constraintHistory: Array, fullTableName: string) => Array} - * */ -const getAddCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistory, fullTableName) => { - const {wrapInQuotes} = require('../../../utils/general')(_); - - return constraintHistory - .filter(historyEntry => historyEntry.new && !historyEntry.old) - .map(historyEntry => { - const { chkConstrName, constrExpression } = historyEntry.new; - return ddlProvider.addCheckConstraint(fullTableName, wrapInQuotes(chkConstrName), constrExpression); - }) - .map(script => AlterScriptDto.getInstance([script], true, false)); -} - -/** - * @return {(constraintHistory: Array, fullTableName: string) => Array} - * */ -const getUpdateCheckConstraintScriptDtos = (_, ddlProvider) => (constraintHistory, fullTableName) => { - const {wrapInQuotes} = require('../../../utils/general')(_); - - return constraintHistory - .filter(historyEntry => { - if (historyEntry.old && historyEntry.new) { - const oldExpression = historyEntry.old.constrExpression; - const newExpression = historyEntry.new.constrExpression; - return oldExpression !== newExpression; - } - return false; - }) - .map(historyEntry => { - const { chkConstrName: oldConstrainName } = historyEntry.old; - const dropConstraintScript = ddlProvider.dropConstraint(fullTableName, wrapInQuotes(oldConstrainName)); - - const { chkConstrName: newConstrainName, constrExpression: newConstraintExpression } = historyEntry.new; - const addConstraintScript = ddlProvider.addCheckConstraint(fullTableName, wrapInQuotes(newConstrainName), newConstraintExpression); - - return [ - AlterScriptDto.getInstance([dropConstraintScript], true, true), - AlterScriptDto.getInstance([addConstraintScript], true, false), - ]; - }) - .flat(); -} - -/** - * @return {(collection: AlterCollectionDto) => Array} - * */ -const getModifyCheckConstraintScriptDtos = (_, ddlProvider) => (collection) => { - const {getFullTableName} = require('../../../utils/general')(_); - const fullTableName = getFullTableName(collection); - const constraintHistory = mapCheckConstraintNamesToChangeHistory(_)(collection); - - const addCheckConstraintScripts = getAddCheckConstraintScriptDtos(_, ddlProvider)(constraintHistory, fullTableName); - const dropCheckConstraintScripts = getDropCheckConstraintScriptDtos(_, ddlProvider)(constraintHistory, fullTableName); - const updateCheckConstraintScripts = getUpdateCheckConstraintScriptDtos(_, ddlProvider)(constraintHistory, fullTableName); - - return [ - ...addCheckConstraintScripts, - ...dropCheckConstraintScripts, - ...updateCheckConstraintScripts, - ] -} - -module.exports = { - getModifyCheckConstraintScriptDtos -} diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js deleted file mode 100644 index 7b9fbd6..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/commentsHelper.js +++ /dev/null @@ -1,64 +0,0 @@ -const {AlterScriptDto} = require("../../types/AlterScriptDto"); -const {AlterCollectionDto} = require('../../types/AlterCollectionDto'); - -/** - * @return {(collection: AlterCollectionDto) => AlterScriptDto} - */ -const getUpdatedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) => { - const {getFullTableName, wrapComment} = require('../../../utils/general')(_); - - const descriptionInfo = collection?.role.compMod?.description; - if (!descriptionInfo) { - return undefined; - } - - const {old: oldComment, new: newComment} = descriptionInfo; - if (!newComment || newComment === oldComment) { - return undefined; - } - - const tableName = getFullTableName(collection); - const comment = wrapComment(newComment); - - const script = ddlProvider.updateTableComment(tableName, comment); - return AlterScriptDto.getInstance([script], true, false); -} - -/** - * @return {(collection: AlterCollectionDto) => AlterScriptDto} - */ -const getDeletedCommentOnCollectionScriptDto = (_, ddlProvider) => (collection) => { - const {getFullTableName} = require('../../../utils/general')(_); - - const descriptionInfo = collection?.role.compMod?.description; - if (!descriptionInfo) { - return undefined; - } - - const {old: oldComment, new: newComment} = descriptionInfo; - if (!oldComment || newComment) { - return undefined; - } - - const tableName = getFullTableName(collection); - - const script = ddlProvider.dropTableComment(tableName); - return AlterScriptDto.getInstance([script], true, true); -} - -/** - * @return {(collection: AlterCollectionDto) => Array} - * */ -const getModifyEntityCommentsScriptDtos = (_, ddlProvider) => collection => { - const updatedCommentScript = getUpdatedCommentOnCollectionScriptDto(_, ddlProvider)(collection); - const deletedCommentScript = getDeletedCommentOnCollectionScriptDto(_, ddlProvider)(collection); - - return [ - updatedCommentScript, - deletedCommentScript - ].filter(Boolean); -}; - -module.exports = { - getModifyEntityCommentsScriptDtos -} diff --git a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js b/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js deleted file mode 100644 index 1d63983..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/entityHelpers/primaryKeyHelper.js +++ /dev/null @@ -1,732 +0,0 @@ -const {AlterScriptDto} = require('../../types/AlterScriptDto'); -const { - AlterCollectionDto, - AlterCollectionColumnDto, - AlterCollectionRoleCompModPKDto, - AlterCollectionColumnPrimaryKeyOptionDto, - AlterCollectionRoleCompModPrimaryKey -} = require('../../types/AlterCollectionDto'); - -const amountOfColumnsInRegularPk = 1; - -class PkTransitionDto { - - /** - * @type {boolean} - * */ - didTransitionHappen - - /** - * @type {boolean | undefined} - * */ - wasPkChangedInTransition - - /** - * @return {PkTransitionDto} - * */ - static noTransition() { - return { - didTransitionHappen: false, - } - } - - /** - * @param wasPkChangedInTransition {boolean} - * @return {PkTransitionDto} - * */ - static transition(wasPkChangedInTransition) { - return { - didTransitionHappen: true, - wasPkChangedInTransition - } - } - -} - -class PkScriptModificationDto { - - /** - * @type string - * */ - script - - /** - * @type boolean - * */ - isDropScript - - /** - * @type {string} - * */ - fullTableName - - /** - * @type {boolean} - * */ - isActivated - - /** - * @param fullTableName {string} - * @param script {string} - * @param isDropScript {boolean} - * @param isActivated {boolean} - * */ - constructor( - script, - fullTableName, - isDropScript, - isActivated - ) { - this.script = script; - this.isDropScript = isDropScript; - this.fullTableName = fullTableName; - this.isActivated = isActivated; - } - -} - -/** - * @param entityName {string} - * @return {string} - * */ -const getDefaultConstraintName = (entityName) => { - return `${entityName}_pkey`; -} - -/** - * @param optionHolder {AlterCollectionColumnPrimaryKeyOptionDto} - * @return {} - * */ -const extractOptionsForComparisonWithRegularPkOptions = (optionHolder) => { - return { - constraintName: optionHolder.constraintName, - indexStorageParameters: optionHolder.indexStorageParameters, - indexInclude: optionHolder.indexInclude, - } -} - -/** - * @param columnJsonSchema {AlterCollectionColumnDto} - * @return {Array>} - * */ -const getCustomPropertiesOfRegularPkForComparisonWithRegularPkOptions = (columnJsonSchema) => { - /** - * @type {Array} - * */ - const constraintOptions = columnJsonSchema.primaryKeyOptions || []; - return constraintOptions - .map(option => extractOptionsForComparisonWithRegularPkOptions(option)); -} - -/** - * @param compositePk {AlterCollectionRoleCompModPKDto} - * @return {Array>} - * */ -const getCustomPropertiesOfCompositePkForComparisonWithRegularPkOptions = (compositePk) => { - const optionsForComparison = extractOptionsForComparisonWithRegularPkOptions(compositePk); - return [optionsForComparison] - .filter(o => Object.values(o).some(Boolean)); -} - -/** - * @return {(collection: AlterCollectionDto) => PkTransitionDto} - * */ -const wasCompositePkChangedInTransitionFromCompositeToRegular = (_) => (collection) => { - /** - * @type {AlterCollectionRoleCompModPrimaryKey} - * */ - const pkDto = collection?.role?.compMod?.primaryKey || {}; - /** - * @type {AlterCollectionRoleCompModPKDto[]} - * */ - const oldPrimaryKeys = pkDto.old || []; - const idsOfColumns = oldPrimaryKeys.flatMap(pk => pk.compositePrimaryKey.map(dto => dto.keyId)) - if (idsOfColumns.length !== amountOfColumnsInRegularPk) { - // We return false, because it wouldn't count as transition between regular PK and composite PK - // if composite PK did not constraint exactly 1 column - return PkTransitionDto.noTransition(); - } - const idOfPkColumn = idsOfColumns[0]; - const newColumnJsonSchema = Object.values(collection.properties) - .find(columnJsonSchema => columnJsonSchema.GUID === idOfPkColumn); - if (!newColumnJsonSchema) { - return PkTransitionDto.noTransition(); - } - const isNewColumnARegularPrimaryKey = newColumnJsonSchema?.primaryKey && !newColumnJsonSchema?.compositePrimaryKey; - if (!isNewColumnARegularPrimaryKey) { - return PkTransitionDto.noTransition(); - } - const constraintOptions = getCustomPropertiesOfRegularPkForComparisonWithRegularPkOptions(newColumnJsonSchema); - const areOptionsEqual = oldPrimaryKeys.some((compositePk) => { - if (compositePk.compositePrimaryKey.length !== amountOfColumnsInRegularPk) { - return false; - } - const oldCompositePkAsRegularPkOptions = getCustomPropertiesOfCompositePkForComparisonWithRegularPkOptions(compositePk); - return _(oldCompositePkAsRegularPkOptions).differenceWith(constraintOptions, _.isEqual).isEmpty(); - }); - - return PkTransitionDto.transition(!areOptionsEqual); -} - -/** - * @return {(collection: AlterCollectionDto) => PkTransitionDto} - * */ -const wasCompositePkChangedInTransitionFromRegularToComposite = (_) => (collection) => { - /** - * @type {AlterCollectionRoleCompModPrimaryKey} - * */ - const pkDto = collection?.role?.compMod?.primaryKey || {}; - /** - * @type {AlterCollectionRoleCompModPKDto[]} - * */ - const newPrimaryKeys = pkDto.new || []; - const idsOfColumns = newPrimaryKeys.flatMap(pk => pk.compositePrimaryKey.map(dto => dto.keyId)) - if (idsOfColumns.length !== amountOfColumnsInRegularPk) { - // We return false, because it wouldn't count as transition between regular PK and composite PK - // if composite PK does not constraint exactly 1 column - return PkTransitionDto.noTransition(); - } - const idOfPkColumn = idsOfColumns[0]; - const oldColumnJsonSchema = Object.values(collection.role.properties) - .find(columnJsonSchema => columnJsonSchema.GUID === idOfPkColumn); - if (!oldColumnJsonSchema) { - return PkTransitionDto.noTransition(); - } - const isOldColumnARegularPrimaryKey = oldColumnJsonSchema?.primaryKey && !oldColumnJsonSchema?.compositePrimaryKey; - if (!isOldColumnARegularPrimaryKey) { - return PkTransitionDto.noTransition(); - } - const constraintOptions = getCustomPropertiesOfRegularPkForComparisonWithRegularPkOptions(oldColumnJsonSchema); - const areOptionsEqual = newPrimaryKeys.some((compositePk) => { - if (compositePk.compositePrimaryKey.length !== amountOfColumnsInRegularPk) { - return false; - } - const oldCompositePkAsRegularPkOptions = getCustomPropertiesOfCompositePkForComparisonWithRegularPkOptions(compositePk); - return _(oldCompositePkAsRegularPkOptions).differenceWith(constraintOptions, _.isEqual).isEmpty(); - }); - - return PkTransitionDto.transition(!areOptionsEqual); -} - -/** - * @param primaryKey {AlterCollectionRoleCompModPKDto} - * @param entityName {string} - * @return {string} - * */ -const getConstraintNameForCompositePk = (primaryKey, entityName) => { - if (primaryKey.constraintName) { - return primaryKey.constraintName; - } - return getDefaultConstraintName(entityName); -} - -/** - * @param _ - * @return {( - * primaryKey: AlterCollectionRoleCompModPKDto, - * entityName: string, - * entityJsonSchema: AlterCollectionDto, - * ) => { - * name: string, - * keyType: string, - * columns: Array<{ - * isActivated: boolean, - * name: string, - * }>, - * include: Array<{ - * isActivated: boolean, - * name: string, - * }>, - * storageParameters: string, - * } - * } - * */ -const getCreateCompositePKDDLProviderConfig = (_) => ( - primaryKey, - entityName, - entity -) => { - const constraintName = getConstraintNameForCompositePk(primaryKey, entityName); - const pkColumns = _.toPairs(entity.role.properties) - .filter(([name, jsonSchema]) => Boolean(primaryKey.compositePrimaryKey.find(keyDto => keyDto.keyId === jsonSchema.GUID))) - .map(([name, jsonSchema]) => ({ - name, - isActivated: jsonSchema.isActivated, - })); - - let storageParameters = ''; - let includeColumns = []; - if (primaryKey.indexStorageParameters) { - storageParameters = primaryKey.indexStorageParameters; - } - if (primaryKey.indexInclude) { - includeColumns = _.toPairs(entity.role.properties) - .filter(([name, jsonSchema]) => Boolean(primaryKey.indexInclude.find(keyDto => keyDto.keyId === jsonSchema.GUID))) - .map(([name, jsonSchema]) => ({ - name, - isActivated: jsonSchema.isActivated, - })); - } - - return { - name: constraintName, - keyType: 'PRIMARY KEY', - columns: pkColumns, - include: includeColumns, - storageParameters, - } -} - -/** - * @return {(collection: AlterCollectionDto) => Array} - * */ -const getAddCompositePkScriptDtos = (_, ddlProvider) => (collection) => { - const { - getFullCollectionName, - getSchemaOfAlterCollection, - getEntityName, - } = require('../../../utils/general')(_); - - /** - * @type {AlterCollectionRoleCompModPrimaryKey} - * */ - const pkDto = collection?.role?.compMod?.primaryKey || {}; - const newPrimaryKeys = pkDto.new || []; - const oldPrimaryKeys = pkDto.old || []; - if (newPrimaryKeys.length === 0 && oldPrimaryKeys.length === 0) { - return []; - } - const transitionToCompositeDto = wasCompositePkChangedInTransitionFromRegularToComposite(_)(collection); - if (transitionToCompositeDto.didTransitionHappen && !transitionToCompositeDto.wasPkChangedInTransition) { - return []; - } - if (newPrimaryKeys.length === oldPrimaryKeys.length) { - const areKeyArraysEqual = _(oldPrimaryKeys).differenceWith(newPrimaryKeys, _.isEqual).isEmpty(); - if (areKeyArraysEqual) { - return [] - } - } - - const collectionSchema = getSchemaOfAlterCollection(collection); - const fullTableName = getFullCollectionName(collectionSchema); - const entityName = getEntityName(collectionSchema); - - return newPrimaryKeys - .map((newPk) => { - const ddlConfig = getCreateCompositePKDDLProviderConfig(_)(newPk, entityName, collection); - const statementDto = ddlProvider.createKeyConstraint( - fullTableName, - collection.isActivated, - ddlConfig - ); - return new PkScriptModificationDto(statementDto.statement, fullTableName, false, statementDto.isActivated); - }) - .filter(scriptDto => Boolean(scriptDto.script)); -} - -/** - * @return {(collection: AlterCollectionDto) => Array} - * */ -const getDropCompositePkScriptDtos = (_, ddlProvider) => (collection) => { - const { - getFullCollectionName, - getSchemaOfAlterCollection, - getEntityName, - wrapInQuotes - } = require('../../../utils/general')(_); - - const pkDto = collection?.role?.compMod?.primaryKey || {}; - const newPrimaryKeys = pkDto.new || []; - const oldPrimaryKeys = pkDto.old || []; - if (newPrimaryKeys.length === 0 && oldPrimaryKeys.length === 0) { - return []; - } - const transitionToCompositeDto = wasCompositePkChangedInTransitionFromCompositeToRegular(_)(collection); - if (transitionToCompositeDto.didTransitionHappen && !transitionToCompositeDto.wasPkChangedInTransition) { - return []; - } - if (newPrimaryKeys.length === oldPrimaryKeys.length) { - const areKeyArraysEqual = _(oldPrimaryKeys).differenceWith(newPrimaryKeys, _.isEqual).isEmpty(); - if (areKeyArraysEqual) { - return [] - } - } - - const collectionSchema = getSchemaOfAlterCollection(collection); - const fullTableName = getFullCollectionName(collectionSchema); - const entityName = getEntityName(collectionSchema); - - return oldPrimaryKeys - .map((oldPk) => { - let constraintName = getDefaultConstraintName(entityName); - if (oldPk.constraintName) { - constraintName = oldPk.constraintName; - } - const ddlConstraintName = wrapInQuotes(constraintName); - const script = ddlProvider.dropPkConstraint(fullTableName, ddlConstraintName); - return new PkScriptModificationDto(script, fullTableName, true, collection.isActivated); - }) - .filter(scriptDto => Boolean(scriptDto.script)); -} - -/** - * @return {(collection: AlterCollectionDto) => Array} - * */ -const getModifyCompositePkScriptDtos = (_, ddlProvider) => (collection) => { - const dropCompositePkScriptDtos = getDropCompositePkScriptDtos(_, ddlProvider)(collection); - const addCompositePkScriptDtos = getAddCompositePkScriptDtos(_, ddlProvider)(collection); - - return [ - ...dropCompositePkScriptDtos, - ...addCompositePkScriptDtos, - ].filter(Boolean); -} - -/** - * @param columnJsonSchema {AlterCollectionColumnDto} - * @param entityName {string} - * @return {string} - * */ -const getConstraintNameForRegularPk = (columnJsonSchema, entityName) => { - const constraintOptions = columnJsonSchema.primaryKeyOptions; - if (constraintOptions?.length && constraintOptions?.length > 0) { - /** - * @type {AlterCollectionColumnPrimaryKeyOptionDto} - * */ - const constraintOption = constraintOptions[0]; - if (constraintOption.constraintName) { - return constraintOption.constraintName; - } - } - return getDefaultConstraintName(entityName); -} - -/** - * @param _ - * @return {( - * name: string, - * columnJsonSchema: AlterCollectionColumnDto, - * entityName: string, - * entityJsonSchema: AlterCollectionDto, - * ) => { - * name: string, - * keyType: string, - * columns: Array<{ - * isActivated: boolean, - * name: string, - * }>, - * include: Array<{ - * isActivated: boolean, - * name: string, - * }>, - * storageParameters: string, - * } - * } - * */ -const getCreateRegularPKDDLProviderConfig = (_) => ( - columnName, - columnJsonSchema, - entityName, - entity -) => { - const constraintName = getConstraintNameForRegularPk(columnJsonSchema, entityName); - const pkColumns = [{ - name: columnName, - isActivated: columnJsonSchema.isActivated, - }]; - - let storageParameters = ''; - let includeColumns = []; - const constraintOptions = columnJsonSchema.primaryKeyOptions; - if (constraintOptions?.length && constraintOptions?.length > 0) { - /** - * @type {AlterCollectionColumnPrimaryKeyOptionDto} - * */ - const constraintOption = constraintOptions[0]; - if (constraintOption.indexStorageParameters) { - storageParameters = constraintOption.indexStorageParameters; - } - if (constraintOption.indexInclude) { - includeColumns = _.toPairs(entity.role.properties) - .filter(([name, jsonSchema]) => Boolean(constraintOption.indexInclude.find(keyDto => keyDto.keyId === jsonSchema.GUID))) - .map(([name, jsonSchema]) => ({ - name, - isActivated: jsonSchema.isActivated, - })); - } - } - - return { - name: constraintName, - keyType: 'PRIMARY KEY', - columns: pkColumns, - include: includeColumns, - storageParameters, - } -} - - -/** - * @return {(columnJsonSchema: AlterCollectionColumnDto, collection: AlterCollectionDto) => boolean} - * */ -const wasFieldChangedToBeARegularPk = (_) => (columnJsonSchema, collection) => { - const oldName = columnJsonSchema.compMod.oldField.name; - const oldColumnJsonSchema = collection.role.properties[oldName]; - - const isRegularPrimaryKey = columnJsonSchema.primaryKey && !columnJsonSchema.compositePrimaryKey; - const wasTheFieldAnyPrimaryKey = Boolean(oldColumnJsonSchema?.primaryKey); - - return isRegularPrimaryKey && !wasTheFieldAnyPrimaryKey; -} - -/** - * @return {(columnJsonSchema: AlterCollectionColumnDto, collection: AlterCollectionDto) => PkTransitionDto} - * */ -const wasRegularPkChangedInTransitionFromCompositeToRegular = (_) => (columnJsonSchema, collection) => { - const oldName = columnJsonSchema.compMod.oldField.name; - const oldColumnJsonSchema = collection.role.properties[oldName]; - - const isRegularPrimaryKey = columnJsonSchema.primaryKey && !columnJsonSchema.compositePrimaryKey; - const wasTheFieldAnyPrimaryKey = Boolean(oldColumnJsonSchema?.primaryKey); - - if (!(isRegularPrimaryKey && wasTheFieldAnyPrimaryKey)) { - return PkTransitionDto.noTransition(); - } - - /** - * @type {AlterCollectionRoleCompModPrimaryKey} - * */ - const pkDto = collection?.role?.compMod?.primaryKey || {}; - const newPrimaryKeys = pkDto.new || []; - /** - * @type {AlterCollectionRoleCompModPKDto[]} - * */ - const oldPrimaryKeys = pkDto.old || []; - const wasTheFieldACompositePrimaryKey = oldPrimaryKeys.some(compPk => compPk.compositePrimaryKey.some((pk) => pk.keyId === oldColumnJsonSchema.GUID)); - const isTheFieldACompositePrimaryKey = newPrimaryKeys.some(compPk => compPk.compositePrimaryKey.some((pk) => pk.keyId === columnJsonSchema.GUID)); - - const wasCompositePkRemoved = wasTheFieldACompositePrimaryKey && !isTheFieldACompositePrimaryKey; - - if (isRegularPrimaryKey && wasCompositePkRemoved) { - // return compare custom properties and amount of columns. - // If there was a transition and amount of composite PK columns is not equal - // to amount of regular pk columns, we must recreate PK - const constraintOptions = getCustomPropertiesOfRegularPkForComparisonWithRegularPkOptions(columnJsonSchema); - const areOptionsEqual = oldPrimaryKeys.some((oldCompositePk) => { - if (oldCompositePk.compositePrimaryKey.length !== amountOfColumnsInRegularPk) { - return false; - } - const oldCompositePkAsRegularPkOptions = getCustomPropertiesOfCompositePkForComparisonWithRegularPkOptions(oldCompositePk); - return _(oldCompositePkAsRegularPkOptions).differenceWith(constraintOptions, _.isEqual).isEmpty(); - }); - return PkTransitionDto.transition(!areOptionsEqual); - } - - return PkTransitionDto.noTransition(); -} - -/** - * @return {(columnJsonSchema: AlterCollectionColumnDto, collection: AlterCollectionDto) => PkTransitionDto} - * */ -const wasRegularPkChangedInTransitionFromRegularToComposite = (_) => (columnJsonSchema, collection) => { - const oldName = columnJsonSchema.compMod.oldField.name; - const oldColumnJsonSchema = collection.role.properties[oldName]; - - const wasRegularPrimaryKey = oldColumnJsonSchema.primaryKey && !oldColumnJsonSchema.compositePrimaryKey; - const isTheFieldAnyPrimaryKey = Boolean(columnJsonSchema?.primaryKey); - - if (!(wasRegularPrimaryKey && isTheFieldAnyPrimaryKey)) { - return PkTransitionDto.noTransition(); - } - - /** - * @type {AlterCollectionRoleCompModPrimaryKey} - * */ - const pkDto = collection?.role?.compMod?.primaryKey || {}; - const newPrimaryKeys = pkDto.new || []; - /** - * @type {AlterCollectionRoleCompModPKDto[]} - * */ - const oldPrimaryKeys = pkDto.old || []; - const wasTheFieldACompositePrimaryKey = oldPrimaryKeys.some(compPk => compPk.compositePrimaryKey.some((pk) => pk.keyId === oldColumnJsonSchema.GUID)); - const isTheFieldACompositePrimaryKey = newPrimaryKeys.some(compPk => compPk.compositePrimaryKey.some((pk) => pk.keyId === columnJsonSchema.GUID)); - - const wasCompositePkAdded = isTheFieldACompositePrimaryKey && !wasTheFieldACompositePrimaryKey; - - if (wasRegularPrimaryKey && wasCompositePkAdded) { - // return compare custom properties and amount of columns. - // If there was a transition and amount of composite PK columns is not equal - // to amount of regular pk columns, we must recreate PK - const constraintOptions = getCustomPropertiesOfRegularPkForComparisonWithRegularPkOptions(oldColumnJsonSchema); - const areOptionsEqual = newPrimaryKeys.some((oldCompositePk) => { - if (oldCompositePk.compositePrimaryKey.length !== amountOfColumnsInRegularPk) { - return false; - } - const oldCompositePkAsRegularPkOptions = getCustomPropertiesOfCompositePkForComparisonWithRegularPkOptions(oldCompositePk); - return _(oldCompositePkAsRegularPkOptions).differenceWith(constraintOptions, _.isEqual).isEmpty(); - }); - return PkTransitionDto.transition(!areOptionsEqual); - } - - return PkTransitionDto.noTransition(); -} - -/** - * @return {(columnJsonSchema: AlterCollectionColumnDto, collection: AlterCollectionDto) => boolean} - * */ -const isFieldNoLongerARegularPk = (_) => (columnJsonSchema, collection) => { - const oldName = columnJsonSchema.compMod.oldField.name; - - const oldJsonSchema = collection.role.properties[oldName]; - const wasTheFieldARegularPrimaryKey = oldJsonSchema?.primaryKey && !oldJsonSchema?.compositePrimaryKey; - - const isNotAnyPrimaryKey = !columnJsonSchema.primaryKey && !columnJsonSchema.compositePrimaryKey; - return wasTheFieldARegularPrimaryKey && isNotAnyPrimaryKey; -} - -/** - * @return {(columnJsonSchema: AlterCollectionColumnDto, collection: AlterCollectionDto) => boolean} - * */ -const wasRegularPkModified = (_) => (columnJsonSchema, collection) => { - const oldName = columnJsonSchema.compMod.oldField.name; - const oldJsonSchema = collection.role.properties[oldName] || {}; - - const isRegularPrimaryKey = columnJsonSchema.primaryKey && !columnJsonSchema.compositePrimaryKey; - const wasTheFieldARegularPrimaryKey = oldJsonSchema?.primaryKey && !oldJsonSchema?.compositePrimaryKey; - - if (!(isRegularPrimaryKey && wasTheFieldARegularPrimaryKey)) { - return false; - } - const constraintOptions = getCustomPropertiesOfRegularPkForComparisonWithRegularPkOptions(columnJsonSchema); - const oldConstraintOptions = getCustomPropertiesOfRegularPkForComparisonWithRegularPkOptions(oldJsonSchema); - const areOptionsEqual = _(oldConstraintOptions).differenceWith(constraintOptions, _.isEqual).isEmpty(); - return !areOptionsEqual; -} - -/** - * @return {(collection: AlterCollectionDto) => Array} - * */ -const getAddPkScriptDtos = (_, ddlProvider) => (collection) => { - const { - getFullCollectionName, - getSchemaOfAlterCollection, - getEntityName, - } = require('../../../utils/general')(_); - - const collectionSchema = getSchemaOfAlterCollection(collection); - const fullTableName = getFullCollectionName(collectionSchema); - const entityName = getEntityName(collectionSchema); - - return _.toPairs(collection.properties) - .filter(([name, jsonSchema]) => { - if (wasFieldChangedToBeARegularPk(_)(jsonSchema, collection)) { - return true; - } - const transitionToRegularDto = wasRegularPkChangedInTransitionFromCompositeToRegular(_)(jsonSchema, collection); - if (transitionToRegularDto.didTransitionHappen) { - return transitionToRegularDto.wasPkChangedInTransition; - } - return wasRegularPkModified(_)(jsonSchema, collection); - }) - .map(([name, jsonSchema]) => { - const ddlConfig = getCreateRegularPKDDLProviderConfig(_)(name, jsonSchema, entityName, collection); - const statementDto = ddlProvider.createKeyConstraint( - fullTableName, - collection.isActivated, - ddlConfig - ); - return new PkScriptModificationDto(statementDto.statement, fullTableName, false, statementDto.isActivated); - }) - .filter(scriptDto => Boolean(scriptDto.script)); -} - -/** - * @return {(collection: AlterCollectionDto) => Array} - * */ -const getDropPkScriptDto = (_, ddlProvider) => (collection) => { - const { - getFullCollectionName, - getSchemaOfAlterCollection, - getEntityName, - wrapInQuotes - } = require('../../../utils/general')(_); - - const collectionSchema = getSchemaOfAlterCollection(collection); - const fullTableName = getFullCollectionName(collectionSchema); - const entityName = getEntityName(collectionSchema); - - return _.toPairs(collection.properties) - .filter(([name, jsonSchema]) => { - if (isFieldNoLongerARegularPk(_)(jsonSchema, collection)) { - return true; - } - const transitionToRegularDto = wasRegularPkChangedInTransitionFromRegularToComposite(_)(jsonSchema, collection); - if (transitionToRegularDto.didTransitionHappen) { - return transitionToRegularDto.wasPkChangedInTransition; - } - return wasRegularPkModified(_)(jsonSchema, collection); - }) - .map(([name, jsonSchema]) => { - const oldName = jsonSchema.compMod.oldField.name; - const oldJsonSchema = collection.role.properties[oldName]; - const ddlConstraintName = wrapInQuotes(getConstraintNameForRegularPk(oldJsonSchema, entityName)); - - const script = ddlProvider.dropPkConstraint(fullTableName, ddlConstraintName); - return new PkScriptModificationDto(script, fullTableName, true, collection.isActivated); - }) - .filter(scriptDto => Boolean(scriptDto.script)); -} - -/** - * @return {(collection: AlterCollectionDto) => Array} - * */ -const getModifyPkScriptDtos = (_, ddlProvider) => (collection) => { - const dropPkScriptDtos = getDropPkScriptDto(_, ddlProvider)(collection); - const addPkScriptDtos = getAddPkScriptDtos(_, ddlProvider)(collection); - - return [ - ...dropPkScriptDtos, - ...addPkScriptDtos, - ].filter(Boolean); -} - -/** - * @param constraintDtos {PkScriptModificationDto[]} - * @return {PkScriptModificationDto[]} - * */ -const sortModifyPkConstraints = (constraintDtos) => { - return constraintDtos.sort((c1, c2) => { - if (c1.fullTableName === c2.fullTableName) { - // Number(true) = 1, Number(false) = 0; - // This ensures that DROP script appears before CREATE script - // if the same table has 2 scripts that drop and recreate PK - return Number(c2.isDropScript) - Number(c1.isDropScript); - } - // This sorts all statements based on full table name, ASC - return c1.fullTableName < c2.fullTableName; - }); -} - -/** - * @return {(collection: AlterCollectionDto) => Array} - * */ -const getModifyPkConstraintsScriptDtos = (_, ddlProvider) => (collection) => { - const modifyCompositePkScriptDtos = getModifyCompositePkScriptDtos(_, ddlProvider)(collection); - const modifyPkScriptDtos = getModifyPkScriptDtos(_, ddlProvider)(collection); - - const allDtos = [ - ...modifyCompositePkScriptDtos, - ...modifyPkScriptDtos, - ]; - const sortedAllDtos = sortModifyPkConstraints(allDtos); - - return sortedAllDtos - .map(dto => { - return AlterScriptDto.getInstance([dto.script], dto.isActivated, dto.isDropScript); - }) - .filter(Boolean); -} - -module.exports = { - getModifyPkConstraintsScriptDtos, -} diff --git a/forward_engineering/alterScript/alterScriptHelpers/viewHelpers/commentsHelper.js b/forward_engineering/alterScript/alterScriptHelpers/viewHelpers/commentsHelper.js deleted file mode 100644 index a96f0c1..0000000 --- a/forward_engineering/alterScript/alterScriptHelpers/viewHelpers/commentsHelper.js +++ /dev/null @@ -1,52 +0,0 @@ -const {AlterScriptDto} = require("../../types/AlterScriptDto"); - -const extractDescription = (view) => { - return view?.role?.compMod?.description || {}; -} - -/** - * @return {(view: Object) => AlterScriptDto | undefined} - * */ -const getUpsertCommentsScriptDto = (_, ddlProvider) => (view) => { - const {getFullViewName, wrapComment} = require('../../../utils/general')(_); - - const description = extractDescription(view); - if (description.new && description.new !== description.old) { - const wrappedComment = wrapComment(description.new); - const viewName = getFullViewName(view); - const script = ddlProvider.updateViewComment(viewName, wrappedComment); - return AlterScriptDto.getInstance([script], true, false); - } - return undefined; -} - -/** - * @return {(view: Object) => AlterScriptDto | undefined} - * */ -const getDropCommentsScriptDto = (_, ddlProvider) => (view) => { - const description = extractDescription(view); - const {getFullViewName} = require('../../../utils/general')(_); - - if (description.old && !description.new) { - const viewName = getFullViewName(view); - const script = ddlProvider.dropViewComment(viewName); - return AlterScriptDto.getInstance([script], true, true); - } - return undefined; -} - -/** - * @return {(view: Object) => AlterScriptDto[]} - * */ -const getModifyViewCommentsScriptDtos = (_, ddlProvider) => (view) => { - const upsertCommentScript = getUpsertCommentsScriptDto(_, ddlProvider)(view); - const dropCommentScript = getDropCommentsScriptDto(_, ddlProvider)(view); - return [ - upsertCommentScript, - dropCommentScript - ].filter(Boolean); -} - -module.exports = { - getModifyViewCommentsScriptDtos -} diff --git a/forward_engineering/alterScript/types/AlterCollectionDto.js b/forward_engineering/alterScript/types/AlterCollectionDto.js deleted file mode 100644 index 485de01..0000000 --- a/forward_engineering/alterScript/types/AlterCollectionDto.js +++ /dev/null @@ -1,406 +0,0 @@ -class ColumnCompModField { - - /** - * @type {string} - */ - type - - /** - * @type {string} - */ - name - - /** - * @type {string} - */ - mode -} - -class AlterCollectionColumnCompModDto { - - /** - * @type {ColumnCompModField} - * */ - oldField - - /** - * @type {ColumnCompModField} - * */ - newField - -} - -class AlterCollectionColumnPrimaryKeyOptionDto { - /** - * @type {string} - * */ - id - - /** - * @type {string} - * */ - constraintName - - /** - * @type {string} - * */ - indexStorageParameters - - /** - * @type {Array<{ - * keyId: string, - * type?: string, - * }>} - * */ - indexInclude -} - -class AlterCollectionColumnDto { - /** - * @type {string} - */ - type - - /** - * @type {boolean} - */ - isActivated - - /** - * @type {boolean} - */ - primaryKey - - /** - * @type {boolean} - */ - unique - - /** - * @type {string} - */ - mode - - /** - * @type {number} - */ - length - - /** - * @type {[ - * "compositePartitionKey", - * "compositePrimaryKey", - * "compositeUniqueKey", - * "triggerUpdateColumns", - * ]} - */ - compositeKey - - /** - * @type {boolean} - */ - compositePartitionKey - - /** - * @type {boolean} - */ - compositePrimaryKey - - /** - * @type {boolean} - */ - compositeUniqueKey - - /** - * @type {Array | undefined} - * */ - primaryKeyOptions - - /** - * @type {boolean} - */ - triggerUpdateColumns - - /** - * @type {AlterCollectionColumnCompModDto} - * */ - compMod - - /** - * @type {string} - */ - GUID -} - -class AlterCollectionRoleDefinitionDto { - - /** - * @type {string} - */ - id - - /** - * @type {string} - */ - type - - /** - * @type {Array} - */ - properties -} - -class AlterCollectionRoleCompModPKDto extends AlterCollectionColumnPrimaryKeyOptionDto{ - - /** - * @type {Array<{ - * type: string, - * keyId: string, - * }>} - * */ - compositePrimaryKey - -} - -class AlterCollectionRoleCompModPrimaryKey { - /** - * @type {AlterCollectionRoleCompModPKDto[] | undefined} - * */ - new - /** - * @type {AlterCollectionRoleCompModPKDto[] | undefined} - * */ - old - -} - -class AlterCollectionRoleCompModDto { - /** - * @type {string} - */ - keyspaceName - - /** - * @type {{ - * name: string, - * isActivated: boolean, - * ifNotExist: boolean, - * }} - */ - bucketProperties - - /** - * @type {{ - * new: string, - * old: string, - * }} - */ - collectionName - - /** - * @type {{ - * new: boolean, - * old: boolean, - * }} - */ - isActivated - - /** - * @type {{ - * new: string, - * old: string, - * }} - */ - bucketId - - /** - * @type {{ - * new: boolean, - * old: boolean, - * }} - */ - ifNotExist - - /** - * @type {{ - * new: string, - * old: string, - * }} - */ - on_commit - - /** - * @type {AlterCollectionRoleCompModPrimaryKey} - */ - primaryKey - - /** - * @type {Array<{ - * [propertyName: string]: AlterCollectionColumnDto - * }>} - */ - newProperties -} - -class AlterCollectionRoleDto { - - /** - * @type {string} - */ - id - - /** - * @type {"object"} - */ - type - - /** - * @type {string} - */ - collectionName - - /** - * @type {{ - * [propertyName: string]: AlterCollectionColumnDto - * }} - */ - properties - - /** - * @type {AlterCollectionRoleDefinitionDto} - * */ - definitions - - /** - * @type {boolean} - */ - isActivated - - /** - * @type {boolean} - */ - additionalProperties - - /** - * @type {boolean} - */ - memory_optimized - - /** - * @type {Array} - */ - collectionUsers - - /** - * @type {boolean} - */ - ifNotExist - - /** - * @type {string} - */ - on_commit - - /** - * @type {string} - */ - bucketId - - /** - * @type {AlterCollectionRoleCompModDto} - * */ - compMod - - /** - * @type {string} - */ - name - - /** - * @type {"entity"} - */ - roleType - - /** - * @type {Array} - */ - patternProperties -} - -class AlterCollectionDto { - - /** - * @type {"object"} - */ - type - - /** - * @type {boolean} - */ - isActivated - - /** - * @type {boolean} - */ - unique - - /** - * @type {"object"} - */ - subtype - - /** - * @type {{ - * [preopertyName: string]: AlterCollectionColumnDto - * }} - * */ - properties - - /** - * @type {[ - * "compositePartitionKey", - * "compositePrimaryKey", - * "compositeUniqueKey", - * "triggerUpdateColumns", - * ]} - */ - compositeKey - - /** - * @type {boolean} - */ - compositePartitionKey - - /** - * @type {boolean} - */ - compositePrimaryKey - - /** - * @type {boolean} - */ - compositeUniqueKey - - /** - * @type {boolean} - */ - triggerUpdateColumns - - /** - * @type {AlterCollectionRoleDto} - * */ - role - - /** - * @type {string} - */ - GUID -} - -module.exports = { - AlterCollectionDto, - AlterCollectionRoleDto, - AlterCollectionColumnDto, - AlterCollectionRoleCompModPrimaryKey, - AlterCollectionRoleCompModPKDto, -} diff --git a/forward_engineering/alterScript/types/AlterRelationshipDto.js b/forward_engineering/alterScript/types/AlterRelationshipDto.js deleted file mode 100644 index eee563e..0000000 --- a/forward_engineering/alterScript/types/AlterRelationshipDto.js +++ /dev/null @@ -1,274 +0,0 @@ -class AlterRelationshipFKField { - - /** - * @type {boolean} - */ - isActivated - - /** - * @type {string} - */ - name -} - -class AlterRelationshipParentDto { - - /** - * @type {{ - * name: string, - * isActivated: boolean - * }} - */ - bucket - - /** - * @type {{ - * name: string, - * isActivated: boolean, - * fkFields: Array - * }} - */ - collection -} - -class AlterRelationshipChildDto { - - /** - * @type {{ - * name: string, - * isActivated: boolean - * }} - */ - bucket - - /** - * @type {{ - * name: string, - * isActivated: boolean, - * fkFields: Array - * }} - */ - collection -} - -class AlterRelationshipCustomProperties { - - /** - * @type {string} - */ - relationshipOnDelete - - /** - * @type {string} - */ - relationshipOnUpdate - - /** - * @type {string} - */ - relationshipMatch - -} - -class AlterRelationshipRoleCompModDto { - - /** - * @type {boolean} - */ - created - - /** - * @type {boolean} - */ - deleted - - /** - * @type {boolean | undefined} - */ - modified - - /** - * @type {AlterRelationshipParentDto} - * */ - parent - - /** - * @type {AlterRelationshipChildDto} - * */ - child - - /** - * @type {{ - * new: string, - * old: string, - * } | undefined} - */ - name - - /** - * @type {{ - * new: string, - * old: string, - * } | undefined} - */ - description - - /** - * @type {{ - * old?: AlterRelationshipCustomProperties, - * new?: AlterRelationshipCustomProperties - * } | undefined} - * */ - customProperties - - /** - * @type {{ - * new?: boolean, - * old?: boolean, - * }} - */ - isActivated -} - -class AlterRelationshipRoleDto { - - /** - * @type {string} - */ - id - - /** - * @type {string} - */ - name - - /** - * @type {"Foreign Key"} - */ - relationshipType - - /** - * @type {Array>} - */ - parentField - - /** - * @type {string} - */ - parentCardinality - - /** - * @type {Array>} - */ - childField - - /** - * @type {boolean} - */ - isActivated - - /** - * @type {string} - */ - childCardinality - - /** - * @type {string} - */ - parentCollection - - /** - * @type {string} - */ - childCollection - - /** - * @type {Object} - */ - hackoladeStyles - - /** - * @type {AlterRelationshipRoleCompModDto} - * */ - compMod - - /** - * @type {"relationship"} - */ - roleType -} - -class AlterRelationshipDto { - - /** - * @type {"object"} - */ - type - - /** - * @type {boolean} - */ - isActivated - - /** - * @type {boolean} - */ - unique - - /** - * @type {"object"} - */ - subtype - - /** - * @type {[ - * "compositePartitionKey", - * "compositePrimaryKey", - * "compositeUniqueKey", - * "triggerUpdateColumns", - * ]} - */ - compositeKey - - /** - * @type {boolean} - */ - compositePartitionKey - - /** - * @type {boolean} - */ - compositePrimaryKey - - /** - * @type {boolean} - */ - compositeUniqueKey - - /** - * @type {boolean} - */ - triggerUpdateColumns - - /** - * @type {AlterRelationshipRoleDto} - */ - role - - /** - * @type {string} - */ - GUID - -} - - -module.exports = { - AlterRelationshipRoleCompModDto, - AlterRelationshipRoleDto, - AlterRelationshipDto, - AlterRelationshipFKField, - AlterRelationshipParentDto, - AlterRelationshipChildDto, - AlterRelationshipCustomProperties -} diff --git a/forward_engineering/alterScript/types/AlterScriptDto.js b/forward_engineering/alterScript/types/AlterScriptDto.js deleted file mode 100644 index 2cc8551..0000000 --- a/forward_engineering/alterScript/types/AlterScriptDto.js +++ /dev/null @@ -1,99 +0,0 @@ -class ModificationScript { - /** - * @type string - * */ - script - - /** - * @type boolean - * */ - isDropScript -} - -class AlterScriptDto { - /** - * @type {boolean | undefined} - * */ - isActivated - - /** - * @type {Array} - * */ - scripts - - /** - * @param scripts {Array} - * @param isActivated {boolean} - * @param isDropScripts {boolean} - * @return {Array} - * */ - static getInstances(scripts, isActivated, isDropScripts) { - return (scripts || []) - .filter(Boolean) - .map(script => ({ - isActivated, - scripts: [{ - isDropScript: isDropScripts, - script - }] - })); - } - - /** - * @param scripts {Array} - * @param isActivated {boolean} - * @param isDropScripts {boolean} - * @return {AlterScriptDto | undefined} - * */ - static getInstance(scripts, isActivated, isDropScripts) { - if (!scripts?.filter(Boolean)?.length) { - return undefined; - } - return { - isActivated, - scripts: scripts - .filter(Boolean) - .map(script => ({ - isDropScript: isDropScripts, - script, - })) - } - } - - /** - * @param dropScript {string | undefined} - * @param createScript {string | undefined} - * @param isActivated {boolean} - * @return {AlterScriptDto | undefined} - * */ - static getDropAndRecreateInstance(dropScript, createScript, isActivated) { - /** - * @type {ModificationScript[]} - * */ - const scriptModificationDtos = []; - if (Boolean(dropScript)) { - scriptModificationDtos.push({ - isDropScript: true, - script: dropScript, - }) - } - if (Boolean(createScript)) { - scriptModificationDtos.push({ - isDropScript: false, - script: createScript, - }); - } - if (!scriptModificationDtos?.length) { - return undefined; - } - return { - isActivated, - scripts: scriptModificationDtos, - } - } -} - -module.exports = { - ModificationScript, - AlterScriptDto, -} diff --git a/forward_engineering/api.js b/forward_engineering/api.js index 94b6b6d..d7aad87 100644 --- a/forward_engineering/api.js +++ b/forward_engineering/api.js @@ -1,79 +1,308 @@ -const reApi = require('../reverse_engineering/api'); -const {createLogger} = require('../reverse_engineering/helpers/loggerHelper'); -const applyToInstanceHelper = require('./applyToInstanceHelper'); -const { - buildEntityLevelAlterScript, - buildContainerLevelAlterScript, - doesContainerLevelAlterScriptContainDropStatements, - doesEntityLevelAlterScriptContainDropStatements -} = require("./alterScript/alterScriptBuilder"); +"use strict";var vt=Object.defineProperty;var ju=Object.getOwnPropertyDescriptor;var zu=Object.getOwnPropertyNames;var Xu=Object.prototype.hasOwnProperty;var i=(t,e)=>vt(t,"name",{value:e,configurable:!0});var Zu=(t,e)=>()=>(t&&(e=t(t=0)),e);var C=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ju=(t,e)=>{for(var r in e)vt(t,r,{get:e[r],enumerable:!0})},el=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of zu(e))!Xu.call(t,s)&&s!==r&&vt(t,s,{get:()=>e[s],enumerable:!(n=ju(e,s))||n.enumerable});return t};var tl=t=>el(vt({},"__esModule",{value:!0}),t);var tr=C((ME,ci)=>{"use strict";var rl=i(({title:t,logger:e,hiddenKeys:r})=>({info(n,s={}){e.log("info",{message:n,...s},t,r)},progress(n,s="",o=""){e.progress({message:n,containerName:s,entityName:o})},error(n){e.log("error",nl(n),t)}}),"createLogger"),nl=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError");ci.exports={createLogger:rl}});var li=C((kE,ui)=>{var nt=1e3,st=nt*60,it=st*60,ot=it*24,sl=ot*365.25;ui.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return il(t);if(r==="number"&&isNaN(t)===!1)return e.long?al(t):ol(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function il(t){if(t=String(t),!(t.length>100)){var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*sl;case"days":case"day":case"d":return r*ot;case"hours":case"hour":case"hrs":case"hr":case"h":return r*it;case"minutes":case"minute":case"mins":case"min":case"m":return r*st;case"seconds":case"second":case"secs":case"sec":case"s":return r*nt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}i(il,"parse");function ol(t){return t>=ot?Math.round(t/ot)+"d":t>=it?Math.round(t/it)+"h":t>=st?Math.round(t/st)+"m":t>=nt?Math.round(t/nt)+"s":t+"ms"}i(ol,"fmtShort");function al(t){return wt(t,ot,"day")||wt(t,it,"hour")||wt(t,st,"minute")||wt(t,nt,"second")||t+" ms"}i(al,"fmtLong");function wt(t,e,r){if(!(t{B=pi.exports=nr.debug=nr.default=nr;B.coerce=ml;B.disable=ll;B.enable=ul;B.enabled=pl;B.humanize=li();B.names=[];B.skips=[];B.formatters={};var rr;function cl(t){var e=0,r;for(r in t)e=(e<<5)-e+t.charCodeAt(r),e|=0;return B.colors[Math.abs(e)%B.colors.length]}i(cl,"selectColor");function nr(t){function e(){if(e.enabled){var r=e,n=+new Date,s=n-(rr||n);r.diff=s,r.prev=rr,r.curr=n,rr=n;for(var o=new Array(arguments.length),a=0;a{ue=di.exports=sr();ue.log=hl;ue.formatArgs=fl;ue.save=yl;ue.load=mi;ue.useColors=dl;ue.storage=typeof chrome<"u"&&typeof chrome.storage<"u"?chrome.storage.local:gl();ue.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function dl(){return typeof window<"u"&&window.process&&window.process.type==="renderer"?!0:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}i(dl,"useColors");ue.formatters.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}};function fl(t){var e=this.useColors;if(t[0]=(e?"%c":"")+this.namespace+(e?" %c":" ")+t[0]+(e?"%c ":" ")+"+"+ue.humanize(this.diff),!!e){var r="color: "+this.color;t.splice(1,0,r,"color: inherit");var n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,function(o){o!=="%%"&&(n++,o==="%c"&&(s=n))}),t.splice(s,0,r)}}i(fl,"formatArgs");function hl(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}i(hl,"log");function yl(t){try{t==null?ue.storage.removeItem("debug"):ue.storage.debug=t}catch{}}i(yl,"save");function mi(){var t;try{t=ue.storage.debug}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}i(mi,"load");ue.enable(mi());function gl(){try{return window.localStorage}catch{}}i(gl,"localstorage")});var Ei=C((te,gi)=>{var hi=require("tty"),at=require("util");te=gi.exports=sr();te.init=Nl;te.log=Tl;te.formatArgs=Sl;te.save=Cl;te.load=yi;te.useColors=_l;te.colors=[6,2,3,4,5,1];te.inspectOpts=Object.keys(process.env).filter(function(t){return/^debug_/i.test(t)}).reduce(function(t,e){var r=e.substring(6).toLowerCase().replace(/_([a-z])/g,function(s,o){return o.toUpperCase()}),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});var Ge=parseInt(process.env.DEBUG_FD,10)||2;Ge!==1&&Ge!==2&&at.deprecate(function(){},"except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)")();var El=Ge===1?process.stdout:Ge===2?process.stderr:Al(Ge);function _l(){return"colors"in te.inspectOpts?!!te.inspectOpts.colors:hi.isatty(Ge)}i(_l,"useColors");te.formatters.o=function(t){return this.inspectOpts.colors=this.useColors,at.inspect(t,this.inspectOpts).split(` +`).map(function(e){return e.trim()}).join(" ")};te.formatters.O=function(t){return this.inspectOpts.colors=this.useColors,at.inspect(t,this.inspectOpts)};function Sl(t){var e=this.namespace,r=this.useColors;if(r){var n=this.color,s=" \x1B[3"+n+";1m"+e+" \x1B[0m";t[0]=s+t[0].split(` +`).join(` +`+s),t.push("\x1B[3"+n+"m+"+te.humanize(this.diff)+"\x1B[0m")}else t[0]=new Date().toUTCString()+" "+e+" "+t[0]}i(Sl,"formatArgs");function Tl(){return El.write(at.format.apply(at,arguments)+` +`)}i(Tl,"log");function Cl(t){t==null?delete process.env.DEBUG:process.env.DEBUG=t}i(Cl,"save");function yi(){return process.env.DEBUG}i(yi,"load");function Al(t){var e,r=process.binding("tty_wrap");switch(r.guessHandleType(t)){case"TTY":e=new hi.WriteStream(t),e._type="tty",e._handle&&e._handle.unref&&e._handle.unref();break;case"FILE":var n=require("fs");e=new n.SyncWriteStream(t,{autoClose:!1}),e._type="fs";break;case"PIPE":case"TCP":var s=require("net");e=new s.Socket({fd:t,readable:!1,writable:!0}),e.readable=!1,e.read=null,e._type="pipe",e._handle&&e._handle.unref&&e._handle.unref();break;default:throw new Error("Implement me. Unknown stream file type!")}return e.fd=t,e._isStdio=!0,e}i(Al,"createWritableStdioStream");function Nl(t){t.inspectOpts={};for(var e=Object.keys(te.inspectOpts),r=0;r{typeof process<"u"&&process.type==="renderer"?ir.exports=fi():ir.exports=Ei()});var _i=C(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.default=null});var wi=C((VE,vi)=>{var Ti=9007199254740991,bl="[object Arguments]",vl="[object Function]",wl="[object GeneratorFunction]",Ol=/^(?:0|[1-9]\d*)$/;function Ci(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}i(Ci,"apply");function Il(t,e){for(var r=-1,n=Array(t);++r1?r[s-1]:void 0,a=s>2?r[2]:void 0;for(o=t.length>3&&typeof o=="function"?(s--,o):void 0,a&&kl(r[0],r[1],a)&&(o=s<3?void 0:o,s=1),e=Object(e);++n-1&&t%1==0&&t-1&&t%1==0&&t<=Ti}i(Vl,"isLength");function lr(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}i(lr,"isObject");function Hl(t){return!!t&&typeof t=="object"}i(Hl,"isObjectLike");var Ql=ql(function(t,e,r,n){Ml(e,Yl(e),t,n)}),Wl=Ni(function(t){return t.push(void 0,Dl),Ci(Ql,void 0,t)});function Yl(t){return ur(t)?Pl(t,!0):xl(t)}i(Yl,"keysIn");vi.exports=Wl});var Ii=C((QE,Oi)=>{var jl=require("util"),zl=wi(),Xl=or()("tunnel-ssh-config"),pr=i(function(t,e){Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=t,this.extra=e},"ConfigError");jl.inherits(pr,Error);function Zl(t){var e=process.env;if(zl(t||{},{username:e.TUNNELSSH_USER||e.USER||e.USERNAME||"root",port:22,host:null,srcPort:0,srcHost:"127.0.0.1",dstPort:null,dstHost:"127.0.0.1",localHost:"127.0.0.1",localPort:t.dstPort,agent:process.env.SSH_AUTH_SOCK}),!t.host)throw new pr("host not set");if(!t.dstPort)throw new pr("dstPort not set");return Xl("ssh-config",function(){var r=["password","privateKey"];return Object.keys(t).reduce(function(n,s){return r.indexOf(s)===-1?n[s]=t[s]:n[s]="***HIDDEN***",n},{})}()),t}i(Zl,"createConfig");Oi.exports=Zl});var Pi=C((YE,Ri)=>{var Jl=require("net"),mr=or()("tunnel-ssh"),ep=_i().Client,tp=Ii(),rp=require("events"),np=i(function(){},"noop");function sp(t,e){var r=new ep;return e.on("close",r.end.bind(r)),r.on("ready",function(){mr("sshConnection:ready"),e.emit("sshConnection",r,e),r.forwardOut(t.srcHost,t.srcPort,t.dstHost,t.dstPort,function(n,s){if(n){e.emit("error",n),mr("Destination port:",n);return}mr("sshStream:create"),e.emit("sshStream",s),e.pipe(s).pipe(e)})}),r}i(sp,"bindSSHConnection");function ip(t,e){return e.reduce(function(r,n){return delete r[n],r},Object.assign({},t))}i(ip,"omit");function op(t){var e,r=[],n=0;return e=Jl.createServer(function(s){var o;n++,s.on("error",e.emit.bind(e,"error")),s.on("close",function(){n--,n===0&&(t.keepAlive||setTimeout(function(){n===0&&e.close()},2))}),e.emit("netConnection",s,e),o=sp(t,s),o.on("error",e.emit.bind(e,"error")),s.on("sshStream",function(a){a.on("error",function(){e.close()})}),r.push(o,s);try{o.connect(ip(t,["localPort","localHost"]))}catch(a){e.emit("error",a)}}),e.on("close",function(){r.forEach(function(s){s.end()})}),e}i(op,"createServer");function ap(t,e){var r,n;e||(e=np);try{n=tp(t),r=op(n),r.listen(n.localPort,n.localHost,function(s){e(s,r)})}catch(s){r=new rp.EventEmitter,setImmediate(function(){e(s),r.emit("error",s)})}return r}i(ap,"tunnel");Ri.exports=ap});var fr=C(Di=>{"use strict";Di.parse=function(t,e){return new dr(t,e).parse()};var Ot=class Ot{constructor(e,r){this.source=e,this.transform=r||cp,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var r;(this.recorded.length>0||e)&&(r=this.recorded.join(""),r==="NULL"&&!e&&(r=null),r!==null&&(r=this.transform(r)),this.entries.push(r),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var r,n,s;for(this.consumeDimensions();!this.isEof();)if(r=this.nextCharacter(),r.value==="{"&&!s)this.dimension++,this.dimension>1&&(n=new Ot(this.source.substr(this.position-1),this.transform),this.entries.push(n.parse(!0)),this.position+=n.position-2);else if(r.value==="}"&&!s){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else r.value==='"'&&!r.escaped?(s&&this.newEntry(!0),s=!s):r.value===","&&!s?this.newEntry():this.record(r.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};i(Ot,"ArrayParser");var dr=Ot;function cp(t){return t}i(cp,"identity")});var hr=C((ZE,Li)=>{var up=fr();Li.exports={create:function(t,e){return{parse:function(){return up.parse(t,e)}}}}});var qi=C((JE,Mi)=>{"use strict";var lp=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,pp=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,mp=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,dp=/^-?infinity$/;Mi.exports=i(function(e){if(dp.test(e))return Number(e.replace("i","I"));var r=lp.exec(e);if(!r)return fp(e)||null;var n=!!r[8],s=parseInt(r[1],10);n&&(s=xi(s));var o=parseInt(r[2],10)-1,a=r[3],c=parseInt(r[4],10),l=parseInt(r[5],10),u=parseInt(r[6],10),p=r[7];p=p?1e3*parseFloat(p):0;var d,h=hp(e);return h!=null?(d=new Date(Date.UTC(s,o,a,c,l,u,p)),yr(s)&&d.setUTCFullYear(s),h!==0&&d.setTime(d.getTime()-h)):(d=new Date(s,o,a,c,l,u,p),yr(s)&&d.setFullYear(s)),d},"parseDate");function fp(t){var e=pp.exec(t);if(e){var r=parseInt(e[1],10),n=!!e[4];n&&(r=xi(r));var s=parseInt(e[2],10)-1,o=e[3],a=new Date(r,s,o);return yr(r)&&a.setFullYear(r),a}}i(fp,"getDate");function hp(t){if(t.endsWith("+00"))return 0;var e=mp.exec(t.split(" ")[1]);if(e){var r=e[1];if(r==="Z")return 0;var n=r==="-"?-1:1,s=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return s*n*1e3}}i(hp,"timeZoneOffset");function xi(t){return-(t-1)}i(xi,"bcYearToNegativeYear");function yr(t){return t>=0&&t<100}i(yr,"is0To99")});var Fi=C((t_,ki)=>{ki.exports=gp;var yp=Object.prototype.hasOwnProperty;function gp(t){for(var e=1;e{"use strict";var Ep=Fi();Ui.exports=Ve;function Ve(t){if(!(this instanceof Ve))return new Ve(t);Ep(this,Rp(t))}i(Ve,"PostgresInterval");var _p=["seconds","minutes","hours","days","months","years"];Ve.prototype.toPostgres=function(){var t=_p.filter(this.hasOwnProperty,this);return this.milliseconds&&t.indexOf("seconds")<0&&t.push("seconds"),t.length===0?"0":t.map(function(e){var r=this[e]||0;return e==="seconds"&&this.milliseconds&&(r=(r+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),r+" "+e},this).join(" ")};var Sp={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},Tp=["years","months","days"],Cp=["hours","minutes","seconds"];Ve.prototype.toISOString=Ve.prototype.toISO=function(){var t=Tp.map(r,this).join(""),e=Cp.map(r,this).join("");return"P"+t+"T"+e;function r(n){var s=this[n]||0;return n==="seconds"&&this.milliseconds&&(s=(s+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),s+Sp[n]}};var gr="([+-]?\\d+)",Ap=gr+"\\s+years?",Np=gr+"\\s+mons?",bp=gr+"\\s+days?",vp="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",wp=new RegExp([Ap,Np,bp,vp].map(function(t){return"("+t+")?"}).join("\\s*")),Bi={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},Op=["hours","minutes","seconds","milliseconds"];function Ip(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}i(Ip,"parseMilliseconds");function Rp(t){if(!t)return{};var e=wp.exec(t),r=e[8]==="-";return Object.keys(Bi).reduce(function(n,s){var o=Bi[s],a=e[o];return!a||(a=s==="milliseconds"?Ip(a):parseInt(a,10),!a)||(r&&~Op.indexOf(s)&&(a*=-1),n[s]=a),n},{})}i(Rp,"parse")});var Gi=C((i_,Ki)=>{"use strict";Ki.exports=i(function(e){if(/^\\x/.test(e))return new Buffer(e.substr(2),"hex");for(var r="",n=0;n{var lt=fr(),pt=hr(),It=qi(),Hi=$i(),Qi=Gi();function Rt(t){return i(function(r){return r===null?r:t(r)},"nullAllowed")}i(Rt,"allowNull");function Wi(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}i(Wi,"parseBool");function Pp(t){return t?lt.parse(t,Wi):null}i(Pp,"parseBoolArray");function Dp(t){return parseInt(t,10)}i(Dp,"parseBaseTenInt");function Er(t){return t?lt.parse(t,Rt(Dp)):null}i(Er,"parseIntegerArray");function Lp(t){return t?lt.parse(t,Rt(function(e){return Yi(e).trim()})):null}i(Lp,"parseBigIntegerArray");var xp=i(function(t){if(!t)return null;var e=pt.create(t,function(r){return r!==null&&(r=Cr(r)),r});return e.parse()},"parsePointArray"),_r=i(function(t){if(!t)return null;var e=pt.create(t,function(r){return r!==null&&(r=parseFloat(r)),r});return e.parse()},"parseFloatArray"),ge=i(function(t){if(!t)return null;var e=pt.create(t);return e.parse()},"parseStringArray"),Sr=i(function(t){if(!t)return null;var e=pt.create(t,function(r){return r!==null&&(r=It(r)),r});return e.parse()},"parseDateArray"),Mp=i(function(t){if(!t)return null;var e=pt.create(t,function(r){return r!==null&&(r=Hi(r)),r});return e.parse()},"parseIntervalArray"),qp=i(function(t){return t?lt.parse(t,Rt(Qi)):null},"parseByteAArray"),Tr=i(function(t){return parseInt(t,10)},"parseInteger"),Yi=i(function(t){var e=String(t);return/^\d+$/.test(e)?e:t},"parseBigInteger"),Vi=i(function(t){return t?lt.parse(t,Rt(JSON.parse)):null},"parseJsonArray"),Cr=i(function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},"parsePoint"),kp=i(function(t){if(t[0]!=="<"&&t[1]!=="(")return null;for(var e="(",r="",n=!1,s=2;s{"use strict";var me=1e6;function Bp(t){var e=t.readInt32BE(0),r=t.readUInt32BE(4),n="";e<0&&(e=~e+(r===0),r=~r+1>>>0,n="-");var s="",o,a,c,l,u,p;{if(o=e%me,e=e/me>>>0,a=4294967296*o+r,r=a/me>>>0,c=""+(a-me*r),r===0&&e===0)return n+c+s;for(l="",u=6-c.length,p=0;p>>0,a=4294967296*o+r,r=a/me>>>0,c=""+(a-me*r),r===0&&e===0)return n+c+s;for(l="",u=6-c.length,p=0;p>>0,a=4294967296*o+r,r=a/me>>>0,c=""+(a-me*r),r===0&&e===0)return n+c+s;for(l="",u=6-c.length,p=0;p{var Up=Zi(),V=i(function(t,e,r,n,s){r=r||0,n=n||!1,s=s||function(f,S,y){return f*Math.pow(2,y)+S};var o=r>>3,a=i(function(f){return n?~f&255:f},"inv"),c=255,l=8-r%8;e>r%8);var u=0;r%8+e>=8&&(u=s(0,a(t[o])&c,l));for(var p=e+r>>3,d=o+1;d0&&(u=s(u,a(t[p])>>8-h,h)),u},"parseBits"),to=i(function(t,e,r){var n=Math.pow(2,r-1)-1,s=V(t,1),o=V(t,r,1);if(o===0)return 0;var a=1,c=i(function(u,p,d){u===0&&(u=1);for(var h=1;h<=d;h++)a/=2,(p&1<0&&(u+=a);return u},"parsePrecisionBits"),l=V(t,e,r+1,!1,c);return o==Math.pow(2,r+1)-1?l===0?s===0?1/0:-1/0:NaN:(s===0?1:-1)*Math.pow(2,o-n)*l},"parseFloatFromBits"),$p=i(function(t){return V(t,1)==1?-1*(V(t,15,1,!0)+1):V(t,15,1)},"parseInt16"),Ji=i(function(t){return V(t,1)==1?-1*(V(t,31,1,!0)+1):V(t,31,1)},"parseInt32"),Kp=i(function(t){return to(t,23,8)},"parseFloat32"),Gp=i(function(t){return to(t,52,11)},"parseFloat64"),Vp=i(function(t){var e=V(t,16,32);if(e==49152)return NaN;for(var r=Math.pow(1e4,V(t,16,16)),n=0,s=[],o=V(t,16),a=0;a>3,(s+=p<<3)>>3),d;console.log("ERROR: ElementType not implemented: "+u)},"parseElement"),l=i(function(u,p){var d=[],h;if(u.length>1){var f=u.shift();for(h=0;h0},"parseBool"),Wp=i(function(t){t(20,Up),t(21,$p),t(23,Ji),t(26,Ji),t(1700,Vp),t(700,Kp),t(701,Gp),t(16,Qp),t(1114,eo.bind(null,!1)),t(1184,eo.bind(null,!0)),t(1e3,mt),t(1007,mt),t(1016,mt),t(1008,mt),t(1009,mt),t(25,Hp)},"init");ro.exports={init:Wp}});var io=C((d_,so)=>{so.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var ht=C(ft=>{var Yp=zi(),jp=no(),zp=hr(),Xp=io();ft.getTypeParser=Zp;ft.setTypeParser=Jp;ft.arrayParser=zp;ft.builtins=Xp;var dt={text:{},binary:{}};function oo(t){return String(t)}i(oo,"noParse");function Zp(t,e){return e=e||"text",dt[e]&&dt[e][t]||oo}i(Zp,"getTypeParser");function Jp(t,e,r){typeof e=="function"&&(r=e,e="text"),dt[e][t]=r}i(Jp,"setTypeParser");Yp.init(function(t,e){dt.text[t]=e});jp.init(function(t,e){dt.binary[t]=e})});var yt=C((y_,Ar)=>{"use strict";Ar.exports={host:"localhost",user:process.platform==="win32"?process.env.USERNAME:process.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var He=ht(),em=He.getTypeParser(20,"text"),tm=He.getTypeParser(1016,"text");Ar.exports.__defineSetter__("parseInt8",function(t){He.setTypeParser(20,"text",t?He.getTypeParser(23,"text"):em),He.setTypeParser(1016,"text",t?He.getTypeParser(1007,"text"):tm)})});var gt=C((g_,co)=>{"use strict";var rm=yt();function nm(t){var e=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return'"'+e+'"'}i(nm,"escapeElement");function ao(t){for(var e="{",r=0;r0&&(e=e+","),t[r]===null||typeof t[r]>"u")e=e+"NULL";else if(Array.isArray(t[r]))e=e+ao(t[r]);else if(ArrayBuffer.isView(t[r])){var n=t[r];if(!(n instanceof Buffer)){var s=Buffer.from(n.buffer,n.byteOffset,n.byteLength);s.length===n.byteLength?n=s:n=s.slice(n.byteOffset,n.byteOffset+n.byteLength)}e+="\\\\x"+n.toString("hex")}else e+=nm(Pt(t[r]));return e=e+"}",e}i(ao,"arrayString");var Pt=i(function(t,e){if(t==null)return null;if(t instanceof Buffer)return t;if(ArrayBuffer.isView(t)){var r=Buffer.from(t.buffer,t.byteOffset,t.byteLength);return r.length===t.byteLength?r:r.slice(t.byteOffset,t.byteOffset+t.byteLength)}return t instanceof Date?rm.parseInputDatesAsUTC?om(t):im(t):Array.isArray(t)?ao(t):typeof t=="object"?sm(t,e):t.toString()},"prepareValue");function sm(t,e){if(t&&typeof t.toPostgres=="function"){if(e=e||[],e.indexOf(t)!==-1)throw new Error('circular reference detected while preparing "'+t+'" for query');return e.push(t),Pt(t.toPostgres(Pt),e)}return JSON.stringify(t)}i(sm,"prepareObject");function oe(t,e){for(t=""+t;t.length{"use strict";var Et=require("crypto");function Nr(t){return Et.createHash("md5").update(t,"utf-8").digest("hex")}i(Nr,"md5");function lm(t,e,r){var n=Nr(e+t),s=Nr(Buffer.concat([Buffer.from(n),r]));return"md5"+s}i(lm,"postgresMd5PasswordHash");function pm(t){return Et.createHash("sha256").update(t).digest()}i(pm,"sha256");function mm(t,e){return Et.createHmac("sha256",t).update(e).digest()}i(mm,"hmacSha256");async function dm(t,e,r){return Et.pbkdf2Sync(t,e,r,32,"sha256")}i(dm,"deriveKey");uo.exports={postgresMd5PasswordHash:lm,randomBytes:Et.randomBytes,deriveKey:dm,sha256:pm,hmacSha256:mm,md5:Nr}});var ho=C((T_,fo)=>{var po=require("crypto");fo.exports={postgresMd5PasswordHash:hm,randomBytes:fm,deriveKey:Em,sha256:ym,hmacSha256:gm,md5:br};var mo=po.webcrypto||globalThis.crypto,Qe=mo.subtle,vr=new TextEncoder;function fm(t){return mo.getRandomValues(Buffer.alloc(t))}i(fm,"randomBytes");async function br(t){try{return po.createHash("md5").update(t,"utf-8").digest("hex")}catch{let r=typeof t=="string"?vr.encode(t):t,n=await Qe.digest("MD5",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}}i(br,"md5");async function hm(t,e,r){var n=await br(e+t),s=await br(Buffer.concat([Buffer.from(n),r]));return"md5"+s}i(hm,"postgresMd5PasswordHash");async function ym(t){return await Qe.digest("SHA-256",t)}i(ym,"sha256");async function gm(t,e){let r=await Qe.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await Qe.sign("HMAC",r,vr.encode(e))}i(gm,"hmacSha256");async function Em(t,e,r){let n=await Qe.importKey("raw",vr.encode(t),"PBKDF2",!1,["deriveBits"]),s={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:r};return await Qe.deriveBits(s,n,32*8,["deriveBits"])}i(Em,"deriveKey")});var Or=C((A_,wr)=>{"use strict";var _m=parseInt(process.versions&&process.versions.node&&process.versions.node.split(".")[0])<15;_m?wr.exports=lo():wr.exports=ho()});var _o=C((N_,Eo)=>{"use strict";var qe=Or();function Sm(t){if(t.indexOf("SCRAM-SHA-256")===-1)throw new Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let e=qe.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:e,response:"n,,n=*,r="+e,message:"SASLInitialResponse"}}i(Sm,"startSession");async function Tm(t,e,r){if(t.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof r!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let n=Nm(r);if(n.nonce.startsWith(t.clientNonce)){if(n.nonce.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var s="n=*,r="+t.clientNonce,o="r="+n.nonce+",s="+n.salt+",i="+n.iteration,a="c=biws,r="+n.nonce,c=s+","+o+","+a,l=Buffer.from(n.salt,"base64"),u=await qe.deriveKey(e,l,n.iteration),p=await qe.hmacSha256(u,"Client Key"),d=await qe.sha256(p),h=await qe.hmacSha256(d,c),f=vm(Buffer.from(p),Buffer.from(h)).toString("base64"),S=await qe.hmacSha256(u,"Server Key"),y=await qe.hmacSha256(S,c);t.message="SASLResponse",t.serverSignature=Buffer.from(y).toString("base64"),t.response=a+",p="+f}i(Tm,"continueSession");function Cm(t,e){if(t.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:r}=bm(e);if(r!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}i(Cm,"finalizeSession");function Am(t){if(typeof t!="string")throw new TypeError("SASL: text must be a string");return t.split("").map((e,r)=>t.charCodeAt(r)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}i(Am,"isPrintableChars");function yo(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}i(yo,"isBase64");function go(t){if(typeof t!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(t.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let r=e[0],n=e.substring(2);return[r,n]}))}i(go,"parseAttributePairs");function Nm(t){let e=go(t),r=e.get("r");if(r){if(!Am(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let n=e.get("s");if(n){if(!yo(n))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let s=e.get("i");if(s){if(!/^[1-9][0-9]*$/.test(s))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let o=parseInt(s,10);return{nonce:r,salt:n,iteration:o}}i(Nm,"parseServerFirstMessage");function bm(t){let r=go(t).get("v");if(r){if(!yo(r))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:r}}i(bm,"parseServerFinalMessage");function vm(t,e){if(!Buffer.isBuffer(t))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(t.length!==e.length)throw new Error("Buffer lengths must match");if(t.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(t.map((r,n)=>t[n]^e[n]))}i(vm,"xorBuffers");Eo.exports={startSession:Sm,continueSession:Tm,finalizeSession:Cm}});var Ir=C((v_,So)=>{"use strict";var wm=ht();function Dt(t){this._types=t||wm,this.text={},this.binary={}}i(Dt,"TypeOverrides");Dt.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};Dt.prototype.setTypeParser=function(t,e,r){typeof e=="function"&&(r=e,e="text"),this.getOverrides(e)[t]=r};Dt.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};So.exports=Dt});var Co=C((O_,To)=>{"use strict";function Rr(t){if(t.charAt(0)==="/"){let c=t.split(" ");return{host:c[0],database:c[1]}}let e={},r,n=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(t)&&(t=encodeURI(t).replace(/\%25(\d\d)/g,"%$1"));try{r=new URL(t,"postgres://base")}catch{r=new URL(t.replace("@/","@___DUMMY___/"),"postgres://base"),n=!0}for(let c of r.searchParams.entries())e[c[0]]=c[1];if(e.user=e.user||decodeURIComponent(r.username),e.password=e.password||decodeURIComponent(r.password),r.protocol=="socket:")return e.host=decodeURI(r.pathname),e.database=r.searchParams.get("db"),e.client_encoding=r.searchParams.get("encoding"),e;let s=n?"":r.hostname;e.host?s&&/^%2f/i.test(s)&&(r.pathname=s+r.pathname):e.host=decodeURIComponent(s),e.port||(e.port=r.port);let o=r.pathname.slice(1)||null;e.database=o?decodeURI(o):null,(e.ssl==="true"||e.ssl==="1")&&(e.ssl=!0),e.ssl==="0"&&(e.ssl=!1),(e.sslcert||e.sslkey||e.sslrootcert||e.sslmode)&&(e.ssl={});let a=e.sslcert||e.sslkey||e.sslrootcert?require("fs"):null;switch(e.sslcert&&(e.ssl.cert=a.readFileSync(e.sslcert).toString()),e.sslkey&&(e.ssl.key=a.readFileSync(e.sslkey).toString()),e.sslrootcert&&(e.ssl.ca=a.readFileSync(e.sslrootcert).toString()),e.sslmode){case"disable":{e.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{e.ssl.rejectUnauthorized=!1;break}}return e}i(Rr,"parse");To.exports=Rr;Rr.parse=Rr});var Lr=C((R_,bo)=>{"use strict";var Om=require("dns"),No=yt(),Ao=Co().parse,le=i(function(t,e,r){return r===void 0?r=process.env["PG"+t.toUpperCase()]:r===!1||(r=process.env[r]),e[t]||r||No[t]},"val"),Im=i(function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return No.ssl},"readSSLConfigFromEnvironment"),We=i(function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quoteParamValue"),Ee=i(function(t,e,r){var n=e[r];n!=null&&t.push(r+"="+We(n))},"add"),Dr=class Dr{constructor(e){e=typeof e=="string"?Ao(e):e||{},e.connectionString&&(e=Object.assign({},e,Ao(e.connectionString))),this.user=le("user",e),this.database=le("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(le("port",e),10),this.host=le("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:le("password",e)}),this.binary=le("binary",e),this.options=le("options",e),this.ssl=typeof e.ssl>"u"?Im():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=le("client_encoding",e),this.replication=le("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=le("application_name",e,"PGAPPNAME"),this.fallback_application_name=le("fallback_application_name",e,!1),this.statement_timeout=le("statement_timeout",e,!1),this.lock_timeout=le("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=le("idle_in_transaction_session_timeout",e,!1),this.query_timeout=le("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){var r=[];Ee(r,this,"user"),Ee(r,this,"password"),Ee(r,this,"port"),Ee(r,this,"application_name"),Ee(r,this,"fallback_application_name"),Ee(r,this,"connect_timeout"),Ee(r,this,"options");var n=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(Ee(r,n,"sslmode"),Ee(r,n,"sslca"),Ee(r,n,"sslkey"),Ee(r,n,"sslcert"),Ee(r,n,"sslrootcert"),this.database&&r.push("dbname="+We(this.database)),this.replication&&r.push("replication="+We(this.replication)),this.host&&r.push("host="+We(this.host)),this.isDomainSocket)return e(null,r.join(" "));this.client_encoding&&r.push("client_encoding="+We(this.client_encoding)),Om.lookup(this.host,function(s,o){return s?e(s,null):(r.push("hostaddr="+We(o)),e(null,r.join(" ")))})}};i(Dr,"ConnectionParameters");var Pr=Dr;bo.exports=Pr});var Oo=C((D_,wo)=>{"use strict";var Rm=ht(),vo=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,Mr=class Mr{constructor(e,r){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=r,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){var r;e.text?r=vo.exec(e.text):r=vo.exec(e.command),r&&(this.command=r[1],r[3]?(this.oid=parseInt(r[2],10),this.rowCount=parseInt(r[3],10)):r[2]&&(this.rowCount=parseInt(r[2],10)))}_parseRowAsArray(e){for(var r=new Array(e.length),n=0,s=e.length;n{"use strict";var{EventEmitter:Pm}=require("events"),Io=Oo(),Ro=gt(),kr=class kr extends Pm{constructor(e,r,n){super(),e=Ro.normalizeQueryConfig(e,r,n),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new Io(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new Io(this._rowMode,this.types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let r;if(!this._canceledDueToError){try{r=this._result.parseRow(e.fields)}catch(n){this._canceledDueToError=n;return}this.emit("row",r,this._result),this._accumulateRows&&this._result.addRow(r)}}handleCommandComplete(e,r){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&r.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,r){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(r){process.nextTick(()=>{throw r})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let r=e.parsedStatements[this.name];return this.text&&r&&this.text!==r?new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`):this.values&&!Array.isArray(this.values)?new Error("Query values must be an array"):(this.requiresPreparation()?this.prepare(e):e.query(this.text),null)}hasBeenParsed(e){return this.name&&e.parsedStatements[this.name]}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,r){e.execute({portal:this.portal,rows:r}),r?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||e.parse({text:this.text,name:this.name,types:this.types});try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:Ro.prepareValue})}catch(r){this.handleError(r,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,r){}};i(kr,"Query");var qr=kr;Po.exports=qr});var dn=C(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.NoticeMessage=L.DataRowMessage=L.CommandCompleteMessage=L.ReadyForQueryMessage=L.NotificationResponseMessage=L.BackendKeyDataMessage=L.AuthenticationMD5Password=L.ParameterStatusMessage=L.ParameterDescriptionMessage=L.RowDescriptionMessage=L.Field=L.CopyResponse=L.CopyDataMessage=L.DatabaseError=L.copyDone=L.emptyQuery=L.replicationStart=L.portalSuspended=L.noData=L.closeComplete=L.bindComplete=L.parseComplete=void 0;L.parseComplete={name:"parseComplete",length:5};L.bindComplete={name:"bindComplete",length:5};L.closeComplete={name:"closeComplete",length:5};L.noData={name:"noData",length:5};L.portalSuspended={name:"portalSuspended",length:5};L.replicationStart={name:"replicationStart",length:4};L.emptyQuery={name:"emptyQuery",length:4};L.copyDone={name:"copyDone",length:4};var Zr=class Zr extends Error{constructor(e,r,n){super(e),this.length=r,this.name=n}};i(Zr,"DatabaseError");var Fr=Zr;L.DatabaseError=Fr;var Jr=class Jr{constructor(e,r){this.length=e,this.chunk=r,this.name="copyData"}};i(Jr,"CopyDataMessage");var Br=Jr;L.CopyDataMessage=Br;var en=class en{constructor(e,r,n,s){this.length=e,this.name=r,this.binary=n,this.columnTypes=new Array(s)}};i(en,"CopyResponse");var Ur=en;L.CopyResponse=Ur;var tn=class tn{constructor(e,r,n,s,o,a,c){this.name=e,this.tableID=r,this.columnID=n,this.dataTypeID=s,this.dataTypeSize=o,this.dataTypeModifier=a,this.format=c}};i(tn,"Field");var $r=tn;L.Field=$r;var rn=class rn{constructor(e,r){this.length=e,this.fieldCount=r,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};i(rn,"RowDescriptionMessage");var Kr=rn;L.RowDescriptionMessage=Kr;var nn=class nn{constructor(e,r){this.length=e,this.parameterCount=r,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};i(nn,"ParameterDescriptionMessage");var Gr=nn;L.ParameterDescriptionMessage=Gr;var sn=class sn{constructor(e,r,n){this.length=e,this.parameterName=r,this.parameterValue=n,this.name="parameterStatus"}};i(sn,"ParameterStatusMessage");var Vr=sn;L.ParameterStatusMessage=Vr;var on=class on{constructor(e,r){this.length=e,this.salt=r,this.name="authenticationMD5Password"}};i(on,"AuthenticationMD5Password");var Hr=on;L.AuthenticationMD5Password=Hr;var an=class an{constructor(e,r,n){this.length=e,this.processID=r,this.secretKey=n,this.name="backendKeyData"}};i(an,"BackendKeyDataMessage");var Qr=an;L.BackendKeyDataMessage=Qr;var cn=class cn{constructor(e,r,n,s){this.length=e,this.processId=r,this.channel=n,this.payload=s,this.name="notification"}};i(cn,"NotificationResponseMessage");var Wr=cn;L.NotificationResponseMessage=Wr;var un=class un{constructor(e,r){this.length=e,this.status=r,this.name="readyForQuery"}};i(un,"ReadyForQueryMessage");var Yr=un;L.ReadyForQueryMessage=Yr;var ln=class ln{constructor(e,r){this.length=e,this.text=r,this.name="commandComplete"}};i(ln,"CommandCompleteMessage");var jr=ln;L.CommandCompleteMessage=jr;var pn=class pn{constructor(e,r){this.length=e,this.fields=r,this.name="dataRow",this.fieldCount=r.length}};i(pn,"DataRowMessage");var zr=pn;L.DataRowMessage=zr;var mn=class mn{constructor(e,r){this.length=e,this.message=r,this.name="notice"}};i(mn,"NoticeMessage");var Xr=mn;L.NoticeMessage=Xr});var Lo=C(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.Writer=void 0;var hn=class hn{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){var r=this.buffer.length-this.offset;if(r>1)+e;this.buffer=Buffer.allocUnsafe(s),n.copy(this.buffer)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{var r=Buffer.byteLength(e);this.ensure(r+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=r}return this.buffer[this.offset++]=0,this}addString(e=""){var r=Buffer.byteLength(e);return this.ensure(r),this.buffer.write(e,this.offset),this.offset+=r,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let r=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(r,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){var r=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),r}};i(hn,"Writer");var fn=hn;Lt.Writer=fn});var Mo=C(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.serialize=void 0;var yn=Lo(),H=new yn.Writer,Dm=i(t=>{H.addInt16(3).addInt16(0);for(let n of Object.keys(t))H.addCString(n).addCString(t[n]);H.addCString("client_encoding").addCString("UTF8");var e=H.addCString("").flush(),r=e.length+4;return new yn.Writer().addInt32(r).add(e).flush()},"startup"),Lm=i(()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},"requestSsl"),xm=i(t=>H.addCString(t).flush(112),"password"),Mm=i(function(t,e){return H.addCString(t).addInt32(Buffer.byteLength(e)).addString(e),H.flush(112)},"sendSASLInitialResponseMessage"),qm=i(function(t){return H.addString(t).flush(112)},"sendSCRAMClientFinalMessage"),km=i(t=>H.addCString(t).flush(81),"query"),xo=[],Fm=i(t=>{let e=t.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let r=t.types||xo;for(var n=r.length,s=H.addCString(e).addCString(t.text).addInt16(n),o=0;o{let e=t.portal||"",r=t.statement||"",n=t.binary||!1,s=t.values||xo,o=s.length;return H.addCString(e).addCString(r),H.addInt16(o),Bm(s,t.valueMapper),H.addInt16(o),H.add(Ye.flush()),H.addInt16(n?1:0),H.flush(66)},"bind"),$m=Buffer.from([69,0,0,0,9,0,0,0,0,0]),Km=i(t=>{if(!t||!t.portal&&!t.rows)return $m;let e=t.portal||"",r=t.rows||0,n=Buffer.byteLength(e),s=4+n+1+4,o=Buffer.allocUnsafe(1+s);return o[0]=69,o.writeInt32BE(s,1),o.write(e,5,"utf-8"),o[n+5]=0,o.writeUInt32BE(r,o.length-4),o},"execute"),Gm=i((t,e)=>{let r=Buffer.allocUnsafe(16);return r.writeInt32BE(16,0),r.writeInt16BE(1234,4),r.writeInt16BE(5678,6),r.writeInt32BE(t,8),r.writeInt32BE(e,12),r},"cancel"),gn=i((t,e)=>{let n=4+Buffer.byteLength(e)+1,s=Buffer.allocUnsafe(1+n);return s[0]=t,s.writeInt32BE(n,1),s.write(e,5,"utf-8"),s[n]=0,s},"cstringMessage"),Vm=H.addCString("P").flush(68),Hm=H.addCString("S").flush(68),Qm=i(t=>t.name?gn(68,`${t.type}${t.name||""}`):t.type==="P"?Vm:Hm,"describe"),Wm=i(t=>{let e=`${t.type}${t.name||""}`;return gn(67,e)},"close"),Ym=i(t=>H.add(t).flush(100),"copyData"),jm=i(t=>gn(102,t),"copyFail"),xt=i(t=>Buffer.from([t,0,0,0,4]),"codeOnlyBuffer"),zm=xt(72),Xm=xt(83),Zm=xt(88),Jm=xt(99),ed={startup:Dm,password:xm,requestSsl:Lm,sendSASLInitialResponseMessage:Mm,sendSCRAMClientFinalMessage:qm,query:km,parse:Fm,bind:Um,execute:Km,describe:Qm,close:Wm,flush:()=>zm,sync:()=>Xm,end:()=>Zm,copyData:Ym,copyDone:()=>Jm,copyFail:jm,cancel:Gm};Mt.serialize=ed});var qo=C(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.BufferReader=void 0;var td=Buffer.allocUnsafe(0),_n=class _n{constructor(e=0){this.offset=e,this.buffer=td,this.encoding="utf-8"}setBuffer(e,r){this.offset=e,this.buffer=r}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}string(e){let r=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,r}cstring(){let e=this.offset,r=e;for(;this.buffer[r++]!==0;);return this.offset=r,this.buffer.toString(this.encoding,e,r-1)}bytes(e){let r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}};i(_n,"BufferReader");var En=_n;qt.BufferReader=En});var Bo=C(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.Parser=void 0;var Q=dn(),rd=qo(),Sn=1,nd=4,ko=Sn+nd,Fo=Buffer.allocUnsafe(0),Cn=class Cn{constructor(e){if(this.buffer=Fo,this.bufferLength=0,this.bufferOffset=0,this.reader=new rd.BufferReader,(e==null?void 0:e.mode)==="binary")throw new Error("Binary mode not supported yet");this.mode=(e==null?void 0:e.mode)||"text"}parse(e,r){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,s=this.bufferOffset;for(;s+ko<=n;){let o=this.buffer[s],a=this.buffer.readUInt32BE(s+Sn),c=Sn+a;if(c+s<=n){let l=this.handlePacket(s+ko,o,a,this.buffer);r(l),s+=c}else break}s===n?(this.buffer=Fo,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=n-s,this.bufferOffset=s)}mergeBuffer(e){if(this.bufferLength>0){let r=this.bufferLength+e.byteLength;if(r+this.bufferOffset>this.buffer.byteLength){let s;if(r<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)s=this.buffer;else{let o=this.buffer.byteLength*2;for(;r>=o;)o*=2;s=Buffer.allocUnsafe(o)}this.buffer.copy(s,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=s,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=r}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,r,n,s){switch(r){case 50:return Q.bindComplete;case 49:return Q.parseComplete;case 51:return Q.closeComplete;case 110:return Q.noData;case 115:return Q.portalSuspended;case 99:return Q.copyDone;case 87:return Q.replicationStart;case 73:return Q.emptyQuery;case 68:return this.parseDataRowMessage(e,n,s);case 67:return this.parseCommandCompleteMessage(e,n,s);case 90:return this.parseReadyForQueryMessage(e,n,s);case 65:return this.parseNotificationMessage(e,n,s);case 82:return this.parseAuthenticationResponse(e,n,s);case 83:return this.parseParameterStatusMessage(e,n,s);case 75:return this.parseBackendKeyData(e,n,s);case 69:return this.parseErrorMessage(e,n,s,"error");case 78:return this.parseErrorMessage(e,n,s,"notice");case 84:return this.parseRowDescriptionMessage(e,n,s);case 116:return this.parseParameterDescriptionMessage(e,n,s);case 71:return this.parseCopyInMessage(e,n,s);case 72:return this.parseCopyOutMessage(e,n,s);case 100:return this.parseCopyData(e,n,s);default:return new Q.DatabaseError("received invalid response: "+r.toString(16),n,"error")}}parseReadyForQueryMessage(e,r,n){this.reader.setBuffer(e,n);let s=this.reader.string(1);return new Q.ReadyForQueryMessage(r,s)}parseCommandCompleteMessage(e,r,n){this.reader.setBuffer(e,n);let s=this.reader.cstring();return new Q.CommandCompleteMessage(r,s)}parseCopyData(e,r,n){let s=n.slice(e,e+(r-4));return new Q.CopyDataMessage(r,s)}parseCopyInMessage(e,r,n){return this.parseCopyMessage(e,r,n,"copyInResponse")}parseCopyOutMessage(e,r,n){return this.parseCopyMessage(e,r,n,"copyOutResponse")}parseCopyMessage(e,r,n,s){this.reader.setBuffer(e,n);let o=this.reader.byte()!==0,a=this.reader.int16(),c=new Q.CopyResponse(r,s,o,a);for(let l=0;l{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.DatabaseError=Pe.serialize=Pe.parse=void 0;var sd=dn();Object.defineProperty(Pe,"DatabaseError",{enumerable:!0,get:function(){return sd.DatabaseError}});var id=Mo();Object.defineProperty(Pe,"serialize",{enumerable:!0,get:function(){return id.serialize}});var od=Bo();function ad(t,e){let r=new od.Parser;return t.on("data",n=>r.parse(n,e)),new Promise(n=>t.on("end",()=>n()))}i(ad,"parse");Pe.parse=ad});var Uo={};Ju(Uo,{default:()=>cd});var cd,$o=Zu(()=>{cd={}});var Ko=C((Y_,Nn)=>{Nn.exports.getStream=i(function(e){let r=require("net");if(typeof r.Socket=="function")return new r.Socket;{let{CloudflareSocket:n}=($o(),tl(Uo));return new n(e)}},"getStream");Nn.exports.getSecureStream=i(function(e){var r=require("tls");return r.connect?r.connect(e):(e.socket.startTls(e),e.socket)},"getSecureStream")});var wn=C((X_,Go)=>{"use strict";var z_=require("net"),ud=require("events").EventEmitter,{parse:ld,serialize:re}=An(),{getStream:pd,getSecureStream:md}=Ko(),dd=re.flush(),fd=re.sync(),hd=re.end(),vn=class vn extends ud{constructor(e){super(),e=e||{},this.stream=e.stream||pd(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=e.ssl||!1,this._ending=!1,this._emitMessage=!1;var r=this;this.on("newListener",function(n){n==="message"&&(r._emitMessage=!0)})}connect(e,r){var n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,r),this.stream.once("connect",function(){n._keepAlive&&n.stream.setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit("connect")});let s=i(function(o){n._ending&&(o.code==="ECONNRESET"||o.code==="EPIPE")||n.emit("error",o)},"reportStreamError");if(this.stream.on("error",s),this.stream.on("close",function(){n.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(o){var a=o.toString("utf8");switch(a){case"S":break;case"N":return n.stream.end(),n.emit("error",new Error("The server does not support SSL connections"));default:return n.stream.end(),n.emit("error",new Error("There was an error establishing an SSL connection"))}let c={socket:n.stream};n.ssl!==!0&&(Object.assign(c,n.ssl),"key"in n.ssl&&(c.key=n.ssl.key));var l=require("net");l.isIP&&l.isIP(r)===0&&(c.servername=r);try{n.stream=md(c)}catch(u){return n.emit("error",u)}n.attachListeners(n.stream),n.stream.on("error",s),n.emit("sslconnect")})}attachListeners(e){ld(e,r=>{var n=r.name==="error"?"errorMessage":r.name;this._emitMessage&&this.emit("message",r),this.emit(n,r)})}requestSsl(){this.stream.write(re.requestSsl())}startup(e){this.stream.write(re.startup(e))}cancel(e,r){this._send(re.cancel(e,r))}password(e){this._send(re.password(e))}sendSASLInitialResponseMessage(e,r){this._send(re.sendSASLInitialResponseMessage(e,r))}sendSCRAMClientFinalMessage(e){this._send(re.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(re.query(e))}parse(e){this._send(re.parse(e))}bind(e){this._send(re.bind(e))}execute(e){this._send(re.execute(e))}flush(){this.stream.writable&&this.stream.write(dd)}sync(){this._ending=!0,this._send(fd)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(hd,()=>{this.stream.end()})}close(e){this._send(re.close(e))}describe(e){this._send(re.describe(e))}sendCopyFromChunk(e){this._send(re.copyData(e))}endCopyFrom(){this._send(re.copyDone())}sendCopyFail(e){this._send(re.copyFail(e))}};i(vn,"Connection");var bn=vn;Go.exports=bn});var Wo=C((J_,Qo)=>{"use strict";var{Transform:yd}=require("stream"),{StringDecoder:gd}=require("string_decoder"),De=Symbol("last"),Ft=Symbol("decoder");function Ed(t,e,r){let n;if(this.overflow){if(n=this[Ft].write(t).split(this.matcher),n.length===1)return r();n.shift(),this.overflow=!1}else this[De]+=this[Ft].write(t),n=this[De].split(this.matcher);this[De]=n.pop();for(let s=0;sthis.maxLength,this.overflow&&!this.skipOverflow){r(new Error("maximum buffer reached"));return}r()}i(Ed,"transform");function _d(t){if(this[De]+=this[Ft].end(),this[De])try{Ho(this,this.mapper(this[De]))}catch(e){return t(e)}t()}i(_d,"flush");function Ho(t,e){e!==void 0&&t.push(e)}i(Ho,"push");function Vo(t){return t}i(Vo,"noop");function Sd(t,e,r){switch(t=t||/\r?\n/,e=e||Vo,r=r||{},arguments.length){case 1:typeof t=="function"?(e=t,t=/\r?\n/):typeof t=="object"&&!(t instanceof RegExp)&&!t[Symbol.split]&&(r=t,t=/\r?\n/);break;case 2:typeof t=="function"?(r=e,e=t,t=/\r?\n/):typeof e=="object"&&(r=e,e=Vo)}r=Object.assign({},r),r.autoDestroy=!0,r.transform=Ed,r.flush=_d,r.readableObjectMode=!0;let n=new yd(r);return n[De]="",n[Ft]=new gd("utf8"),n.matcher=t,n.mapper=e,n.maxLength=r.maxLength,n.skipOverflow=r.skipOverflow||!1,n.overflow=!1,n._destroy=function(s,o){this._writableState.errorEmitted=!1,o(s)},n}i(Sd,"split");Qo.exports=Sd});var zo=C((tS,Oe)=>{"use strict";var Yo=require("path"),Td=require("stream").Stream,Cd=Wo(),jo=require("util"),Ad=5432,Bt=process.platform==="win32",_t=process.stderr,Nd=56,bd=7,vd=61440,wd=32768;function Od(t){return(t&vd)==wd}i(Od,"isRegFile");var je=["host","port","database","user","password"],On=je.length,Id=je[On-1];function In(){var t=_t instanceof Td&&_t.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(` +`);_t.write(jo.format.apply(jo,e))}}i(In,"warn");Object.defineProperty(Oe.exports,"isWin",{get:function(){return Bt},set:function(t){Bt=t}});Oe.exports.warnTo=function(t){var e=_t;return _t=t,e};Oe.exports.getFileName=function(t){var e=t||process.env,r=e.PGPASSFILE||(Bt?Yo.join(e.APPDATA||"./","postgresql","pgpass.conf"):Yo.join(e.HOME||"./",".pgpass"));return r};Oe.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Bt?!0:(e=e||"",Od(t.mode)?t.mode&(Nd|bd)?(In('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(In('WARNING: password file "%s" is not a plain file',e),!1))};var Rd=Oe.exports.match=function(t,e){return je.slice(0,-1).reduce(function(r,n,s){return s==1&&Number(t[n]||Ad)===Number(e[n])?r&&!0:r&&(e[n]==="*"||e[n]===t[n])},!0)};Oe.exports.getPassword=function(t,e,r){var n,s=e.pipe(Cd());function o(l){var u=Pd(l);u&&Dd(u)&&Rd(t,u)&&(n=u[Id],s.end())}i(o,"onLine");var a=i(function(){e.destroy(),r(n)},"onEnd"),c=i(function(l){e.destroy(),In("WARNING: error on reading file: %s",l),r(void 0)},"onErr");e.on("error",c),s.on("data",o).on("end",a).on("error",c)};var Pd=Oe.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",r="",n=0,s=0,o=0,a={},c=!1,l=i(function(p,d,h){var f=t.substring(d,h);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(f=f.replace(/\\([:\\])/g,"$1")),a[je[p]]=f},"addToObj"),u=0;u=0&&e==":"&&r!=="\\"&&(l(n,s,u+1),s=u+2,n+=1)}return a=Object.keys(a).length===On?a:null,a},Dd=Oe.exports.isValidEntry=function(t){for(var e={0:function(a){return a.length>0},1:function(a){return a==="*"?!0:(a=Number(a),isFinite(a)&&a>0&&a<9007199254740992&&Math.floor(a)===a)},2:function(a){return a.length>0},3:function(a){return a.length>0},4:function(a){return a.length>0}},r=0;r{"use strict";var nS=require("path"),Xo=require("fs"),Ut=zo();Rn.exports=function(t,e){var r=Ut.getFileName();Xo.stat(r,function(n,s){if(n||!Ut.usePgPass(s,r))return e(void 0);var o=Xo.createReadStream(r);Ut.getPassword(t,o,e)})};Rn.exports.warnTo=Ut.warnTo});var ra=C((iS,ta)=>{"use strict";var Ld=require("events").EventEmitter,Jo=gt(),Pn=_o(),xd=Ir(),Md=Lr(),ea=Do(),qd=yt(),kd=wn(),Fd=Or(),Dn=class Dn extends Ld{constructor(e){super(),this.connectionParameters=new Md(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var r=e||{};this._Promise=r.Promise||global.Promise,this._types=new xd(r.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=r.connection||new kd({stream:r.stream,ssl:this.connectionParameters.ssl,keepAlive:r.keepAlive||!1,keepAliveInitialDelayMillis:r.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=r.binary||qd.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=r.connectionTimeoutMillis||0}_errorAllQueries(e){let r=i(n=>{process.nextTick(()=>{n.handleError(e,this.connection)})},"enqueueError");this.activeQuery&&(r(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(r),this.queryQueue.length=0}_connect(e){var r=this,n=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let s=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(s)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{n._ending=!0,n.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){r.ssl?n.requestSsl():n.startup(r.getStartupConf())}),n.on("sslconnect",function(){n.startup(r.getStartupConf())}),this._attachListeners(n),n.once("end",()=>{let s=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(s),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(s):this._handleErrorEvent(s):this._connectionError||this._handleErrorEvent(s)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((r,n)=>{this._connect(s=>{s?n(s):r()})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_checkPgPass(e){let r=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password()).then(n=>{if(n!==void 0){if(typeof n!="string"){r.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(n=>{r.emit("error",n)});else if(this.password!==null)e();else try{Zo()(this.connectionParameters,s=>{s!==void 0&&(this.connectionParameters.password=this.password=s),e()})}catch(n){this.emit("error",n)}}_handleAuthCleartextPassword(e){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._checkPgPass(async()=>{try{let r=await Fd.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(r)}catch(r){this.emit("error",r)}})}_handleAuthSASL(e){this._checkPgPass(()=>{try{this.saslSession=Pn.startSession(e.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(r){this.connection.emit("error",r)}})}async _handleAuthSASLContinue(e){try{await Pn.continueSession(this.saslSession,this.password,e.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(r){this.connection.emit("error",r)}}_handleAuthSASLFinal(e){try{Pn.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(r){this.connection.emit("error",r)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:r}=this;this.activeQuery=null,this.readyForQuery=!0,r&&r.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let r=this.activeQuery;if(!r){this._handleErrorEvent(e);return}this.activeQuery=null,r.handleError(e,this.connection)}_handleRowDescription(e){this.activeQuery.handleRowDescription(e)}_handleDataRow(e){this.activeQuery.handleDataRow(e)}_handlePortalSuspended(e){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(e){this.activeQuery.handleCommandComplete(e,this.connection)}_handleParseComplete(e){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(e){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(e){this.activeQuery.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){var e=this.connectionParameters,r={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(r.application_name=n),e.replication&&(r.replication=""+e.replication),e.statement_timeout&&(r.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(r.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(r.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(r.options=e.options),r}cancel(e,r){if(e.activeQuery===r){var n=this.connection;this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){n.cancel(e.processID,e.secretKey)})}else e.queryQueue.indexOf(r)!==-1&&e.queryQueue.splice(e.queryQueue.indexOf(r),1)}setTypeParser(e,r,n){return this._types.setTypeParser(e,r,n)}getTypeParser(e,r){return this._types.getTypeParser(e,r)}escapeIdentifier(e){return Jo.escapeIdentifier(e)}escapeLiteral(e){return Jo.escapeLiteral(e)}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let e=this.activeQuery.submit(this.connection);e&&process.nextTick(()=>{this.activeQuery.handleError(e,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(e,r,n){var s,o,a,c,l;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(a=e.query_timeout||this.connectionParameters.query_timeout,o=s=e,typeof r=="function"&&(s.callback=s.callback||r)):(a=this.connectionParameters.query_timeout,s=new ea(e,r,n),s.callback||(o=new this._Promise((u,p)=>{s.callback=(d,h)=>d?p(d):u(h)}).catch(u=>{throw Error.captureStackTrace(u),u}))),a&&(l=s.callback,c=setTimeout(()=>{var u=new Error("Query read timeout");process.nextTick(()=>{s.handleError(u,this.connection)}),l(u),s.callback=()=>{};var p=this.queryQueue.indexOf(s);p>-1&&this.queryQueue.splice(p,1),this._pulseQueryQueue()},a),s.callback=(u,p)=>{clearTimeout(c),l(u,p)}),this.binary&&!s.binary&&(s.binary=!0),s._result&&!s._result._types&&(s._result._types=this._types),this._queryable?this._ending?(process.nextTick(()=>{s.handleError(new Error("Client was closed and is not queryable"),this.connection)}),o):(this.queryQueue.push(s),this._pulseQueryQueue(),o):(process.nextTick(()=>{s.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),o)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e)e();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),e)this.connection.once("end",e);else return new this._Promise(r=>{this.connection.once("end",r)})}};i(Dn,"Client");var $t=Dn;$t.Query=ea;ta.exports=$t});var oa=C((aS,ia)=>{"use strict";var Bd=require("events").EventEmitter,na=i(function(){},"NOOP"),sa=i((t,e)=>{let r=t.findIndex(e);return r===-1?void 0:t.splice(r,1)[0]},"removeWhere"),Mn=class Mn{constructor(e,r,n){this.client=e,this.idleListener=r,this.timeoutId=n}};i(Mn,"IdleItem");var Ln=Mn,qn=class qn{constructor(e){this.callback=e}};i(qn,"PendingItem");var ze=qn;function Ud(){throw new Error("Release called on client which has already been released to the pool.")}i(Ud,"throwOnDoubleRelease");function Kt(t,e){if(e)return{callback:e,result:void 0};let r,n,s=i(function(a,c){a?r(a):n(c)},"cb"),o=new t(function(a,c){n=a,r=c}).catch(a=>{throw Error.captureStackTrace(a),a});return{callback:s,result:o}}i(Kt,"promisify");function $d(t,e){return i(function r(n){n.client=e,e.removeListener("error",r),e.on("error",()=>{t.log("additional client error after disconnection due to error",n)}),t._remove(e),t.emit("error",n,e)},"idleListener")}i($d,"makeIdleListener");var kn=class kn extends Bd{constructor(e,r){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||r||Fn().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(r=>{this._remove(r.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let r=this._idle.pop();clearTimeout(r.timeoutId);let n=r.client;n.ref&&n.ref();let s=r.idleListener;return this._acquireClient(n,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e){let r=sa(this._idle,n=>n.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(n=>n!==e),e.end(),this.emit("remove",e)}connect(e){if(this.ending){let s=new Error("Cannot use a pool after calling end on the pool");return e?e(s):this.Promise.reject(s)}let r=Kt(this.Promise,e),n=r.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new ze(r.callback)),n;let s=i((c,l,u)=>{clearTimeout(a),r.callback(c,l,u)},"queueCallback"),o=new ze(s),a=setTimeout(()=>{sa(this._pendingQueue,c=>c.callback===s),o.timedOut=!0,r.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return this._pendingQueue.push(o),n}return this.newClient(new ze(r.callback)),n}newClient(e){let r=new this.Client(this.options);this._clients.push(r);let n=$d(this,r);this.log("checking client timeout");let s,o=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{this.log("ending client due to timeout"),o=!0,r.connection?r.connection.stream.destroy():r.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),r.connect(a=>{if(s&&clearTimeout(s),r.on("error",n),a)this.log("client failed to connect",a),this._clients=this._clients.filter(c=>c!==r),o&&(a.message="Connection terminated due to connection timeout"),this._pulseQueue(),e.timedOut||e.callback(a,void 0,na);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let c=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(r),this._idle.findIndex(u=>u.client===r)!==-1&&this._acquireClient(r,new ze((u,p,d)=>d()),n,!1)},this.options.maxLifetimeSeconds*1e3);c.unref(),r.once("end",()=>clearTimeout(c))}return this._acquireClient(r,e,n,!0)}})}_acquireClient(e,r,n,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n),e.removeListener("error",n),r.timedOut?s&&this.options.verify?this.options.verify(e,e.release):e.release():s&&this.options.verify?this.options.verify(e,o=>{if(o)return e.release(o),r.callback(o,void 0,na);r.callback(void 0,e,e.release)}):r.callback(void 0,e,e.release)}_releaseOnce(e,r){let n=!1;return s=>{n&&Ud(),n=!0,this._release(e,r,s)}}_release(e,r,n){if(e.on("error",r),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",n,e),n||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses){e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e),this._pulseQueue();return}if(this._expired.has(e)){this.log("remove expired client"),this._expired.delete(e),this._remove(e),this._pulseQueue();return}let o;this.options.idleTimeoutMillis&&(o=setTimeout(()=>{this.log("remove idle client"),this._remove(e)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&o.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new Ln(e,r,o)),this._pulseQueue()}query(e,r,n){if(typeof e=="function"){let o=Kt(this.Promise,e);return setImmediate(function(){return o.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),o.result}typeof r=="function"&&(n=r,r=void 0);let s=Kt(this.Promise,n);return n=s.callback,this.connect((o,a)=>{if(o)return n(o);let c=!1,l=i(u=>{c||(c=!0,a.release(u),n(u))},"onError");a.once("error",l),this.log("dispatching query");try{a.query(e,r,(u,p)=>{if(this.log("query dispatched"),a.removeListener("error",l),!c)return c=!0,a.release(u),u?n(u):n(void 0,p)})}catch(u){return a.release(u),n(u)}}),s.result}end(e){if(this.log("ending"),this.ending){let n=new Error("Called end on pool more than once");return e?e(n):this.Promise.reject(n)}this.ending=!0;let r=Kt(this.Promise,e);return this._endCallback=r.callback,this._pulseQueue(),r.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,r)=>e+(this._expired.has(r)?1:0),0)}get totalCount(){return this._clients.length}};i(kn,"Pool");var xn=kn;ia.exports=xn});var ua=C((uS,ca)=>{"use strict";var aa=require("events").EventEmitter,Kd=require("util"),Bn=gt(),Xe=ca.exports=function(t,e,r){aa.call(this),t=Bn.normalizeQueryConfig(t,e,r),this.text=t.text,this.values=t.values,this.name=t.name,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};Kd.inherits(Xe,aa);var Gd={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};Xe.prototype.handleError=function(t){var e=this.native.pq.resultErrorFields();if(e)for(var r in e){var n=Gd[r]||r;t[n]=e[r]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};Xe.prototype.then=function(t,e){return this._getPromise().then(t,e)};Xe.prototype.catch=function(t){return this._getPromise().catch(t)};Xe.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};Xe.prototype.submit=function(t){this.state="running";var e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;var r=i(function(o,a,c){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),o)return e.handleError(o);e._emitRowEvents&&(c.length>1?a.forEach((l,u)=>{l.forEach(p=>{e.emit("row",p,c[u])})}):a.forEach(function(l){e.emit("row",l,c)})),e.state="end",e.emit("end",c),e.callback&&e.callback(null,c)},"after");if(process.domain&&(r=process.domain.bind(r)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var n=(this.values||[]).map(Bn.prepareValue);if(t.namedQueries[this.name]){if(this.text&&t.namedQueries[this.name]!==this.text){let o=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return r(o)}return t.native.execute(this.name,n,r)}return t.native.prepare(this.name,this.text,n.length,function(o){return o?r(o):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,n,r))})}else if(this.values){if(!Array.isArray(this.values)){let o=new Error("Query values must be an array");return r(o)}var s=this.values.map(Bn.prepareValue);t.native.query(this.text,s,r)}else t.native.query(this.text,r)}});var fa=C((pS,da)=>{"use strict";var la;try{la=require("pg-native")}catch(t){throw t}var Vd=Ir(),pa=require("events").EventEmitter,Hd=require("util"),Qd=Lr(),ma=ua(),de=da.exports=function(t){pa.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new Vd(t.types),this.native=new la({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var e=this.connectionParameters=new Qd(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};de.Query=ma;Hd.inherits(de,pa);de.prototype._errorAllQueries=function(t){let e=i(r=>{process.nextTick(()=>{r.native=this.native,r.handleError(t)})},"enqueueError");this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};de.prototype._connect=function(t){var e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(r,n){if(e.connectionParameters.nativeConnectionString&&(n=e.connectionParameters.nativeConnectionString),r)return t(r);e.native.connect(n,function(s){if(s)return e.native.end(),t(s);e._connected=!0,e.native.on("error",function(o){e._queryable=!1,e._errorAllQueries(o),e.emit("error",o)}),e.native.on("notification",function(o){e.emit("notification",{channel:o.relname,payload:o.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t()})})};de.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,r)=>{this._connect(n=>{n?r(n):e()})})};de.prototype.query=function(t,e,r){var n,s,o,a,c;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")o=t.query_timeout||this.connectionParameters.query_timeout,s=n=t,typeof e=="function"&&(t.callback=e);else if(o=this.connectionParameters.query_timeout,n=new ma(t,e,r),!n.callback){let l,u;s=new this._Promise((p,d)=>{l=p,u=d}).catch(p=>{throw Error.captureStackTrace(p),p}),n.callback=(p,d)=>p?u(p):l(d)}return o&&(c=n.callback,a=setTimeout(()=>{var l=new Error("Query read timeout");process.nextTick(()=>{n.handleError(l,this.connection)}),c(l),n.callback=()=>{};var u=this._queryQueue.indexOf(n);u>-1&&this._queryQueue.splice(u,1),this._pulseQueryQueue()},o),n.callback=(l,u)=>{clearTimeout(a),c(l,u)}),this._queryable?this._ending?(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client was closed and is not queryable"))}),s):(this._queryQueue.push(n),this._pulseQueryQueue(),s):(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client has encountered a connection error and is not queryable"))}),s)};de.prototype.end=function(t){var e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,t));var r;return t||(r=new this._Promise(function(n,s){t=i(o=>o?s(o):n(),"cb")})),this.native.end(function(){e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})}),r};de.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};de.prototype._pulseQueryQueue=function(t){if(this._connected&&!this._hasActiveQuery()){var e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);var r=this;e.once("_done",function(){r._pulseQueryQueue()})}};de.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};de.prototype.ref=function(){};de.prototype.unref=function(){};de.prototype.setTypeParser=function(t,e,r){return this._types.setTypeParser(t,e,r)};de.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)}});var Un=C((dS,ha)=>{"use strict";ha.exports=fa()});var Fn=C((fS,St)=>{"use strict";var Wd=ra(),Yd=yt(),jd=wn(),zd=oa(),{DatabaseError:Xd}=An(),{escapeIdentifier:Zd,escapeLiteral:Jd}=gt(),ef=i(t=>{var e;return e=class extends zd{constructor(n){super(n,t)}},i(e,"BoundPool"),e},"poolFactory"),$n=i(function(t){this.defaults=Yd,this.Client=t,this.Query=this.Client.Query,this.Pool=ef(this.Client),this._pools=[],this.Connection=jd,this.types=ht(),this.DatabaseError=Xd,this.escapeIdentifier=Zd,this.escapeLiteral=Jd},"PG");typeof process.env.NODE_PG_FORCE_NATIVE<"u"?St.exports=new $n(Un()):(St.exports=new $n(Wd),Object.defineProperty(St.exports,"native",{configurable:!0,enumerable:!1,get(){var t=null;try{t=new $n(Un())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(St.exports,"native",{value:t}),t}}))});var ga=C((yS,ya)=>{"use strict";var ke=require("fs"),tf=Pi(),rf=Fn(),nf="The server does not support SSL connections",sf="28000",of=i(t=>{let e={username:t.ssh_user,host:t.ssh_host,port:t.ssh_port,dstHost:t.host,dstPort:t.port,localHost:"127.0.0.1",localPort:t.port,keepAlive:!0};return t.ssh_method==="privateKey"?Object.assign({},e,{privateKey:ke.readFileSync(t.ssh_key_file),passphrase:t.ssh_key_passphrase}):Object.assign({},e,{password:t.ssh_password})},"getSshConfig"),af=i(t=>new Promise((e,r)=>{tf(of(t),(n,s)=>{n?r(n):e({tunnel:s,info:Object.assign({},t,{host:"127.0.0.1"})})})}),"connectViaSsh"),cf=i((t,e)=>{let r=t.sslType;if(!r||r==="disable"||r==="allow")return!1;if(["require","prefer"].includes(r)&&!t.certAuthority)return{rejectUnauthorized:!1};let n={checkServerIdentity(s,o){e.info("Certificate",{hostname:s,cert:{subject:o.subject,issuer:o.issuer,valid_from:o.valid_from,valid_to:o.valid_to}})}};return ke.existsSync(t.certAuthority)&&(n.ca=ke.readFileSync(t.certAuthority).toString()),ke.existsSync(t.clientCert)&&(n.cert=ke.readFileSync(t.clientCert).toString()),ke.existsSync(t.clientPrivateKey)&&(n.key=ke.readFileSync(t.clientPrivateKey).toString()),n},"getSslOptions"),uf=i(t=>({Off:"disable",TRUST_ALL_CERTIFICATES:"allow",TRUST_CUSTOM_CA_SIGNED_CERTIFICATES:"prefer",TRUST_SERVER_CLIENT_CERTIFICATES:"verify-full"})[t]||t,"mapSslType"),lf=i(async(t,e)=>{let r=null;if(t.ssh){let{info:o,tunnel:a}=await af(t);r=a,t=o}t=Object.assign({},t,{sslType:uf(t.sslType)});let n={host:t.host,user:t.userName,password:t.userPassword,port:t.port,keepAlive:!0,ssl:cf(t,e),connectionTimeoutMillis:Number(t.queryRequestTimeout)||6e4,query_timeout:Number(t.queryRequestTimeout)||6e4,statement_timeout:Number(t.queryRequestTimeout)||6e4,database:t.database||t.maintenanceDatabase,application_name:"Hackolade",idleTimeoutMillis:Number(t.queryRequestTimeout)||1e4,sslType:t.sslType};return{client:await Kn(n,e),sshTunnel:r}},"createClient"),pf=i((t,e,r)=>{var n;if(r.message===nf&&t.sslType==="prefer")return e.info("Retry connection without SSL (SSL mode 'prefer')"),e.error(r),Kn({...t,isRetry:!0,ssl:!1},e);if(((n=r.code)==null?void 0:n.toString())===sf&&t.sslType==="allow")return e.info("Retry connection with SSL (SSL mode 'allow')"),e.error(r),Kn({...t,isRetry:!0,ssl:{rejectUnauthorized:!1}},e);throw r},"retryOnSslError"),Kn=i((t,e)=>{let r=new rf.Pool(t);return r.connect().then(n=>(n.release(),r)).catch(async n=>{if(await r.end(),t.isRetry)throw n;return pf(t,e,n)})},"createConnectionPool");ya.exports={createClient:lf}});var Gn=C((ES,Sa)=>{"use strict";var Ea=i(t=>` + SELECT obj_description(oid, 'pg_proc') AS description, + proname AS function_name, + provolatile AS volatility, + proparallel AS parallel, + proisstrict AS strict, + proretset AS returns_set, + proleakproof AS leak_proof, + procost AS estimated_cost, + prorows AS estimated_rows, + prosrc AS body, + ${t===10?"CASE WHEN proiswindow is true THEN 'w' ELSE '' END AS kind":"prokind AS kind"} + FROM pg_catalog.pg_proc WHERE pronamespace = $1;`,"getGET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL"),_a={PING:"SELECT schema_name FROM information_schema.schemata LIMIT 1;",GET_VERSION:"SELECT version()",GET_VERSION_AS_NUM:"SHOW server_version_num;",GET_SCHEMA_NAMES:"SELECT schema_name FROM information_schema.schemata;",GET_TABLE_NAMES:` + SELECT tables.table_name, tables.table_type + FROM information_schema.tables AS tables + INNER JOIN ( + SELECT pg_class.relname AS table_name, + pg_namespace.nspname AS table_schema + FROM pg_catalog.pg_class AS pg_class + INNER JOIN pg_catalog.pg_namespace AS pg_namespace + ON (pg_namespace.oid = pg_class.relnamespace) + WHERE (pg_class.relispartition = false OR pg_class.relispartition IS NULL) AND pg_class.relkind = ANY ('{"r","v","t","m","p"}') + ) AS catalog_table_data + ON (catalog_table_data.table_name = tables.table_name AND catalog_table_data.table_schema = tables.table_schema) + WHERE tables.table_schema = $1; + `,GET_NAMESPACE_OID:"SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = $1",GET_TABLE_LEVEL_DATA:` + SELECT pc.oid, pc.relpersistence, pc.reloptions, pg_get_expr(pc.relpartbound, pc.oid) AS partition_expr + FROM pg_catalog.pg_class AS pc + WHERE pc.relname = $1 AND pc.relnamespace = $2;`,GET_TABLE_TOAST_OPTIONS:` + SELECT reloptions AS toast_options + FROM pg_catalog.pg_class + WHERE oid = + (SELECT reltoastrelid + FROM pg_catalog.pg_class + WHERE relname=$1 AND relnamespace = $2 + LIMIT 1)`,GET_TABLE_COLUMNS:` + SELECT * FROM information_schema.columns + WHERE table_name = $1 AND table_schema = $2 + ORDER BY ordinal_position`,GET_TABLE_COLUMNS_ADDITIONAL_DATA:` + SELECT pg_attribute.attname AS name, + pg_attribute.attndims AS number_of_array_dimensions, + pg_description.description, + pg_attribute.atttypmod AS attribute_mode + FROM pg_catalog.pg_attribute AS pg_attribute + LEFT JOIN pg_catalog.pg_description AS pg_description ON (pg_description.objsubid=pg_attribute.attnum + AND pg_description.objoid = pg_attribute.attrelid) + WHERE pg_attribute.attrelid = $1;`,GET_DESCRIPTION_BY_OID:"SELECT obj_description($1, $2)",GET_ROWS_COUNT:t=>`SELECT COUNT(*) AS quantity FROM ${t};`,GET_SAMPLED_DATA:(t,e)=>`SELECT ${e} FROM ${t} LIMIT $1;`,GET_SAMPLED_DATA_SIZE:(t,e)=>` + SELECT sum(pg_column_size(_hackolade_tmp_sampling_tbl.*)) AS _hackolade_tmp_sampling_tbl_size + FROM (SELECT ${e} FROM ${t} LIMIT $1) AS _hackolade_tmp_sampling_tbl;`,GET_TABLE_CONSTRAINTS:` + SELECT pcon.conname AS constraint_name, + pcon.contype AS constraint_type, + pcon.conkey AS constraint_keys, + pg_catalog.pg_get_expr(pcon.conbin, pcon.conrelid) AS expression, + obj_description(pcon.oid, 'pg_constraint') AS description, + pc.reloptions AS storage_parameters + FROM pg_catalog.pg_constraint AS pcon + LEFT JOIN pg_catalog.pg_class AS pc + ON pcon.conindid = pc.oid + WHERE pcon.conrelid = $1;`,GET_TABLE_INDEXES:` + SELECT indexname, + index_id, + index_method, + index_unique, + number_of_keys, + where_expression, + array_agg(attname ORDER BY ord)::text[] AS columns, + array_agg(coll ORDER BY ord) AS collations, + array_agg(opclass ORDER BY ord) AS opclasses, + array_agg(expression ORDER BY ord) AS expressions, + array_agg(ascending ORDER BY ord) AS ascendings, + array_agg(nulls_first ORDER BY ord) AS nulls_first, + reloptions AS storage_parameters + FROM ( + SELECT ct.oid AS table_oid, + c.relname AS indexname, + m.amname AS index_method, + indexes.indisunique AS index_unique, + indexes.ord, + attribute.attname, + c.reloptions, + indexes.indnkeyatts AS number_of_keys, + ti.index_id AS index_id, + pg_catalog.pg_get_expr(indpred, indrelid) AS where_expression, + CASE + WHEN collation_namespace.nspname is not null THEN format('%I.%I',collation_namespace.nspname,collation_t.collname) + END AS coll, + CASE + WHEN opclass_t.opcname is not null THEN format('%I.%I',opclas_namespace.nspname,opclass_t.opcname) + END AS opclass, + CASE + WHEN NOT m.amcanorder THEN '' + WHEN indexes.indoption[indexes.ord - 1] & 1 = 1 THEN 'DESC' ELSE 'ASC' + END AS ascending, + CASE + WHEN NOT m.amcanorder THEN '' + WHEN indexes.indoption[indexes.ord - 1] & 2 = 2 THEN 'NULLS FIRST' ELSE 'NULLS LAST' + END AS nulls_first, + pg_catalog.pg_get_indexdef(indexes.indexrelid, ord, false) AS expression + FROM + ( + SELECT *, + generate_series(1,array_length(i.indkey,1)) AS ord, + unnest(i.indkey) AS key, + unnest(i.indcollation) AS coll, + unnest(i.indclass) AS class, + unnest(i.indoption) AS option + FROM pg_catalog.pg_index i + ) indexes + JOIN pg_catalog.pg_class c ON (c.oid=indexes.indexrelid) + JOIN pg_catalog.pg_class ct ON (ct.oid=indexes.indrelid) + JOIN pg_catalog.pg_am m ON (m.oid=c.relam) + LEFT JOIN pg_catalog.pg_attribute attribute + ON (attribute.attrelid=indexes.indrelid AND attribute.attnum=indexes.key) + LEFT JOIN pg_catalog.pg_collation collation_t ON (collation_t.oid=indexes.coll) + LEFT JOIN pg_catalog.pg_namespace collation_namespace ON (collation_namespace.oid=collation_t.collnamespace) + LEFT JOIN pg_catalog.pg_opclass opclass_t ON (opclass_t.oid=indexes.class) + LEFT JOIN pg_catalog.pg_namespace opclas_namespace ON (opclas_namespace.oid=opclass_t.opcnamespace) + INNER JOIN crdb_internal.table_indexes ti ON ( + indexes.indrelid = ti.descriptor_id + AND c.relname = ti.index_name + ) + ) s2 + WHERE table_oid = $1 + GROUP BY + indexname, + index_id, + index_method, + index_unique, + reloptions, + number_of_keys, + where_expression; + `,GET_TABLE_INDEX_PARTITIONING_DATA:` + SELECT + partitions.name AS partition_name, + partitions.index_id, + parent_name, + column_names, + list_value, + range_value, + index_name + FROM crdb_internal.partitions + INNER JOIN crdb_internal.table_indexes + ON partitions.table_id = table_indexes.descriptor_id + AND partitions.index_id = table_indexes.index_id + WHERE table_indexes.descriptor_id = $1; + `,GET_TABLE_INDEX_CREATE_INFO:` + SELECT index_name, + is_sharded, + is_visible, + create_statement + FROM crdb_internal.table_indexes WHERE descriptor_id = $1; + `,GET_TABLE_FOREIGN_KEYS:` + SELECT pcon.conname AS relationship_name, + pcon.conkey AS table_columns_positions, + pcon.confdeltype AS relationship_on_delete, + pcon.confupdtype AS relationship_on_update, + pcon.confmatchtype AS relationship_match, + pc_foreign_table.relname AS foreign_table_name, + ARRAY( + SELECT column_name::text FROM unnest(pcon.confkey) AS column_position + JOIN information_schema.columns ON (ordinal_position = column_position) + WHERE table_name = pc_foreign_table.relname AND table_schema = foreign_table_namespace.nspname)::text[] AS foreign_columns, + foreign_table_namespace.nspname AS foreign_table_schema + FROM pg_catalog.pg_constraint AS pcon + LEFT JOIN pg_catalog.pg_class AS pc ON pcon.conindid = pc.oid + LEFT JOIN pg_catalog.pg_class AS pc_foreign_table ON (pcon.confrelid = pc_foreign_table.oid) + JOIN pg_catalog.pg_namespace AS foreign_table_namespace ON (pc_foreign_table.relnamespace = foreign_table_namespace.oid) + WHERE pcon.conrelid = $1 AND pcon.contype = 'f';`,GET_VIEW_DATA:"SELECT * FROM information_schema.views WHERE table_name = $1 AND table_schema = $2;",GET_VIEW_SELECT_STMT_FALLBACK:"SELECT definition FROM pg_views WHERE viewname = $1 AND schemaname = $2;",GET_VIEW_OPTIONS:` + SELECT oid, + reloptions AS view_options, + relpersistence AS persistence, + obj_description(oid, 'pg_class') AS description + FROM pg_catalog.pg_class + WHERE relname = $1 AND relnamespace = $2;`,GET_FUNCTIONS_WITH_PROCEDURES:` + SELECT specific_name, + routine_name AS name, + routine_type, + routine_definition, + external_language, + security_type, + type_udt_name AS return_data_type + FROM information_schema.routines + WHERE specific_schema=$1;`,GET_FUNCTIONS_WITH_PROCEDURES_ARGS:` + SELECT parameter_name, + parameter_mode, + parameter_default, + data_type, + udt_name + FROM information_schema.parameters + WHERE specific_name = $1 + ORDER BY ordinal_position;`,GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL:Ea(),GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:Ea(10),GET_USER_DEFINED_TYPES:` + SELECT pg_type.typrelid AS pg_class_oid, + pg_type.typname AS name, + pg_type.typtype AS type, + pg_catalog.array_agg(pg_enum.enumlabel)::text[] AS enum_values, + range_subtype_type.typname AS range_subtype, + range_collation.collname AS range_collation_name, + range_opclass.opcname AS range_opclass_name, + range_canonical_proc.proname AS range_canonical_proc, + range_diff_proc.proname AS range_diff_proc + FROM pg_catalog.pg_type AS pg_type + LEFT JOIN pg_catalog.pg_class AS pg_class ON (pg_class.oid = pg_type.typrelid) + LEFT JOIN pg_catalog.pg_namespace AS pg_namespace ON (pg_namespace.oid = pg_type.typnamespace) + LEFT JOIN pg_catalog.pg_enum AS pg_enum ON (pg_enum.enumtypid = pg_type.oid) + LEFT JOIN pg_catalog.pg_range AS pg_range ON (pg_range.rngtypid = pg_type.oid) + LEFT JOIN pg_catalog.pg_type AS range_subtype_type ON (range_subtype_type.oid = pg_range.rngsubtype) + LEFT JOIN pg_catalog.pg_collation AS range_collation ON (range_collation.oid = pg_range.rngcollation) + LEFT JOIN pg_catalog.pg_opclass AS range_opclass ON (range_opclass.oid = pg_range.rngsubopc) + LEFT JOIN pg_catalog.pg_proc AS range_canonical_proc ON (range_canonical_proc.oid = pg_range.rngcanonical) + LEFT JOIN pg_catalog.pg_proc AS range_diff_proc ON (range_diff_proc.oid = pg_range.rngsubdiff) + WHERE pg_namespace.nspname = $1 + AND ( + (pg_type.typtype = 'c' AND (pg_class.relkind = 'c' OR pg_class.relkind IS NULL)) + OR pg_type.typtype = 'e' + OR pg_type.typtype = 'r' + ) + GROUP BY pg_class_oid, + pg_type.typname, + pg_type.typtype, + pg_class.oid, + range_subtype, + range_collation_name, + range_opclass_name, + range_canonical_proc, + range_diff_proc;`,GET_COMPOSITE_TYPE_COLUMNS:` + SELECT pg_attribute.attname AS column_name, + pg_type.typname AS data_type, + pg_get_expr(pg_attrdef.adbin, pg_attrdef.adrelid) AS columns_default, + pg_attribute.attnotnull AS not_null, + pg_collation.collname AS collation_name, + pg_attribute.attndims AS number_of_array_dimensions, + pg_attribute.atttypmod AS character_maximum_length + FROM pg_catalog.pg_attribute AS pg_attribute + LEFT JOIN pg_catalog.pg_type AS pg_type ON (pg_type.oid = pg_attribute.atttypid) + LEFT JOIN pg_catalog.pg_attrdef AS pg_attrdef ON (pg_attrdef.adrelid = pg_attribute.attrelid + AND pg_attrdef.adnum = pg_attribute.attnum) + LEFT JOIN pg_catalog.pg_collation AS pg_collation ON (pg_collation.oid = pg_attribute.attcollation) + WHERE pg_attribute.attrelid = $1`,GET_DB_NAME:"SELECT current_database();",GET_DB_ENCODING:"SHOW SERVER_ENCODING;",GET_DB_COLLATE_NAME:"SELECT default_collate_name FROM information_schema.character_sets;",GET_DATABASES:"SELECT datname AS database_name FROM pg_catalog.pg_database WHERE datistemplate != TRUE AND datallowconn = TRUE;"},mf=i(t=>(Object.entries(_a).find(([r,n])=>t===n)||[])[0]||"Custom query","getQueryName");Sa.exports={getQueryName:mf,..._a}});var Ca=C((SS,Ta)=>{"use strict";var df=Gn(),Fe=null,Gt=null;Ta.exports={initializeClient(t,e){Fe=t,Gt=e,Fe.on("error",r=>e.error(r))},isClientInitialized(){return!!Fe},releaseClient(){return Fe?new Promise(t=>{Fe.end(()=>{Fe=null,t()})}):Promise.resolve()},async query(t,e,r=!1){let n=df.getQueryName(t);Gt.info("Execute query",{queryName:n,params:e});let s=Date.now(),o=await Fe.query(t,e),a=Date.now()-s;Gt.info("Query executed",{queryName:n,params:e,duration:a,rowsCount:o.rowCount});let c=o.rows||[];return r?c[0]:c},async queryTolerant(t,e,r=!1){try{return await this.query(t,e,r)}catch(n){return n.query=t,n.params=e,Gt.error(n),null}}}});var ba=C((TS,Na)=>{"use strict";var Aa=i(t=>{let e=t.reduce((n,s)=>s.properties?{...n,[s.name]:{...s,...Aa(s.properties)}}:{...n,[s.name]:s},{}),r=Object.entries(e).filter(([n,s])=>s.required).map(([n])=>n);return{properties:e,required:r}},"getJsonSchema");Na.exports={getJsonSchema:Aa}});var Qn=C((AS,va)=>{"use strict";var Be=null,ff=i(t=>{Be=t.require("lodash")},"setDependencies"),Vn={column_default:"default",is_nullable:{keyword:"required",map:(t,e,r)=>({YES:!1,NO:!0})[r]},not_null:"required",data_type:"type",numeric_precision:"precision",numeric_scale:"scale",datetime_precision:"timePrecision",attribute_mode:{keyword:"timePrecision",check:(t,e,r)=>r!==-1&&Af(t.data_type)},interval_type:"intervalOptions",collation_name:"collationRule",column_name:"name",number_of_array_dimensions:"numberOfArrayDimensions",udt_name:"udt_name",character_maximum_length:{keyword:"length",map:(t,e,r)=>Number(r)},description:"description"},hf=i((t,e,r)=>{let n=Vn[e];if(!n||typeof n=="string")return r;let s=n.check||((c,l,u)=>!0),o=n.map||((c,l,u)=>u),a="";return s(t,e,r)&&(a=r),o(t,e,a)},"getColumnValue"),yf=i(t=>e=>Be.chain(e).toPairs().map(([r,n])=>{var s;return[((s=Vn[r])==null?void 0:s.keyword)||Vn[r],hf(e,r,n)]}).filter(([r,n])=>r&&!Be.isNil(n)).fromPairs().thru(gf(t)).value(),"mapColumnData"),gf=i(t=>e=>({...e,...Ef(t,e)}),"setColumnType"),Ef=i((t,e)=>e.type==="ARRAY"?_f(t,e):e.type==="USER-DEFINED"?Hn(t,e.udt_name):Hn(t,e.type),"getType"),_f=i((t,e)=>({...Hn(t,e.udt_name.slice(1)),array_type:Be.fill(Array(e.numberOfArrayDimensions),"")}),"getArrayType"),Hn=i((t,e)=>{switch(e){case"bigserial":case"real":case"double precision":case"smallserial":case"serial":case"money":return{type:"numeric",mode:e};case"numeric":case"dec":case"decimal":return{type:"numeric",mode:"decimal"};case"int2":case"smallint":return{type:"numeric",mode:"int2"};case"int4":case"integer":return{type:"numeric",mode:"int4"};case"int":case"int8":case"int64":case"bigint":return{type:"numeric",mode:"int"};case"float4":return{type:"numeric",mode:"real"};case"float8":return{type:"numeric",mode:"double precision"};case"bit":case"char":case"text":case"tsvector":case"tsquery":return{type:"char",mode:e};case"bit varying":return{type:"char",mode:"varbit"};case"character":return{type:"char",mode:"char"};case"character varying":return{type:"char",mode:"varchar"};case"bpchar":return{type:"char",mode:"char"};case"point":case"line":case"lseg":case"box":case"path":case"polygon":case"circle":case"box2d":case"box3d":case"geometry":case"geometry_dump":case"geography":return{type:"geometry",mode:e};case"bytea":return{type:"binary",mode:e};case"inet":case"cidr":case"macaddr":case"macaddr8":return{type:"inet",mode:e};case"date":case"time":case"timestamp":case"interval":return{type:"datetime",mode:e};case"timestamptz":case"timestamp with time zone":return{type:"datetime",mode:"timestamp",timezone:"WITH TIME ZONE"};case"timestamp without time zone":return{type:"datetime",mode:"timestamp",timezone:"WITHOUT TIME ZONE"};case"timetz":case"time with time zone":return{type:"datetime",mode:"time",timezone:"WITH TIME ZONE"};case"time without time zone":return{type:"datetime",mode:"time",timezone:"WITHOUT TIME ZONE"};case"json":case"jsonb":return{type:"json",mode:e,subtype:"object"};case"int4range":case"int8range":case"numrange":case"daterange":case"tsrange":case"tstzrange":return{type:"range",mode:e};case"int4multirange":case"int8multirange":case"nummultirange":case"tsmultirange":case"tstzmultirange":case"datemultirange":return{type:"multirange",mode:e};case"uuid":case"xml":case"boolean":return{type:e};case"bool":return{type:"boolean"};case"oid":case"regclass":case"regcollation":case"regconfig":case"regdictionary":case"regnamespace":case"regoper":case"regoperator":case"regproc":case"regprocedure":case"regrole":case"regtype":return{type:"oid",mode:e};default:return Be.some(t,{name:e})?{$ref:`#/definitions/${e}`}:{type:"char",mode:"varchar"}}},"mapType"),Sf=i((t,e)=>{let r=Be.first(e)||{};return t.map(n=>{if(n.type!=="json")return n;let s=r[n.name],o=Tf(s),a=Cf(o);return{...n,subtype:a}})},"setSubtypeFromSampledJsonValues"),Tf=i(t=>{try{return JSON.parse(t)}catch{return{}}},"safeParse"),Cf=i(t=>{if(Array.isArray(t))return"array";let e=typeof t;return e==="undefined"?"object":e},"getParsedJsonValueType"),Af=i(t=>Be.includes(["timestamp with time zone","timestamp without time zone","time with time zone","time without time zone"],t),"canHaveTimePrecision");va.exports={setDependencies:ff,mapColumnData:yf,setSubtypeFromSampledJsonValues:Sf}});var Tt=C((bS,wa)=>{"use strict";var Nf=["ALL","ANALYSE","ANALYZE","AND","ANY","ARRAY","ASC","ASYMMETRIC","AUTHORIZATION","BINARY","BOTH","CASE","CAST","CHECK","COLLATE","COLUMN","CONCURRENTLY","CONSTRAINT","CREATE","CROSS","CURRENT_CATALOG","CURRENT_DATE","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DEFAULT","DEFERRABLE","DESC","DISTINCT","DO","ELSE","END","EXCEPT","FALSE","FOR","FOREIGN","FREEZE","FROM","FULL","GRANT","GROUP","HAVING","ILIKE","IN","INITIALLY","INTERSECT","INTO","IS","ISNULL","JOIN","LATERAL","LEADING","LEFT","LIKE","LIMIT","LOCALTIME","LOCALTIMESTAMP","NATURAL","NOT","NULL","OFFSET","ON","ONLY","OR","ORDER","OUTER","OVERLAPS","PLACING","PRIMARY","REFERENCES","RETURNING","RIGHT","SELECT","SESSION_USER","SIMILAR","SOME","SYMMETRIC","TABLE","TABLESAMPLE","THEN","TO","TRAILING","TRUE","UNION","UNIQUE","USER","USING","VARIADIC","VERBOSE","WHEN","WHERE","WINDOW","WITH"],Ze=null,bf=i(t=>{Ze=t.require("lodash")},"setDependencies"),vf=i(t=>Ze.chain(t).toPairs().reject(([e,r])=>Ze.isNil(r)).fromPairs().value(),"clearEmptyPropertiesInObject"),wf=i(t=>e=>{var r;return(r=Ze.find(t,{ordinal_position:e}))==null?void 0:r.column_name},"getColumnNameByPosition"),Of=i(t=>/\s|\W/.test(t)||Ze.includes(Nf,Ze.toUpper(t))?`"${t}"`:t,"wrapInQuotes");wa.exports={clearEmptyPropertiesInObject:vf,setDependencies:bf,getColumnNameByPosition:wf,wrapInQuotes:Of}});var Ra=C((wS,Ia)=>{"use strict";var{getColumnNameByPosition:If}=Tt(),Wn=null,Rf=i(t=>{Wn=t.require("lodash")},"setDependencies"),Oa=i(t=>{switch(t){case"a":return"NO ACTION";case"r":return"RESTRICT";case"c":return"CASCADE";case"n":return"SET NULL";case"d":return"SET DEFAULT";default:return""}},"prepareDeleteAndUpdate"),Pf=i(t=>{switch(t){case"f":return"FULL";case"s":return"SIMPLE";default:return""}},"prepareMatch"),Df=i((t,e,r,n)=>Wn.map(t,s=>({relationshipName:s.relationship_name,dbName:s.foreign_table_schema,parentCollection:s.foreign_table_name,parentField:s.foreign_columns,childDbName:r,childCollection:e,childField:Wn.map(s.table_columns_positions,If(n)),relationshipType:"Foreign Key",relationshipInfo:{relationshipOnDelete:Oa(s.relationship_on_delete),relationshipOnUpdate:Oa(s.relationship_on_update),relationshipMatch:Pf(s.relationship_match)}})),"prepareForeignKeys");Ia.exports={setDependencies:Rf,prepareForeignKeys:Df}});var La=C((IS,Da)=>{"use strict";var Vt=null,Lf=i(t=>{Vt=t.require("lodash")},"setDependencies"),Pa=i(t=>Vt.map(t,e=>({argumentMode:e.parameter_mode,argumentName:e.parameter_name,argumentType:xf(e.data_type,e.udt_name),defaultExpression:e.parameter_default})),"mapFunctionArgs"),xf=i((t,e)=>t==="USER-DEFINED"?e:t==="ARRAY"?e.slice(1)+"[]":t,"getArgType"),Mf=i(t=>{switch(t){case"i":return"IMMUTABLE";case"s":return"STABLE";case"v":default:return"VOLATILE"}},"getVolatility"),qf=i(t=>{switch(t){case"s":return"SAFE";case"r":return"RESTICTED";case"u":return"UNSAFE";default:return""}},"getParallel"),kf=i(t=>t?"STRICT":"CALLED ON NULL INPUT","getNullArgs"),Ff=i((t,e,r)=>({name:t.name,functionDescription:r==null?void 0:r.description,functionArguments:Pa(e),functionReturnsSetOf:r==null?void 0:r.returns_set,functionReturnType:t.return_data_type,functionLanguage:Vt.toLower(t.external_language),functionBody:t.routine_definition??(r==null?void 0:r.body),functionWindow:(r==null?void 0:r.kind)==="w",functionVolatility:Mf(r==null?void 0:r.volatility),functionLeakProof:r==null?void 0:r.leak_proof,functionNullArgs:kf(r==null?void 0:r.strict),functionSqlSecurity:t.security_type,functionParallel:qf(t.parallel),functionExecutionCost:t.estimated_cost,functionExecutionRows:t.estimated_rows}),"mapFunctionData"),Bf=i((t,e,r)=>({name:t.name,description:r==null?void 0:r.description,language:Vt.toLower(t.external_language),inputArgs:Pa(e),body:t.routine_definition}),"mapProcedureData");Da.exports={setDependencies:Lf,mapFunctionData:Ff,mapProcedureData:Bf}});var ka=C((PS,qa)=>{"use strict";var Uf=i(t=>e=>{if(!e)return null;let r=Kf(e),n=Gf(t)(e),s=Vf(e);return[{partitionMethod:r,compositePartitionKey:n,partitioning_expression:s}]},"preparePartition"),Yn=i((t={})=>t.list_value?"LIST":t.range_value?"RANGE":"","getPartitionMethodByRow"),xa=i((t=[])=>t.filter(e=>!e.parent_name),"getParentPartitionRows"),$f=i((t=[],e=null)=>t.filter(r=>r.parent_name===e),"getChildPartitionRows"),Kf=i((t=[])=>{let e=xa(t);if(!e.length)return"";let r=e[0];return Yn(r)},"getPartitionMethod"),Gf=i(t=>(e=[])=>{let n=e.filter(s=>!s.parent_name).flatMap(s=>(s.column_names||"").split(",").map(a=>a.trim()));return t.uniq(n)},"getCompositePartitionKey"),Vf=i(t=>{let e=xa(t);if(!e.length)return"";let r=e[0],n=Yn(r),s=r.column_names||"",o=e.map(a=>Ma({partition:a,paddingFactor:1,partitionResult:t})).join(`, +`);return`PARTITION BY ${n} (${s}) ( +${o} +)`},"getPartitionExpression"),Ma=i(({partition:t,partitionResult:e,paddingFactor:r})=>{let n=t.list_value?"VALUES IN":"VALUES FROM",s=t.list_value||t.range_value||"",o=" ".repeat(r),a=`${o}PARTITION ${t.partition_name} ${n} ${s}`,c=$f(e,t.partition_name);if(c.length){let l=c.map(h=>Ma({partition:h,partitionResult:e,paddingFactor:r+1})).join(`, +`),u=c[0],p=Yn(u),d=u.column_names||"";return a+` PARTITION BY ${p} (${d}) ( +`+l+` +`+o+")"}return a},"getSinglePartitionExpression");qa.exports={preparePartition:Uf}});var Ka=C((LS,$a)=>{"use strict";var{clearEmptyPropertiesInObject:Ht,getColumnNameByPosition:Fa}=Tt(),{preparePartition:Hf}=ka(),G=null,Qf=i(t=>{G=t.require("lodash")},"setDependencies"),Wf=i(t=>{let e={};for(let r of Object.keys(t))r.startsWith("ttl")?(e.ttl_storage_parameters||(e.ttl_storage_parameters={}),e.ttl_storage_parameters[r]=t[r]):e[r]=t[r];return e},"groupTtlStorageParams"),Ba=i((t,e)=>{if(!t&&!e)return null;let r=fh(t),n=Ht(r),s=Wf(n);return Ht(s)},"prepareStorageParameters"),jn=i(t=>G.split(t,"="),"splitByEqualitySymbol"),Yf=i(t=>G.find(t,{type:"json"}),"checkHaveJsonTypes"),jf=i((t,e)=>{if(e.active==="absolute")return Number(e.absolute.value);let r=Math.ceil(t*e.relative.value/100);return Math.min(r,e.maxValue)},"getSampleDocSize"),zf=i((t,e,r)=>G.reduce(t,(n,s)=>{switch(s.constraint_type){case"c":return{...n,chkConstr:[...n.chkConstr,Jf(s)]};case"p":return{...n,primaryKey:[...n.primaryKey,Xf(s,e)]};case"u":return{...n,uniqueKey:[...n.uniqueKey,Zf(s,e)]};default:return n}},{chkConstr:[],uniqueKey:[],primaryKey:[]}),"prepareTableConstraints"),Xf=i((t,e)=>({constraintName:t.constraint_name,compositePrimaryKey:G.map(t.constraint_keys,Fa(e)),indexStorageParameters:G.join(t.storage_parameters,",")}),"getPrimaryKeyConstraint"),Zf=i((t,e)=>({constraintName:t.constraint_name,compositeUniqueKey:G.map(t.constraint_keys,Fa(e)),indexStorageParameters:G.join(t.storage_parameters,","),indexComment:t.description}),"getUniqueKeyConstraint"),Jf=i(t=>({chkConstrName:t.constraint_name,constrExpression:t.expression,notValid:t.notValid,constrDescription:t.description}),"getCheckConstraint"),eh=i((t,e=[])=>e.find(n=>n.index_name===t)||{}||{},"getIndexCreateInfoRowByName"),th=i(t=>{switch(t.toUpperCase()){case"INVERTED":return"gin";case"PREFIX":return"btree";default:return t}},"parseIndexMethod"),rh=i((t,e)=>(t||[]).filter(r=>r.index_name===e.indexname&&r.index_id===e.index_id),"getIndexPartitioningRows"),nh=i(({tableIndexesResult:t,tableIndexesCreateInfoResult:e=[],tableIndexesPartitioningResult:r})=>G.map(t,n=>{let s=eh(n.indexname,e),o=s.create_statement,a=ch(n,o),c=G.slice(a,0,n.number_of_keys),l=G.chain(a).slice(n.number_of_keys).map(y=>G.pick(y,"name")).value(),u=s.is_visible?"VISIBLE":"NOT VISIBLE",p=!!s.is_sharded,d=rh(r,n),f=(Hf(G)(d)||[{}])[0].partitioning_expression,S={indxName:n.indexname,index_method:th(n.index_method),unique:n.index_unique??!1,index_storage_parameter:lh(n.storage_parameters,o),where:n.where_expression||"",partitioning_expression:f,include:l,columns:c,using_hash:p,visibility:u};return Ht(S)}),"prepareTableIndexes"),sh=i(({createStatement:t,columnName:e})=>{let r=["(",","],n=0;for(;n{let r=t.substring(e),n=r.indexOf(","),s=r.indexOf(")");return n===-1?e+s:e+Math.min(n,s)},"getColumnDefinitionEnd"),oh=i(({createStatement:t,columnName:e})=>{let r=sh({columnName:e,createStatement:t});if(r===-1)return"";let n=ih({columnDefinitionStart:r,createStatement:t});return n===-1?"":t.substring(r,n)},"getIndexColumnQueryDefinition"),ah=i(({indexData:t,itemIndex:e,columnName:r,createStatement:n})=>{let s=G.get(t,`opclasses.${e}`,"");if(s)return s;let o=oh({columnName:r,createStatement:n});if(!o)return"";let a=o.substring(r.length).trim();return a?a.toUpperCase().replaceAll("ASC","").replaceAll("DESC","").replaceAll("NULLS FIRST","").replaceAll("NULLS LAST","").toLowerCase().trim():""},"getIndexColumnOpClass"),ch=i((t,e)=>G.chain(t.columns).map((r,n)=>{if(!r)return;let s=G.get(t,`ascendings.${n}`,"ASC"),o=G.get(t,`nulls_first.${n}`,"NULLS FIRST"),a=ah({columnName:r,createStatement:e,itemIndex:n,indexData:t}),c=G.get(t,`collations.${n}`,"");return{name:r,sortOrder:s,nullsOrder:o,opclass:a,collation:c}}).compact().value(),"mapIndexColumns"),Ua=i(t=>{let e={fillfactor:t.fillfactor,bucket_count:t.bucket_count,geometry_max_x:t.geometry_max_x,geometry_max_y:t.geometry_max_y,geometry_min_x:t.geometry_min_x,geometry_min_y:t.geometry_min_y,s2_level_mod:t.s2_level_mod,s2_max_cells:t.s2_max_cells,s2_max_level:t.s2_max_level};return Ht(e)},"hydrateIndexStorageParameters"),uh=i(t=>{let e=/\s+with\s+\(.*?\)/im,r=t.match(e);if(!(r!=null&&r.length))return null;let n=r[0],s=7,o=n.length-1,a=n.substring(s,o).split(",").map(l=>l.trim()),c=G.fromPairs(G.map(a,l=>jn(l)));return Ua(c)},"parseIndexStorageParametersFromDdl"),lh=i((t,e)=>{if(!t)return uh(e);let r=G.fromPairs(G.map(t,n=>jn(n)));return Ua(r)},"getIndexStorageParameters"),ph=i((t,e)=>{let r=(t==null?void 0:t.relpersistence)==="t",n=(t==null?void 0:t.relpersistence)==="u",s=Ba(t==null?void 0:t.reloptions,e),o=t.partition_expr;return{temporary:r,unlogged:n,storage_parameter:s,partitionBounds:o}},"prepareTableLevelData"),mh=i(t=>{switch(dh(t)){case"number":case"boolean":return JSON.parse(t);case"string":default:return t}},"convertValueToType"),dh=i(t=>{try{let e=typeof JSON.parse(t);return e==="object"?"string":e}catch{return"string"}},"getTypeOfValue"),fh=i(t=>G.chain(t).map(jn).map(([e,r])=>[e,mh(r)]).fromPairs().value()||{},"prepareOptions"),hh=i((t,e)=>G.map(e,({parent_table_name:r})=>({parentTable:[t,r]})),"prepareTableInheritance");$a.exports={prepareStorageParameters:Ba,setDependencies:Qf,checkHaveJsonTypes:Yf,prepareTableConstraints:zf,prepareTableLevelData:ph,prepareTableIndexes:nh,getSampleDocSize:jf,prepareTableInheritance:hh}});var Va=C((MS,Ga)=>{"use strict";var{mapColumnData:yh}=Qn(),zn=null,gh=i(t=>{zn=t.require("lodash")},"setDependencies"),Eh=i(t=>zn.chain(t).map(e=>{switch(e.type){case"e":return _h(e);case"r":return Sh(e);case"c":return Th(e);default:return null}}).compact().value(),"getUserDefinedTypes"),_h=i(t=>({name:t.name,type:"enum",enum:t.enum_values||[]}),"getEnumType"),Sh=i(t=>({name:t.name,type:"range_udt",rangeSubtype:t.range_subtype||"",operatorClass:t.range_opclass_name||"",collation:t.range_collation_name||"",canonicalFunction:t.range_canonical_proc||"",subtypeDiffFunction:t.range_diff_proc||""}),"getRangeType"),Th=i(t=>{let e=zn.map(t.columns,yh([]));return{name:t.name,type:"composite",properties:e}},"getCompositeType"),Ch=i(t=>t.type==="c","isTypeComposite");Ga.exports={setDependencies:gh,getUserDefinedTypes:Eh,isTypeComposite:Ch}});var Qa=C((kS,Ha)=>{"use strict";var{clearEmptyPropertiesInObject:Ah,wrapInQuotes:Nh}=Tt(),Ie=null,bh=i(t=>{Ie=t.require("lodash")},"setDependencies"),Xn=" (v)",vh=i(t=>t==="VIEW","isViewByTableType"),wh=i(t=>Ie.endsWith(t,Xn),"isViewByName"),Oh=i(t=>t.slice(0,-Xn.length),"removeViewNameSuffix"),Ih=i(t=>`${t}${Xn}`,"setViewSuffix"),Rh=i((t,e,r={})=>{let n=Ie.trim(e.view_definition||r.definition||"");return n?`CREATE VIEW ${Nh(t)} AS ${n}`:""},"generateCreateViewScript"),Ph=i((t,e)=>{let r={withCheckOption:t.check_option!=="NONE"||Ie.isNil(t.check_option),checkTestingScope:Dh(t.check_option),viewOptions:Ie.fromPairs(Ie.map(e==null?void 0:e.view_options,xh)),temporary:(e==null?void 0:e.persistence)==="t",recursive:Lh(t),description:e==null?void 0:e.description};return Ah(r)},"prepareViewData"),Dh=i(t=>t==="NONE"?"":t,"getCheckTestingScope"),Lh=i(t=>Ie.startsWith(Ie.trim(t.view_definition),"WITH RECURSIVE"),"isViewRecursive"),xh=i(t=>Ie.split(t,"="),"splitByEqualitySymbol");Ha.exports={setDependencies:bh,isViewByTableType:vh,isViewByName:wh,removeViewNameSuffix:Oh,generateCreateViewScript:Rh,setViewSuffix:Ih,prepareViewData:Ph}});var ja=C((BS,Ya)=>{"use strict";var Mh=i((t,e)=>[qh,kh].reduce(({attributes:r,entityLevel:n},s)=>s(r,n),{attributes:t,entityLevel:e}),"reorganizeConstraints"),qh=i((t,e)=>{var o,a,c;if(((c=(a=(o=e.primaryKey)==null?void 0:o[0])==null?void 0:a.compositePrimaryKey)==null?void 0:c.length)!==1)return{attributes:t,entityLevel:e};let n=e.primaryKey[0],s=n.compositePrimaryKey[0];return{attributes:Fh(t,s,n),entityLevel:Kh(e)}},"reorganizePrimaryKeys"),kh=i((t,e)=>(e.uniqueKey||[]).reduce(({attributes:r,entityLevel:n},s)=>{if(!(s.compositeUniqueKey.length===1))return{attributes:r,entityLevel:n};let a=s.compositeUniqueKey[0];return{attributes:Uh(r,a,s),entityLevel:Gh(n,s)}},{attributes:t,entityLevel:e}),"reorganizeUniqueKeys"),Fh=i((t,e,r)=>t.map(n=>n.name!==e?n:Bh(n,r)),"setAttributesPrimaryKeyData"),Bh=i((t,e)=>({...t,primaryKey:!0,primaryKeyOptions:Wa(e)}),"setPrimaryKeyData"),Uh=i((t,e,r)=>t.map(n=>n.name!==e?n:$h(n,r)),"setAttributesUniqueKeyData"),$h=i((t,e)=>({...t,unique:!0,uniqueKeyOptions:Wa(e)}),"setUniqueKeyData"),Wa=i(t=>[{constraintName:t.constraintName,indexInclude:t.indexInclude,indexStorageParameters:t.indexStorageParameters,indexComment:t.indexComment}],"getOptions"),Kh=i(t=>({...t,primaryKey:[]}),"clearPrimaryKeys"),Gh=i((t,e)=>{let r=t.uniqueKey.filter(n=>n.constraintName!==e.constraintName);return{...t,uniqueKey:r}},"filterUniqueKeys");Ya.exports={reorganizeConstraints:Mh}});var Zn=C(($S,Ja)=>{"use strict";var{createClient:Vh}=ga(),k=Ca(),{getJsonSchema:za}=ba(),{setDependencies:Hh,mapColumnData:Qh,setSubtypeFromSampledJsonValues:Wh}=Qn(),{setDependencies:Yh,clearEmptyPropertiesInObject:Xa}=Tt(),{setDependencies:jh,prepareForeignKeys:zh}=Ra(),{setDependencies:Xh,mapFunctionData:Zh,mapProcedureData:Jh}=La(),{setDependencies:ey,checkHaveJsonTypes:ty,prepareTableConstraints:ry,getSampleDocSize:ny,prepareTableLevelData:sy,prepareTableIndexes:iy}=Ka(),{setDependencies:oy,getUserDefinedTypes:ay,isTypeComposite:cy}=Va(),{setDependencies:uy,isViewByTableType:ly,isViewByName:py,removeViewNameSuffix:my,generateCreateViewScript:dy,setViewSuffix:fy,prepareViewData:hy}=Qa(),F=Gn(),{reorganizeConstraints:yy}=ja(),Qt=null,J=null,_e=null,Za=14;Ja.exports={setDependencies(t){J=t.require("lodash"),Yh(t),ey(t),Hh(t),jh(t),uy(t),Xh(t),oy(t)},async connect(t,e){k.isClientInitialized()&&await this.disconnect();let{client:r,sshTunnel:n}=await Vh(t,e);k.initializeClient(r,e),Qt=n,_e=e,Za=await this._getServerVersion()},async disconnect(){Qt&&(Qt.close(),Qt=null),await k.releaseClient()},pingDb(){return k.query(F.PING)},applyScript(t){return k.query(t)},async getDatabaseNames(){return J.map(await k.query(F.GET_DATABASES),"database_name")},async logVersion(){let t=await k.queryTolerant(F.GET_VERSION,[],!0),e=(t==null?void 0:t.version)||"Version not retrieved"},async getAllSchemasNames(){return(await k.query(F.GET_SCHEMA_NAMES)).map(({schema_name:e})=>e).filter(e=>!gy(e))},async getTablesNames(t){let e=await k.query(F.GET_TABLE_NAMES,[t]),r=["FOREIGN TABLE"];return e.filter(({table_type:n})=>!J.includes(r,n)).map(({table_name:n,table_type:s})=>ly(s)?fy(n):n)},async getDbLevelData(){var n,s,o;_e.progress("Get database data");let t=(n=await k.queryTolerant(F.GET_DB_NAME,[],!0))==null?void 0:n.current_database,e=(s=await k.queryTolerant(F.GET_DB_ENCODING,[],!0))==null?void 0:s.server_encoding,r=(o=await k.queryTolerant(F.GET_DB_COLLATE_NAME,[],!0))==null?void 0:o.default_collate_name;return Xa({database_name:t,encoding:e,LC_COLLATE:r,LC_CTYPE:r})},async retrieveEntitiesData(t,e,r){let n=await this._retrieveUserDefinedTypes(t),s=await k.queryTolerant(F.GET_NAMESPACE_OID,[t],!0),o=s==null?void 0:s.oid,[a,c]=J.partition(e,py),l=c.map(d=>({tableName:d})),u=await Ct(J.uniq(l),J.bind(this._retrieveSingleTableData,this,r,o,t,n));return{views:await Ct(a,J.bind(this._retrieveSingleViewData,this,o,t)),tables:u,modelDefinitions:za(n)}},async retrieveSchemaLevelData(t,e){var u;if(e)return _e.info("Functions and procedures ignored"),{functions:[],procedures:[]};_e.progress("Get Functions and Procedures",t);let r=(u=await k.queryTolerant(F.GET_NAMESPACE_OID,[t],!0))==null?void 0:u.oid,n=await k.queryTolerant(F.GET_FUNCTIONS_WITH_PROCEDURES,[t]),s=await k.queryTolerant(Ey(Za),[r]),[o,a]=J.partition(J.filter(n,"routine_type"),{routine_type:"FUNCTION"}),c=await Ct(o,async p=>{let d=await k.queryTolerant(F.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[p.specific_name]),h=J.find(s,{function_name:p.name});return Zh(p,d,h)}),l=await Ct(a,async p=>{let d=await k.queryTolerant(F.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[p.specific_name]),h=J.find(s,{function_name:p.name});return Jh(p,d,h)});return{functions:c,procedures:l}},async _retrieveUserDefinedTypes(t){_e.progress("Get User-Defined Types",t);let e=await k.queryTolerant(F.GET_USER_DEFINED_TYPES,[t]),r=await Ct(e,async n=>cy(n)?{...n,columns:await k.queryTolerant(F.GET_COMPOSITE_TYPE_COLUMNS,[n.pg_class_oid])}:n);return ay(r)},async _retrieveSingleTableData(t,e,r,n,{tableName:s}){_e.progress("Get table data",r,s);let o=await k.queryTolerant(F.GET_TABLE_LEVEL_DATA,[s,e],!0),a=o==null?void 0:o.oid,c=await k.queryTolerant(F.GET_TABLE_TOAST_OPTIONS,[s,e],!0),l=await this._getTableColumns(s,r,a),p=await k.queryTolerant(F.GET_DESCRIPTION_BY_OID,[a,"pg_class"],!0),d=await k.queryTolerant(F.GET_TABLE_CONSTRAINTS,[a]),h=await k.queryTolerant(F.GET_TABLE_INDEXES,[a]),f=await k.queryTolerant(F.GET_TABLE_INDEX_PARTITIONING_DATA,[a]),S=await k.queryTolerant(F.GET_TABLE_INDEX_CREATE_INFO,[a]),y=await k.queryTolerant(F.GET_TABLE_FOREIGN_KEYS,[a]);_e.info("Table data retrieved",{schemaName:r,tableName:s,columnTypes:l.map(Te=>Te.data_type)});let T=sy(o,c),_=_y(p),D=ry(d,l,h),N=iy({tableIndexesResult:h,tableIndexesCreateInfoResult:S,tableIndexesPartitioningResult:f}),O=zh(y,s,r,l),R={description:_,Indxs:N,...T,...D},A=Xa(R),b=l.map(Qh(n)),x=ty(b),U=[];x&&(U=await this._getDocuments(r,s,b,t),b=Wh(b,U));let{attributes:W,entityLevel:Se}=yy(b,A);return{name:s,entityLevel:Se,jsonSchema:za(W),documents:U,relationships:O}},async _getTableColumns(t,e,r){_e.progress("Get columns",e,t);let n=await k.query(F.GET_TABLE_COLUMNS,[t,e]),s=await k.queryTolerant(F.GET_TABLE_COLUMNS_ADDITIONAL_DATA,[r]);return J.map(n,o=>({...o,ordinal_position:Number(o.ordinal_position),...J.find(s,{name:o.column_name})||{}}))},async _getDocuments(t,e,r,n){var p;_e.progress("Sampling table",t,e);let s=`${t}.${e}`,o=((p=await k.queryTolerant(F.GET_ROWS_COUNT(s),[],!0))==null?void 0:p.quantity)||0,a=ny(o,n),c=r.filter(({type:d})=>J.includes(["json","jsonb"],d)),l=J.map(c,"name").join(", "),u=await k.queryTolerant(F.GET_SAMPLED_DATA_SIZE(s,l),[a],!0);return _e.info("Sampling table",{tableName:e,jsonColumnsNumber:c.length,samplingDataSize:u==null?void 0:u._hackolade_tmp_sampling_tbl_size}),await k.queryTolerant(F.GET_SAMPLED_DATA(s,l),[a])},async _retrieveSingleViewData(t,e,r){_e.progress("Get view data",e,r),r=my(r);let n=await k.query(F.GET_VIEW_DATA,[r,e],!0),s=!n.view_definition&&await k.queryTolerant(F.GET_VIEW_SELECT_STMT_FALLBACK,[r,e],!0),o=await k.queryTolerant(F.GET_VIEW_OPTIONS,[r,t],!0),a=dy(r,n,s),c=hy(n,o);return a?{name:r,data:c,ddl:{script:a,type:"postgres"}}:(_e.info("View select statement was not retrieved",{schemaName:e,viewName:r}),{name:r,data:c,jsonSchema:{properties:[]}})},async _getServerVersion(){let t=await k.queryTolerant(F.GET_VERSION_AS_NUM,[],!0),e=J.toNumber(t==null?void 0:t.server_version_num);return e>=1e5&&e<11e4?10:e>=11e4&&e<12e4?11:e>=12e4&&e<13e4?12:e>=13e4&&e<14e4?13:(e>=14e4&&e<15e4,14)}};var gy=i(t=>!!(J.startsWith(t,"pg_")||J.includes(["information_schema"],t)),"isSystemSchema"),Ey=i(t=>t===10?F.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:F.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL,"getGetFunctionsAdditionalDataQuery"),_y=i(t=>t==null?void 0:t.obj_description,"getDescriptionFromResult"),Ct=i((t,e)=>Promise.all(J.map(t,e)),"mapPromises")});var tc=C((GS,ec)=>{"use strict";var{createLogger:Wt}=tr(),X=Zn();ec.exports={async disconnect(t,e,r,n){await X.disconnect(),r()},async testConnection(t,e,r,n){try{Jn("Test connection",t,e);let s=Wt({title:"Test connection instance log",hiddenKeys:t.hiddenKeys,logger:e});X.setDependencies(n),await X.connect(t,s),await X.pingDb(),await X.logVersion(),r()}catch(s){e.log("error",Ue(s),"Test connection instance log"),r(Ue(s))}finally{await X.disconnect()}},async getDatabases(t,e,r,n){try{Jn("Get databases",t,e);let s=Wt({title:"Get DB names",hiddenKeys:t.hiddenKeys,logger:e});X.setDependencies(n),await X.connect(t,s),await X.logVersion();let o=await X.getDatabaseNames();return e.log("info",o,"All databases list",t.hiddenKeys),r(null,o)}catch(s){return e.log("error",s),r(Ue(s))}},getDocumentKinds:function(t,e,r){r(null,[])},async getDbCollectionsNames(t,e,r,n){try{Jn("Get DB table names",t,e);let s=Wt({title:"Get DB collections names",hiddenKeys:t.hiddenKeys,logger:e});X.setDependencies(n),await X.connect(t,s),await X.logVersion();let a=await(await X.getAllSchemasNames()).reduce(async(c,l)=>{let u=await c;try{let p=await X.getTablesNames(l);return u.concat({dbName:l,dbCollections:p,isEmpty:p.length===0})}catch(p){return s.info(`Error reading database "${l}"`),s.error(p),u.concat({dbName:l,dbCollections:[],isEmpty:!0,status:!0})}},Promise.resolve([]));r(null,a)}catch(s){e.log("error",Ue(s),"Get DB collections names"),r(Ue(s)),await X.disconnect()}},async getDbCollectionsData(t,e,r,n){try{e.log("info",t,"Retrieve tables data:",t.hiddenKeys);let s=Wt({title:"Get DB collections data log",hiddenKeys:t.hiddenKeys,logger:e});s.progress("Start reverse engineering...");let o=t.collectionData.collections,a=t.collectionData.dataBaseNames,c=await X.getDbLevelData(),{packages:l,relationships:u}=await Promise.all(a.map(async p=>{let{tables:d,views:h,modelDefinitions:f}=await X.retrieveEntitiesData(p,o[p],t.recordSamplingSettings),{functions:S,procedures:y}=await X.retrieveSchemaLevelData(p,t.ignoreUdfUdpTriggers);return s.progress("Schema data fetched successfully",p),{schemaName:p,tables:d,views:h,functions:S,procedures:y,modelDefinitions:f}})).then(p=>{let d=p.flatMap(({tables:f})=>f.map(S=>S.relationships)).flat();return{packages:p.flatMap(({schemaName:f,tables:S,views:y,functions:T,procedures:_,modelDefinitions:D})=>{let N={UDFs:T,Procedures:_},O=S.map(R=>({dbName:f,collectionName:R.name,documents:R.documents,views:[],emptyBucket:!1,entityLevel:R.entityLevel,validation:{jsonSchema:R.jsonSchema},bucketInfo:N,modelDefinitions:D})).sort(R=>n.require("lodash").isEmpty(R.entityLevel.inherits)?-1:1);if(y!=null&&y.length){let R={dbName:f,views:y,emptyBucket:!1};return[...O,R]}return O}),relationships:d}}).then(({packages:p,relationships:d})=>({packages:Sy(p),relationships:d}));s.info("The data is processed and sent to the application",{packagesLength:l==null?void 0:l.length,relationshipsLength:u==null?void 0:u.length}),r(null,l,c,u)}catch(s){e.log("error",Ue(s),"Retrieve tables data"),r(Ue(s))}finally{await X.disconnect()}}};var Ue=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError"),Jn=i((t,e,r)=>{r.clear(),r.log("info",e,"connectionInfo",e.hiddenKeys)},"logInfo"),Sy=i(t=>t.sort((e,r)=>!e.collectionName&&!r.collectionName?0:e.collectionName?r.collectionName?e.collectionName.localeCompare(r.collectionName):-1:1),"orderPackages")});var nc=C((HS,rc)=>{"use strict";var Yt=Zn(),Ty=i(async(t,e,r)=>{try{Yt.setDependencies(r),await Yt.connect(t,e),await Yt.logVersion(),await Yt.applyScript(Cy(t.script))}catch(n){throw e.error(n),Ay(n)}},"applyToInstance"),Cy=i(t=>{let e=/CREATE DATABASE[^;]*;/gi;return t.replace(e,"")},"removeCreateDbScript"),Ay=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError");rc.exports={applyToInstance:Ty}});var se=C((WS,sc)=>{"use strict";var rs=class rs{script;isDropScript};i(rs,"ModificationScript");var es=rs,ns=class ns{isActivated;scripts;static getInstances(e,r,n){return(e||[]).filter(Boolean).map(s=>({isActivated:r,scripts:[{isDropScript:n,script:s}]}))}static getInstance(e,r,n){var s;if((s=e==null?void 0:e.filter(Boolean))!=null&&s.length)return{isActivated:r,scripts:e.filter(Boolean).map(o=>({isDropScript:n,script:o}))}}static getDropAndRecreateInstance(e,r,n){let s=[];if(e&&s.push({isDropScript:!0,script:e}),r&&s.push({isDropScript:!1,script:r}),!!(s!=null&&s.length))return{isActivated:n,scripts:s}}};i(ns,"AlterScriptDto");var ts=ns;sc.exports={ModificationScript:es,AlterScriptDto:ts}});var Je=C((jS,ic)=>{"use strict";var ls=class ls{id;constraintName;indexStorageParameters;indexInclude};i(ls,"AlterCollectionColumnPrimaryKeyOptionDto");var ss=ls,ps=class ps{type;isActivated;primaryKey;unique;mode;length;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;primaryKeyOptions;triggerUpdateColumns;compMod;GUID};i(ps,"AlterCollectionColumnDto");var is=ps,ms=class ms extends ss{compositePrimaryKey};i(ms,"AlterCollectionRoleCompModPKDto");var os=ms,ds=class ds{new;old};i(ds,"AlterCollectionRoleCompModPrimaryKey");var as=ds,fs=class fs{id;type;collectionName;properties;definitions;isActivated;additionalProperties;memory_optimized;collectionUsers;ifNotExist;on_commit;bucketId;compMod;name;roleType;patternProperties};i(fs,"AlterCollectionRoleDto");var cs=fs,hs=class hs{type;isActivated;unique;subtype;properties;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;triggerUpdateColumns;role;GUID};i(hs,"AlterCollectionDto");var us=hs;ic.exports={AlterCollectionDto:us,AlterCollectionRoleDto:cs,AlterCollectionColumnDto:is,AlterCollectionRoleCompModPrimaryKey:as,AlterCollectionRoleCompModPKDto:os}});var ac=C((XS,oc)=>{"use strict";var Ny=Object.freeze({ALL:"ALL",ANALYSE:"ANALYSE",ANALYZE:"ANALYZE",AND:"AND",ANY:"ANY",ARRAY:"ARRAY",ASC:"ASC",ASYMMETRIC:"ASYMMETRIC",AUTHORIZATION:"AUTHORIZATION",BINARY:"BINARY",BOTH:"BOTH",CASE:"CASE",CAST:"CAST",CHECK:"CHECK",COLLATE:"COLLATE",COLUMN:"COLUMN",CONCURRENTLY:"CONCURRENTLY",CONSTRAINT:"CONSTRAINT",CREATE:"CREATE",CROSS:"CROSS",CURRENT_CATALOG:"CURRENT_CATALOG",CURRENT_DATE:"CURRENT_DATE",CURRENT_ROLE:"CURRENT_ROLE",CURRENT_SCHEMA:"CURRENT_SCHEMA",CURRENT_TIME:"CURRENT_TIME",CURRENT_TIMESTAMP:"CURRENT_TIMESTAMP",CURRENT_USER:"CURRENT_USER",DEFAULT:"DEFAULT",DEFERRABLE:"DEFERRABLE",DESC:"DESC",DISTINCT:"DISTINCT",DO:"DO",ELSE:"ELSE",END:"END",EXCEPT:"EXCEPT",FALSE:"FALSE",FOR:"FOR",FOREIGN:"FOREIGN",FREEZE:"FREEZE",FROM:"FROM",FULL:"FULL",GRANT:"GRANT",GROUP:"GROUP",HAVING:"HAVING",ILIKE:"ILIKE",IN:"IN",INITIALLY:"INITIALLY",INTERSECT:"INTERSECT",INTO:"INTO",IS:"IS",ISNULL:"ISNULL",JOIN:"JOIN",LATERAL:"LATERAL",LEADING:"LEADING",LEFT:"LEFT",LIKE:"LIKE",LIMIT:"LIMIT",LOCALTIME:"LOCALTIME",LOCALTIMESTAMP:"LOCALTIMESTAMP",NATURAL:"NATURAL",NOT:"NOT",NULL:"NULL",OFFSET:"OFFSET",ON:"ON",ONLY:"ONLY",OR:"OR",ORDER:"ORDER",OUTER:"OUTER",OVERLAPS:"OVERLAPS",PLACING:"PLACING",PRIMARY:"PRIMARY",REFERENCES:"REFERENCES",RETURNING:"RETURNING",RIGHT:"RIGHT",SELECT:"SELECT",SESSION_USER:"SESSION_USER",SIMILAR:"SIMILAR",SOME:"SOME",SYMMETRIC:"SYMMETRIC",TABLE:"TABLE",TABLESAMPLE:"TABLESAMPLE",THEN:"THEN",TO:"TO",TRAILING:"TRAILING",TRUE:"TRUE",UNION:"UNION",UNIQUE:"UNIQUE",USER:"USER",USING:"USING",VARIADIC:"VARIADIC",VERBOSE:"VERBOSE",WHEN:"WHEN",WHERE:"WHERE",WINDOW:"WINDOW",WITH:"WITH"}),by=Object.values(Ny);oc.exports={ReservedWordsAsArray:by}});var q=C((eT,cc)=>{"use strict";var{AlterCollectionDto:ZS,AlterCollectionRoleDto:JS}=Je(),{ReservedWordsAsArray:vy}=ac(),wy=/\t|\n|'|\f|\r/gm;cc.exports=t=>{let e=i(g=>t.get(g,"[0].code")||t.get(g,"[0].name",""),"getDbName"),r=i(g=>g&&(g.code||g.collectionName)||"","getEntityName"),n=i(g=>g&&(g.code||g.name)||"","getViewName"),s=i(g=>Object.assign({},t.get(g,"[0]",{}),{name:e(g)}),"getDbData"),o=i(g=>t.get(g,"[0].viewOn"),"getViewOn"),a=i((g,w=" ")=>g.split(` +`).map(M=>w+M).join(` +`),"tab"),c=i((g,w)=>Object.keys(g).map(t.toLower).includes(t.toLower(w)),"hasType"),l=i(g=>({...g,...t.omit(g==null?void 0:g.role,"properties")||{}}),"getSchemaOfAlterCollection"),u=i(g=>{var $;let w=r(g),M=($=g.compMod)==null?void 0:$.keyspaceName;return U(w,M)},"getFullCollectionName"),p=i(g=>Object.entries(g).filter(([w,M])=>!t.isNil(M)).reduce((w,[M,$])=>({...w,[M]:$}),{}),"clean"),d=i(g=>g.every(w=>t.get(w,"isActivated",!0)),"checkAllKeysActivated"),h=i(g=>g.length?g.every(w=>!t.get(w,"isActivated",!0)):!1,"checkAllKeysDeactivated"),f=i((g,w)=>{let M=g.filter(Y=>t.get(Y,"isActivated",!0)).map(w),$=g.filter(Y=>!t.get(Y,"isActivated",!0)).map(w);return{activatedItems:M,deactivatedItems:$}},"divideIntoActivatedAndDeactivated"),S=i((g,{isActivated:w,isPartOfLine:M,inlineComment:$="--"})=>g?w!==!1?g:M?"/* "+g+" */":g.includes(` +`)?`/* +`+g+` */ +`:$+" "+g:"","commentIfDeactivated"),y=i((g,w="'",M="'")=>{let $=g[0];return g[g.length-1]===w&&$===M?g:`${w}${g}${M}`},"wrap"),T=i((g,w)=>w.some(M=>(g==null?void 0:g.oldField[M])!==(g==null?void 0:g.newField[M])),"checkFieldPropertiesChanged"),_=i(g=>{var Y;let w={...g,...t.omit(g==null?void 0:g.role,"properties")||{}},M=r(w),$=(Y=w.compMod)==null?void 0:Y.keyspaceName;return U(M,$)},"getFullTableName"),D=i((g,w)=>`${_(g)}.${W(w)}`,"getFullColumnName"),N=i(g=>{var Y;let w={...g,...t.omit(g==null?void 0:g.role,"properties")||{}},M=n(w),$=(Y=w.compMod)==null?void 0:Y.keyspaceName;return U(M,$)},"getFullViewName"),O=i(g=>g.code||g.name,"getUdtName"),R=i((g="")=>{let w=g.match(/\d+/);return Number(t.get(w,[0],0))},"getDbVersion"),A=i((g="")=>g.replace(wy,w=>`\\${w}`),"prepareComment"),b=i(g=>`E'${A(JSON.stringify(g)).slice(1,-1)}'`,"wrapComment"),x=i(g=>t.map(g,w=>{let M=w.defaultExpression?`DEFAULT ${w.defaultExpression}`:"";return t.trim(`${w.argumentMode} ${w.argumentName||""} ${w.argumentType} ${M}`)}).join(", "),"getFunctionArguments"),U=i((g,w)=>w?`${W(w)}.${W(g)}`:W(g),"getNamePrefixedWithSchemaName"),W=i(g=>/\s|\W/.test(g)||t.includes(vy,t.toUpper(g))?`"${g}"`:g,"wrapInQuotes"),Se=i(({name:g})=>W(g),"columnMapToString"),Te=i((g,w,M,$=Se)=>{var E;let Y=f(g,$),m=(E=Y==null?void 0:Y.deactivatedItems)!=null&&E.length?S(Y.deactivatedItems.join(", "),{isActivated:!1,isPartOfLine:!0}):"";return!w&&M?" ("+Y.activatedItems.join(", ")+m+")":" ("+g.map($).join(", ")+")"},"getColumnsList"),Ae=i(g=>g?g.alias?`${W(g.name)} as ${W(g.alias)}`:W(g.name):"","getKeyWithAlias");return{getDbName:e,getDbData:s,getEntityName:r,getViewName:n,getViewOn:o,tab:a,hasType:c,clean:p,checkAllKeysActivated:d,checkAllKeysDeactivated:h,divideIntoActivatedAndDeactivated:f,commentIfDeactivated:S,wrap:y,checkFieldPropertiesChanged:T,getFullTableName:_,getFullColumnName:D,getFullViewName:N,getUdtName:O,getDbVersion:R,wrapComment:b,getFunctionArguments:x,getNamePrefixedWithSchemaName:U,wrapInQuotes:W,getColumnsList:Te,getViewData:i(g=>Array.isArray(g)?g.reduce((w,M)=>{if(!M.tableName)return w.columns.push(Ae(M)),w;let $=`${W(M.dbName)}.${W(M.tableName)}`;return w.tables.includes($)||w.tables.push($),w.columns.push({statement:`${$}.${Ae(M)}`,isActivated:M.isActivated}),w},{tables:[],columns:[]}):{tables:[],columns:[]},"getViewData"),getSchemaOfAlterCollection:l,getFullCollectionName:u}}});var mc=C((rT,pc)=>{"use strict";var{AlterScriptDto:uc}=se(),lc=i(t=>{var e,r;return((r=(e=t==null?void 0:t.role)==null?void 0:e.compMod)==null?void 0:r.description)||{}},"extractDescription"),Oy=i((t,e)=>r=>{let{wrapComment:n,wrapInQuotes:s}=q()(t),o=lc(r);if(o.new&&o.new!==o.old){let a=n(o.new),c=s(r.role.name),l=e.updateSchemaComment(c,a);return uc.getInstance([l],!0,!1)}},"getUpsertCommentsScriptDto"),Iy=i((t,e)=>r=>{let{wrapInQuotes:n}=q()(t),s=lc(r);if(s.old&&!s.new){let o=n(r.role.name),a=e.dropSchemaComment(o);return uc.getInstance([a],!0,!0)}},"getDropCommentsScriptDto"),Ry=i((t,e)=>r=>{let n=Oy(t,e)(r),s=Iy(t,e)(r);return[n,s].filter(Boolean)},"getModifySchemaCommentsScriptDtos");pc.exports={getModifySchemaCommentsScriptDtos:Ry}});var fc=C((sT,dc)=>{"use strict";dc.exports={number:"numeric",string:"text",date:"date",timestamp:"timestamp",binary:"bytea",boolean:"boolean",document:"jsonb",array:"jsonb",objectId:"uuid",default:"char"}});var yc=C((iT,hc)=>{"use strict";hc.exports={char:{size:1},varchar:{mode:"varying"},text:{mode:"text"},bit:{size:1,mode:"bit"},varbit:{size:1,mode:"varying"},tsvector:{mode:"text"},tsquery:{mode:"text"},smallint:{capacity:2},integer:{capacity:4},bigint:{capacity:8},numeric:{capacity:12,mode:"decimal"},real:{capacity:4,mode:"floating"},"double precision":{capacity:8,mode:"floating"},smallserial:{capacity:2},serial:{capacity:4},bigserial:{capacity:8},money:{capacity:8,mode:"decimal"},bytea:{size:4,mode:"binary"},date:{format:"YYYY-MM-DD"},time:{format:"hh:mm:ss.nnnnnn"},timestamp:{format:"YYYY-MM-DD hh:mm:ss"},interval:{format:"PnYnMnDTnHnMnS"},boolean:{mode:"boolean"},int4range:{mode:"range",modeType:"integer",capacity:4},int8range:{mode:"range",modeType:"integer",capacity:8},numrange:{mode:"range",modeType:"decimal",capacity:12},daterange:{mode:"range",modeType:"date",format:"YYYY-MM-DD"},tsrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},int4multirange:{mode:"multirange",modeType:"integer",capacity:4},int8multirange:{mode:"multirange",modeType:"integer",capacity:8},nummultirange:{mode:"multirange",modeType:"decimal",capacity:12},datemultirange:{mode:"multirange",modeType:"date",format:"YYYY-MM-DD"},tsmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},geometry:{format:"euclidian",mode:"geospatial"},geography:{format:"euclidian",mode:"geospatial"},box2d:{format:"euclidian",mode:"geospatial"},box3d:{format:"euclidian",mode:"geospatial"},geometry_dump:{format:"euclidian",mode:"geospatial"},point:{format:"euclidian",mode:"geospatial"},line:{format:"euclidian",mode:"geospatial"},lseg:{format:"euclidian",mode:"geospatial"},box:{format:"euclidian",mode:"geospatial"},path:{format:"euclidian",mode:"geospatial"},polygon:{format:"euclidian",mode:"geospatial"},circle:{format:"euclidian",mode:"geospatial"},inet:{mode:"ip"},cidr:{mode:"ip"},macaddr:{},macaddr8:{},uuid:{mode:"uuid"},oid:{mode:"uuid"},regclass:{},regcollation:{},regconfig:{},regdictionary:{},regnamespace:{},regoper:{},regoperator:{},regproc:{},regprocedure:{},regrole:{},regtype:{},xml:{mode:"xml"},json:{format:"semi-structured"},jsonb:{format:"semi-structured"},int:{},int2:{},int4:{},decimal:{},float:{},composite:{format:"semi-structured",mode:"object"},enum:{mode:"enum"},range_udt:{mode:"range"},domain:{mode:"domain"}}});var Ec=C((oT,gc)=>{"use strict";gc.exports={createDatabase:"CREATE DATABASE ${name}${template}${encoding}${collate}${characterClassification};\n",createSchema:"CREATE SCHEMA${ifNotExist} ${name};\nSET search_path TO ${name};\n\n${comment}\n",comment:"COMMENT ON ${object} ${objectName} IS ${comment};\n",createTable:"CREATE${temporary} TABLE${ifNotExist} ${name} (\n${columnDefinitions}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n)${options};\n\n${comment}${columnDescriptions}",createTablePartitionOf:"CREATE${temporary} TABLE${ifNotExist} ${name}\n${partitionOf} ${openParenthesis}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n${closeParenthesis}${options};\n\n${comment}${columnDescriptions}",generatedColumnClause:" GENERATED ALWAYS AS (${generationExpression}) STORED",columnDefinition:"${name} ${type}${collation}${generatedColumnClause}${primaryKey}${uniqueKey}${defaultValue}${notNull}",checkConstraint:"${name} CHECK (${expression})${notValid}",createForeignKeyConstraint:"${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable} (${primaryKey})${match}${onDelete}${onUpdate}",createKeyConstraint:"${constraintName}${keyType}${columns}${includeNonKey}${storageParameters}",alterColumnType:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET DATA TYPE ${dataType};",addNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET NOT NULL;",dropNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} DROP NOT NULL;",renameColumn:"ALTER TABLE IF EXISTS ${tableName} RENAME COLUMN ${oldColumnName} TO ${newColumnName};",addCheckConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD CONSTRAINT ${constraintName} CHECK (${expression});",dropConstraint:"ALTER TABLE IF EXISTS ${tableName} DROP CONSTRAINT IF EXISTS ${constraintName};",createForeignKey:"ALTER TABLE IF EXISTS ${foreignTable} ADD CONSTRAINT ${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable}(${primaryKey})${match}${onDelete}${onUpdate};",dropForeignKey:"ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName};",addPkConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD ${constraintStatement};",dropTable:"DROP TABLE IF EXISTS ${tableName};",addColumn:"ALTER TABLE IF EXISTS ${tableName} ADD COLUMN IF NOT EXISTS ${columnDefinition};",dropColumn:"ALTER TABLE IF EXISTS ${tableName} DROP COLUMN IF EXISTS ${columnName};",dropDomain:"DROP DOMAIN IF EXISTS ${udtName};",dropType:"DROP TYPE IF EXISTS ${udtName};",alterTypeAddAttribute:"ALTER TYPE ${udtName} ADD ATTRIBUTE ${columnDefinition};",alterTypeDropAttribute:"ALTER TYPE ${udtName} DROP ATTRIBUTE IF EXISTS ${attributeName};",alterTypeRenameAttribute:"ALTER TYPE ${udtName} RENAME ATTRIBUTE ${oldAttributeName} TO ${newAttributeName};",alterTypeChangeAttributeType:"ALTER TYPE ${udtName} ALTER ATTRIBUTE ${attributeName} SET DATA TYPE ${newDataType};",updateCommentOnTable:"COMMENT ON TABLE ${tableName} IS ${comment};",updateCommentOnColumn:"COMMENT ON COLUMN ${columnName} IS ${comment};",updateCommentOnSchema:"COMMENT ON SCHEMA ${schemaName} IS ${comment};",updateCommentOnView:"COMMENT ON VIEW ${viewName} IS ${comment};",createSchemaOnly:"CREATE SCHEMA IF NOT EXISTS ${schemaName};",dropSchema:"DROP SCHEMA IF EXISTS ${schemaName};",index:"CREATE${unique} INDEX${concurrently}${ifNotExist} ${name}\n ON ${tableName}${using}${keys}${options};\n",createView:"CREATE${orReplace}${temporary} VIEW ${name}${withOptions}\nAS ${selectStatement}${checkOption};\n\n${comment}\n",viewSelectStatement:"SELECT ${keys}\n FROM ${tableName}",dropView:"DROP VIEW IF EXISTS ${viewName};",createFunction:"CREATE${orReplace} FUNCTION ${name}\n (${parameters})\n RETURNS ${returnType}\n LANGUAGE ${language}\n${properties}AS $BODY$\n${definition}\n$BODY$;\n",createProcedure:"CREATE${orReplace} PROCEDURE ${name} (${parameters})\n LANGUAGE ${language}\nAS $BODY$\n${body}\n$BODY$;\n",createCompositeType:`CREATE TYPE \${name} AS ( + \${columnDefinitions} +); -module.exports = { - generateScript(data, logger, callback, app) { - try { - const script = buildEntityLevelAlterScript(data, app); - callback(null, script); - } catch (error) { - logger.log('error', {message: error.message, stack: error.stack}, 'CockroachDB Forward-Engineering Error'); +\${comment}`,createEnumType:"CREATE TYPE ${name} AS ENUM (${values});\n\n${comment}",createRangeType:"CREATE TYPE ${name} AS RANGE (\n SUBTYPE=${subtype}${options}\n);\n\n${comment}",createDomainType:"CREATE DOMAIN ${name} AS ${underlyingType}${notNull}${collate}${default}${constraints};\n\n${comment}"}});var Tc=C((aT,Sc)=>{"use strict";var _c=i((t="")=>new RegExp("\\$\\{(.*?)\\}",t),"template"),Py=i(t=>t.match(_c("gi"))||[],"getAllTemplates"),Dy=i(t=>(t.match(_c("i"))||[])[1],"parseTemplate"),Ly=i((t,e)=>Py(t).reduce((r,n)=>{let s=Dy(n);return r.replace(n,()=>e[s]||e[s]===0?e[s]:"")},t),"assignTemplates");Sc.exports=Ly});var Ac=C((uT,Cc)=>{"use strict";Cc.exports=({_:t,commentIfDeactivated:e,checkAllKeysDeactivated:r,assignTemplates:n,wrapInQuotes:s,getColumnsList:o})=>({generateConstraintsString:i((h,f)=>{var _,D;let S=e(((h==null?void 0:h.deactivatedItems)||[]).join(`, + `),{isActivated:!f,isPartOfLine:!0}),y=(_=h==null?void 0:h.activatedItems)!=null&&_.length?`, + `+h.activatedItems.join(`, + `):"",T=(D=h==null?void 0:h.deactivatedItems)!=null&&D.length?` + `+S:"";return y+T},"generateConstraintsString"),foreignKeysToString:i(h=>{if(Array.isArray(h)){let f=h.filter(T=>t.get(T,"isActivated",!0)).map(T=>s(t.trim(T.name))),S=h.filter(T=>!t.get(T,"isActivated",!0)).map(T=>s(t.trim(T.name))),y=S.length?e(S,{isActivated:!1,isPartOfLine:!0}):"";return f.join(", ")+y}return h},"foreignKeysToString"),foreignActiveKeysToString:i(h=>h.map(f=>t.trim(f.name)).join(", "),"foreignActiveKeysToString"),createKeyConstraint:i((h,f)=>S=>{let y=s(t.trim(S.name)),T=r(S.columns||[]),_=t.isEmpty(S.columns)?"":o(S.columns,T,f),D=S.include.length?` INCLUDE${o(S.include,T,f)}`:"",N=S.storageParameters?` WITH (${S.storageParameters})`:"";return{statement:n(h.createKeyConstraint,{constraintName:S.name?`CONSTRAINT ${y} `:"",keyType:S.keyType,columns:_,includeNonKey:D,storageParameters:N}),isActivated:!T}},"createKeyConstraint"),getConstraintsWarnings:i((h=[])=>t.isEmpty(h)?"":` + `+h.map(f=>{let S=f.name?` [constraint name: ${f.name}]`:"";return`-- ${f.errorMessage}${S}`}).join(` + `),"getConstraintsWarnings"),additionalPropertiesForForeignKey:i(h=>{let f=t.get(h,"relationshipOnDelete",""),S=t.get(h,"relationshipOnUpdate",""),y=t.get(h,"relationshipMatch","");return{foreignOnDelete:f,foreignOnUpdate:S,foreignMatch:y}},"additionalPropertiesForForeignKey")})});var bc=C((pT,Nc)=>{"use strict";Nc.exports=(t,e)=>{let r=i((y,T)=>Object.entries(y.properties).map(T),"mapProperties"),n=i(y=>y.compositeUniqueKey?!1:!!y.unique,"isUniqueKey"),s=i(y=>{var T,_;return n(y)&&(((T=y.uniqueKeyOptions)==null?void 0:T.length)===1&&!((_=t.first(y.uniqueKeyOptions))!=null&&_.constraintName)||t.isEmpty(y.uniqueKeyOptions))},"isInlineUnique"),o=i(y=>y.compositeUniqueKey||y.compositePrimaryKey?!1:!!y.primaryKey,"isPrimaryKey"),a=i(y=>{var T;return o(y)&&!((T=t.first(y.primaryKeyOptions))!=null&&T.constraintName)},"isInlinePrimaryKey"),c=i(({options:y,columnName:T,isActivated:_,jsonSchema:D,dbVersion:N})=>e({keyType:"UNIQUE",name:y.constraintName,columns:[{name:T,isActivated:_}],include:d(y.indexInclude||[],D),storageParameters:y.indexStorageParameters,comment:y.indexComment}),"hydrateUniqueOptions"),l=i((y,T,_,D)=>e({keyType:"PRIMARY KEY",name:y.constraintName,columns:[{name:T,isActivated:_}],include:d(y.indexInclude||[],D),storageParameters:y.indexStorageParameters,comment:y.indexComment}),"hydratePrimaryKeyOptions"),u=i((y,T)=>Object.keys(T).find(_=>T[_].GUID===y),"findName"),p=i((y,T)=>t.get(Object.values(T).find(_=>_.GUID===y),"isActivated",!0),"checkIfActivated"),d=i((y,T)=>t.map(y,_=>({name:u(_.keyId,T.properties),isActivated:p(_.keyId,T.properties)})),"getKeys"),h=i(y=>Array.isArray(y.primaryKey)?y.primaryKey.map(T=>t.isEmpty(T.compositePrimaryKey)?{name:T.constraintName,errorMessage:"A primary key constraint cannot be created without any primary key selected"}:{...l(T,null,null,y),columns:d(T.compositePrimaryKey,y)}):[],"getCompositePrimaryKeys"),f=i((y,T)=>Array.isArray(y.uniqueKey)?y.uniqueKey.map(_=>t.isEmpty(_.compositeUniqueKey)?{name:_.constraintName,errorMessage:"A unique key constraint cannot be created without any unique key selected"}:{...c({options:_,columnName:null,isActivated:null,jsonSchema:y,dbVersion:T}),columns:d(_.compositeUniqueKey,y)}):[],"getCompositeUniqueKeys");return{getTableKeyConstraints:i((y,T)=>{if(!y.properties)return[];let _=r(y,([N,O])=>{if(!(!o(O)||a(O)))return l(t.first(O.primaryKeyOptions),N,O.isActivated,y)}).filter(Boolean),D=t.flatten(r(y,([N,O])=>!n(O)||s(O)?[]:(O.uniqueKeyOptions||[]).map(R=>c({options:R,columnName:N,isActivated:O.isActivated,jsonSchema:y,dbVersion:T})))).filter(Boolean);return[..._,...h(y),...D,...f(y,T)]},"getTableKeyConstraints"),isInlineUnique:s,isInlinePrimaryKey:a,getKeys:d,hydratePrimaryKeyOptions:l,hydrateUniqueOptions:c}}});var wc=C((dT,vc)=>{"use strict";vc.exports=({_:t,templates:e,assignTemplates:r,getFunctionArguments:n,getNamePrefixedWithSchemaName:s,wrapComment:o})=>{let a=i((N,O)=>t.map(O,R=>{let A=R.functionOrReplace?" OR REPLACE":"",b=r(e.createFunction,{name:s(R.name,N),orReplace:A,parameters:n(R.functionArguments),returnType:R.functionReturnsSetOf?`SETOF ${R.functionReturnType}`:R.functionReturnType,language:R.functionLanguage,properties:c(R),definition:R.functionBody}),x=R.functionDescription?r(e.comment,{object:"FUNCTION",objectName:s(R.name,N),comment:o(R.functionDescription)}):"";return[b,x].filter(Boolean).join(` +`)}).join(` +`),"getFunctionsScript"),c=i(N=>{let O=i(R=>R?` ${R} +`:"","wrap");return[{key:"functionWindow",getValue:l},{key:"functionVolatility",getValue:u},{key:"functionLeakProof",getValue:p},{key:"functionNullArgs",getValue:d},{key:"functionSqlSecurity",getValue:h},{key:"functionParallel",getValue:f},{key:"functionExecutionCost",getValue:S},{key:"functionExecutionRows",getValue:y},{key:"functionSupportFunction",getValue:T},{key:"functionConfigurationParameters",getValue:_}].map(R=>O(R.getValue(N[R.key],N))).filter(Boolean).join("")},"getProperties"),l=i((N,O)=>O.language!=="c"||!N?"":"WINDOW","getWindow"),u=i(N=>N,"getVolatility"),p=i(N=>N?"LEAKPROOF":"NOT LEAKPROOF","getLeakProof"),d=i(N=>N,"getNullArgs"),h=i(N=>{if(N)return`SECURITY ${N}`},"getSqlSecurity"),f=i(N=>{if(N)return`PARALLEL ${N}`},"getParallel"),S=i(N=>{if(N)return`COST ${N}`},"getExecutionCost"),y=i((N,O)=>!N||!O.functionReturnsSetOf&&!D(O)?"":`ROWS ${N}`,"getExecutionRows"),T=i(N=>{if(N)return`SUPPORT ${N}`},"getSupportFunction"),_=i(N=>{if(N)return`SET ${N}`},"getConfigurationParameters"),D=i(N=>(N.functionReturnType||"").trim().toUpperCase().startsWith("TABLE"),"isFunctionReturnsTable");return{getFunctionsScript:a}}});var Ic=C((hT,Oc)=>{"use strict";Oc.exports=({_:t,templates:e,assignTemplates:r,getFunctionArguments:n,getNamePrefixedWithSchemaName:s})=>({getProceduresScript:i((a,c)=>t.map(c,l=>{let u=l.orReplace?" OR REPLACE":"";return r(e.createProcedure,{name:s(l.name,a),orReplace:u,parameters:n(l.inputArgs),language:l.language,body:l.body})}).join(` +`),"getProceduresScript")})});var Pc=C((gT,Rc)=>{"use strict";Rc.exports=({_:t,getColumnsList:e,checkAllKeysDeactivated:r})=>{let n=i((p,d)=>p?" TEMPORARY":d?" UNLOGGED":"","getTableTemporaryValue"),s=i(p=>{let d=i(f=>f?`${f} +`:"","wrap"),h=[{key:"inherits",getValue:l("INHERITS")},{key:"partitionBounds",getValue:l("")},{key:"partitioning",getValue:o},{key:"usingMethod",getValue:l("USING")},{key:"storage_parameter",getValue:u},{key:"on_commit",getValue:c},{key:"selectStatement",getValue:l("AS")}].map(f=>d(f.getValue(p[f.key],p))).filter(Boolean).join("");return t.trim(h)?` ${t.trim(h)}`:""},"getTableOptions"),o=i((p,{isActivated:d})=>{if(p&&p.partitionMethod){let f=a(p,d)+` (${p.partitioning_expression})`;return`PARTITION BY ${p.partitionMethod}${f}`}},"getPartitioning"),a=i((p,d)=>{let h=r(p.compositePartitionKey);return e(p.compositePartitionKey,h,d)},"getPartitionKeys"),c=i((p,d)=>{if(p&&d.temporary)return`ON COMMIT ${p}`},"getOnCommit"),l=i(p=>d=>{if(d)return`${p} ${d}`},"getBasicValue"),u=i(p=>{if(t.isEmpty(p))return"";let d=["ttl_storage_parameters"],h=["id",...d];return t.chain(p).toPairs().flatMap(([f,S])=>d.includes(f)?t.toPairs(S):[[f,S]]).reject(([f])=>t.includes(h,f)).map(([f,S])=>{if(!(!S&&S!==0))return`${f}=${S}`}).compact().join(`, + `).trim().thru(f=>{if(f)return`WITH ( + ${f} +)`}).value()},"getStorageParameters");return{getTableTemporaryValue:n,getTableOptions:s}}});var Lc=C((_T,Dc)=>{"use strict";Dc.exports=({_:t,commentIfDeactivated:e,assignTemplates:r,templates:n,getNamePrefixedWithSchemaName:s,wrapComment:o})=>{let a=["composite","enum","range_udt","domain"],c=i((f,S)=>{let y=s(f.name,f.schemaName),T=r(n.comment,{object:"TYPE",objectName:y,comment:o(f.comment)});switch(f.type){case"composite":return r(n.createCompositeType,{name:y,columnDefinitions:t.join(S,`, + `),comment:f.comment?T:""});case"enum":return r(n.createEnumType,{name:y,values:t.map(f.enum,_=>`'${_}'`).join(", "),comment:f.comment?T:""});case"range_udt":return r(n.createRangeType,{name:y,subtype:f.rangeSubtype,options:u(f),comment:f.comment?T:""});case"domain":{let _=r(n.comment,{object:"DOMAIN",objectName:y,comment:o(f.comment)});return r(n.createDomainType,{name:y,underlyingType:f.underlyingType,notNull:f.nullable?"":" NOT NULL",collate:f.collation?` + COLLATE ${f.collation}`:"",default:f.default?` + DEFAULT ${f.default}`:"",constraints:p(f),comment:f.comment?_:""})}default:return""}},"getPlainUdt"),l=i(f=>a.includes(f.type),"isNotPlainType"),u=i(f=>{let S=i(T=>T?` ${T}`:"","wrap"),y=[{key:"operatorClass",getValue:d("SUBTYPE_OPCLASS")},{key:"collation",getValue:d("COLLATION")},{key:"canonicalFunction",getValue:d("CANONICAL")},{key:"subtypeDiffFunction",getValue:d("SUBTYPE_DIFF")},{key:"multiRangeType",getValue:d("MULTIRANGE_TYPE_NAME")}].map(T=>S(T.getValue(f[T.key]))).filter(Boolean).join(`, +`);return t.trim(y)?`, + `+t.trim(y):""},"getRangeOptions"),p=i(f=>t.map(f.checkConstraints,S=>S.name?` + CONSTRAINT ${S.name} CHECK (${S.expression})`:` + CHECK (${S.expression})`).join(""),"getDomainConstraints"),d=i(f=>S=>{if(S)return`${f}=${S}`},"getBasicValue");return{getUserDefinedType:i((f,S)=>e(c(f,S),{isActivated:f.isActivated}),"getUserDefinedType"),isNotPlainType:l}}});var Mc=C((TT,xc)=>{"use strict";xc.exports=({_:t,wrapInQuotes:e,checkAllKeysDeactivated:r,getColumnsList:n})=>{let s=i(({name:u,sortOrder:p,nullsOrder:d,opclass:h})=>{let f=p?` ${p}`:"",S=d?` ${d}`:"",y=h?` ${h}`:"";return`${e(u)}${y}${f}${S}`},"mapIndexKey"),o=i((u=[],p)=>{let d=r(u);return n(u,d,p,s)},"getIndexKeys"),a=i((u,p)=>{var O;let d=n(u.include||[],r(u.include||[]),p),h=["btree"],f=u.using_hash&&h.includes(u.index_method)?" USING HASH":"",S=(O=u.include)!=null&&O.length?` INCLUDE ${t.trim(d)}`:"",y=u.partitioning_expression||"",T=c(u),_=T?` WITH ( + ${T})`:"",D=u.where?` WHERE ${u.where}`:"",N=u.visibility?` ${u.visibility}`:"";return t.compact([" ",f,S,y,_,D,N]).join(` +`)},"getIndexOptions"),c=i(u=>{let p=["id"];return t.chain(u.index_storage_parameter).toPairs().map(([d,h])=>{if(!(p.includes(d)||t.isNil(h)||h===""))return`${d}=${l(h)}`}).compact().join(`, + `).value()},"getWithOptions"),l=i(u=>t.isBoolean(u)?u?"ON":"OFF":u,"getValue");return{getIndexKeys:o,getIndexOptions:a}}});var kc=C((AT,qc)=>{"use strict";qc.exports=({_:t,assignTemplates:e,templates:r,commentIfDeactivated:n,wrapComment:s,wrapInQuotes:o})=>{let a=i((A,b)=>`${A}(${b})`,"addLength"),c=i((A,b,x)=>t.isNumber(x)?`${A}(${b},${x})`:`${A}(${b})`,"addScalePrecision"),l=i((A,b)=>t.isNumber(b)?`${A}(${b})`:A,"addPrecision"),u=i((A,b)=>b?`${A} ${b}`:A,"addWithTimezone"),p=i(({type:A,typeModifier:b,srid:x})=>{let U=x?`, ${x}`:"";return b&&b!==""?`${A}(${b}${U})`:A},"addTypeModifier"),d=i((A,b)=>{let x=(b==null?void 0:b.map(U=>`[${(U==null?void 0:U.array_size_limit)??""}]`).join("").trim())||"";return`${A}${x}`},"addArrayDecorator"),h=i(A=>["char","varchar","bit","varbit"].includes(A),"canHaveLength"),f=i(A=>["numeric","decimal"].includes(A),"canHavePrecision"),S=i(A=>["time","timestamp"].includes(A),"canHaveTimePrecision"),y=i(A=>["numeric","decimal"].includes(A),"canHaveScale"),T=i(A=>["geography","geometry"].includes(A),"canHaveTypeModifier"),_=i((A,b)=>(h(A)&&t.isNumber(b.length)?A=a(A,b.length):f(A)&&y(A)&&t.isNumber(b.precision)?A=c(A,b.precision,b.scale):f(A)&&t.isNumber(b.precision)?A=l(A,b.precision):T(A)?A=p({type:A,typeModifier:b.typeModifier,srid:b.srid}):S(A)&&(t.isNumber(b.timePrecision)||b.timezone)&&(A=u(l(A,b.timePrecision),b.timezone)),d(A,b.array_type)),"decorateType"),D=i(A=>["char","varchar","text","bit","varbit"].includes(A),"isString"),N=i(A=>["date","time","timestamp","interval"].includes(A),"isDateTime");return{decorateType:_,decorateDefault:i((A,b,x)=>{let U=["current_timestamp","null"];return(D(A)||N(A))&&!U.includes(t.toLower(b))&&!x?s(b):b},"decorateDefault"),getColumnComments:i((A,b)=>t.chain(b).filter("comment").map(x=>{let U=e(r.comment,{object:"COLUMN",objectName:`${A}.${o(x.name)}`,comment:s(x.comment)});return n(U,x)}).join(` +`).value(),"getColumnComments")}}});var ee=C((bT,Bc)=>{"use strict";var xy=fc(),Fc=yc(),P=Ec();Bc.exports=(t,e,r)=>{let n=r.require("lodash"),{tab:s,commentIfDeactivated:o,checkAllKeysDeactivated:a,divideIntoActivatedAndDeactivated:c,hasType:l,wrap:u,clean:p,wrapComment:d,getFunctionArguments:h,wrapInQuotes:f,getNamePrefixedWithSchemaName:S,getColumnsList:y,getViewData:T}=q()(n),_=Tc(),{generateConstraintsString:D,foreignKeysToString:N,foreignActiveKeysToString:O,createKeyConstraint:R,getConstraintsWarnings:A,additionalPropertiesForForeignKey:b}=Ac()({_:n,commentIfDeactivated:o,checkAllKeysDeactivated:a,assignTemplates:_,getColumnsList:y,wrapInQuotes:f}),x=bc()(n,p),{getFunctionsScript:U}=wc()({_:n,templates:P,assignTemplates:_,getFunctionArguments:h,getNamePrefixedWithSchemaName:S,wrapComment:d}),{getProceduresScript:W}=Ic()({_:n,templates:P,assignTemplates:_,getFunctionArguments:h,getNamePrefixedWithSchemaName:S}),{getTableTemporaryValue:Se,getTableOptions:Te}=Pc()({_:n,checkAllKeysDeactivated:a,getColumnsList:y}),{getUserDefinedType:Ae,isNotPlainType:Re}=Lc()({_:n,commentIfDeactivated:o,assignTemplates:_,templates:P,getNamePrefixedWithSchemaName:S,wrapComment:d}),{getIndexKeys:g,getIndexOptions:w}=Mc()({_:n,wrapInQuotes:f,checkAllKeysDeactivated:a,getColumnsList:y}),{decorateType:M,decorateDefault:$,getColumnComments:Y}=kc()({_:n,wrap:u,assignTemplates:_,templates:P,commentIfDeactivated:o,wrapInQuotes:f,wrapComment:d});return{createDatabase(m){if(!m.databaseName)return"";let{collate:E,characterClassification:v}=m;return _(P.createDatabase,{name:f(m.databaseName),template:m.template?` + TEMPLATE ${m.template}`:"",encoding:m.encoding?` + ENCODING = '${m.encoding}'`:"",collate:E?` + LC_COLLATE = '${m.collate}'`:"",characterClassification:v?` + LC_CTYPE = '${v}'`:""})},createSchema({schemaName:m,ifNotExist:E,comments:v,udfs:I,procedures:K}){let ne=_(P.comment,{object:"SCHEMA",objectName:f(m),comment:d(v)}),Z=_(P.createSchema,{name:f(m),ifNotExist:E?" IF NOT EXISTS":"",comment:v?ne:""}),j=U(m,I),ie=W(m,K);return n.chain([Z,j,ie]).compact().map(n.trim).join(` - callback({message: error.message, stack: error.stack}); - } - }, +`).trim().value()},createTable({name:m,columns:E,checkConstraints:v,foreignKeyConstraints:I,schemaData:K,columnDefinitions:ne,keyConstraints:Z,inherits:j,description:ie,ifNotExist:pe,usingMethod:he,on_commit:z,partitioning:fe,storage_parameter:Ne,temporary:be,unlogged:Ce,selectStatement:ve,partitionOf:ce,partitionBounds:Le},we){let Nt=pe?" IF NOT EXISTS":"",Ke=S(m,K.schemaName),bt=_(P.comment,{object:"TABLE",objectName:Ke,comment:d(ie)}),ye=c(Z.filter(({errorMessage:Me})=>!Me).map(R(P,we)),Me=>Me.statement),er=A(Z.filter(({errorMessage:Me})=>Me)),xe=`${D(ye,we)}${er}`,si=ce?xe==null?void 0:xe.slice(1):xe,Ku=c(I,Me=>Me.statement),ii=D(Ku,we),Gu=` +`+Y(Ke,ne),Vu=ce?P.createTablePartitionOf:P.createTable,Hu=ce&&!xe?` + `:`, + `,oi=n.isEmpty(v)?"":u(n.join(v,`, + `),Hu,""),ai=ce&&!si&&!oi&&!ii,Qu=ai?"":"(",Wu=ai?"":")",Yu=_(Vu,{temporary:Se(be,Ce),ifNotExist:Nt,name:Ke,columnDefinitions:ce?"":" "+n.join(E,`, + `),keyConstraints:si,checkConstraints:oi,foreignKeyConstraints:ii,options:Te({inherits:j,partitioning:fe,usingMethod:he,on_commit:z,storage_parameter:Ne,selectStatement:ve,partitionBounds:Le}),comment:ie?bt:"",partitionOf:ce?` PARTITION OF ${ce} `:"",columnDescriptions:Gu,openParenthesis:Qu,closeParenthesis:Wu});return o([Yu].map(n.trim).join(` - generateViewScript(data, logger, callback, app) { - callback(new Error('Forward-Engineering of delta model on view level is not supported')); - }, +`).trim()+` +`,{isActivated:we})},convertColumnDefinition(m){let E=m.nullable?"":" NOT NULL",v=m.primaryKey?" "+R(P,!0)(m.primaryKeyOptions).statement:"",I=m.unique?" "+R(P,!0)(m.uniqueKeyOptions).statement:"",K=m.collationRule?` COLLATE "${m.collationRule}"`:"",ne=Array.isArray(m.array_type)&&m.array_type.length>0,Z=n.isUndefined(m.default)?"":" DEFAULT "+$(m.type,m.default,ne),j=m.dbVersion>=12&&m.generatedColumn&&m.columnGenerationExpression?_(P.generatedColumnClause,{generationExpression:m.columnGenerationExpression}):"";return o(_(P.columnDefinition,{name:f(m.name),type:M(m.type,m),generatedColumnClause:j,notNull:E,primaryKey:v,uniqueKey:I,collation:K,defaultValue:Z}),{isActivated:m.isActivated})},createIndex(m,E,v,I=!0){let K=E.unique&&E.index_method==="btree",ne=f(E.indxName),Z=K?" UNIQUE":"",j=E.concurrently?" CONCURRENTLY":"",ie=E.ifNotExist?" IF NOT EXISTS":"",pe=E.index_method?` USING ${n.toUpper(E.index_method)}`:"",he=g(E.index_method==="btree"?E.columns:n.map(E.columns,fe=>n.omit(fe,"sortOrder","nullsOrder")),I),z=w(E,I);return o(_(P.index,{unique:Z,concurrently:j,ifNotExist:ie,name:ne,using:pe,keys:he,options:z,tableName:S(m,E.schemaName)}),{isActivated:E.isActivated})},createCheckConstraint(m){return _(P.checkConstraint,{name:m.name?`CONSTRAINT ${f(m.name)}`:"",expression:n.trim(m.expression).replace(/^\(([\s\S]*)\)$/,"$1"),notValid:m.notValid?" NOT VALID":""})},createForeignKeyConstraint({name:m,foreignKey:E,primaryTable:v,primaryKey:I,primaryTableActivated:K,foreignTableActivated:ne,foreignSchemaName:Z,primarySchemaName:j,customProperties:ie,isActivated:pe},he,z){let fe=a(I),Ne=a(E),be=!fe&&!Ne&&K&&ne,{foreignOnDelete:Ce,foreignOnUpdate:ve,foreignMatch:ce}=b(ie),Le=_(P.createForeignKeyConstraint,{primaryTable:S(v,j||z.schemaName),name:m?`CONSTRAINT ${f(m)}`:"",foreignKey:be?N(E):O(E),primaryKey:be?N(I):O(I),onDelete:Ce?` ON DELETE ${Ce}`:"",onUpdate:ve?` ON UPDATE ${ve}`:"",match:ce?` MATCH ${ce}`:""});return{statement:n.trim(Le),isActivated:be&&pe}},createForeignKey({name:m,foreignTable:E,foreignKey:v,primaryTable:I,primaryKey:K,primaryTableActivated:ne,foreignTableActivated:Z,foreignSchemaName:j,primarySchemaName:ie,customProperties:pe,isActivated:he},z,fe){let Ne=a(K),be=a(v),Ce=!Ne&&!be&&ne&&Z,{foreignOnDelete:ve,foreignOnUpdate:ce,foreignMatch:Le}=b(pe),we=_(P.createForeignKey,{primaryTable:S(I,ie||fe.schemaName),foreignTable:S(E,j||fe.schemaName),name:m?f(m):"",foreignKey:Ce?N(v):O(v),primaryKey:Ce?N(K):O(K),onDelete:ve?` ON DELETE ${ve}`:"",onUpdate:ce?` ON UPDATE ${ce}`:"",match:Le?` MATCH ${Le}`:""});return{statement:n.trim(we),isActivated:Ce&&he}},createView(m,E,v){var we,Nt,Ke,bt;let I=S(m.name,m.schemaName),K=_(P.comment,{object:"VIEW",objectName:I,comment:d(m.comment)}),Z=a(m.keys||[])||!v,{columns:j,tables:ie}=T(m.keys),pe=j.map(ye=>ye.statement).join(`, + `);if(!Z){let ye=c(j,xe=>xe.statement),er=ye.deactivatedItems.length?o(ye.deactivatedItems.join(`, + `),{isActivated:!1,isPartOfLine:!0}):"";pe=ye.activatedItems.join(`, + `)+er}let he=n.trim(m.selectStatement)?n.trim(s(m.selectStatement)):_(P.viewSelectStatement,{tableName:ie.join(", "),keys:pe}),z=(we=m.viewOptions)!=null&&we.check_option?`check_option=${(Nt=m.viewOptions)==null?void 0:Nt.check_option}`:"",fe=(Ke=m.viewOptions)!=null&&Ke.security_barrier?"security_barrier":"",Ne=15,{getDbVersion:be}=q()(n),Ce=(bt=m.viewOptions)!=null&&bt.security_invoker&&be(E.dbVersion)>=Ne?"security_invoker":"",ve=z||fe||Ce?` + WITH (${n.compact([z,fe,Ce]).join(",")})`:"",ce=i(ye=>ye.withCheckOption&&ye.checkTestingScope?` + WITH ${ye.checkTestingScope} CHECK OPTION`:ye.withCheckOption?` + WITH CHECK OPTION`:"","getCheckOption");return[o(_(P.createView,{name:I,orReplace:m.orReplace?" OR REPLACE":"",temporary:m.temporary?" TEMPORARY":"",checkOption:ce(m),comment:m.comment?K:"",withOptions:ve,selectStatement:he}),{isActivated:!Z})].map(n.trim).join(` - generateContainerScript(data, logger, callback, app) { - try { - const script = buildContainerLevelAlterScript(data, app); - callback(null, script); - } catch (error) { - logger.log('error', {message: error.message, stack: error.stack}, 'CockroachDB Forward-Engineering Error'); +`).trim()+` +`},dropView(m){let E={viewName:m};return _(P.dropView,E)},createViewIndex(){return""},createUdt(m){let E=n.map(m.properties,this.convertColumnDefinition);return Ae(m,E)},getDefaultType(m){return xy[m]},getTypesDescriptors(){return Fc},hasType(m){return l(Fc,m)},hydrateDatabase({modelData:m}){return m=n.get(m,"0",{}),{databaseName:m.database_name,encoding:m.encoding,template:m.template,collate:m.LC_COLLATE,characterClassification:m.LC_CTYPE,dbVersion:m.dbVersion}},hydrateColumn({columnDefinition:m,jsonSchema:E,schemaData:v,definitionJsonSchema:I={},parentJsonSchema:K}){let ne=n.includes(["char","varchar","text"],m.type)?E.collationRule:"",Z=["time","timestamp"],j=n.includes(Z,m.type)?E.timePrecision:"",ie=n.includes(Z,m.type)?E.timezone:"",pe=m.type==="interval"?E.intervalOptions:"",{getDbVersion:he}=q()(n),z=he(v.dbVersion),fe=n.omit(x.hydratePrimaryKeyOptions(n.first(E.primaryKeyOptions)||{},m.name,m.isActivated,K),"columns"),Ne=n.omit(x.hydrateUniqueOptions({options:n.first(E.uniqueKeyOptions)||{},columnName:m.name,isActivated:m.isActivated,jsonSchema:K,dbVersion:z}),"columns");return{name:m.name,type:m.type,primaryKey:x.isInlinePrimaryKey(E),primaryKeyOptions:fe,unique:x.isInlineUnique(E),uniqueKeyOptions:Ne,nullable:m.nullable,default:m.default,comment:E.refDescription||E.description||I.description,isActivated:m.isActivated,scale:m.scale,precision:m.precision,length:m.length,enum:E.enum,array_type:E.array_type,unit:E.unit,rangeSubtype:E.rangeSubtype,operatorClass:E.operatorClass,collation:E.collation,canonicalFunction:E.canonicalFunction,subtypeDiffFunction:E.subtypeDiffFunction,multiRangeType:E.multiRangeType,schemaName:v.schemaName,underlyingType:E.underlyingType,checkConstraints:E.checkConstraints,typeModifier:E.typeModifier,srid:E.srid,collationRule:ne,timePrecision:j,timezone:ie,intervalOptions:pe,dbVersion:z,generatedColumn:!!E.generatedColumn,columnGenerationExpression:E.columnGenerationExpression}},hydrateJsonSchemaColumn(m,E){return!m.$ref||n.isEmpty(E)||Re(E)?m:(m=n.omit(m,"$ref"),{...E,...m})},hydrateIndex(m,E,v){return{...m,schemaName:v.schemaName}},hydrateViewIndex(m){return{}},hydrateCheckConstraint(m){return{name:m.chkConstrName,expression:m.constrExpression,notValid:m.notValid}},hydrateSchema(m,E){let v=n.get(E,"modelData.0.dbVersion");return{schemaName:m.name,ifNotExist:m.ifNotExist,comments:m.description,udfs:(E==null?void 0:E.udfs)||[],procedures:(E==null?void 0:E.procedures)||[],dbVersion:v}},hydrateTable({tableData:m,entityData:E,jsonSchema:v}){let I=E[0],K=n.chain(I.inherits).map(({parentTable:z})=>n.get(m,`relatedSchemas[${z}]`,"")).compact().map(z=>z.code||z.collectionName).join(", ").thru(z=>z?`(${z})`:"").value(),ne=n.first(I.partitioning)||{},Z=x.getKeys(ne.compositePartitionKey,v),j=n.get(m,`relatedSchemas[${I.partitionOf}]`),ie=j?S(j.collectionName,j.bucketName):"",{getDbVersion:pe}=q()(n),he=pe(n.get(m,"dbData.dbVersion",""));return{...m,partitionOf:ie,keyConstraints:x.getTableKeyConstraints(v,he),inherits:K,selectStatement:n.trim(I.selectStatement),partitioning:n.assign({},ne,{compositePartitionKey:Z}),...n.pick(I,"temporary","unlogged","description","ifNotExist","usingMethod","on_commit","storage_parameter","partitionBounds")}},hydrateViewColumn(m){return{name:m.name,tableName:m.entityName,alias:m.alias,isActivated:m.isActivated,dbName:m.dbName}},hydrateView({viewData:m,entityData:E,relatedSchemas:v}){let I=E[0];return{name:m.name,keys:m.keys,comment:I.description,orReplace:I.orReplace,temporary:I.temporary,recursive:I.recursive,viewOptions:I.viewOptions,selectStatement:I.selectStatement,withCheckOption:I.withCheckOption,checkTestingScope:I.withCheckOption?I.checkTestingScope:"",schemaName:m.schemaData.schemaName}},commentIfDeactivated(m,E,v){return m},alterColumnType(m,E,v,I){let K=v;return I.length?K+=`(${I.length})`:I.precision&&I.scale?K+=`(${I.precision},${I.scale})`:I.precision&&(K+=`(${I.precision})`),_(P.alterColumnType,{tableName:m,columnName:E,dataType:K})},setNotNullConstraint(m,E){return _(P.addNotNullConstraint,{tableName:m,columnName:E})},dropNotNullConstraint(m,E){return _(P.dropNotNullConstraint,{tableName:m,columnName:E})},renameColumn(m,E,v){return _(P.renameColumn,{tableName:m,oldColumnName:E,newColumnName:v})},addCheckConstraint(m,E,v){let I={tableName:m,constraintName:E,expression:v};return _(P.addCheckConstraint,I)},dropConstraint(m,E){let v={tableName:m,constraintName:E};return _(P.dropConstraint,v)},updateTableComment(m,E){let v={tableName:m,comment:E};return _(P.updateCommentOnTable,v)},dropTableComment(m){let E={tableName:m,comment:"NULL"};return _(P.updateCommentOnTable,E)},updateColumnComment(m,E){let v={columnName:m,comment:E};return _(P.updateCommentOnColumn,v)},dropColumnComment(m){let E={columnName:m,comment:"NULL"};return _(P.updateCommentOnColumn,E)},updateSchemaComment(m,E){let v={schemaName:m,comment:E};return _(P.updateCommentOnSchema,v)},dropSchemaComment(m){let E={schemaName:m,comment:"NULL"};return _(P.updateCommentOnSchema,E)},updateViewComment(m,E){let v={viewName:m,comment:E};return _(P.updateCommentOnView,v)},dropViewComment(m){let E={viewName:m,comment:"NULL"};return _(P.updateCommentOnView,E)},createSchemaOnly(m){let E={schemaName:m};return _(P.createSchemaOnly,E)},dropSchema(m){let E={schemaName:m};return _(P.dropSchema,E)},dropTable(m){let E={tableName:m};return _(P.dropTable,E)},addColumn(m,E){let v={tableName:m,columnDefinition:E};return _(P.addColumn,v)},dropColumn(m,E){let v={tableName:m,columnName:E};return _(P.dropColumn,v)},dropDomain(m){let E={udtName:m};return _(P.dropDomain,E)},dropType(m){let E={udtName:m};return _(P.dropType,E)},alterTypeAddAttribute(m,E){let v={udtName:m,columnDefinition:E};return _(P.alterTypeAddAttribute,v)},alterTypeDropAttribute(m,E){let v={udtName:m,attributeName:E};return _(P.alterTypeDropAttribute,v)},alterTypeRenameAttribute(m,E,v){let I={udtName:m,oldAttributeName:E,newAttributeName:v};return _(P.alterTypeRenameAttribute,I)},alterTypeChangeAttributeType(m,E,v){let I={udtName:m,attributeName:E,newDataType:v};return _(P.alterTypeChangeAttributeType,I)},dropForeignKey(m,E){let v={tableName:m,fkConstraintName:E};return _(P.dropForeignKey,v)},createKeyConstraint(m,E,v){let I=R(P,E)(v);return{statement:_(P.addPkConstraint,{constraintStatement:(I.statement||"").trim(),tableName:m}),isActivated:I.isActivated}},dropPkConstraint(m,E){let v={tableName:m,constraintName:E};return _(P.dropConstraint,v)}}}});var Kc=C((wT,$c)=>{"use strict";var{getModifySchemaCommentsScriptDtos:My}=mc(),{AlterScriptDto:Uc}=se(),qy=i(t=>e=>{let r=t.require("lodash"),n=ee()(null,null,t),{wrapInQuotes:s}=q()(r),o=n.createSchemaOnly(s(e));return Uc.getInstance([o],!0,!1)},"getAddContainerScriptDto"),ky=i(t=>e=>{let r=t.require("lodash"),n=ee()(null,null,t),{wrapInQuotes:s}=q()(r),o=n.dropSchema(s(e));return Uc.getInstance([o],!0,!0)},"getDeleteContainerScriptDto"),Fy=i(t=>e=>{let r=t.require("lodash"),n=ee()(null,null,t);return[...My(r,n)(e)]},"getModifyContainerScriptDtos");$c.exports={getAddContainerScriptDto:qy,getDeleteContainerScriptDto:ky,getModifyContainerScriptDtos:Fy}});var Vc=C((RT,Gc)=>{"use strict";var{AlterCollectionDto:IT}=Je(),{AlterScriptDto:jt}=se(),By=i(t=>e=>{var a;let r=(a=e==null?void 0:e.compMod)==null?void 0:a.chkConstr;if(!r)return[];let n=r.new||[],s=r.old||[];return t.chain([...n,...s]).map(c=>c.chkConstrName).uniq().value().map(c=>({old:t.find(s,{chkConstrName:c}),new:t.find(n,{chkConstrName:c})}))},"mapCheckConstraintNamesToChangeHistory"),Uy=i((t,e)=>(r,n)=>{let{wrapInQuotes:s}=q()(t);return r.filter(o=>o.old&&!o.new).map(o=>{let a=s(o.old.chkConstrName);return e.dropConstraint(n,a)}).map(o=>jt.getInstance([o],!0,!0))},"getDropCheckConstraintScriptDtos"),$y=i((t,e)=>(r,n)=>{let{wrapInQuotes:s}=q()(t);return r.filter(o=>o.new&&!o.old).map(o=>{let{chkConstrName:a,constrExpression:c}=o.new;return e.addCheckConstraint(n,s(a),c)}).map(o=>jt.getInstance([o],!0,!1))},"getAddCheckConstraintScriptDtos"),Ky=i((t,e)=>(r,n)=>{let{wrapInQuotes:s}=q()(t);return r.filter(o=>{if(o.old&&o.new){let a=o.old.constrExpression,c=o.new.constrExpression;return a!==c}return!1}).map(o=>{let{chkConstrName:a}=o.old,c=e.dropConstraint(n,s(a)),{chkConstrName:l,constrExpression:u}=o.new,p=e.addCheckConstraint(n,s(l),u);return[jt.getInstance([c],!0,!0),jt.getInstance([p],!0,!1)]}).flat()},"getUpdateCheckConstraintScriptDtos"),Gy=i((t,e)=>r=>{let{getFullTableName:n}=q()(t),s=n(r),o=By(t)(r),a=$y(t,e)(o,s),c=Uy(t,e)(o,s),l=Ky(t,e)(o,s);return[...a,...c,...l]},"getModifyCheckConstraintScriptDtos");Gc.exports={getModifyCheckConstraintScriptDtos:Gy}});var Wc=C((LT,Qc)=>{"use strict";var{AlterScriptDto:Hc}=se(),{AlterCollectionDto:DT}=Je(),Vy=i((t,e)=>r=>{var d;let{getFullTableName:n,wrapComment:s}=q()(t),o=(d=r==null?void 0:r.role.compMod)==null?void 0:d.description;if(!o)return;let{old:a,new:c}=o;if(!c||c===a)return;let l=n(r),u=s(c),p=e.updateTableComment(l,u);return Hc.getInstance([p],!0,!1)},"getUpdatedCommentOnCollectionScriptDto"),Hy=i((t,e)=>r=>{var u;let{getFullTableName:n}=q()(t),s=(u=r==null?void 0:r.role.compMod)==null?void 0:u.description;if(!s)return;let{old:o,new:a}=s;if(!o||a)return;let c=n(r),l=e.dropTableComment(c);return Hc.getInstance([l],!0,!0)},"getDeletedCommentOnCollectionScriptDto"),Qy=i((t,e)=>r=>{let n=Vy(t,e)(r),s=Hy(t,e)(r);return[n,s].filter(Boolean)},"getModifyEntityCommentsScriptDtos");Qc.exports={getModifyEntityCommentsScriptDtos:Qy}});var jc=C((MT,Yc)=>{"use strict";var{AlterScriptDto:Wy}=se(),Yy=i((t,e,r)=>{let n=t.role.properties[e],s=n==null?void 0:n.length,o=r==null?void 0:r.length;return s!==o},"hasLengthChanged"),jy=i((t,e,r)=>{let n=t.role.properties[e],s=n==null?void 0:n.precision,o=r==null?void 0:r.precision,a=n==null?void 0:n.scale,c=r==null?void 0:r.scale;return s!==o||a!==c},"hasPrecisionOrScaleChanged"),zy=i((t,e)=>r=>{let{checkFieldPropertiesChanged:n,getFullTableName:s,wrapInQuotes:o}=q()(t),a=s(r);return t.toPairs(r.properties).filter(([c,l])=>{let u=n(l.compMod,["type","mode"]);if(!u){let p=l.compMod.oldField.name,d=Yy(r,p,l),h=jy(r,p,l);return d||h}return u}).map(([c,l])=>{let u=l.compMod.newField.mode||l.compMod.newField.type,p=o(c),d=t.pick(l,["length","precision","scale"]);return e.alterColumnType(a,p,u,d)}).map(c=>Wy.getInstance([c],!0,!1))},"getUpdateTypesScriptDtos");Yc.exports={getUpdateTypesScriptDtos:zy}});var Zc=C((kT,Xc)=>{"use strict";var{AlterScriptDto:zc}=se(),Xy=i((t,e)=>r=>{let{getFullTableName:n,wrapInQuotes:s}=q()(t),o=n(r),a=r.required||[],c=r.role.required||[],l=t.difference(a,c),u=t.difference(c,a),p=t.toPairs(r.properties).filter(([h,f])=>{let S=f.compMod.oldField.name,y=u.includes(S);return l.includes(h)&&!y}).map(([h])=>e.setNotNullConstraint(o,s(h))).map(h=>zc.getInstance([h],!0,!1)),d=t.toPairs(r.properties).filter(([h,f])=>{let S=f.compMod.oldField.name,y=u.includes(S),T=l.includes(h);return y&&!T}).map(([h])=>e.dropNotNullConstraint(o,s(h))).map(h=>zc.getInstance([h],!0,!0));return[...p,...d]},"getModifyNonNullColumnsScriptDtos");Xc.exports={getModifyNonNullColumnsScriptDtos:Xy}});var tu=C((BT,eu)=>{"use strict";var{AlterScriptDto:Jc}=se(),Zy=i((t,e)=>r=>{let{getFullColumnName:n,wrapComment:s}=q()(t);return t.toPairs(r.properties).filter(([o,a])=>{var p;let c=a.description,l=a.compMod.oldField.name,u=(p=r.role.properties[l])==null?void 0:p.description;return c&&(!u||c!==u)}).map(([o,a])=>{let c=a.description,l=s(c),u=n(r,o);return e.updateColumnComment(u,l)}).map(o=>Jc.getInstance([o],!0,!1))},"getUpdatedCommentOnColumnScriptDtos"),Jy=i((t,e)=>r=>{let{getFullColumnName:n}=q()(t);return t.toPairs(r.properties).filter(([s,o])=>{var u;let a=o.description,c=o.compMod.oldField.name;return((u=r.role.properties[c])==null?void 0:u.description)&&!a}).map(([s,o])=>{let a=n(r,s);return e.dropColumnComment(a)}).map(s=>Jc.getInstance([s],!0,!0))},"getDeletedCommentOnColumnScriptDtos"),eg=i((t,e)=>r=>{let n=Zy(t,e)(r),s=Jy(t,e)(r);return[...n,...s]},"getModifiedCommentOnColumnScriptDtos");eu.exports={getModifiedCommentOnColumnScriptDtos:eg}});var nu=C(($T,ru)=>{"use strict";var{AlterScriptDto:tg}=se(),rg=i((t,e)=>r=>{let{checkFieldPropertiesChanged:n,getFullTableName:s,wrapInQuotes:o}=q()(t),a=s(r);return t.values(r.properties).filter(c=>n(c.compMod,["name"])).map(c=>{let l=o(c.compMod.oldField.name),u=o(c.compMod.newField.name);return e.renameColumn(a,l,u)}).map(c=>tg.getInstance([c],!0,!1))},"getRenameColumnScriptDtos");ru.exports={getRenameColumnScriptDtos:rg}});var cu=C((YT,au)=>{"use strict";var{AlterScriptDto:ng}=se(),{AlterCollectionDto:GT,AlterCollectionColumnDto:VT,AlterCollectionRoleCompModPKDto:HT,AlterCollectionColumnPrimaryKeyOptionDto:QT,AlterCollectionRoleCompModPrimaryKey:WT}=Je(),et=1,gs=class gs{didTransitionHappen;wasPkChangedInTransition;static noTransition(){return{didTransitionHappen:!1}}static transition(e){return{didTransitionHappen:!0,wasPkChangedInTransition:e}}};i(gs,"PkTransitionDto");var ae=gs,Es=class Es{script;isDropScript;fullTableName;isActivated;constructor(e,r,n,s){this.script=e,this.isDropScript=n,this.fullTableName=r,this.isActivated=s}};i(Es,"PkScriptModificationDto");var tt=Es,ys=i(t=>`${t}_pkey`,"getDefaultConstraintName"),su=i(t=>({constraintName:t.constraintName,indexStorageParameters:t.indexStorageParameters,indexInclude:t.indexInclude}),"extractOptionsForComparisonWithRegularPkOptions"),rt=i(t=>(t.primaryKeyOptions||[]).map(r=>su(r)),"getCustomPropertiesOfRegularPkForComparisonWithRegularPkOptions"),zt=i(t=>[su(t)].filter(r=>Object.values(r).some(Boolean)),"getCustomPropertiesOfCompositePkForComparisonWithRegularPkOptions"),sg=i(t=>e=>{var p,d;let n=(((d=(p=e==null?void 0:e.role)==null?void 0:p.compMod)==null?void 0:d.primaryKey)||{}).old||[],s=n.flatMap(h=>h.compositePrimaryKey.map(f=>f.keyId));if(s.length!==et)return ae.noTransition();let o=s[0],a=Object.values(e.properties).find(h=>h.GUID===o);if(!a||!((a==null?void 0:a.primaryKey)&&!(a!=null&&a.compositePrimaryKey)))return ae.noTransition();let l=rt(a),u=n.some(h=>{if(h.compositePrimaryKey.length!==et)return!1;let f=zt(h);return t(f).differenceWith(l,t.isEqual).isEmpty()});return ae.transition(!u)},"wasCompositePkChangedInTransitionFromCompositeToRegular"),ig=i(t=>e=>{var p,d;let n=(((d=(p=e==null?void 0:e.role)==null?void 0:p.compMod)==null?void 0:d.primaryKey)||{}).new||[],s=n.flatMap(h=>h.compositePrimaryKey.map(f=>f.keyId));if(s.length!==et)return ae.noTransition();let o=s[0],a=Object.values(e.role.properties).find(h=>h.GUID===o);if(!a||!((a==null?void 0:a.primaryKey)&&!(a!=null&&a.compositePrimaryKey)))return ae.noTransition();let l=rt(a),u=n.some(h=>{if(h.compositePrimaryKey.length!==et)return!1;let f=zt(h);return t(f).differenceWith(l,t.isEqual).isEmpty()});return ae.transition(!u)},"wasCompositePkChangedInTransitionFromRegularToComposite"),og=i((t,e)=>t.constraintName?t.constraintName:ys(e),"getConstraintNameForCompositePk"),ag=i(t=>(e,r,n)=>{let s=og(e,r),o=t.toPairs(n.role.properties).filter(([l,u])=>!!e.compositePrimaryKey.find(p=>p.keyId===u.GUID)).map(([l,u])=>({name:l,isActivated:u.isActivated})),a="",c=[];return e.indexStorageParameters&&(a=e.indexStorageParameters),e.indexInclude&&(c=t.toPairs(n.role.properties).filter(([l,u])=>!!e.indexInclude.find(p=>p.keyId===u.GUID)).map(([l,u])=>({name:l,isActivated:u.isActivated}))),{name:s,keyType:"PRIMARY KEY",columns:o,include:c,storageParameters:a}},"getCreateCompositePKDDLProviderConfig"),cg=i((t,e)=>r=>{var f,S;let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:o}=q()(t),a=((S=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:S.primaryKey)||{},c=a.new||[],l=a.old||[];if(c.length===0&&l.length===0)return[];let u=ig(t)(r);if(u.didTransitionHappen&&!u.wasPkChangedInTransition)return[];if(c.length===l.length&&t(l).differenceWith(c,t.isEqual).isEmpty())return[];let p=s(r),d=n(p),h=o(p);return c.map(y=>{let T=ag(t)(y,h,r),_=e.createKeyConstraint(d,r.isActivated,T);return new tt(_.statement,d,!1,_.isActivated)}).filter(y=>!!y.script)},"getAddCompositePkScriptDtos"),ug=i((t,e)=>r=>{var S,y;let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:o,wrapInQuotes:a}=q()(t),c=((y=(S=r==null?void 0:r.role)==null?void 0:S.compMod)==null?void 0:y.primaryKey)||{},l=c.new||[],u=c.old||[];if(l.length===0&&u.length===0)return[];let p=sg(t)(r);if(p.didTransitionHappen&&!p.wasPkChangedInTransition)return[];if(l.length===u.length&&t(u).differenceWith(l,t.isEqual).isEmpty())return[];let d=s(r),h=n(d),f=o(d);return u.map(T=>{let _=ys(f);T.constraintName&&(_=T.constraintName);let D=a(_),N=e.dropPkConstraint(h,D);return new tt(N,h,!0,r.isActivated)}).filter(T=>!!T.script)},"getDropCompositePkScriptDtos"),lg=i((t,e)=>r=>{let n=ug(t,e)(r),s=cg(t,e)(r);return[...n,...s].filter(Boolean)},"getModifyCompositePkScriptDtos"),iu=i((t,e)=>{let r=t.primaryKeyOptions;if(r!=null&&r.length&&(r==null?void 0:r.length)>0){let n=r[0];if(n.constraintName)return n.constraintName}return ys(e)},"getConstraintNameForRegularPk"),pg=i(t=>(e,r,n,s)=>{let o=iu(r,n),a=[{name:e,isActivated:r.isActivated}],c="",l=[],u=r.primaryKeyOptions;if(u!=null&&u.length&&(u==null?void 0:u.length)>0){let p=u[0];p.indexStorageParameters&&(c=p.indexStorageParameters),p.indexInclude&&(l=t.toPairs(s.role.properties).filter(([d,h])=>!!p.indexInclude.find(f=>f.keyId===h.GUID)).map(([d,h])=>({name:d,isActivated:h.isActivated})))}return{name:o,keyType:"PRIMARY KEY",columns:a,include:l,storageParameters:c}},"getCreateRegularPKDDLProviderConfig"),mg=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n],o=e.primaryKey&&!e.compositePrimaryKey,a=!!(s!=null&&s.primaryKey);return o&&!a},"wasFieldChangedToBeARegularPk"),dg=i(t=>(e,r)=>{var f,S;let n=e.compMod.oldField.name,s=r.role.properties[n],o=e.primaryKey&&!e.compositePrimaryKey,a=!!(s!=null&&s.primaryKey);if(!(o&&a))return ae.noTransition();let c=((S=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:S.primaryKey)||{},l=c.new||[],u=c.old||[],p=u.some(y=>y.compositePrimaryKey.some(T=>T.keyId===s.GUID)),d=l.some(y=>y.compositePrimaryKey.some(T=>T.keyId===e.GUID));if(o&&(p&&!d)){let y=rt(e),T=u.some(_=>{if(_.compositePrimaryKey.length!==et)return!1;let D=zt(_);return t(D).differenceWith(y,t.isEqual).isEmpty()});return ae.transition(!T)}return ae.noTransition()},"wasRegularPkChangedInTransitionFromCompositeToRegular"),fg=i(t=>(e,r)=>{var f,S;let n=e.compMod.oldField.name,s=r.role.properties[n],o=s.primaryKey&&!s.compositePrimaryKey,a=!!(e!=null&&e.primaryKey);if(!(o&&a))return ae.noTransition();let c=((S=(f=r==null?void 0:r.role)==null?void 0:f.compMod)==null?void 0:S.primaryKey)||{},l=c.new||[],p=(c.old||[]).some(y=>y.compositePrimaryKey.some(T=>T.keyId===s.GUID)),h=l.some(y=>y.compositePrimaryKey.some(T=>T.keyId===e.GUID))&&!p;if(o&&h){let y=rt(s),T=l.some(_=>{if(_.compositePrimaryKey.length!==et)return!1;let D=zt(_);return t(D).differenceWith(y,t.isEqual).isEmpty()});return ae.transition(!T)}return ae.noTransition()},"wasRegularPkChangedInTransitionFromRegularToComposite"),hg=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n],o=(s==null?void 0:s.primaryKey)&&!(s!=null&&s.compositePrimaryKey),a=!e.primaryKey&&!e.compositePrimaryKey;return o&&a},"isFieldNoLongerARegularPk"),ou=i(t=>(e,r)=>{let n=e.compMod.oldField.name,s=r.role.properties[n]||{},o=e.primaryKey&&!e.compositePrimaryKey,a=(s==null?void 0:s.primaryKey)&&!(s!=null&&s.compositePrimaryKey);if(!(o&&a))return!1;let c=rt(e),l=rt(s);return!t(l).differenceWith(c,t.isEqual).isEmpty()},"wasRegularPkModified"),yg=i((t,e)=>r=>{let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:o}=q()(t),a=s(r),c=n(a),l=o(a);return t.toPairs(r.properties).filter(([u,p])=>{if(mg(t)(p,r))return!0;let d=dg(t)(p,r);return d.didTransitionHappen?d.wasPkChangedInTransition:ou(t)(p,r)}).map(([u,p])=>{let d=pg(t)(u,p,l,r),h=e.createKeyConstraint(c,r.isActivated,d);return new tt(h.statement,c,!1,h.isActivated)}).filter(u=>!!u.script)},"getAddPkScriptDtos"),gg=i((t,e)=>r=>{let{getFullCollectionName:n,getSchemaOfAlterCollection:s,getEntityName:o,wrapInQuotes:a}=q()(t),c=s(r),l=n(c),u=o(c);return t.toPairs(r.properties).filter(([p,d])=>{if(hg(t)(d,r))return!0;let h=fg(t)(d,r);return h.didTransitionHappen?h.wasPkChangedInTransition:ou(t)(d,r)}).map(([p,d])=>{let h=d.compMod.oldField.name,f=r.role.properties[h],S=a(iu(f,u)),y=e.dropPkConstraint(l,S);return new tt(y,l,!0,r.isActivated)}).filter(p=>!!p.script)},"getDropPkScriptDto"),Eg=i((t,e)=>r=>{let n=gg(t,e)(r),s=yg(t,e)(r);return[...n,...s].filter(Boolean)},"getModifyPkScriptDtos"),_g=i(t=>t.sort((e,r)=>e.fullTableName===r.fullTableName?Number(r.isDropScript)-Number(e.isDropScript):e.fullTableNamer=>{let n=lg(t,e)(r),s=Eg(t,e)(r),o=[...n,...s];return _g(o).map(c=>ng.getInstance([c.script],c.isActivated,c.isDropScript)).filter(Boolean)},"getModifyPkConstraintsScriptDtos");au.exports={getModifyPkConstraintsScriptDtos:Sg}});var At=C((zT,uu)=>{"use strict";uu.exports=t=>{let{createColumnDefinition:e}=t.require("@hackolade/ddl-fe-utils"),r=i(s=>s.$ref?s.$ref.split("/").pop():s.mode||s.childType||s.type,"getType");return{createColumnDefinitionBySchema:i(({name:s,jsonSchema:o,parentJsonSchema:a,ddlProvider:c,schemaData:l,definitionJsonSchema:u})=>e({name:s,jsonSchema:o,parentJsonSchema:a,ddlProvider:c,schemaData:l,definitionJsonSchema:u,getType:r}),"createColumnDefinitionBySchema")}}});var du=C((JT,mu)=>{"use strict";var{getModifyCheckConstraintScriptDtos:Tg}=Vc(),{getModifyEntityCommentsScriptDtos:Cg}=Wc(),{getUpdateTypesScriptDtos:Ag}=jc(),{getModifyNonNullColumnsScriptDtos:Ng}=Zc(),{getModifiedCommentOnColumnScriptDtos:bg}=tu(),{getRenameColumnScriptDtos:vg}=nu(),{AlterScriptDto:Xt}=se(),{AlterCollectionDto:ZT}=Je(),{getModifyPkConstraintsScriptDtos:wg}=cu(),Og=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>o=>{let a=t.require("lodash"),{getEntityName:c}=q()(a),{createColumnDefinitionBySchema:l}=At()(t),u=ee()(null,null,t),{getDefinitionByReference:p}=t.require("@hackolade/ddl-fe-utils"),h={schemaName:o.compMod.keyspaceName,dbVersion:e},f={...o,...a.omit(o==null?void 0:o.role,"properties")||{}},S=a.toPairs(f.properties).map(([N,O])=>{let R=p({propertySchema:O,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return l({name:N,jsonSchema:O,parentJsonSchema:f,ddlProvider:u,schemaData:h,definitionJsonSchema:R})}),y=(f.chkConstr||[]).map(N=>u.createCheckConstraint(u.hydrateCheckConstraint(N))),T={name:c(f),columns:S.map(u.convertColumnDefinition),checkConstraints:y,foreignKeyConstraints:[],schemaData:h,columnDefinitions:S,dbData:{dbVersion:e}},_=u.hydrateTable({tableData:T,entityData:[f],jsonSchema:f}),D=u.createTable(_,f.isActivated);return Xt.getInstance([D],!0,!1)},"getAddCollectionScriptDto"),Ig=i(t=>e=>{let r=t.require("lodash"),n=ee()(null,null,t),{getFullTableName:s}=q()(r),o=s(e),a=n.dropTable(o);return Xt.getInstance([a],!0,!0)},"getDeleteCollectionScriptDto"),Rg=i(t=>e=>{let r=t.require("lodash"),n=ee()(null,null,t),s=Tg(r,n)(e),o=Cg(r,n)(e),a=wg(r,n)(e);return[...s,...o,...a].filter(Boolean)},"getModifyCollectionScriptDtos"),lu=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>(o,a)=>{var D;let c=t.require("lodash"),{getEntityName:l,getNamePrefixedWithSchemaName:u}=q()(c),{createColumnDefinitionBySchema:p}=At()(t),d=ee()(null,null,t),{getDefinitionByReference:h}=t.require("@hackolade/ddl-fe-utils"),f={...o,...c.omit(o==null?void 0:o.role,"properties")||{}},S=l(f),y=(D=f.compMod)==null?void 0:D.keyspaceName,T=u(S,y),_={schemaName:y,dbVersion:e};return c.toPairs(o.properties).filter(([N,O])=>a([N,O])).map(([N,O])=>{let R=h({propertySchema:O,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return p({name:N,jsonSchema:O,parentJsonSchema:f,ddlProvider:d,schemaData:_,definitionJsonSchema:R})}).map(d.convertColumnDefinition).map(N=>d.addColumn(T,N)).map(N=>Xt.getInstance([N],!0,!1)).filter(Boolean)},"getAddColumnsByConditionScriptDtos"),Pg=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>o=>lu({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})(o,([a,c])=>!c.compMod),"getAddColumnScriptDtos"),pu=i(t=>(e,r)=>{var h;let n=t.require("lodash"),s=ee()(null,null,t),{getEntityName:o,getNamePrefixedWithSchemaName:a,wrapInQuotes:c}=q()(n),l={...e,...n.omit(e==null?void 0:e.role,"properties")||{}},u=o(l),p=(h=l.compMod)==null?void 0:h.keyspaceName,d=a(u,p);return n.toPairs(e.properties).filter(([f,S])=>r([f,S])).map(([f])=>{let S=c(f);return s.dropColumn(d,S)}).map(f=>Xt.getInstance([f],!0,!0)).filter(Boolean)},"getDeleteColumnsByConditionScriptDtos"),Dg=i(t=>e=>pu(t)(e,([r,n])=>!n.compMod),"getDeleteColumnScriptDtos"),Lg=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>o=>{let a=t.require("lodash");return a.toPairs(o.properties).filter(([c,l])=>{let u=l.compMod.oldField.name,p=o.role.properties[u];return p.generatedColumn!==l.generatedColumn||p.columnGenerationExpression!==l.columnGenerationExpression}).flatMap(([c,l])=>{let u={...o,properties:a.fromPairs([[c,l]])},p=pu(t)(u,()=>!0),d=lu({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})(u,()=>!0);return[...p,...d]}).filter(Boolean)},"getDropAndRecreateColumnsScriptDtos"),xg=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>o=>{let a=t.require("lodash"),c=ee()(null,null,t),l=vg(a,c)(o),u=Lg({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})(o);if(u.length)return[...l,...u].filter(Boolean);let p=Ag(a,c)(o),d=Ng(a,c)(o),h=bg(a,c)(o);return[...l,...p,...d,...h].filter(Boolean)},"getModifyColumnScriptDtos");mu.exports={getAddCollectionScriptDto:Og,getDeleteCollectionScriptDto:Ig,getModifyCollectionScriptDtos:Rg,getAddColumnScriptDtos:Pg,getDeleteColumnScriptDtos:Dg,getModifyColumnScriptDtos:xg}});var hu=C((tC,fu)=>{"use strict";var{AlterScriptDto:$e}=se(),Mg=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>o=>{let a=t.require("lodash"),{createColumnDefinitionBySchema:c}=At()(t),l=ee()(null,null,t),{getDefinitionByReference:u}=t.require("@hackolade/ddl-fe-utils"),p={dbVersion:e},d=a.toPairs(o.properties||{}).map(([y,T])=>{let _=u({propertySchema:T,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return c({name:y,jsonSchema:T,parentJsonSchema:o,ddlProvider:l,schemaData:p,definitionJsonSchema:_})}),f={...c({name:o.code||o.name,jsonSchema:o,parentJsonSchema:{required:[]},definitionJsonSchema:{},ddlProvider:l,schemaData:p}),properties:d},S=l.createUdt(f);return $e.getInstance([S],!0,!1)},"getCreateUdtScriptDto"),qg=i(t=>e=>{let r=t.require("lodash"),n=ee()(null,null,t),{getUdtName:s,wrapInQuotes:o}=q()(r),a=o(s(e));if(e.type==="domain"){let c=n.dropDomain(a);return $e.getInstance([c],!0,!0)}else{let c=n.dropType(a);return $e.getInstance([c],!0,!0)}},"getDeleteUdtScriptDto"),kg=i(({app:t,dbVersion:e,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s})=>o=>{let a=t.require("lodash"),{createColumnDefinitionBySchema:c}=At()(t),{getUdtName:l,wrapInQuotes:u}=q()(a),p=ee()(null,null,t),{getDefinitionByReference:d}=t.require("@hackolade/ddl-fe-utils"),h=u(l(o)),f={dbVersion:e};return a.toPairs(o.properties).filter(([S,y])=>!y.compMod).map(([S,y])=>{let T=d({propertySchema:y,modelDefinitions:r,internalDefinitions:n,externalDefinitions:s});return c({name:S,jsonSchema:y,parentJsonSchema:{required:[]},ddlProvider:p,schemaData:f,definitionJsonSchema:T})}).map(p.convertColumnDefinition).map(S=>p.alterTypeAddAttribute(h,S)).map(S=>$e.getInstance([S],!0,!1)).filter(Boolean)},"getAddColumnToTypeScriptDtos"),Fg=i(t=>e=>{let r=t.require("lodash"),n=ee()(null,null,t),{wrapInQuotes:s}=q()(r),o=s(e.code||e.name);return r.toPairs(e.properties).filter(([a,c])=>!c.compMod).map(([a])=>n.alterTypeDropAttribute(o,s(a))).map(a=>$e.getInstance([a],!0,!0)).filter(Boolean)},"getDeleteColumnFromTypeScriptDtos"),Bg=i(t=>e=>{let r=t.require("lodash"),n=ee()(null,null,t),{checkFieldPropertiesChanged:s,wrapInQuotes:o}=q()(r),a=o(e.code||e.name),c=r.values(e.properties).filter(u=>s(u.compMod,["name"])).map(u=>{let p=o(u.compMod.oldField.name),d=o(u.compMod.newField.name);return n.alterTypeRenameAttribute(a,p,d)}).map(u=>$e.getInstance([u],!0,!1)),l=r.toPairs(e.properties).filter(([u,p])=>s(p.compMod,["type","mode"])).map(([u,p])=>{let d=o(u),h=p.compMod.newField.mode||p.compMod.newField.type;return n.alterTypeChangeAttributeType(a,d,h)}).map(u=>$e.getInstance([u],!0,!1));return[...c,...l].filter(Boolean)},"getModifyColumnOfTypeScriptDtos");fu.exports={getCreateUdtScriptDto:Mg,getDeleteUdtScriptDto:qg,getAddColumnToTypeScriptDtos:kg,getDeleteColumnFromTypeScriptDtos:Fg,getModifyColumnOfTypeScriptDtos:Bg}});var _u=C((nC,Eu)=>{"use strict";var{AlterScriptDto:yu}=se(),gu=i(t=>{var e,r;return((r=(e=t==null?void 0:t.role)==null?void 0:e.compMod)==null?void 0:r.description)||{}},"extractDescription"),Ug=i((t,e)=>r=>{let{getFullViewName:n,wrapComment:s}=q()(t),o=gu(r);if(o.new&&o.new!==o.old){let a=s(o.new),c=n(r),l=e.updateViewComment(c,a);return yu.getInstance([l],!0,!1)}},"getUpsertCommentsScriptDto"),$g=i((t,e)=>r=>{let n=gu(r),{getFullViewName:s}=q()(t);if(n.old&&!n.new){let o=s(r),a=e.dropViewComment(o);return yu.getInstance([a],!0,!0)}},"getDropCommentsScriptDto"),Kg=i((t,e)=>r=>{let n=Ug(t,e)(r),s=$g(t,e)(r);return[n,s].filter(Boolean)},"getModifyViewCommentsScriptDtos");Eu.exports={getModifyViewCommentsScriptDtos:Kg}});var Cu=C((iC,Tu)=>{"use strict";var{getModifyViewCommentsScriptDtos:Gg}=_u(),{AlterScriptDto:Su}=se(),Vg=i(t=>e=>{let r=ee()(null,null,t),n={name:e.code||e.name,keys:[],schemaData:{schemaName:""}},s=r.hydrateView({viewData:n,entityData:[e]}),o=r.createView(s,{},e.isActivated);return Su.getInstance([o],!0,!1)},"getAddViewScriptDto"),Hg=i(t=>e=>{let r=t.require("lodash"),n=ee()(null,null,t),{wrapInQuotes:s}=q()(r),o=s(e.code||e.name),a=n.dropView(o);return Su.getInstance([a],!0,!0)},"getDeleteViewScriptDto"),Qg=i(t=>e=>{let r=t.require("lodash"),n=ee()(null,null,t);return[...Gg(r,n)(e)].filter(Boolean)},"getModifyViewScriptDtos");Tu.exports={getAddViewScriptDto:Vg,getDeleteViewScriptDto:Hg,getModifyViewScriptDtos:Qg}});var Nu=C((aC,Au)=>{"use strict";var vs=class vs{isActivated;name};i(vs,"AlterRelationshipFKField");var _s=vs,ws=class ws{bucket;collection};i(ws,"AlterRelationshipParentDto");var Ss=ws,Os=class Os{bucket;collection};i(Os,"AlterRelationshipChildDto");var Ts=Os,Is=class Is{relationshipOnDelete;relationshipOnUpdate;relationshipMatch};i(Is,"AlterRelationshipCustomProperties");var Cs=Is,Rs=class Rs{created;deleted;modified;parent;child;name;description;customProperties;isActivated};i(Rs,"AlterRelationshipRoleCompModDto");var As=Rs,Ps=class Ps{id;name;relationshipType;parentField;parentCardinality;childField;isActivated;childCardinality;parentCollection;childCollection;hackoladeStyles;compMod;roleType};i(Ps,"AlterRelationshipRoleDto");var Ns=Ps,Ds=class Ds{type;isActivated;unique;subtype;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;triggerUpdateColumns;role;GUID};i(Ds,"AlterRelationshipDto");var bs=Ds;Au.exports={AlterRelationshipRoleCompModDto:As,AlterRelationshipRoleDto:Ns,AlterRelationshipDto:bs,AlterRelationshipFKField:_s,AlterRelationshipParentDto:Ss,AlterRelationshipChildDto:Ts,AlterRelationshipCustomProperties:Cs}});var Ru=C((lC,Iu)=>{"use strict";var{AlterScriptDto:Ls}=se(),{AlterRelationshipDto:uC}=Nu(),Zt=i(t=>t.role.name,"getRelationshipName"),Wg=i(t=>e=>{let{getNamePrefixedWithSchemaName:r}=q()(t),n=e.role.compMod,s=n.child.bucket.name,o=n.child.collection.name;return r(o,s)},"getFullChildTableName"),bu=i((t,e)=>r=>{var o,a,c,l,u;let n=r.role.compMod,s=((o=n.name)==null?void 0:o.new)||Zt(r)||"";return t.createForeignKey({name:s,foreignKey:n.child.collection.fkFields,primaryKey:n.parent.collection.fkFields,customProperties:(a=n.customProperties)==null?void 0:a.new,foreignTable:n.child.collection.name,foreignSchemaName:n.child.bucket.name,foreignTableActivated:n.child.collection.isActivated,primaryTable:n.parent.collection.name,primarySchemaName:n.parent.bucket.name,primaryTableActivated:n.parent.collection.isActivated,isActivated:!!((u=(l=(c=r.role)==null?void 0:c.compMod)==null?void 0:l.isActivated)!=null&&u.new)})},"getAddSingleForeignKeyStatementDto"),vu=i(t=>{var r,n,s,o,a,c,l,u,p,d,h;let e=t.role.compMod;return e?[((r=e.name)==null?void 0:r.new)||Zt(t),(n=e.parent)==null?void 0:n.bucket,(s=e.parent)==null?void 0:s.collection,(c=(a=(o=e.parent)==null?void 0:o.collection)==null?void 0:a.fkFields)==null?void 0:c.length,(l=e.child)==null?void 0:l.bucket,(u=e.child)==null?void 0:u.collection,(h=(d=(p=e.child)==null?void 0:p.collection)==null?void 0:d.fkFields)==null?void 0:h.length].every(f=>!!f):!1},"canRelationshipBeAdded"),Yg=i((t,e)=>r=>r.filter(n=>vu(n)).map(n=>{let s=bu(t,e)(n);return Ls.getInstance([s.statement],s.isActivated,!1)}).filter(Boolean).filter(n=>n.scripts.some(s=>!!s.script)),"getAddForeignKeyScriptDtos"),wu=i((t,e)=>r=>{var d,h,f,S;let{wrapInQuotes:n}=q()(e),s=r.role.compMod,o=Wg(e)(r),a=((d=s.name)==null?void 0:d.old)||Zt(r)||"",c=n(a),l=t.dropForeignKey(o,c),u=!!((S=(f=(h=r.role)==null?void 0:h.compMod)==null?void 0:f.isActivated)!=null&&S.new),p=s.child.collection.isActivated;return{statement:l,isActivated:u&&p}},"getDeleteSingleForeignKeyStatementDto"),Ou=i(t=>{var r,n,s;let e=t.role.compMod;return e?[((r=e.name)==null?void 0:r.old)||Zt(t),(n=e.child)==null?void 0:n.bucket,(s=e.child)==null?void 0:s.collection].every(o=>!!o):!1},"canRelationshipBeDeleted"),jg=i((t,e)=>r=>r.filter(n=>Ou(n)).map(n=>{let s=wu(t,e)(n);return Ls.getInstance([s.statement],s.isActivated,!0)}).filter(Boolean).filter(n=>n.scripts.some(s=>!!s.script)),"getDeleteForeignKeyScriptDtos"),zg=i((t,e)=>r=>r.filter(n=>vu(n)&&Ou(n)).map(n=>{let s=wu(t,e)(n),o=bu(t,e)(n),a=o.isActivated&&s.isActivated;return Ls.getDropAndRecreateInstance(s.statement,o.statement,a)}).filter(Boolean).filter(n=>n.scripts.some(s=>!!s.script)),"getModifyForeignKeyScriptDtos");Iu.exports={getDeleteForeignKeyScriptDtos:jg,getModifyForeignKeyScriptDtos:zg,getAddForeignKeyScriptDtos:Yg}});var Du=C((mC,Pu)=>{"use strict";var Fs=class Fs{message;stack};i(Fs,"PluginError");var xs=Fs,Bs=class Bs{require};i(Bs,"App");var Ms=Bs,Us=class Us{log;clear};i(Us,"Logger");var qs=Us,$s=class $s{jsonSchema;modelDefinitions;internalDefinitions;externalDefinitions;containerData;entityData;entities;views;viewData;relationships;collectionRefsDefinitionsMap;isUpdateScript;level;host;clusterId;accessToken;applyToInstanceQueryRequestTimeout;script;hiddenKeys;options;modelData};i($s,"CoreData");var ks=$s;Pu.exports={App:Ms,CoreData:ks,Logger:qs,PluginError:xs}});var xu=C((fC,Lu)=>{"use strict";var zs=class zs{name;isActivated};i(zs,"ContainerJsonSchema");var Ks=zs,Xs=class Xs{backgroundColor};i(Xs,"ContainerStyles");var Gs=Xs,Zs=class Zs{collectionName;isActivated;bucketId;additionalProperties;tableIfNotExists};i(Zs,"EntityData");var Vs=Zs,Js=class Js{$schema;type;GUID};i(Js,"InternalDefinitions");var Hs=Js,ei=class ei{$schema;type;GUID};i(ei,"ModelDefinitions");var Qs=ei,ti=class ti{$schema;type;GUID};i(ti,"ExternalDefinitions");var Ws=ti,ri=class ri{type;isActivated;mode;subtype;compositeKey;compositePartitionKey;compositeClusteringKey;compositePrimaryKey;compositeUniqueKey;GUID};i(ri,"FieldJsonSchema");var Ys=ri,ni=class ni{$schema;type;title;properties;isActivated;additionalProperties;tableIfNotExists;GUID};i(ni,"EntityJsonSchema");var js=ni;Lu.exports={ContainerJsonSchema:Ks,ContainerStyles:Gs,EntityData:Vs,InternalDefinitions:Hs,ModelDefinitions:Qs,ExternalDefinitions:Ws,FieldJsonSchema:Ys,EntityJsonSchema:js}});var qu=C((AC,Mu)=>{"use strict";var{getAddContainerScriptDto:Xg,getDeleteContainerScriptDto:Zg,getModifyContainerScriptDtos:Jg}=Kc(),{getAddCollectionScriptDto:eE,getDeleteCollectionScriptDto:tE,getAddColumnScriptDtos:rE,getDeleteColumnScriptDtos:nE,getModifyColumnScriptDtos:sE,getModifyCollectionScriptDtos:iE}=du(),{getDeleteUdtScriptDto:oE,getCreateUdtScriptDto:aE,getAddColumnToTypeScriptDtos:cE,getDeleteColumnFromTypeScriptDtos:uE,getModifyColumnOfTypeScriptDtos:lE}=hu(),{getAddViewScriptDto:pE,getDeleteViewScriptDto:mE,getModifyViewScriptDtos:dE}=Cu(),{getModifyForeignKeyScriptDtos:fE,getDeleteForeignKeyScriptDtos:hE,getAddForeignKeyScriptDtos:yE}=Ru(),{AlterScriptDto:yC,ModificationScript:gC}=se(),{App:EC,CoreData:_C}=Du(),{InternalDefinitions:SC,ModelDefinitions:TC,ExternalDefinitions:CC}=xu(),gE=i(({collection:t,app:e})=>{var l,u,p,d,h,f,S,y,T,_,D,N;let r=(d=(p=(u=(l=t.properties)==null?void 0:l.containers)==null?void 0:u.properties)==null?void 0:p.added)==null?void 0:d.items,n=(y=(S=(f=(h=t.properties)==null?void 0:h.containers)==null?void 0:f.properties)==null?void 0:S.deleted)==null?void 0:y.items,s=(N=(D=(_=(T=t.properties)==null?void 0:T.containers)==null?void 0:_.properties)==null?void 0:D.modified)==null?void 0:N.items,o=[].concat(r).filter(Boolean).map(O=>Xg(e)(Object.keys(O.properties)[0])),a=[].concat(n).filter(Boolean).map(O=>Zg(e)(Object.keys(O.properties)[0])),c=[].concat(s).filter(Boolean).map(O=>Object.values(O.properties)[0]).flatMap(O=>Jg(e)(O));return[...o,...a,...c].filter(Boolean)},"getAlterContainersScriptDtos"),EE=i(({collection:t,app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:o})=>{var h,f,S,y,T,_,D,N,O,R,A,b,x,U,W,Se,Te,Ae,Re,g,w,M,$,Y;let a=[].concat((y=(S=(f=(h=t.properties)==null?void 0:h.entities)==null?void 0:f.properties)==null?void 0:S.added)==null?void 0:y.items).filter(Boolean).map(m=>Object.values(m.properties)[0]).filter(m=>{var E;return(E=m.compMod)==null?void 0:E.created}).map(eE({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:o})),c=[].concat((N=(D=(_=(T=t.properties)==null?void 0:T.entities)==null?void 0:_.properties)==null?void 0:D.deleted)==null?void 0:N.items).filter(Boolean).map(m=>Object.values(m.properties)[0]).filter(m=>{var E;return(E=m.compMod)==null?void 0:E.deleted}).map(tE(e)),l=[].concat((b=(A=(R=(O=t.properties)==null?void 0:O.entities)==null?void 0:R.properties)==null?void 0:A.modified)==null?void 0:b.items).filter(Boolean).map(m=>Object.values(m.properties)[0]).flatMap(iE(e)),u=[].concat((Se=(W=(U=(x=t.properties)==null?void 0:x.entities)==null?void 0:U.properties)==null?void 0:W.added)==null?void 0:Se.items).filter(Boolean).map(m=>Object.values(m.properties)[0]).filter(m=>!m.compMod).flatMap(rE({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:o})),p=[].concat((g=(Re=(Ae=(Te=t.properties)==null?void 0:Te.entities)==null?void 0:Ae.properties)==null?void 0:Re.deleted)==null?void 0:g.items).filter(Boolean).map(m=>Object.values(m.properties)[0]).filter(m=>!m.compMod).flatMap(nE(e)),d=[].concat((Y=($=(M=(w=t.properties)==null?void 0:w.entities)==null?void 0:M.properties)==null?void 0:$.modified)==null?void 0:Y.items).filter(Boolean).map(m=>Object.values(m.properties)[0]).filter(m=>!m.compMod).flatMap(sE({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:o}));return[...a,...c,...l,...u,...p,...d].filter(Boolean)},"getAlterCollectionsScriptDtos"),_E=i((t,e)=>{var o,a,c,l,u,p,d,h,f,S,y,T;let r=[].concat((l=(c=(a=(o=t.properties)==null?void 0:o.views)==null?void 0:a.properties)==null?void 0:c.added)==null?void 0:l.items).filter(Boolean).map(_=>Object.values(_.properties)[0]).map(_=>({..._,..._.role||{}})).filter(_=>{var D;return((D=_.compMod)==null?void 0:D.created)&&_.selectStatement}).map(pE(e)),n=[].concat((h=(d=(p=(u=t.properties)==null?void 0:u.views)==null?void 0:p.properties)==null?void 0:d.deleted)==null?void 0:h.items).filter(Boolean).map(_=>Object.values(_.properties)[0]).map(_=>({..._,..._.role||{}})).map(mE(e)),s=[].concat((T=(y=(S=(f=t.properties)==null?void 0:f.views)==null?void 0:S.properties)==null?void 0:y.modified)==null?void 0:T.items).filter(Boolean).map(_=>Object.values(_.properties)[0]).map(_=>({..._,..._.role||{}})).flatMap(_=>dE(e)(_));return[...n,...r,...s].filter(Boolean)},"getAlterViewScriptDtos"),SE=i(({collection:t,app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:o})=>{var d,h,f,S,y,T,_,D,N,O,R,A,b,x,U,W,Se,Te,Ae,Re;let a=[].concat((S=(f=(h=(d=t.properties)==null?void 0:d.modelDefinitions)==null?void 0:h.properties)==null?void 0:f.added)==null?void 0:S.items).filter(Boolean).map(g=>Object.values(g.properties)[0]).map(g=>({...g,...e.require("lodash").omit(g.role,"properties")||{}})).filter(g=>{var w;return(w=g.compMod)==null?void 0:w.created}).map(aE({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:o})),c=[].concat((D=(_=(T=(y=t.properties)==null?void 0:y.modelDefinitions)==null?void 0:T.properties)==null?void 0:_.deleted)==null?void 0:D.items).filter(Boolean).map(g=>Object.values(g.properties)[0]).map(g=>({...g,...e.require("lodash").omit(g.role,"properties")||{}})).filter(g=>{var w;return(w=g.compMod)==null?void 0:w.deleted}).map(oE(e)),l=[].concat((A=(R=(O=(N=t.properties)==null?void 0:N.modelDefinitions)==null?void 0:O.properties)==null?void 0:R.added)==null?void 0:A.items).filter(Boolean).map(g=>Object.values(g.properties)[0]).filter(g=>!g.compMod).map(g=>({...g,...e.require("lodash").omit(g.role,"properties")||{}})).filter(g=>g.childType==="composite").flatMap(cE({app:e,dbVersion:r,modelDefinitions:n,internalDefinitions:s,externalDefinitions:o})),u=[].concat((W=(U=(x=(b=t.properties)==null?void 0:b.modelDefinitions)==null?void 0:x.properties)==null?void 0:U.deleted)==null?void 0:W.items).filter(Boolean).map(g=>Object.values(g.properties)[0]).filter(g=>!g.compMod).map(g=>({...g,...e.require("lodash").omit(g.role,"properties")||{}})).filter(g=>g.childType==="composite").flatMap(uE(e)),p=[].concat((Re=(Ae=(Te=(Se=t.properties)==null?void 0:Se.modelDefinitions)==null?void 0:Te.properties)==null?void 0:Ae.modified)==null?void 0:Re.items).filter(Boolean).map(g=>Object.values(g.properties)[0]).filter(g=>!g.compMod).map(g=>({...g,...e.require("lodash").omit(g.role,"properties")||{}})).filter(g=>g.childType==="composite").flatMap(lE(e));return[...c,...a,...l,...u,...p].filter(Boolean)},"getAlterModelDefinitionsScriptDtos"),TE=i(({collection:t,app:e})=>{var p,d,h,f,S,y,T,_,D,N,O,R;let r=e.require("lodash"),n=ee()(null,null,e),s=[].concat((f=(h=(d=(p=t.properties)==null?void 0:p.relationships)==null?void 0:d.properties)==null?void 0:h.added)==null?void 0:f.items).filter(Boolean).map(A=>Object.values(A.properties)[0]).filter(A=>{var b,x;return(x=(b=A==null?void 0:A.role)==null?void 0:b.compMod)==null?void 0:x.created}),o=[].concat((_=(T=(y=(S=t.properties)==null?void 0:S.relationships)==null?void 0:y.properties)==null?void 0:T.deleted)==null?void 0:_.items).filter(Boolean).map(A=>Object.values(A.properties)[0]).filter(A=>{var b,x;return(x=(b=A==null?void 0:A.role)==null?void 0:b.compMod)==null?void 0:x.deleted}),a=[].concat((R=(O=(N=(D=t.properties)==null?void 0:D.relationships)==null?void 0:N.properties)==null?void 0:O.modified)==null?void 0:R.items).filter(Boolean).map(A=>Object.values(A.properties)[0]).filter(A=>{var b,x;return(x=(b=A==null?void 0:A.role)==null?void 0:b.compMod)==null?void 0:x.modified}),c=hE(n,r)(o),l=yE(n,r)(s),u=fE(n,r)(a);return[...c,...l,...u].filter(Boolean)},"getAlterRelationshipsScriptDtos"),CE=i(t=>{if(!t)return;let e=t.scripts.map(r=>({...r,script:(r.script||"").trim()})).filter(r=>!!r.script);if(e.length)return{...t,scripts:e}},"prettifyAlterScriptDto"),AE=i((t,e)=>{var h;let r=JSON.parse(t.jsonSchema);if(!r)throw new Error('"comparisonModelCollection" is not found. Alter script can be generated only from Delta model');let n=JSON.parse(t.modelDefinitions),s=JSON.parse(t.internalDefinitions),o=JSON.parse(t.externalDefinitions),a=(h=t.modelData[0])==null?void 0:h.dbVersion,c=gE({collection:r,app:e}),l=EE({collection:r,app:e,dbVersion:a,modelDefinitions:n,internalDefinitions:s,externalDefinitions:o}),u=_E(r,e),p=SE({collection:r,app:e,dbVersion:a,modelDefinitions:n,internalDefinitions:s,externalDefinitions:o}),d=TE({collection:r,app:e});return[...c,...p,...l,...u,...d].filter(Boolean).map(f=>CE(f)).filter(Boolean)},"getAlterScriptDtos");Mu.exports={getAlterScriptDtos:AE}});var Uu=C((vC,Bu)=>{"use strict";var{getAlterScriptDtos:Jt}=qu(),{AlterScriptDto:bC}=se(),ku=i(t=>(e,r)=>{let{commentIfDeactivated:n}=q()(t);return e.map(s=>s.isActivated===!1?s.scripts.map(o=>n(o.script,{isActivated:!1,isPartOfLine:!1})):r?s.scripts.map(o=>o.script):s.scripts.map(o=>n(o.script,{isActivated:!o.isDropScript,isPartOfLine:!1}))).flat().filter(Boolean).map(s=>s.trim()).filter(Boolean).join(` - callback({message: error.message, stack: error.stack}); - } - }, - - getDatabases(connectionInfo, logger, callback, app) { - logger.progress({message: 'Find all databases'}); - - reApi.getDatabases(connectionInfo, logger, callback, app); - }, - - applyToInstance(connectionInfo, logger, callback, app) { - logger.clear(); - logger.log( - 'info', - app.require('lodash').omit(connectionInfo, 'script', 'containerData'), - 'connectionInfo', - connectionInfo.hiddenKeys, - ); - - const cockroachDBLogger = createLogger({ - title: 'Apply to instance', - hiddenKeys: connectionInfo.hiddenKeys, - logger, - }); - - applyToInstanceHelper.applyToInstance(connectionInfo, cockroachDBLogger, app).then(callback, callback); - }, - - testConnection(connectionInfo, logger, callback, app) { - reApi.testConnection(connectionInfo, logger, callback, app).then(callback, callback); - }, - - isDropInStatements(data, logger, callback, app) { - try { - if (data.level === 'container') { - const containsDropStatements = doesContainerLevelAlterScriptContainDropStatements(data, app); - callback(null, containsDropStatements); - } else { - const containsDropStatements = doesEntityLevelAlterScriptContainDropStatements(data, app); - callback(null, containsDropStatements); - } - } catch (e) { - callback({message: e.message, stack: e.stack}); - } - }, -}; +`)},"joinAlterScriptDtosIntoScript"),NE=i((t,e)=>{var o,a;let r=e.require("lodash"),n=Jt(t,e),s=(a=(o=t.options)==null?void 0:o.additionalOptions)==null?void 0:a.some(c=>c.id==="applyDropStatements"&&c.value);return ku(r)(n,s)},"buildEntityLevelAlterScript"),bE=i((t,e)=>Jt(t,e).some(n=>n.isActivated&&n.scripts.some(s=>s.isDropScript)),"doesEntityLevelAlterScriptContainDropStatements"),Fu=i(t=>({...t,jsonSchema:t.collections[0],internalDefinitions:Object.values(t.internalDefinitions)[0]}),"mapCoreDataForContainerLevelScripts"),vE=i((t,e)=>{var a,c;let r=Fu(t),n=e.require("lodash"),s=Jt(r,e),o=(c=(a=r.options)==null?void 0:a.additionalOptions)==null?void 0:c.some(l=>l.id==="applyDropStatements"&&l.value);return ku(n)(s,o)},"buildContainerLevelAlterScript"),wE=i((t,e)=>{let r=Fu(t);return Jt(r,e).some(s=>s.isActivated&&s.scripts.some(o=>o.isDropScript))},"doesContainerLevelAlterScriptContainDropStatements");Bu.exports={buildEntityLevelAlterScript:NE,doesEntityLevelAlterScriptContainDropStatements:bE,buildContainerLevelAlterScript:vE,doesContainerLevelAlterScriptContainDropStatements:wE}});var $u=tc(),{createLogger:OE}=tr(),IE=nc(),{buildEntityLevelAlterScript:RE,buildContainerLevelAlterScript:PE,doesContainerLevelAlterScriptContainDropStatements:DE,doesEntityLevelAlterScriptContainDropStatements:LE}=Uu();module.exports={generateScript(t,e,r,n){try{let s=RE(t,n);r(null,s)}catch(s){e.log("error",{message:s.message,stack:s.stack},"CockroachDB Forward-Engineering Error"),r({message:s.message,stack:s.stack})}},generateViewScript(t,e,r,n){r(new Error("Forward-Engineering of delta model on view level is not supported"))},generateContainerScript(t,e,r,n){try{let s=PE(t,n);r(null,s)}catch(s){e.log("error",{message:s.message,stack:s.stack},"CockroachDB Forward-Engineering Error"),r({message:s.message,stack:s.stack})}},getDatabases(t,e,r,n){e.progress({message:"Find all databases"}),$u.getDatabases(t,e,r,n)},applyToInstance(t,e,r,n){e.clear(),e.log("info",n.require("lodash").omit(t,"script","containerData"),"connectionInfo",t.hiddenKeys);let s=OE({title:"Apply to instance",hiddenKeys:t.hiddenKeys,logger:e});IE.applyToInstance(t,s,n).then(r,r)},testConnection(t,e,r,n){$u.testConnection(t,e,r,n).then(r,r)},isDropInStatements(t,e,r,n){try{if(t.level==="container"){let s=DE(t,n);r(null,s)}else{let s=LE(t,n);r(null,s)}}catch(s){r({message:s.message,stack:s.stack})}}}; diff --git a/forward_engineering/applyToInstanceHelper.js b/forward_engineering/applyToInstanceHelper.js deleted file mode 100644 index f8e9490..0000000 --- a/forward_engineering/applyToInstanceHelper.js +++ /dev/null @@ -1,27 +0,0 @@ -const cockroachDBService = require('../reverse_engineering/helpers/cockroachDBService'); - -const applyToInstance = async (connectionInfo, logger, app) => { - try { - cockroachDBService.setDependencies(app); - await cockroachDBService.connect(connectionInfo, logger); - await cockroachDBService.logVersion(); - await cockroachDBService.applyScript(removeCreateDbScript(connectionInfo.script)); - } catch (error) { - logger.error(error); - throw prepareError(error); - } -}; - -const removeCreateDbScript = script => { - const createDbScriptRegexp = /CREATE DATABASE[^;]*;/gi; - - return script.replace(createDbScriptRegexp, ''); -}; - -const prepareError = error => { - error = JSON.stringify(error, Object.getOwnPropertyNames(error)); - error = JSON.parse(error); - return error; -}; - -module.exports = { applyToInstance }; diff --git a/forward_engineering/configs/defaultTypes.js b/forward_engineering/configs/defaultTypes.js deleted file mode 100644 index dd4230c..0000000 --- a/forward_engineering/configs/defaultTypes.js +++ /dev/null @@ -1,12 +0,0 @@ -module.exports = { - number: 'numeric', - string: 'text', - date: 'date', - timestamp: 'timestamp', - binary: 'bytea', - boolean: 'boolean', - document: 'jsonb', - array: 'jsonb', - objectId: 'uuid', - default: 'char', -}; diff --git a/forward_engineering/configs/descriptors.js b/forward_engineering/configs/descriptors.js deleted file mode 100644 index 74e800b..0000000 --- a/forward_engineering/configs/descriptors.js +++ /dev/null @@ -1,242 +0,0 @@ -// The keys of the exported object indicate which types are allowed in this target -// The values are deprecated configs and they are unnecessary to write - -module.exports = { - char: { - size: 1, - }, - varchar: { - mode: 'varying', - }, - text: { - mode: 'text', - }, - bit: { - size: 1, - mode: 'bit', - }, - varbit: { - size: 1, - mode: 'varying', - }, - tsvector: { - mode: 'text', - }, - tsquery: { - mode: 'text', - }, - smallint: { - capacity: 2, - }, - integer: { - capacity: 4, - }, - bigint: { - capacity: 8, - }, - numeric: { - capacity: 12, - mode: 'decimal', - }, - real: { - capacity: 4, - mode: 'floating', - }, - 'double precision': { - capacity: 8, - mode: 'floating', - }, - smallserial: { - capacity: 2, - }, - serial: { - capacity: 4, - }, - bigserial: { - capacity: 8, - }, - money: { - capacity: 8, - mode: 'decimal', - }, - bytea: { - size: 4, - mode: 'binary', - }, - date: { - format: 'YYYY-MM-DD', - }, - time: { - format: 'hh:mm:ss.nnnnnn', - }, - timestamp: { - format: 'YYYY-MM-DD hh:mm:ss', - }, - interval: { - format: 'PnYnMnDTnHnMnS', - }, - boolean: { - mode: 'boolean', - }, - int4range: { - mode: 'range', - modeType: 'integer', - capacity: 4, - }, - int8range: { - mode: 'range', - modeType: 'integer', - capacity: 8, - }, - numrange: { - mode: 'range', - modeType: 'decimal', - capacity: 12, - }, - daterange: { - mode: 'range', - modeType: 'date', - format: 'YYYY-MM-DD', - }, - tsrange: { - mode: 'range', - modeType: 'timestamp', - format: 'YYYY-MM-DD hh:mm:ss', - }, - tstzrange: { - mode: 'range', - modeType: 'timestamp', - format: 'YYYY-MM-DD hh:mm:ss.nnnZ', - }, - - int4multirange: { - mode: 'multirange', - modeType: 'integer', - capacity: 4, - }, - int8multirange: { - mode: 'multirange', - modeType: 'integer', - capacity: 8, - }, - nummultirange: { - mode: 'multirange', - modeType: 'decimal', - capacity: 12, - }, - datemultirange: { - mode: 'multirange', - modeType: 'date', - format: 'YYYY-MM-DD', - }, - tsmultirange: { - mode: 'multirange', - modeType: 'timestamp', - format: 'YYYY-MM-DD hh:mm:ss', - }, - tstzmultirange: { - mode: 'multirange', - modeType: 'timestamp', - format: 'YYYY-MM-DD hh:mm:ss.nnnZ', - }, - geometry: { - format: 'euclidian', - mode: 'geospatial', - }, - geography: { - format: 'euclidian', - mode: 'geospatial', - }, - box2d: { - format: 'euclidian', - mode: 'geospatial', - }, - box3d: { - format: 'euclidian', - mode: 'geospatial', - }, - geometry_dump: { - format: 'euclidian', - mode: 'geospatial', - }, - point: { - format: 'euclidian', - mode: 'geospatial', - }, - line: { - format: 'euclidian', - mode: 'geospatial', - }, - lseg: { - format: 'euclidian', - mode: 'geospatial', - }, - box: { - format: 'euclidian', - mode: 'geospatial', - }, - path: { - format: 'euclidian', - mode: 'geospatial', - }, - polygon: { - format: 'euclidian', - mode: 'geospatial', - }, - circle: { - format: 'euclidian', - mode: 'geospatial', - }, - inet: { - mode: 'ip', - }, - cidr: { - mode: 'ip', - }, - macaddr: {}, - macaddr8: {}, - uuid: { - mode: 'uuid', - }, - oid: { - mode: 'uuid', - }, - regclass: {}, - regcollation: {}, - regconfig: {}, - regdictionary: {}, - regnamespace: {}, - regoper: {}, - regoperator: {}, - regproc: {}, - regprocedure: {}, - regrole: {}, - regtype: {}, - xml: { - mode: 'xml', - }, - json: { - format: 'semi-structured', - }, - jsonb: { - format: 'semi-structured', - }, - int: {}, - int2: {}, - int4: {}, - decimal: {}, - float: {}, - composite: { - format: 'semi-structured', - mode: 'object', - }, - enum: { - mode: 'enum', - }, - range_udt: { - mode: 'range', - }, - domain: { - mode: 'domain', - }, -}; diff --git a/forward_engineering/ddlProvider.js b/forward_engineering/ddlProvider.js index a76ecbe..07b911c 100644 --- a/forward_engineering/ddlProvider.js +++ b/forward_engineering/ddlProvider.js @@ -1,4 +1,58 @@ -// This file reexports actual DDL Provider. -// Core application needs this file to generate FE scripts +"use strict";var gt=Object.defineProperty;var n=(o,I)=>gt(o,"name",{value:I,configurable:!0});var H=(o,I)=>()=>(I||o((I={exports:{}}).exports,I),I.exports);var Ue=H((St,he)=>{"use strict";he.exports={number:"numeric",string:"text",date:"date",timestamp:"timestamp",binary:"bytea",boolean:"boolean",document:"jsonb",array:"jsonb",objectId:"uuid",default:"char"}});var Ke=H((ft,Pe)=>{"use strict";Pe.exports={char:{size:1},varchar:{mode:"varying"},text:{mode:"text"},bit:{size:1,mode:"bit"},varbit:{size:1,mode:"varying"},tsvector:{mode:"text"},tsquery:{mode:"text"},smallint:{capacity:2},integer:{capacity:4},bigint:{capacity:8},numeric:{capacity:12,mode:"decimal"},real:{capacity:4,mode:"floating"},"double precision":{capacity:8,mode:"floating"},smallserial:{capacity:2},serial:{capacity:4},bigserial:{capacity:8},money:{capacity:8,mode:"decimal"},bytea:{size:4,mode:"binary"},date:{format:"YYYY-MM-DD"},time:{format:"hh:mm:ss.nnnnnn"},timestamp:{format:"YYYY-MM-DD hh:mm:ss"},interval:{format:"PnYnMnDTnHnMnS"},boolean:{mode:"boolean"},int4range:{mode:"range",modeType:"integer",capacity:4},int8range:{mode:"range",modeType:"integer",capacity:8},numrange:{mode:"range",modeType:"decimal",capacity:12},daterange:{mode:"range",modeType:"date",format:"YYYY-MM-DD"},tsrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzrange:{mode:"range",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},int4multirange:{mode:"multirange",modeType:"integer",capacity:4},int8multirange:{mode:"multirange",modeType:"integer",capacity:8},nummultirange:{mode:"multirange",modeType:"decimal",capacity:12},datemultirange:{mode:"multirange",modeType:"date",format:"YYYY-MM-DD"},tsmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss"},tstzmultirange:{mode:"multirange",modeType:"timestamp",format:"YYYY-MM-DD hh:mm:ss.nnnZ"},geometry:{format:"euclidian",mode:"geospatial"},geography:{format:"euclidian",mode:"geospatial"},box2d:{format:"euclidian",mode:"geospatial"},box3d:{format:"euclidian",mode:"geospatial"},geometry_dump:{format:"euclidian",mode:"geospatial"},point:{format:"euclidian",mode:"geospatial"},line:{format:"euclidian",mode:"geospatial"},lseg:{format:"euclidian",mode:"geospatial"},box:{format:"euclidian",mode:"geospatial"},path:{format:"euclidian",mode:"geospatial"},polygon:{format:"euclidian",mode:"geospatial"},circle:{format:"euclidian",mode:"geospatial"},inet:{mode:"ip"},cidr:{mode:"ip"},macaddr:{},macaddr8:{},uuid:{mode:"uuid"},oid:{mode:"uuid"},regclass:{},regcollation:{},regconfig:{},regdictionary:{},regnamespace:{},regoper:{},regoperator:{},regproc:{},regprocedure:{},regrole:{},regtype:{},xml:{mode:"xml"},json:{format:"semi-structured"},jsonb:{format:"semi-structured"},int:{},int2:{},int4:{},decimal:{},float:{},composite:{format:"semi-structured",mode:"object"},enum:{mode:"enum"},range_udt:{mode:"range"},domain:{mode:"domain"}}});var Me=H((bt,Fe)=>{"use strict";Fe.exports={createDatabase:"CREATE DATABASE ${name}${template}${encoding}${collate}${characterClassification};\n",createSchema:"CREATE SCHEMA${ifNotExist} ${name};\nSET search_path TO ${name};\n\n${comment}\n",comment:"COMMENT ON ${object} ${objectName} IS ${comment};\n",createTable:"CREATE${temporary} TABLE${ifNotExist} ${name} (\n${columnDefinitions}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n)${options};\n\n${comment}${columnDescriptions}",createTablePartitionOf:"CREATE${temporary} TABLE${ifNotExist} ${name}\n${partitionOf} ${openParenthesis}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n${closeParenthesis}${options};\n\n${comment}${columnDescriptions}",generatedColumnClause:" GENERATED ALWAYS AS (${generationExpression}) STORED",columnDefinition:"${name} ${type}${collation}${generatedColumnClause}${primaryKey}${uniqueKey}${defaultValue}${notNull}",checkConstraint:"${name} CHECK (${expression})${notValid}",createForeignKeyConstraint:"${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable} (${primaryKey})${match}${onDelete}${onUpdate}",createKeyConstraint:"${constraintName}${keyType}${columns}${includeNonKey}${storageParameters}",alterColumnType:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET DATA TYPE ${dataType};",addNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET NOT NULL;",dropNotNullConstraint:"ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} DROP NOT NULL;",renameColumn:"ALTER TABLE IF EXISTS ${tableName} RENAME COLUMN ${oldColumnName} TO ${newColumnName};",addCheckConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD CONSTRAINT ${constraintName} CHECK (${expression});",dropConstraint:"ALTER TABLE IF EXISTS ${tableName} DROP CONSTRAINT IF EXISTS ${constraintName};",createForeignKey:"ALTER TABLE IF EXISTS ${foreignTable} ADD CONSTRAINT ${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable}(${primaryKey})${match}${onDelete}${onUpdate};",dropForeignKey:"ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName};",addPkConstraint:"ALTER TABLE IF EXISTS ${tableName} ADD ${constraintStatement};",dropTable:"DROP TABLE IF EXISTS ${tableName};",addColumn:"ALTER TABLE IF EXISTS ${tableName} ADD COLUMN IF NOT EXISTS ${columnDefinition};",dropColumn:"ALTER TABLE IF EXISTS ${tableName} DROP COLUMN IF EXISTS ${columnName};",dropDomain:"DROP DOMAIN IF EXISTS ${udtName};",dropType:"DROP TYPE IF EXISTS ${udtName};",alterTypeAddAttribute:"ALTER TYPE ${udtName} ADD ATTRIBUTE ${columnDefinition};",alterTypeDropAttribute:"ALTER TYPE ${udtName} DROP ATTRIBUTE IF EXISTS ${attributeName};",alterTypeRenameAttribute:"ALTER TYPE ${udtName} RENAME ATTRIBUTE ${oldAttributeName} TO ${newAttributeName};",alterTypeChangeAttributeType:"ALTER TYPE ${udtName} ALTER ATTRIBUTE ${attributeName} SET DATA TYPE ${newDataType};",updateCommentOnTable:"COMMENT ON TABLE ${tableName} IS ${comment};",updateCommentOnColumn:"COMMENT ON COLUMN ${columnName} IS ${comment};",updateCommentOnSchema:"COMMENT ON SCHEMA ${schemaName} IS ${comment};",updateCommentOnView:"COMMENT ON VIEW ${viewName} IS ${comment};",createSchemaOnly:"CREATE SCHEMA IF NOT EXISTS ${schemaName};",dropSchema:"DROP SCHEMA IF EXISTS ${schemaName};",index:"CREATE${unique} INDEX${concurrently}${ifNotExist} ${name}\n ON ${tableName}${using}${keys}${options};\n",createView:"CREATE${orReplace}${temporary} VIEW ${name}${withOptions}\nAS ${selectStatement}${checkOption};\n\n${comment}\n",viewSelectStatement:"SELECT ${keys}\n FROM ${tableName}",dropView:"DROP VIEW IF EXISTS ${viewName};",createFunction:"CREATE${orReplace} FUNCTION ${name}\n (${parameters})\n RETURNS ${returnType}\n LANGUAGE ${language}\n${properties}AS $BODY$\n${definition}\n$BODY$;\n",createProcedure:"CREATE${orReplace} PROCEDURE ${name} (${parameters})\n LANGUAGE ${language}\nAS $BODY$\n${body}\n$BODY$;\n",createCompositeType:`CREATE TYPE \${name} AS ( + \${columnDefinitions} +); -module.exports = require('./ddlProvider/ddlProvider'); +\${comment}`,createEnumType:"CREATE TYPE ${name} AS ENUM (${values});\n\n${comment}",createRangeType:"CREATE TYPE ${name} AS RANGE (\n SUBTYPE=${subtype}${options}\n);\n\n${comment}",createDomainType:"CREATE DOMAIN ${name} AS ${underlyingType}${notNull}${collate}${default}${constraints};\n\n${comment}"}});var Ye=H((Lt,Ve)=>{"use strict";var Ne=class Ne{id;constraintName;indexStorageParameters;indexInclude};n(Ne,"AlterCollectionColumnPrimaryKeyOptionDto");var le=Ne,Ae=class Ae{type;isActivated;primaryKey;unique;mode;length;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;primaryKeyOptions;triggerUpdateColumns;compMod;GUID};n(Ae,"AlterCollectionColumnDto");var de=Ae,$e=class $e extends le{compositePrimaryKey};n($e,"AlterCollectionRoleCompModPKDto");var Te=$e,Ce=class Ce{new;old};n(Ce,"AlterCollectionRoleCompModPrimaryKey");var ge=Ce,Oe=class Oe{id;type;collectionName;properties;definitions;isActivated;additionalProperties;memory_optimized;collectionUsers;ifNotExist;on_commit;bucketId;compMod;name;roleType;patternProperties};n(Oe,"AlterCollectionRoleDto");var Ee=Oe,Ie=class Ie{type;isActivated;unique;subtype;properties;compositeKey;compositePartitionKey;compositePrimaryKey;compositeUniqueKey;triggerUpdateColumns;role;GUID};n(Ie,"AlterCollectionDto");var ye=Ie;Ve.exports={AlterCollectionDto:ye,AlterCollectionRoleDto:Ee,AlterCollectionColumnDto:de,AlterCollectionRoleCompModPrimaryKey:ge,AlterCollectionRoleCompModPKDto:Te}});var xe=H((Ut,ve)=>{"use strict";var Et=Object.freeze({ALL:"ALL",ANALYSE:"ANALYSE",ANALYZE:"ANALYZE",AND:"AND",ANY:"ANY",ARRAY:"ARRAY",ASC:"ASC",ASYMMETRIC:"ASYMMETRIC",AUTHORIZATION:"AUTHORIZATION",BINARY:"BINARY",BOTH:"BOTH",CASE:"CASE",CAST:"CAST",CHECK:"CHECK",COLLATE:"COLLATE",COLUMN:"COLUMN",CONCURRENTLY:"CONCURRENTLY",CONSTRAINT:"CONSTRAINT",CREATE:"CREATE",CROSS:"CROSS",CURRENT_CATALOG:"CURRENT_CATALOG",CURRENT_DATE:"CURRENT_DATE",CURRENT_ROLE:"CURRENT_ROLE",CURRENT_SCHEMA:"CURRENT_SCHEMA",CURRENT_TIME:"CURRENT_TIME",CURRENT_TIMESTAMP:"CURRENT_TIMESTAMP",CURRENT_USER:"CURRENT_USER",DEFAULT:"DEFAULT",DEFERRABLE:"DEFERRABLE",DESC:"DESC",DISTINCT:"DISTINCT",DO:"DO",ELSE:"ELSE",END:"END",EXCEPT:"EXCEPT",FALSE:"FALSE",FOR:"FOR",FOREIGN:"FOREIGN",FREEZE:"FREEZE",FROM:"FROM",FULL:"FULL",GRANT:"GRANT",GROUP:"GROUP",HAVING:"HAVING",ILIKE:"ILIKE",IN:"IN",INITIALLY:"INITIALLY",INTERSECT:"INTERSECT",INTO:"INTO",IS:"IS",ISNULL:"ISNULL",JOIN:"JOIN",LATERAL:"LATERAL",LEADING:"LEADING",LEFT:"LEFT",LIKE:"LIKE",LIMIT:"LIMIT",LOCALTIME:"LOCALTIME",LOCALTIMESTAMP:"LOCALTIMESTAMP",NATURAL:"NATURAL",NOT:"NOT",NULL:"NULL",OFFSET:"OFFSET",ON:"ON",ONLY:"ONLY",OR:"OR",ORDER:"ORDER",OUTER:"OUTER",OVERLAPS:"OVERLAPS",PLACING:"PLACING",PRIMARY:"PRIMARY",REFERENCES:"REFERENCES",RETURNING:"RETURNING",RIGHT:"RIGHT",SELECT:"SELECT",SESSION_USER:"SESSION_USER",SIMILAR:"SIMILAR",SOME:"SOME",SYMMETRIC:"SYMMETRIC",TABLE:"TABLE",TABLESAMPLE:"TABLESAMPLE",THEN:"THEN",TO:"TO",TRAILING:"TRAILING",TRUE:"TRUE",UNION:"UNION",UNIQUE:"UNIQUE",USER:"USER",USING:"USING",VARIADIC:"VARIADIC",VERBOSE:"VERBOSE",WHEN:"WHEN",WHERE:"WHERE",WINDOW:"WINDOW",WITH:"WITH"}),yt=Object.values(Et);ve.exports={ReservedWordsAsArray:yt}});var oe=H((Ft,ke)=>{"use strict";var{AlterCollectionDto:Pt,AlterCollectionRoleDto:Kt}=Ye(),{ReservedWordsAsArray:Nt}=xe(),At=/\t|\n|'|\f|\r/gm;ke.exports=o=>{let I=n(r=>o.get(r,"[0].code")||o.get(r,"[0].name",""),"getDbName"),R=n(r=>r&&(r.code||r.collectionName)||"","getEntityName"),c=n(r=>r&&(r.code||r.name)||"","getViewName"),f=n(r=>Object.assign({},o.get(r,"[0]",{}),{name:I(r)}),"getDbData"),b=n(r=>o.get(r,"[0].viewOn"),"getViewOn"),U=n((r,T=" ")=>r.split(` +`).map(O=>T+O).join(` +`),"tab"),M=n((r,T)=>Object.keys(r).map(o.toLower).includes(o.toLower(T)),"hasType"),L=n(r=>({...r,...o.omit(r==null?void 0:r.role,"properties")||{}}),"getSchemaOfAlterCollection"),C=n(r=>{var F;let T=R(r),O=(F=r.compMod)==null?void 0:F.keyspaceName;return B(T,O)},"getFullCollectionName"),$=n(r=>Object.entries(r).filter(([T,O])=>!o.isNil(O)).reduce((T,[O,F])=>({...T,[O]:F}),{}),"clean"),y=n(r=>r.every(T=>o.get(T,"isActivated",!0)),"checkAllKeysActivated"),d=n(r=>r.length?r.every(T=>!o.get(T,"isActivated",!0)):!1,"checkAllKeysDeactivated"),a=n((r,T)=>{let O=r.filter(k=>o.get(k,"isActivated",!0)).map(T),F=r.filter(k=>!o.get(k,"isActivated",!0)).map(T);return{activatedItems:O,deactivatedItems:F}},"divideIntoActivatedAndDeactivated"),p=n((r,{isActivated:T,isPartOfLine:O,inlineComment:F="--"})=>r?T!==!1?r:O?"/* "+r+" */":r.includes(` +`)?`/* +`+r+` */ +`:F+" "+r:"","commentIfDeactivated"),s=n((r,T="'",O="'")=>{let F=r[0];return r[r.length-1]===T&&F===O?r:`${T}${r}${O}`},"wrap"),u=n((r,T)=>T.some(O=>(r==null?void 0:r.oldField[O])!==(r==null?void 0:r.newField[O])),"checkFieldPropertiesChanged"),i=n(r=>{var k;let T={...r,...o.omit(r==null?void 0:r.role,"properties")||{}},O=R(T),F=(k=T.compMod)==null?void 0:k.keyspaceName;return B(O,F)},"getFullTableName"),V=n((r,T)=>`${i(r)}.${W(T)}`,"getFullColumnName"),N=n(r=>{var k;let T={...r,...o.omit(r==null?void 0:r.role,"properties")||{}},O=c(T),F=(k=T.compMod)==null?void 0:k.keyspaceName;return B(O,F)},"getFullViewName"),S=n(r=>r.code||r.name,"getUdtName"),h=n((r="")=>{let T=r.match(/\d+/);return Number(o.get(T,[0],0))},"getDbVersion"),l=n((r="")=>r.replace(At,T=>`\\${T}`),"prepareComment"),A=n(r=>`E'${l(JSON.stringify(r)).slice(1,-1)}'`,"wrapComment"),K=n(r=>o.map(r,T=>{let O=T.defaultExpression?`DEFAULT ${T.defaultExpression}`:"";return o.trim(`${T.argumentMode} ${T.argumentName||""} ${T.argumentType} ${O}`)}).join(", "),"getFunctionArguments"),B=n((r,T)=>T?`${W(T)}.${W(r)}`:W(r),"getNamePrefixedWithSchemaName"),W=n(r=>/\s|\W/.test(r)||o.includes(Nt,o.toUpper(r))?`"${r}"`:r,"wrapInQuotes"),me=n(({name:r})=>W(r),"columnMapToString"),ue=n((r,T,O,F=me)=>{var t;let k=a(r,F),e=(t=k==null?void 0:k.deactivatedItems)!=null&&t.length?p(k.deactivatedItems.join(", "),{isActivated:!1,isPartOfLine:!0}):"";return!T&&O?" ("+k.activatedItems.join(", ")+e+")":" ("+r.map(F).join(", ")+")"},"getColumnsList"),ie=n(r=>r?r.alias?`${W(r.name)} as ${W(r.alias)}`:W(r.name):"","getKeyWithAlias");return{getDbName:I,getDbData:f,getEntityName:R,getViewName:c,getViewOn:b,tab:U,hasType:M,clean:$,checkAllKeysActivated:y,checkAllKeysDeactivated:d,divideIntoActivatedAndDeactivated:a,commentIfDeactivated:p,wrap:s,checkFieldPropertiesChanged:u,getFullTableName:i,getFullColumnName:V,getFullViewName:N,getUdtName:S,getDbVersion:h,wrapComment:A,getFunctionArguments:K,getNamePrefixedWithSchemaName:B,wrapInQuotes:W,getColumnsList:ue,getViewData:n(r=>Array.isArray(r)?r.reduce((T,O)=>{if(!O.tableName)return T.columns.push(ie(O)),T;let F=`${W(O.dbName)}.${W(O.tableName)}`;return T.tables.includes(F)||T.tables.push(F),T.columns.push({statement:`${F}.${ie(O)}`,isActivated:O.isActivated}),T},{tables:[],columns:[]}):{tables:[],columns:[]},"getViewData"),getSchemaOfAlterCollection:L,getFullCollectionName:C}}});var qe=H((Vt,Be)=>{"use strict";var De=n((o="")=>new RegExp("\\$\\{(.*?)\\}",o),"template"),$t=n(o=>o.match(De("gi"))||[],"getAllTemplates"),Ct=n(o=>(o.match(De("i"))||[])[1],"parseTemplate"),Ot=n((o,I)=>$t(o).reduce((R,c)=>{let f=Ct(c);return R.replace(c,()=>I[f]||I[f]===0?I[f]:"")},o),"assignTemplates");Be.exports=Ot});var we=H((vt,He)=>{"use strict";He.exports=({_:o,commentIfDeactivated:I,checkAllKeysDeactivated:R,assignTemplates:c,wrapInQuotes:f,getColumnsList:b})=>({generateConstraintsString:n((d,a)=>{var i,V;let p=I(((d==null?void 0:d.deactivatedItems)||[]).join(`, + `),{isActivated:!a,isPartOfLine:!0}),s=(i=d==null?void 0:d.activatedItems)!=null&&i.length?`, + `+d.activatedItems.join(`, + `):"",u=(V=d==null?void 0:d.deactivatedItems)!=null&&V.length?` + `+p:"";return s+u},"generateConstraintsString"),foreignKeysToString:n(d=>{if(Array.isArray(d)){let a=d.filter(u=>o.get(u,"isActivated",!0)).map(u=>f(o.trim(u.name))),p=d.filter(u=>!o.get(u,"isActivated",!0)).map(u=>f(o.trim(u.name))),s=p.length?I(p,{isActivated:!1,isPartOfLine:!0}):"";return a.join(", ")+s}return d},"foreignKeysToString"),foreignActiveKeysToString:n(d=>d.map(a=>o.trim(a.name)).join(", "),"foreignActiveKeysToString"),createKeyConstraint:n((d,a)=>p=>{let s=f(o.trim(p.name)),u=R(p.columns||[]),i=o.isEmpty(p.columns)?"":b(p.columns,u,a),V=p.include.length?` INCLUDE${b(p.include,u,a)}`:"",N=p.storageParameters?` WITH (${p.storageParameters})`:"";return{statement:c(d.createKeyConstraint,{constraintName:p.name?`CONSTRAINT ${s} `:"",keyType:p.keyType,columns:i,includeNonKey:V,storageParameters:N}),isActivated:!u}},"createKeyConstraint"),getConstraintsWarnings:n((d=[])=>o.isEmpty(d)?"":` + `+d.map(a=>{let p=a.name?` [constraint name: ${a.name}]`:"";return`-- ${a.errorMessage}${p}`}).join(` + `),"getConstraintsWarnings"),additionalPropertiesForForeignKey:n(d=>{let a=o.get(d,"relationshipOnDelete",""),p=o.get(d,"relationshipOnUpdate",""),s=o.get(d,"relationshipMatch","");return{foreignOnDelete:a,foreignOnUpdate:p,foreignMatch:s}},"additionalPropertiesForForeignKey")})});var We=H((kt,Ge)=>{"use strict";Ge.exports=(o,I)=>{let R=n((s,u)=>Object.entries(s.properties).map(u),"mapProperties"),c=n(s=>s.compositeUniqueKey?!1:!!s.unique,"isUniqueKey"),f=n(s=>{var u,i;return c(s)&&(((u=s.uniqueKeyOptions)==null?void 0:u.length)===1&&!((i=o.first(s.uniqueKeyOptions))!=null&&i.constraintName)||o.isEmpty(s.uniqueKeyOptions))},"isInlineUnique"),b=n(s=>s.compositeUniqueKey||s.compositePrimaryKey?!1:!!s.primaryKey,"isPrimaryKey"),U=n(s=>{var u;return b(s)&&!((u=o.first(s.primaryKeyOptions))!=null&&u.constraintName)},"isInlinePrimaryKey"),M=n(({options:s,columnName:u,isActivated:i,jsonSchema:V,dbVersion:N})=>I({keyType:"UNIQUE",name:s.constraintName,columns:[{name:u,isActivated:i}],include:y(s.indexInclude||[],V),storageParameters:s.indexStorageParameters,comment:s.indexComment}),"hydrateUniqueOptions"),L=n((s,u,i,V)=>I({keyType:"PRIMARY KEY",name:s.constraintName,columns:[{name:u,isActivated:i}],include:y(s.indexInclude||[],V),storageParameters:s.indexStorageParameters,comment:s.indexComment}),"hydratePrimaryKeyOptions"),C=n((s,u)=>Object.keys(u).find(i=>u[i].GUID===s),"findName"),$=n((s,u)=>o.get(Object.values(u).find(i=>i.GUID===s),"isActivated",!0),"checkIfActivated"),y=n((s,u)=>o.map(s,i=>({name:C(i.keyId,u.properties),isActivated:$(i.keyId,u.properties)})),"getKeys"),d=n(s=>Array.isArray(s.primaryKey)?s.primaryKey.map(u=>o.isEmpty(u.compositePrimaryKey)?{name:u.constraintName,errorMessage:"A primary key constraint cannot be created without any primary key selected"}:{...L(u,null,null,s),columns:y(u.compositePrimaryKey,s)}):[],"getCompositePrimaryKeys"),a=n((s,u)=>Array.isArray(s.uniqueKey)?s.uniqueKey.map(i=>o.isEmpty(i.compositeUniqueKey)?{name:i.constraintName,errorMessage:"A unique key constraint cannot be created without any unique key selected"}:{...M({options:i,columnName:null,isActivated:null,jsonSchema:s,dbVersion:u}),columns:y(i.compositeUniqueKey,s)}):[],"getCompositeUniqueKeys");return{getTableKeyConstraints:n((s,u)=>{if(!s.properties)return[];let i=R(s,([N,S])=>{if(!(!b(S)||U(S)))return L(o.first(S.primaryKeyOptions),N,S.isActivated,s)}).filter(Boolean),V=o.flatten(R(s,([N,S])=>!c(S)||f(S)?[]:(S.uniqueKeyOptions||[]).map(h=>M({options:h,columnName:N,isActivated:S.isActivated,jsonSchema:s,dbVersion:u})))).filter(Boolean);return[...i,...d(s),...V,...a(s,u)]},"getTableKeyConstraints"),isInlineUnique:f,isInlinePrimaryKey:U,getKeys:y,hydratePrimaryKeyOptions:L,hydrateUniqueOptions:M}}});var je=H((Bt,Xe)=>{"use strict";Xe.exports=({_:o,templates:I,assignTemplates:R,getFunctionArguments:c,getNamePrefixedWithSchemaName:f,wrapComment:b})=>{let U=n((N,S)=>o.map(S,h=>{let l=h.functionOrReplace?" OR REPLACE":"",A=R(I.createFunction,{name:f(h.name,N),orReplace:l,parameters:c(h.functionArguments),returnType:h.functionReturnsSetOf?`SETOF ${h.functionReturnType}`:h.functionReturnType,language:h.functionLanguage,properties:M(h),definition:h.functionBody}),K=h.functionDescription?R(I.comment,{object:"FUNCTION",objectName:f(h.name,N),comment:b(h.functionDescription)}):"";return[A,K].filter(Boolean).join(` +`)}).join(` +`),"getFunctionsScript"),M=n(N=>{let S=n(h=>h?` ${h} +`:"","wrap");return[{key:"functionWindow",getValue:L},{key:"functionVolatility",getValue:C},{key:"functionLeakProof",getValue:$},{key:"functionNullArgs",getValue:y},{key:"functionSqlSecurity",getValue:d},{key:"functionParallel",getValue:a},{key:"functionExecutionCost",getValue:p},{key:"functionExecutionRows",getValue:s},{key:"functionSupportFunction",getValue:u},{key:"functionConfigurationParameters",getValue:i}].map(h=>S(h.getValue(N[h.key],N))).filter(Boolean).join("")},"getProperties"),L=n((N,S)=>S.language!=="c"||!N?"":"WINDOW","getWindow"),C=n(N=>N,"getVolatility"),$=n(N=>N?"LEAKPROOF":"NOT LEAKPROOF","getLeakProof"),y=n(N=>N,"getNullArgs"),d=n(N=>{if(N)return`SECURITY ${N}`},"getSqlSecurity"),a=n(N=>{if(N)return`PARALLEL ${N}`},"getParallel"),p=n(N=>{if(N)return`COST ${N}`},"getExecutionCost"),s=n((N,S)=>!N||!S.functionReturnsSetOf&&!V(S)?"":`ROWS ${N}`,"getExecutionRows"),u=n(N=>{if(N)return`SUPPORT ${N}`},"getSupportFunction"),i=n(N=>{if(N)return`SET ${N}`},"getConfigurationParameters"),V=n(N=>(N.functionReturnType||"").trim().toUpperCase().startsWith("TABLE"),"isFunctionReturnsTable");return{getFunctionsScript:U}}});var Ze=H((Ht,ze)=>{"use strict";ze.exports=({_:o,templates:I,assignTemplates:R,getFunctionArguments:c,getNamePrefixedWithSchemaName:f})=>({getProceduresScript:n((U,M)=>o.map(M,L=>{let C=L.orReplace?" OR REPLACE":"";return R(I.createProcedure,{name:f(L.name,U),orReplace:C,parameters:c(L.inputArgs),language:L.language,body:L.body})}).join(` +`),"getProceduresScript")})});var Je=H((Gt,Qe)=>{"use strict";Qe.exports=({_:o,getColumnsList:I,checkAllKeysDeactivated:R})=>{let c=n(($,y)=>$?" TEMPORARY":y?" UNLOGGED":"","getTableTemporaryValue"),f=n($=>{let y=n(a=>a?`${a} +`:"","wrap"),d=[{key:"inherits",getValue:L("INHERITS")},{key:"partitionBounds",getValue:L("")},{key:"partitioning",getValue:b},{key:"usingMethod",getValue:L("USING")},{key:"storage_parameter",getValue:C},{key:"on_commit",getValue:M},{key:"selectStatement",getValue:L("AS")}].map(a=>y(a.getValue($[a.key],$))).filter(Boolean).join("");return o.trim(d)?` ${o.trim(d)}`:""},"getTableOptions"),b=n(($,{isActivated:y})=>{if($&&$.partitionMethod){let a=U($,y)+` (${$.partitioning_expression})`;return`PARTITION BY ${$.partitionMethod}${a}`}},"getPartitioning"),U=n(($,y)=>{let d=R($.compositePartitionKey);return I($.compositePartitionKey,d,y)},"getPartitionKeys"),M=n(($,y)=>{if($&&y.temporary)return`ON COMMIT ${$}`},"getOnCommit"),L=n($=>y=>{if(y)return`${$} ${y}`},"getBasicValue"),C=n($=>{if(o.isEmpty($))return"";let y=["ttl_storage_parameters"],d=["id",...y];return o.chain($).toPairs().flatMap(([a,p])=>y.includes(a)?o.toPairs(p):[[a,p]]).reject(([a])=>o.includes(d,a)).map(([a,p])=>{if(!(!p&&p!==0))return`${a}=${p}`}).compact().join(`, + `).trim().thru(a=>{if(a)return`WITH ( + ${a} +)`}).value()},"getStorageParameters");return{getTableTemporaryValue:c,getTableOptions:f}}});var et=H((Xt,_e)=>{"use strict";_e.exports=({_:o,commentIfDeactivated:I,assignTemplates:R,templates:c,getNamePrefixedWithSchemaName:f,wrapComment:b})=>{let U=["composite","enum","range_udt","domain"],M=n((a,p)=>{let s=f(a.name,a.schemaName),u=R(c.comment,{object:"TYPE",objectName:s,comment:b(a.comment)});switch(a.type){case"composite":return R(c.createCompositeType,{name:s,columnDefinitions:o.join(p,`, + `),comment:a.comment?u:""});case"enum":return R(c.createEnumType,{name:s,values:o.map(a.enum,i=>`'${i}'`).join(", "),comment:a.comment?u:""});case"range_udt":return R(c.createRangeType,{name:s,subtype:a.rangeSubtype,options:C(a),comment:a.comment?u:""});case"domain":{let i=R(c.comment,{object:"DOMAIN",objectName:s,comment:b(a.comment)});return R(c.createDomainType,{name:s,underlyingType:a.underlyingType,notNull:a.nullable?"":" NOT NULL",collate:a.collation?` + COLLATE ${a.collation}`:"",default:a.default?` + DEFAULT ${a.default}`:"",constraints:$(a),comment:a.comment?i:""})}default:return""}},"getPlainUdt"),L=n(a=>U.includes(a.type),"isNotPlainType"),C=n(a=>{let p=n(u=>u?` ${u}`:"","wrap"),s=[{key:"operatorClass",getValue:y("SUBTYPE_OPCLASS")},{key:"collation",getValue:y("COLLATION")},{key:"canonicalFunction",getValue:y("CANONICAL")},{key:"subtypeDiffFunction",getValue:y("SUBTYPE_DIFF")},{key:"multiRangeType",getValue:y("MULTIRANGE_TYPE_NAME")}].map(u=>p(u.getValue(a[u.key]))).filter(Boolean).join(`, +`);return o.trim(s)?`, + `+o.trim(s):""},"getRangeOptions"),$=n(a=>o.map(a.checkConstraints,p=>p.name?` + CONSTRAINT ${p.name} CHECK (${p.expression})`:` + CHECK (${p.expression})`).join(""),"getDomainConstraints"),y=n(a=>p=>{if(p)return`${a}=${p}`},"getBasicValue");return{getUserDefinedType:n((a,p)=>I(M(a,p),{isActivated:a.isActivated}),"getUserDefinedType"),isNotPlainType:L}}});var nt=H((zt,tt)=>{"use strict";tt.exports=({_:o,wrapInQuotes:I,checkAllKeysDeactivated:R,getColumnsList:c})=>{let f=n(({name:C,sortOrder:$,nullsOrder:y,opclass:d})=>{let a=$?` ${$}`:"",p=y?` ${y}`:"",s=d?` ${d}`:"";return`${I(C)}${s}${a}${p}`},"mapIndexKey"),b=n((C=[],$)=>{let y=R(C);return c(C,y,$,f)},"getIndexKeys"),U=n((C,$)=>{var S;let y=c(C.include||[],R(C.include||[]),$),d=["btree"],a=C.using_hash&&d.includes(C.index_method)?" USING HASH":"",p=(S=C.include)!=null&&S.length?` INCLUDE ${o.trim(y)}`:"",s=C.partitioning_expression||"",u=M(C),i=u?` WITH ( + ${u})`:"",V=C.where?` WHERE ${C.where}`:"",N=C.visibility?` ${C.visibility}`:"";return o.compact([" ",a,p,s,i,V,N]).join(` +`)},"getIndexOptions"),M=n(C=>{let $=["id"];return o.chain(C.index_storage_parameter).toPairs().map(([y,d])=>{if(!($.includes(y)||o.isNil(d)||d===""))return`${y}=${L(d)}`}).compact().join(`, + `).value()},"getWithOptions"),L=n(C=>o.isBoolean(C)?C?"ON":"OFF":C,"getValue");return{getIndexKeys:b,getIndexOptions:U}}});var at=H((Qt,rt)=>{"use strict";rt.exports=({_:o,assignTemplates:I,templates:R,commentIfDeactivated:c,wrapComment:f,wrapInQuotes:b})=>{let U=n((l,A)=>`${l}(${A})`,"addLength"),M=n((l,A,K)=>o.isNumber(K)?`${l}(${A},${K})`:`${l}(${A})`,"addScalePrecision"),L=n((l,A)=>o.isNumber(A)?`${l}(${A})`:l,"addPrecision"),C=n((l,A)=>A?`${l} ${A}`:l,"addWithTimezone"),$=n(({type:l,typeModifier:A,srid:K})=>{let B=K?`, ${K}`:"";return A&&A!==""?`${l}(${A}${B})`:l},"addTypeModifier"),y=n((l,A)=>{let K=(A==null?void 0:A.map(B=>`[${(B==null?void 0:B.array_size_limit)??""}]`).join("").trim())||"";return`${l}${K}`},"addArrayDecorator"),d=n(l=>["char","varchar","bit","varbit"].includes(l),"canHaveLength"),a=n(l=>["numeric","decimal"].includes(l),"canHavePrecision"),p=n(l=>["time","timestamp"].includes(l),"canHaveTimePrecision"),s=n(l=>["numeric","decimal"].includes(l),"canHaveScale"),u=n(l=>["geography","geometry"].includes(l),"canHaveTypeModifier"),i=n((l,A)=>(d(l)&&o.isNumber(A.length)?l=U(l,A.length):a(l)&&s(l)&&o.isNumber(A.precision)?l=M(l,A.precision,A.scale):a(l)&&o.isNumber(A.precision)?l=L(l,A.precision):u(l)?l=$({type:l,typeModifier:A.typeModifier,srid:A.srid}):p(l)&&(o.isNumber(A.timePrecision)||A.timezone)&&(l=C(L(l,A.timePrecision),A.timezone)),y(l,A.array_type)),"decorateType"),V=n(l=>["char","varchar","text","bit","varbit"].includes(l),"isString"),N=n(l=>["date","time","timestamp","interval"].includes(l),"isDateTime");return{decorateType:i,decorateDefault:n((l,A,K)=>{let B=["current_timestamp","null"];return(V(l)||N(l))&&!B.includes(o.toLower(A))&&!K?f(A):A},"decorateDefault"),getColumnComments:n((l,A)=>o.chain(A).filter("comment").map(K=>{let B=I(R.comment,{object:"COLUMN",objectName:`${l}.${b(K.name)}`,comment:f(K.comment)});return c(B,K)}).join(` +`).value(),"getColumnComments")}}});var st=H((_t,it)=>{"use strict";var It=Ue(),ot=Ke(),E=Me();it.exports=(o,I,R)=>{let c=R.require("lodash"),{tab:f,commentIfDeactivated:b,checkAllKeysDeactivated:U,divideIntoActivatedAndDeactivated:M,hasType:L,wrap:C,clean:$,wrapComment:y,getFunctionArguments:d,wrapInQuotes:a,getNamePrefixedWithSchemaName:p,getColumnsList:s,getViewData:u}=oe()(c),i=qe(),{generateConstraintsString:V,foreignKeysToString:N,foreignActiveKeysToString:S,createKeyConstraint:h,getConstraintsWarnings:l,additionalPropertiesForForeignKey:A}=we()({_:c,commentIfDeactivated:b,checkAllKeysDeactivated:U,assignTemplates:i,getColumnsList:s,wrapInQuotes:a}),K=We()(c,$),{getFunctionsScript:B}=je()({_:c,templates:E,assignTemplates:i,getFunctionArguments:d,getNamePrefixedWithSchemaName:p,wrapComment:y}),{getProceduresScript:W}=Ze()({_:c,templates:E,assignTemplates:i,getFunctionArguments:d,getNamePrefixedWithSchemaName:p}),{getTableTemporaryValue:me,getTableOptions:ue}=Je()({_:c,checkAllKeysDeactivated:U,getColumnsList:s}),{getUserDefinedType:ie,isNotPlainType:Re}=et()({_:c,commentIfDeactivated:b,assignTemplates:i,templates:E,getNamePrefixedWithSchemaName:p,wrapComment:y}),{getIndexKeys:r,getIndexOptions:T}=nt()({_:c,wrapInQuotes:a,checkAllKeysDeactivated:U,getColumnsList:s}),{decorateType:O,decorateDefault:F,getColumnComments:k}=at()({_:c,wrap:C,assignTemplates:i,templates:E,commentIfDeactivated:b,wrapInQuotes:a,wrapComment:y});return{createDatabase(e){if(!e.databaseName)return"";let{collate:t,characterClassification:m}=e;return i(E.createDatabase,{name:a(e.databaseName),template:e.template?` + TEMPLATE ${e.template}`:"",encoding:e.encoding?` + ENCODING = '${e.encoding}'`:"",collate:t?` + LC_COLLATE = '${e.collate}'`:"",characterClassification:m?` + LC_CTYPE = '${m}'`:""})},createSchema({schemaName:e,ifNotExist:t,comments:m,udfs:g,procedures:P}){let D=i(E.comment,{object:"SCHEMA",objectName:a(e),comment:y(m)}),x=i(E.createSchema,{name:a(e),ifNotExist:t?" IF NOT EXISTS":"",comment:m?D:""}),Y=B(e,g),q=W(e,P);return c.chain([x,Y,q]).compact().map(c.trim).join(` + +`).trim().value()},createTable({name:e,columns:t,checkConstraints:m,foreignKeyConstraints:g,schemaData:P,columnDefinitions:D,keyConstraints:x,inherits:Y,description:q,ifNotExist:G,usingMethod:j,on_commit:v,partitioning:X,storage_parameter:Q,temporary:J,unlogged:Z,selectStatement:_,partitionOf:w,partitionBounds:te},ee){let se=G?" IF NOT EXISTS":"",ae=p(e,P.schemaName),ce=i(E.comment,{object:"TABLE",objectName:ae,comment:y(q)}),z=M(x.filter(({errorMessage:re})=>!re).map(h(E,ee)),re=>re.statement),pe=l(x.filter(({errorMessage:re})=>re)),ne=`${V(z,ee)}${pe}`,Se=w?ne==null?void 0:ne.slice(1):ne,ct=M(g,re=>re.statement),fe=V(ct,ee),mt=` +`+k(ae,D),ut=w?E.createTablePartitionOf:E.createTable,pt=w&&!ne?` + `:`, + `,be=c.isEmpty(m)?"":C(c.join(m,`, + `),pt,""),Le=w&&!Se&&!be&&!fe,lt=Le?"":"(",dt=Le?"":")",Tt=i(ut,{temporary:me(J,Z),ifNotExist:se,name:ae,columnDefinitions:w?"":" "+c.join(t,`, + `),keyConstraints:Se,checkConstraints:be,foreignKeyConstraints:fe,options:ue({inherits:Y,partitioning:X,usingMethod:j,on_commit:v,storage_parameter:Q,selectStatement:_,partitionBounds:te}),comment:q?ce:"",partitionOf:w?` PARTITION OF ${w} `:"",columnDescriptions:mt,openParenthesis:lt,closeParenthesis:dt});return b([Tt].map(c.trim).join(` + +`).trim()+` +`,{isActivated:ee})},convertColumnDefinition(e){let t=e.nullable?"":" NOT NULL",m=e.primaryKey?" "+h(E,!0)(e.primaryKeyOptions).statement:"",g=e.unique?" "+h(E,!0)(e.uniqueKeyOptions).statement:"",P=e.collationRule?` COLLATE "${e.collationRule}"`:"",D=Array.isArray(e.array_type)&&e.array_type.length>0,x=c.isUndefined(e.default)?"":" DEFAULT "+F(e.type,e.default,D),Y=e.dbVersion>=12&&e.generatedColumn&&e.columnGenerationExpression?i(E.generatedColumnClause,{generationExpression:e.columnGenerationExpression}):"";return b(i(E.columnDefinition,{name:a(e.name),type:O(e.type,e),generatedColumnClause:Y,notNull:t,primaryKey:m,uniqueKey:g,collation:P,defaultValue:x}),{isActivated:e.isActivated})},createIndex(e,t,m,g=!0){let P=t.unique&&t.index_method==="btree",D=a(t.indxName),x=P?" UNIQUE":"",Y=t.concurrently?" CONCURRENTLY":"",q=t.ifNotExist?" IF NOT EXISTS":"",G=t.index_method?` USING ${c.toUpper(t.index_method)}`:"",j=r(t.index_method==="btree"?t.columns:c.map(t.columns,X=>c.omit(X,"sortOrder","nullsOrder")),g),v=T(t,g);return b(i(E.index,{unique:x,concurrently:Y,ifNotExist:q,name:D,using:G,keys:j,options:v,tableName:p(e,t.schemaName)}),{isActivated:t.isActivated})},createCheckConstraint(e){return i(E.checkConstraint,{name:e.name?`CONSTRAINT ${a(e.name)}`:"",expression:c.trim(e.expression).replace(/^\(([\s\S]*)\)$/,"$1"),notValid:e.notValid?" NOT VALID":""})},createForeignKeyConstraint({name:e,foreignKey:t,primaryTable:m,primaryKey:g,primaryTableActivated:P,foreignTableActivated:D,foreignSchemaName:x,primarySchemaName:Y,customProperties:q,isActivated:G},j,v){let X=U(g),Q=U(t),J=!X&&!Q&&P&&D,{foreignOnDelete:Z,foreignOnUpdate:_,foreignMatch:w}=A(q),te=i(E.createForeignKeyConstraint,{primaryTable:p(m,Y||v.schemaName),name:e?`CONSTRAINT ${a(e)}`:"",foreignKey:J?N(t):S(t),primaryKey:J?N(g):S(g),onDelete:Z?` ON DELETE ${Z}`:"",onUpdate:_?` ON UPDATE ${_}`:"",match:w?` MATCH ${w}`:""});return{statement:c.trim(te),isActivated:J&&G}},createForeignKey({name:e,foreignTable:t,foreignKey:m,primaryTable:g,primaryKey:P,primaryTableActivated:D,foreignTableActivated:x,foreignSchemaName:Y,primarySchemaName:q,customProperties:G,isActivated:j},v,X){let Q=U(P),J=U(m),Z=!Q&&!J&&D&&x,{foreignOnDelete:_,foreignOnUpdate:w,foreignMatch:te}=A(G),ee=i(E.createForeignKey,{primaryTable:p(g,q||X.schemaName),foreignTable:p(t,Y||X.schemaName),name:e?a(e):"",foreignKey:Z?N(m):S(m),primaryKey:Z?N(P):S(P),onDelete:_?` ON DELETE ${_}`:"",onUpdate:w?` ON UPDATE ${w}`:"",match:te?` MATCH ${te}`:""});return{statement:c.trim(ee),isActivated:Z&&j}},createView(e,t,m){var ee,se,ae,ce;let g=p(e.name,e.schemaName),P=i(E.comment,{object:"VIEW",objectName:g,comment:y(e.comment)}),x=U(e.keys||[])||!m,{columns:Y,tables:q}=u(e.keys),G=Y.map(z=>z.statement).join(`, + `);if(!x){let z=M(Y,ne=>ne.statement),pe=z.deactivatedItems.length?b(z.deactivatedItems.join(`, + `),{isActivated:!1,isPartOfLine:!0}):"";G=z.activatedItems.join(`, + `)+pe}let j=c.trim(e.selectStatement)?c.trim(f(e.selectStatement)):i(E.viewSelectStatement,{tableName:q.join(", "),keys:G}),v=(ee=e.viewOptions)!=null&&ee.check_option?`check_option=${(se=e.viewOptions)==null?void 0:se.check_option}`:"",X=(ae=e.viewOptions)!=null&&ae.security_barrier?"security_barrier":"",Q=15,{getDbVersion:J}=oe()(c),Z=(ce=e.viewOptions)!=null&&ce.security_invoker&&J(t.dbVersion)>=Q?"security_invoker":"",_=v||X||Z?` + WITH (${c.compact([v,X,Z]).join(",")})`:"",w=n(z=>z.withCheckOption&&z.checkTestingScope?` + WITH ${z.checkTestingScope} CHECK OPTION`:z.withCheckOption?` + WITH CHECK OPTION`:"","getCheckOption");return[b(i(E.createView,{name:g,orReplace:e.orReplace?" OR REPLACE":"",temporary:e.temporary?" TEMPORARY":"",checkOption:w(e),comment:e.comment?P:"",withOptions:_,selectStatement:j}),{isActivated:!x})].map(c.trim).join(` + +`).trim()+` +`},dropView(e){let t={viewName:e};return i(E.dropView,t)},createViewIndex(){return""},createUdt(e){let t=c.map(e.properties,this.convertColumnDefinition);return ie(e,t)},getDefaultType(e){return It[e]},getTypesDescriptors(){return ot},hasType(e){return L(ot,e)},hydrateDatabase({modelData:e}){return e=c.get(e,"0",{}),{databaseName:e.database_name,encoding:e.encoding,template:e.template,collate:e.LC_COLLATE,characterClassification:e.LC_CTYPE,dbVersion:e.dbVersion}},hydrateColumn({columnDefinition:e,jsonSchema:t,schemaData:m,definitionJsonSchema:g={},parentJsonSchema:P}){let D=c.includes(["char","varchar","text"],e.type)?t.collationRule:"",x=["time","timestamp"],Y=c.includes(x,e.type)?t.timePrecision:"",q=c.includes(x,e.type)?t.timezone:"",G=e.type==="interval"?t.intervalOptions:"",{getDbVersion:j}=oe()(c),v=j(m.dbVersion),X=c.omit(K.hydratePrimaryKeyOptions(c.first(t.primaryKeyOptions)||{},e.name,e.isActivated,P),"columns"),Q=c.omit(K.hydrateUniqueOptions({options:c.first(t.uniqueKeyOptions)||{},columnName:e.name,isActivated:e.isActivated,jsonSchema:P,dbVersion:v}),"columns");return{name:e.name,type:e.type,primaryKey:K.isInlinePrimaryKey(t),primaryKeyOptions:X,unique:K.isInlineUnique(t),uniqueKeyOptions:Q,nullable:e.nullable,default:e.default,comment:t.refDescription||t.description||g.description,isActivated:e.isActivated,scale:e.scale,precision:e.precision,length:e.length,enum:t.enum,array_type:t.array_type,unit:t.unit,rangeSubtype:t.rangeSubtype,operatorClass:t.operatorClass,collation:t.collation,canonicalFunction:t.canonicalFunction,subtypeDiffFunction:t.subtypeDiffFunction,multiRangeType:t.multiRangeType,schemaName:m.schemaName,underlyingType:t.underlyingType,checkConstraints:t.checkConstraints,typeModifier:t.typeModifier,srid:t.srid,collationRule:D,timePrecision:Y,timezone:q,intervalOptions:G,dbVersion:v,generatedColumn:!!t.generatedColumn,columnGenerationExpression:t.columnGenerationExpression}},hydrateJsonSchemaColumn(e,t){return!e.$ref||c.isEmpty(t)||Re(t)?e:(e=c.omit(e,"$ref"),{...t,...e})},hydrateIndex(e,t,m){return{...e,schemaName:m.schemaName}},hydrateViewIndex(e){return{}},hydrateCheckConstraint(e){return{name:e.chkConstrName,expression:e.constrExpression,notValid:e.notValid}},hydrateSchema(e,t){let m=c.get(t,"modelData.0.dbVersion");return{schemaName:e.name,ifNotExist:e.ifNotExist,comments:e.description,udfs:(t==null?void 0:t.udfs)||[],procedures:(t==null?void 0:t.procedures)||[],dbVersion:m}},hydrateTable({tableData:e,entityData:t,jsonSchema:m}){let g=t[0],P=c.chain(g.inherits).map(({parentTable:v})=>c.get(e,`relatedSchemas[${v}]`,"")).compact().map(v=>v.code||v.collectionName).join(", ").thru(v=>v?`(${v})`:"").value(),D=c.first(g.partitioning)||{},x=K.getKeys(D.compositePartitionKey,m),Y=c.get(e,`relatedSchemas[${g.partitionOf}]`),q=Y?p(Y.collectionName,Y.bucketName):"",{getDbVersion:G}=oe()(c),j=G(c.get(e,"dbData.dbVersion",""));return{...e,partitionOf:q,keyConstraints:K.getTableKeyConstraints(m,j),inherits:P,selectStatement:c.trim(g.selectStatement),partitioning:c.assign({},D,{compositePartitionKey:x}),...c.pick(g,"temporary","unlogged","description","ifNotExist","usingMethod","on_commit","storage_parameter","partitionBounds")}},hydrateViewColumn(e){return{name:e.name,tableName:e.entityName,alias:e.alias,isActivated:e.isActivated,dbName:e.dbName}},hydrateView({viewData:e,entityData:t,relatedSchemas:m}){let g=t[0];return{name:e.name,keys:e.keys,comment:g.description,orReplace:g.orReplace,temporary:g.temporary,recursive:g.recursive,viewOptions:g.viewOptions,selectStatement:g.selectStatement,withCheckOption:g.withCheckOption,checkTestingScope:g.withCheckOption?g.checkTestingScope:"",schemaName:e.schemaData.schemaName}},commentIfDeactivated(e,t,m){return e},alterColumnType(e,t,m,g){let P=m;return g.length?P+=`(${g.length})`:g.precision&&g.scale?P+=`(${g.precision},${g.scale})`:g.precision&&(P+=`(${g.precision})`),i(E.alterColumnType,{tableName:e,columnName:t,dataType:P})},setNotNullConstraint(e,t){return i(E.addNotNullConstraint,{tableName:e,columnName:t})},dropNotNullConstraint(e,t){return i(E.dropNotNullConstraint,{tableName:e,columnName:t})},renameColumn(e,t,m){return i(E.renameColumn,{tableName:e,oldColumnName:t,newColumnName:m})},addCheckConstraint(e,t,m){let g={tableName:e,constraintName:t,expression:m};return i(E.addCheckConstraint,g)},dropConstraint(e,t){let m={tableName:e,constraintName:t};return i(E.dropConstraint,m)},updateTableComment(e,t){let m={tableName:e,comment:t};return i(E.updateCommentOnTable,m)},dropTableComment(e){let t={tableName:e,comment:"NULL"};return i(E.updateCommentOnTable,t)},updateColumnComment(e,t){let m={columnName:e,comment:t};return i(E.updateCommentOnColumn,m)},dropColumnComment(e){let t={columnName:e,comment:"NULL"};return i(E.updateCommentOnColumn,t)},updateSchemaComment(e,t){let m={schemaName:e,comment:t};return i(E.updateCommentOnSchema,m)},dropSchemaComment(e){let t={schemaName:e,comment:"NULL"};return i(E.updateCommentOnSchema,t)},updateViewComment(e,t){let m={viewName:e,comment:t};return i(E.updateCommentOnView,m)},dropViewComment(e){let t={viewName:e,comment:"NULL"};return i(E.updateCommentOnView,t)},createSchemaOnly(e){let t={schemaName:e};return i(E.createSchemaOnly,t)},dropSchema(e){let t={schemaName:e};return i(E.dropSchema,t)},dropTable(e){let t={tableName:e};return i(E.dropTable,t)},addColumn(e,t){let m={tableName:e,columnDefinition:t};return i(E.addColumn,m)},dropColumn(e,t){let m={tableName:e,columnName:t};return i(E.dropColumn,m)},dropDomain(e){let t={udtName:e};return i(E.dropDomain,t)},dropType(e){let t={udtName:e};return i(E.dropType,t)},alterTypeAddAttribute(e,t){let m={udtName:e,columnDefinition:t};return i(E.alterTypeAddAttribute,m)},alterTypeDropAttribute(e,t){let m={udtName:e,attributeName:t};return i(E.alterTypeDropAttribute,m)},alterTypeRenameAttribute(e,t,m){let g={udtName:e,oldAttributeName:t,newAttributeName:m};return i(E.alterTypeRenameAttribute,g)},alterTypeChangeAttributeType(e,t,m){let g={udtName:e,attributeName:t,newDataType:m};return i(E.alterTypeChangeAttributeType,g)},dropForeignKey(e,t){let m={tableName:e,fkConstraintName:t};return i(E.dropForeignKey,m)},createKeyConstraint(e,t,m){let g=h(E,t)(m);return{statement:i(E.addPkConstraint,{constraintStatement:(g.statement||"").trim(),tableName:e}),isActivated:g.isActivated}},dropPkConstraint(e,t){let m={tableName:e,constraintName:t};return i(E.dropConstraint,m)}}}});module.exports=st(); diff --git a/forward_engineering/ddlProvider/ddlHelpers/columnDefinitionHelper.js b/forward_engineering/ddlProvider/ddlHelpers/columnDefinitionHelper.js deleted file mode 100644 index 3247a61..0000000 --- a/forward_engineering/ddlProvider/ddlHelpers/columnDefinitionHelper.js +++ /dev/null @@ -1,109 +0,0 @@ -module.exports = ({ _, assignTemplates, templates, commentIfDeactivated, wrapComment, wrapInQuotes }) => { - const addLength = (type, length) => { - return `${type}(${length})`; - }; - - const addScalePrecision = (type, precision, scale) => { - if (_.isNumber(scale)) { - return `${type}(${precision},${scale})`; - } else { - return `${type}(${precision})`; - } - }; - - const addPrecision = (type, precision) => { - if (_.isNumber(precision)) { - return `${type}(${precision})`; - } - - return type; - }; - - const addWithTimezone = (type, timezone) => { - if (timezone) { - return `${type} ${timezone}`; - } - - return type; - }; - - const addTypeModifier = ({ type, typeModifier, srid }) => { - const typeSrid = srid ? `, ${srid}` : ``; - if (typeModifier && typeModifier !== '') { - return `${type}(${typeModifier}${typeSrid})`; - } - return type; - }; - const addArrayDecorator = (type, array_type) => { - const arrayDecorator = - array_type - ?.map(item => `[${item?.array_size_limit ?? ''}]`) - .join('') - .trim() || ''; - - return `${type}${arrayDecorator}`; - }; - - const canHaveLength = type => ['char', 'varchar', 'bit', 'varbit'].includes(type); - const canHavePrecision = type => ['numeric', 'decimal'].includes(type); - const canHaveTimePrecision = type => ['time', 'timestamp'].includes(type); - const canHaveScale = type => ['numeric', 'decimal'].includes(type); - const canHaveTypeModifier = type => ['geography', 'geometry'].includes(type); - - const decorateType = (type, columnDefinition) => { - if (canHaveLength(type) && _.isNumber(columnDefinition.length)) { - type = addLength(type, columnDefinition.length); - } else if (canHavePrecision(type) && canHaveScale(type) && _.isNumber(columnDefinition.precision)) { - type = addScalePrecision(type, columnDefinition.precision, columnDefinition.scale); - } else if (canHavePrecision(type) && _.isNumber(columnDefinition.precision)) { - type = addPrecision(type, columnDefinition.precision); - } else if (canHaveTypeModifier(type)) { - type = addTypeModifier({ - type, - typeModifier: columnDefinition.typeModifier, - srid: columnDefinition.srid, - }); - } else if ( - canHaveTimePrecision(type) && - (_.isNumber(columnDefinition.timePrecision) || columnDefinition.timezone) - ) { - type = addWithTimezone(addPrecision(type, columnDefinition.timePrecision), columnDefinition.timezone); - } - - return addArrayDecorator(type, columnDefinition.array_type); - }; - - const isString = type => ['char', 'varchar', 'text', 'bit', 'varbit'].includes(type); - const isDateTime = type => ['date', 'time', 'timestamp', 'interval'].includes(type); - - const decorateDefault = (type, defaultValue, isArrayType) => { - const constantsValues = ['current_timestamp', 'null']; - if ((isString(type) || isDateTime(type)) && !constantsValues.includes(_.toLower(defaultValue)) && !isArrayType) { - return wrapComment(defaultValue); - } else { - return defaultValue; - } - }; - - const getColumnComments = (tableName, columnDefinitions) => { - return _.chain(columnDefinitions) - .filter('comment') - .map(columnData => { - const comment = assignTemplates(templates.comment, { - object: 'COLUMN', - objectName: `${tableName}.${wrapInQuotes(columnData.name)}`, - comment: wrapComment(columnData.comment), - }); - - return commentIfDeactivated(comment, columnData); - }) - .join('\n') - .value(); - }; - - return { - decorateType, - decorateDefault, - getColumnComments, - }; -}; diff --git a/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js b/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js deleted file mode 100644 index ac1b08a..0000000 --- a/forward_engineering/ddlProvider/ddlHelpers/constraintsHelper.js +++ /dev/null @@ -1,138 +0,0 @@ -module.exports = ({ - _, - commentIfDeactivated, - checkAllKeysDeactivated, - assignTemplates, - wrapInQuotes, - getColumnsList, - }) => { - const generateConstraintsString = (dividedConstraints, isParentActivated) => { - const deactivatedItemsAsString = commentIfDeactivated( - (dividedConstraints?.deactivatedItems || []).join(',\n\t'), - { - isActivated: !isParentActivated, - isPartOfLine: true, - }, - ); - const activatedConstraints = dividedConstraints?.activatedItems?.length - ? ',\n\t' + dividedConstraints.activatedItems.join(',\n\t') - : ''; - - const deactivatedConstraints = dividedConstraints?.deactivatedItems?.length - ? '\n\t' + deactivatedItemsAsString - : ''; - - return activatedConstraints + deactivatedConstraints; - }; - - const foreignKeysToString = keys => { - if (Array.isArray(keys)) { - const activatedKeys = keys - .filter(key => _.get(key, 'isActivated', true)) - .map(key => wrapInQuotes(_.trim(key.name))); - const deactivatedKeys = keys - .filter(key => !_.get(key, 'isActivated', true)) - .map(key => wrapInQuotes(_.trim(key.name))); - const deactivatedKeysAsString = deactivatedKeys.length - ? commentIfDeactivated(deactivatedKeys, {isActivated: false, isPartOfLine: true}) - : ''; - - return activatedKeys.join(', ') + deactivatedKeysAsString; - } - return keys; - }; - - const foreignActiveKeysToString = keys => { - return keys.map(key => _.trim(key.name)).join(', '); - }; - - /** - * @param templates {Object} - * @param isParentActivated {boolean} - * @return {( - * keyData: { - * name: string, - * keyType: string, - * columns: Array<{ - * isActivated: boolean, - * name: string, - * }>, - * include: Array<{ - * isActivated: boolean, - * name: string, - * }>, - * storageParameters: string, - * } - * ) => { - * statement: string, - * isActivated: boolean, - * }} - * */ - const createKeyConstraint = (templates, isParentActivated) => keyData => { - const constraintName = wrapInQuotes(_.trim(keyData.name)); - const isAllColumnsDeactivated = checkAllKeysDeactivated(keyData.columns || []); - const columns = !_.isEmpty(keyData.columns) - ? getColumnsList(keyData.columns, isAllColumnsDeactivated, isParentActivated) - : ''; - const includeNonKey = keyData.include.length - ? ` INCLUDE${getColumnsList(keyData.include, isAllColumnsDeactivated, isParentActivated)}` - : ''; - const storageParameters = keyData.storageParameters ? ` WITH (${keyData.storageParameters})` : ''; - - return { - statement: assignTemplates(templates.createKeyConstraint, { - constraintName: keyData.name ? `CONSTRAINT ${constraintName} ` : '', - keyType: keyData.keyType, - columns, - includeNonKey, - storageParameters, - }), - isActivated: !isAllColumnsDeactivated, - }; - }; - - const getConstraintsWarnings = (invalidConstraints = []) => { - if (_.isEmpty(invalidConstraints)) { - return ''; - } - - return ( - '\n\t' + - invalidConstraints - .map(keyData => { - const constraintName = keyData.name ? ` [constraint name: ${keyData.name}]` : ''; - - return `-- ${keyData.errorMessage}${constraintName}`; - }) - .join('\n\t') - ); - }; - - /** - * @param relationshipCustomProperties {{ - * relationshipOnDelete?: string, - * relationshipOnUpdate?: string, - * relationshipMatch?: string, - * }} - * @return {{ - * relationshipOnDelete: string, - * relationshipOnUpdate: string, - * relationshipMatch: string, - * }} - * */ - const additionalPropertiesForForeignKey = relationshipCustomProperties => { - const foreignOnDelete = _.get(relationshipCustomProperties, 'relationshipOnDelete', ''); - const foreignOnUpdate = _.get(relationshipCustomProperties, 'relationshipOnUpdate', ''); - const foreignMatch = _.get(relationshipCustomProperties, 'relationshipMatch', ''); - return {foreignOnDelete, foreignOnUpdate, foreignMatch}; - }; - - return { - generateConstraintsString, - foreignKeysToString, - foreignActiveKeysToString, - createKeyConstraint, - getConstraintsWarnings, - additionalPropertiesForForeignKey, - }; -}; diff --git a/forward_engineering/ddlProvider/ddlHelpers/functionHelper.js b/forward_engineering/ddlProvider/ddlHelpers/functionHelper.js deleted file mode 100644 index 68641d5..0000000 --- a/forward_engineering/ddlProvider/ddlHelpers/functionHelper.js +++ /dev/null @@ -1,110 +0,0 @@ -module.exports = ({ - _, - templates, - assignTemplates, - getFunctionArguments, - getNamePrefixedWithSchemaName, - wrapComment, -}) => { - const getFunctionsScript = (schemaName, udfs) => { - return _.map(udfs, udf => { - const orReplace = udf.functionOrReplace ? ' OR REPLACE' : ''; - const createFunctionStatement = assignTemplates(templates.createFunction, { - name: getNamePrefixedWithSchemaName(udf.name, schemaName), - orReplace: orReplace, - parameters: getFunctionArguments(udf.functionArguments), - returnType: udf.functionReturnsSetOf ? `SETOF ${udf.functionReturnType}` : udf.functionReturnType, - language: udf.functionLanguage, - properties: getProperties(udf), - definition: udf.functionBody, - }); - const commentOnFunction = udf.functionDescription - ? assignTemplates(templates.comment, { - object: 'FUNCTION', - objectName: getNamePrefixedWithSchemaName(udf.name, schemaName), - comment: wrapComment(udf.functionDescription), - }) - : ''; - - return [createFunctionStatement, commentOnFunction].filter(Boolean).join('\n'); - }).join('\n'); - }; - - const getProperties = udf => { - const wrap = value => (value ? `\t${value}\n` : ''); - - return [ - { key: 'functionWindow', getValue: getWindow }, - { key: 'functionVolatility', getValue: getVolatility }, - { key: 'functionLeakProof', getValue: getLeakProof }, - { key: 'functionNullArgs', getValue: getNullArgs }, - { key: 'functionSqlSecurity', getValue: getSqlSecurity }, - { key: 'functionParallel', getValue: getParallel }, - { key: 'functionExecutionCost', getValue: getExecutionCost }, - { key: 'functionExecutionRows', getValue: getExecutionRows }, - { key: 'functionSupportFunction', getValue: getSupportFunction }, - { key: 'functionConfigurationParameters', getValue: getConfigurationParameters }, - ] - .map(config => wrap(config.getValue(udf[config.key], udf))) - .filter(Boolean) - .join(''); - }; - - const getWindow = (value, udf) => { - if (udf.language !== 'c' || !value) { - return ''; - } - - return 'WINDOW'; - }; - const getVolatility = value => value; - const getLeakProof = value => { - if (value) { - return 'LEAKPROOF'; - } - - return 'NOT LEAKPROOF'; - }; - const getNullArgs = value => value; - const getSqlSecurity = value => { - if (value) { - return `SECURITY ${value}`; - } - }; - const getParallel = value => { - if (value) { - return `PARALLEL ${value}`; - } - }; - const getExecutionCost = value => { - if (value) { - return `COST ${value}`; - } - }; - const getExecutionRows = (value, udf) => { - if (!value || (!udf.functionReturnsSetOf && !isFunctionReturnsTable(udf))) { - return ''; - } - - return `ROWS ${value}`; - }; - const getSupportFunction = value => { - if (value) { - return `SUPPORT ${value}`; - } - }; - const getConfigurationParameters = value => { - if (value) { - return `SET ${value}`; - } - }; - - const isFunctionReturnsTable = (udf) => { - const returnType = (udf.functionReturnType || '').trim().toUpperCase(); - return returnType.startsWith('TABLE'); - }; - - return { - getFunctionsScript, - }; -}; diff --git a/forward_engineering/ddlProvider/ddlHelpers/indexHelper.js b/forward_engineering/ddlProvider/ddlHelpers/indexHelper.js deleted file mode 100644 index 916128e..0000000 --- a/forward_engineering/ddlProvider/ddlHelpers/indexHelper.js +++ /dev/null @@ -1,64 +0,0 @@ -module.exports = ({ _, wrapInQuotes, checkAllKeysDeactivated, getColumnsList }) => { - const mapIndexKey = ({ name, sortOrder, nullsOrder, opclass }) => { - const sortOrderStr = sortOrder ? ` ${sortOrder}` : ''; - const nullsOrderStr = nullsOrder ? ` ${nullsOrder}` : ''; - const opclassStr = opclass ? ` ${opclass}` : ''; - - return `${wrapInQuotes(name)}${opclassStr}${sortOrderStr}${nullsOrderStr}`; - }; - - const getIndexKeys = (columns = [], isParentActivated) => { - const isAllColumnsDeactivated = checkAllKeysDeactivated(columns); - - return getColumnsList(columns, isAllColumnsDeactivated, isParentActivated, mapIndexKey); - }; - - const getIndexOptions = (index, isParentActivated) => { - const includeKeys = getColumnsList( - index.include || [], - checkAllKeysDeactivated(index.include || []), - isParentActivated, - ); - const indexesThatSupportHashing = ['btree']; - - const usingHash = index.using_hash && indexesThatSupportHashing.includes(index.index_method) ? ' USING HASH' : ''; - const include = index.include?.length ? ` INCLUDE ${_.trim(includeKeys)}` : ''; - const partitioning = index.partitioning_expression || ''; - const withOptionsString = getWithOptions(index); - const withOptions = withOptionsString ? ` WITH (\n\t${withOptionsString})` : ''; - const whereExpression = index.where ? ` WHERE ${index.where}` : ''; - const visibility = index.visibility ? ` ${index.visibility}` : ''; - - return _.compact([' ', usingHash, include, partitioning, withOptions, whereExpression, visibility]).join('\n'); - }; - - const getWithOptions = index => { - const keysToOmit = ['id']; - - return _.chain(index.index_storage_parameter) - .toPairs() - .map(([key, value]) => { - if (keysToOmit.includes(key) || _.isNil(value) || value === '') { - return; - } - - return `${key}=${getValue(value)}`; - }) - .compact() - .join(',\n\t') - .value(); - }; - - const getValue = value => { - if (_.isBoolean(value)) { - return value ? 'ON' : 'OFF'; - } - - return value; - }; - - return { - getIndexKeys, - getIndexOptions, - }; -}; diff --git a/forward_engineering/ddlProvider/ddlHelpers/keyHelper.js b/forward_engineering/ddlProvider/ddlHelpers/keyHelper.js deleted file mode 100644 index 7f1af7e..0000000 --- a/forward_engineering/ddlProvider/ddlHelpers/keyHelper.js +++ /dev/null @@ -1,180 +0,0 @@ -module.exports = (_, clean) => { - const mapProperties = (jsonSchema, iteratee) => { - return Object.entries(jsonSchema.properties).map(iteratee); - }; - - const isUniqueKey = column => { - if (column.compositeUniqueKey) { - return false; - } else if (!column.unique) { - return false; - } else { - return true; - } - }; - - const isInlineUnique = column => { - return ( - isUniqueKey(column) && - ((column.uniqueKeyOptions?.length === 1 && !_.first(column.uniqueKeyOptions)?.constraintName) || - _.isEmpty(column.uniqueKeyOptions)) - ); - }; - - const isPrimaryKey = column => { - if (column.compositeUniqueKey) { - return false; - } else if (column.compositePrimaryKey) { - return false; - } else if (!column.primaryKey) { - return false; - } else { - return true; - } - }; - - const isInlinePrimaryKey = column => { - return isPrimaryKey(column) && !_.first(column.primaryKeyOptions)?.constraintName; - }; - - const hydrateUniqueOptions = ({ options, columnName, isActivated, jsonSchema, dbVersion }) => - clean({ - keyType: 'UNIQUE', - name: options['constraintName'], - columns: [ - { - name: columnName, - isActivated: isActivated, - }, - ], - include: getKeys(options['indexInclude'] || [], jsonSchema), - storageParameters: options['indexStorageParameters'], - comment: options['indexComment'], - }); - - const hydratePrimaryKeyOptions = (options, columnName, isActivated, jsonSchema) => - clean({ - keyType: 'PRIMARY KEY', - name: options['constraintName'], - columns: [ - { - name: columnName, - isActivated: isActivated, - }, - ], - include: getKeys(options['indexInclude'] || [], jsonSchema), - storageParameters: options['indexStorageParameters'], - comment: options['indexComment'], - }); - - const findName = (keyId, properties) => { - return Object.keys(properties).find(name => properties[name].GUID === keyId); - }; - - const checkIfActivated = (keyId, properties) => { - return _.get( - Object.values(properties).find(prop => prop.GUID === keyId), - 'isActivated', - true, - ); - }; - - const getKeys = (keys, jsonSchema) => { - return _.map(keys, key => { - return { - name: findName(key.keyId, jsonSchema.properties), - isActivated: checkIfActivated(key.keyId, jsonSchema.properties), - }; - }); - }; - - const getCompositePrimaryKeys = jsonSchema => { - if (!Array.isArray(jsonSchema.primaryKey)) { - return []; - } - - return jsonSchema.primaryKey.map(primaryKey => - !_.isEmpty(primaryKey.compositePrimaryKey) - ? { - ...hydratePrimaryKeyOptions(primaryKey, null, null, jsonSchema), - columns: getKeys(primaryKey.compositePrimaryKey, jsonSchema), - } - : { - name: primaryKey.constraintName, - errorMessage: 'A primary key constraint cannot be created without any primary key selected', - }, - ); - }; - - const getCompositeUniqueKeys = (jsonSchema, dbVersion) => { - if (!Array.isArray(jsonSchema.uniqueKey)) { - return []; - } - - return jsonSchema.uniqueKey.map(uniqueKey => - !_.isEmpty(uniqueKey.compositeUniqueKey) - ? { - ...hydrateUniqueOptions({ - options: uniqueKey, - columnName: null, - isActivated: null, - jsonSchema, - dbVersion, - }), - columns: getKeys(uniqueKey.compositeUniqueKey, jsonSchema), - } - : { - name: uniqueKey.constraintName, - errorMessage: 'A unique key constraint cannot be created without any unique key selected', - }, - ); - }; - - const getTableKeyConstraints = (jsonSchema, dbVersion) => { - if (!jsonSchema.properties) { - return []; - } - - const primaryKeyConstraints = mapProperties(jsonSchema, ([name, schema]) => { - if (!isPrimaryKey(schema) || isInlinePrimaryKey(schema)) { - return; - } - - return hydratePrimaryKeyOptions(_.first(schema.primaryKeyOptions), name, schema.isActivated, jsonSchema); - }).filter(Boolean); - - const uniqueKeyConstraints = _.flatten( - mapProperties(jsonSchema, ([name, schema]) => { - if (!isUniqueKey(schema) || isInlineUnique(schema)) { - return []; - } - - return (schema.uniqueKeyOptions || []).map(uniqueKey => - hydrateUniqueOptions({ - options: uniqueKey, - columnName: name, - isActivated: schema.isActivated, - jsonSchema, - dbVersion, - }), - ); - }), - ).filter(Boolean); - - return [ - ...primaryKeyConstraints, - ...getCompositePrimaryKeys(jsonSchema), - ...uniqueKeyConstraints, - ...getCompositeUniqueKeys(jsonSchema, dbVersion), - ]; - }; - - return { - getTableKeyConstraints, - isInlineUnique, - isInlinePrimaryKey, - getKeys, - hydratePrimaryKeyOptions, - hydrateUniqueOptions, - }; -}; diff --git a/forward_engineering/ddlProvider/ddlHelpers/procedureHelper.js b/forward_engineering/ddlProvider/ddlHelpers/procedureHelper.js deleted file mode 100644 index a2b1614..0000000 --- a/forward_engineering/ddlProvider/ddlHelpers/procedureHelper.js +++ /dev/null @@ -1,18 +0,0 @@ -module.exports = ({ _, templates, assignTemplates, getFunctionArguments, getNamePrefixedWithSchemaName }) => { - const getProceduresScript = (schemaName, procedures) => { - return _.map(procedures, procedure => { - const orReplace = procedure.orReplace ? ' OR REPLACE' : ''; - - return assignTemplates(templates.createProcedure, { - name: getNamePrefixedWithSchemaName(procedure.name, schemaName), - orReplace: orReplace, - parameters: getFunctionArguments(procedure.inputArgs), - language: procedure.language, - body: procedure.body, - }); - }).join('\n'); - }; - return { - getProceduresScript, - }; -}; diff --git a/forward_engineering/ddlProvider/ddlHelpers/tableHelper.js b/forward_engineering/ddlProvider/ddlHelpers/tableHelper.js deleted file mode 100644 index 1055535..0000000 --- a/forward_engineering/ddlProvider/ddlHelpers/tableHelper.js +++ /dev/null @@ -1,100 +0,0 @@ -module.exports = ({ _, getColumnsList, checkAllKeysDeactivated }) => { - const getTableTemporaryValue = (temporary, unlogged) => { - if (temporary) { - return ' TEMPORARY'; - } - - if (unlogged) { - return ' UNLOGGED'; - } - - return ''; - }; - - const getTableOptions = tableData => { - const wrap = value => (value ? `${value}\n` : ''); - - const statements = [ - { key: 'inherits', getValue: getBasicValue('INHERITS') }, - { key: 'partitionBounds', getValue: getBasicValue('') }, - { key: 'partitioning', getValue: getPartitioning }, - { key: 'usingMethod', getValue: getBasicValue('USING') }, - { key: 'storage_parameter', getValue: getStorageParameters }, - { key: 'on_commit', getValue: getOnCommit }, - { key: 'selectStatement', getValue: getBasicValue('AS') }, - ] - .map(config => wrap(config.getValue(tableData[config.key], tableData))) - .filter(Boolean) - .join(''); - - return _.trim(statements) ? ` ${_.trim(statements)}` : ''; - }; - - const getPartitioning = (value, { isActivated }) => { - if (value && value.partitionMethod) { - const partitionKeys = getPartitionKeys(value, isActivated); - const expression = partitionKeys + ` (${value.partitioning_expression})`; - - return `PARTITION BY ${value.partitionMethod}${expression}`; - } - }; - - const getPartitionKeys = (value, isParentActivated) => { - const isAllColumnsDeactivated = checkAllKeysDeactivated(value.compositePartitionKey); - - return getColumnsList(value.compositePartitionKey, isAllColumnsDeactivated, isParentActivated); - }; - - const getOnCommit = (value, table) => { - if (value && table.temporary) { - return `ON COMMIT ${value}`; - } - }; - - const getBasicValue = prefix => value => { - if (value) { - return `${prefix} ${value}`; - } - }; - - const getStorageParameters = value => { - if (_.isEmpty(value)) { - return ''; - } - - const nestedProperties = ['ttl_storage_parameters']; - const keysToSkip = ['id', ...nestedProperties]; - - return _.chain(value) - .toPairs() - .flatMap(([key, value]) => { - if (nestedProperties.includes(key)) { - return _.toPairs(value); - } - - return [[key, value]]; - }) - .reject(([key]) => _.includes(keysToSkip, key)) - .map(([key, value]) => { - if (!value && value !== 0) { - return; - } - - return `${key}=${value}`; - }) - .compact() - .join(',\n\t') - .trim() - .thru(storageParameters => { - if (storageParameters) { - return `WITH (\n\t${storageParameters}\n)`; - } - }) - .value(); - }; - - return { - getTableTemporaryValue, - getTableOptions, - }; -}; diff --git a/forward_engineering/ddlProvider/ddlHelpers/udtHelper.js b/forward_engineering/ddlProvider/ddlHelpers/udtHelper.js deleted file mode 100644 index 2fd2c5d..0000000 --- a/forward_engineering/ddlProvider/ddlHelpers/udtHelper.js +++ /dev/null @@ -1,104 +0,0 @@ -module.exports = ({ - _, - commentIfDeactivated, - assignTemplates, - templates, - getNamePrefixedWithSchemaName, - wrapComment, -}) => { - const notPlainTypes = ['composite', 'enum', 'range_udt', 'domain']; - const getPlainUdt = (udt, columns) => { - const udtName = getNamePrefixedWithSchemaName(udt.name, udt.schemaName); - const comment = assignTemplates(templates.comment, { - object: 'TYPE', - objectName: udtName, - comment: wrapComment(udt.comment), - }); - - switch (udt.type) { - case 'composite': - return assignTemplates(templates.createCompositeType, { - name: udtName, - columnDefinitions: _.join(columns, ',\n\t'), - comment: udt.comment ? comment : '', - }); - case 'enum': - return assignTemplates(templates.createEnumType, { - name: udtName, - values: _.map(udt.enum, value => `'${value}'`).join(', '), - comment: udt.comment ? comment : '', - }); - case 'range_udt': - return assignTemplates(templates.createRangeType, { - name: udtName, - subtype: udt.rangeSubtype, - options: getRangeOptions(udt), - comment: udt.comment ? comment : '', - }); - case 'domain': { - const comment = assignTemplates(templates.comment, { - object: 'DOMAIN', - objectName: udtName, - comment: wrapComment(udt.comment), - }); - - return assignTemplates(templates.createDomainType, { - name: udtName, - underlyingType: udt.underlyingType, - notNull: !udt.nullable ? ' NOT NULL' : '', - collate: udt.collation ? `\n\tCOLLATE ${udt.collation}` : '', - default: udt.default ? `\n\tDEFAULT ${udt.default}` : '', - constraints: getDomainConstraints(udt), - comment: udt.comment ? comment : '', - }); - } - default: - return ''; - } - }; - - const isNotPlainType = (definitionJsonSchema) => { - return notPlainTypes.includes(definitionJsonSchema.type); - }; - - const getRangeOptions = udt => { - const wrap = value => (value ? `\t${value}` : ''); - - const statements = [ - { key: 'operatorClass', getValue: getBasicValue('SUBTYPE_OPCLASS') }, - { key: 'collation', getValue: getBasicValue('COLLATION') }, - { key: 'canonicalFunction', getValue: getBasicValue('CANONICAL') }, - { key: 'subtypeDiffFunction', getValue: getBasicValue('SUBTYPE_DIFF') }, - { key: 'multiRangeType', getValue: getBasicValue('MULTIRANGE_TYPE_NAME') }, - ] - .map(config => wrap(config.getValue(udt[config.key]))) - .filter(Boolean) - .join(',\n'); - - return _.trim(statements) ? ',\n\t' + _.trim(statements) : ''; - }; - - const getDomainConstraints = udt => { - return _.map(udt.checkConstraints, constraint => { - if (constraint.name) { - return `\n\tCONSTRAINT ${constraint.name} CHECK (${constraint.expression})`; - } - - return `\n\tCHECK (${constraint.expression})`; - }).join(''); - }; - - const getBasicValue = prefix => value => { - if (value) { - return `${prefix}=${value}`; - } - }; - - const getUserDefinedType = (udt, columns) => { - return commentIfDeactivated(getPlainUdt(udt, columns), { - isActivated: udt.isActivated, - }); - }; - - return { getUserDefinedType, isNotPlainType }; -}; diff --git a/forward_engineering/ddlProvider/ddlProvider.js b/forward_engineering/ddlProvider/ddlProvider.js deleted file mode 100644 index 96fc4a4..0000000 --- a/forward_engineering/ddlProvider/ddlProvider.js +++ /dev/null @@ -1,1138 +0,0 @@ -const defaultTypes = require('../configs/defaultTypes'); -const descriptors = require('../configs/descriptors'); -const templates = require('./templates'); - - -module.exports = (baseProvider, options, app) => { - const _ = app.require('lodash'); - const { - tab, - commentIfDeactivated, - checkAllKeysDeactivated, - divideIntoActivatedAndDeactivated, - hasType, - wrap, - clean, - wrapComment, - getFunctionArguments, - wrapInQuotes, - getNamePrefixedWithSchemaName, - getColumnsList, - getViewData, - } = require('../utils/general')(_); - const assignTemplates = require('../utils/assignTemplates'); - - const { - generateConstraintsString, - foreignKeysToString, - foreignActiveKeysToString, - createKeyConstraint, - getConstraintsWarnings, - additionalPropertiesForForeignKey, - } = require('./ddlHelpers/constraintsHelper')({ - _, - commentIfDeactivated, - checkAllKeysDeactivated, - assignTemplates, - getColumnsList, - wrapInQuotes, - }); - const keyHelper = require('./ddlHelpers/keyHelper')(_, clean); - - const { getFunctionsScript } = require('./ddlHelpers/functionHelper')({ - _, - templates, - assignTemplates, - getFunctionArguments, - getNamePrefixedWithSchemaName, - wrapComment, - }); - - const { getProceduresScript } = require('./ddlHelpers/procedureHelper')({ - _, - templates, - assignTemplates, - getFunctionArguments, - getNamePrefixedWithSchemaName, - }); - - const { getTableTemporaryValue, getTableOptions } = require('./ddlHelpers/tableHelper')({ - _, - checkAllKeysDeactivated, - getColumnsList, - }); - - const { getUserDefinedType, isNotPlainType } = require('./ddlHelpers/udtHelper')({ - _, - commentIfDeactivated, - assignTemplates, - templates, - getNamePrefixedWithSchemaName, - wrapComment, - }); - - const { getIndexKeys, getIndexOptions } = require('./ddlHelpers/indexHelper')({ - _, - wrapInQuotes, - checkAllKeysDeactivated, - getColumnsList, - }); - - const { decorateType, decorateDefault, getColumnComments } = - require('./ddlHelpers/columnDefinitionHelper')({ - _, - wrap, - assignTemplates, - templates, - commentIfDeactivated, - wrapInQuotes, - wrapComment, - }); - - return { - createDatabase(modelData) { - if (!modelData.databaseName) { - return ''; - } - - const { collate, characterClassification } = modelData; - - return assignTemplates(templates.createDatabase, { - name: wrapInQuotes(modelData.databaseName), - template: modelData.template ? `\n\tTEMPLATE ${modelData.template}` : '', - encoding: modelData.encoding ? `\n\tENCODING = '${modelData.encoding}'` : '', - collate: collate ? `\n\tLC_COLLATE = '${modelData.collate}'` : '', - characterClassification: characterClassification ? `\n\tLC_CTYPE = '${characterClassification}'` : '', - }); - }, - - createSchema({ schemaName, ifNotExist, comments, udfs, procedures }) { - const comment = assignTemplates(templates.comment, { - object: 'SCHEMA', - objectName: wrapInQuotes(schemaName), - comment: wrapComment(comments), - }); - - const schemaStatement = assignTemplates(templates.createSchema, { - name: wrapInQuotes(schemaName), - ifNotExist: ifNotExist ? ' IF NOT EXISTS' : '', - comment: comments ? comment : '', - }); - - const createFunctionStatement = getFunctionsScript(schemaName, udfs); - const createProceduresStatement = getProceduresScript(schemaName, procedures); - - return _.chain([schemaStatement, createFunctionStatement, createProceduresStatement]) - .compact() - .map(_.trim) - .join('\n\n') - .trim() - .value(); - }, - - createTable( - { - name, - columns, - checkConstraints, - foreignKeyConstraints, - schemaData, - columnDefinitions, - keyConstraints, - inherits, - description, - ifNotExist, - usingMethod, - on_commit, - partitioning, - storage_parameter, - temporary, - unlogged, - selectStatement, - partitionOf, - partitionBounds, - }, - isActivated, - ) { - const ifNotExistStr = ifNotExist ? ' IF NOT EXISTS' : ''; - const tableName = getNamePrefixedWithSchemaName(name, schemaData.schemaName); - const comment = assignTemplates(templates.comment, { - object: 'TABLE', - objectName: tableName, - comment: wrapComment(description), - }); - - const dividedKeysConstraints = divideIntoActivatedAndDeactivated( - keyConstraints - .filter(({ errorMessage }) => !errorMessage) - .map(createKeyConstraint(templates, isActivated)), - key => key.statement, - ); - const constraintWarnings = getConstraintsWarnings( - keyConstraints.filter(({ errorMessage }) => errorMessage), - ); - const keyConstraintsString = `${generateConstraintsString( - dividedKeysConstraints, - isActivated, - )}${constraintWarnings}`; - const keyConstraintsValue = partitionOf ? keyConstraintsString?.slice(1) : keyConstraintsString; - - const dividedForeignKeys = divideIntoActivatedAndDeactivated(foreignKeyConstraints, key => key.statement); - const foreignKeyConstraintsString = generateConstraintsString(dividedForeignKeys, isActivated); - - const columnDescriptions = '\n' + getColumnComments(tableName, columnDefinitions); - const template = partitionOf ? templates.createTablePartitionOf : templates.createTable; - - const checkConstraintPrefix = partitionOf && !keyConstraintsString ? '\n\t' : ',\n\t'; - const checkConstraintsValue = !_.isEmpty(checkConstraints) - ? wrap(_.join(checkConstraints, ',\n\t'), checkConstraintPrefix, '') - : ''; - - const isEmptyPartitionBody = - partitionOf && !keyConstraintsValue && !checkConstraintsValue && !foreignKeyConstraintsString; - const openParenthesis = isEmptyPartitionBody ? '' : '('; - const closeParenthesis = isEmptyPartitionBody ? '' : ')'; - - const tableStatement = assignTemplates(template, { - temporary: getTableTemporaryValue(temporary, unlogged), - ifNotExist: ifNotExistStr, - name: tableName, - columnDefinitions: !partitionOf ? '\t' + _.join(columns, ',\n\t') : '', - keyConstraints: keyConstraintsValue, - checkConstraints: checkConstraintsValue, - foreignKeyConstraints: foreignKeyConstraintsString, - options: getTableOptions({ - inherits, - partitioning, - usingMethod, - on_commit, - storage_parameter, - selectStatement, - partitionBounds, - }), - comment: description ? comment : '', - partitionOf: partitionOf ? ` PARTITION OF ${partitionOf} ` : '', - columnDescriptions, - openParenthesis, - closeParenthesis, - }); - - return commentIfDeactivated( - [tableStatement].map(_.trim).join('\n\n').trim() + '\n', - { isActivated }, - ); - }, - - convertColumnDefinition(columnDefinition) { - const notNull = columnDefinition.nullable ? '' : ' NOT NULL'; - const primaryKey = columnDefinition.primaryKey - ? ' ' + createKeyConstraint(templates, true)(columnDefinition.primaryKeyOptions).statement - : ''; - const uniqueKey = columnDefinition.unique - ? ' ' + createKeyConstraint(templates, true)(columnDefinition.uniqueKeyOptions).statement - : ''; - const collation = columnDefinition.collationRule ? ` COLLATE "${columnDefinition.collationRule}"` : ''; - const isArrayType = Array.isArray(columnDefinition.array_type) && columnDefinition.array_type.length > 0; - const defaultValue = !_.isUndefined(columnDefinition.default) - ? ' DEFAULT ' + decorateDefault(columnDefinition.type, columnDefinition.default, isArrayType) - : ''; - const generatedColumnClause = columnDefinition.dbVersion >= 12 && columnDefinition.generatedColumn && columnDefinition.columnGenerationExpression - ? assignTemplates(templates.generatedColumnClause, { - generationExpression: columnDefinition.columnGenerationExpression, - }) - : ''; - - return commentIfDeactivated( - assignTemplates(templates.columnDefinition, { - name: wrapInQuotes(columnDefinition.name), - type: decorateType(columnDefinition.type, columnDefinition), - generatedColumnClause, - notNull, - primaryKey, - uniqueKey, - collation, - defaultValue, - }), - { - isActivated: columnDefinition.isActivated, - }, - ); - }, - - createIndex(tableName, index, dbData, isParentActivated = true) { - const isUnique = index.unique && index.index_method === 'btree'; - const name = wrapInQuotes(index.indxName); - const unique = isUnique ? ' UNIQUE' : ''; - const concurrently = index.concurrently ? ' CONCURRENTLY' : ''; - const ifNotExist = index.ifNotExist ? ' IF NOT EXISTS' : ''; - const using = index.index_method ? ` USING ${_.toUpper(index.index_method)}` : ''; - - const keys = getIndexKeys( - index.index_method === 'btree' - ? index.columns - : _.map(index.columns, column => _.omit(column, 'sortOrder', 'nullsOrder')), - isParentActivated, - ); - const options = getIndexOptions(index, isParentActivated); - - return commentIfDeactivated( - assignTemplates(templates.index, { - unique, - concurrently, - ifNotExist, - name, - using, - keys, - options, - tableName: getNamePrefixedWithSchemaName(tableName, index.schemaName), - }), - { - isActivated: index.isActivated, - }, - ); - }, - - createCheckConstraint(checkConstraint) { - return assignTemplates(templates.checkConstraint, { - name: checkConstraint.name ? `CONSTRAINT ${wrapInQuotes(checkConstraint.name)}` : '', - expression: _.trim(checkConstraint.expression).replace(/^\(([\s\S]*)\)$/, '$1'), - notValid: checkConstraint.notValid ? ' NOT VALID' : '', - }); - }, - - /** - * @param name {string} - * @param isActivated {boolean} - * @param customProperties {{ - * relationshipOnDelete?: string, - * relationshipOnUpdate?: string, - * relationshipMatch?: string, - * }} - * @param primaryTableActivated {boolean} - * @param foreignTableActivated {boolean} - * @param foreignSchemaName {string} - * @param primarySchemaName {string} - * @param primaryTable {string} - * @param primaryKey {Array<{ - * isActivated: boolean, - * name: string, - * }>} - * @param foreignKey {Array<{ - * isActivated: boolean, - * name: string, - * }>} - * @param schemaData {{ - * schemaName: string - * }} - * @param dbData {any} - * @return {{ - * statement: string, - * isActivated: boolean, - * }} - * */ - createForeignKeyConstraint( - { - name, - foreignKey, - primaryTable, - primaryKey, - primaryTableActivated, - foreignTableActivated, - foreignSchemaName, - primarySchemaName, - customProperties, - isActivated - }, - dbData, - schemaData, - ) { - const isAllPrimaryKeysDeactivated = checkAllKeysDeactivated(primaryKey); - const isAllForeignKeysDeactivated = checkAllKeysDeactivated(foreignKey); - const areKeysActivated = - !isAllPrimaryKeysDeactivated && - !isAllForeignKeysDeactivated && - primaryTableActivated && - foreignTableActivated; - - const { foreignOnDelete, foreignOnUpdate, foreignMatch } = - additionalPropertiesForForeignKey(customProperties); - - const foreignKeyStatement = assignTemplates(templates.createForeignKeyConstraint, { - primaryTable: getNamePrefixedWithSchemaName(primaryTable, primarySchemaName || schemaData.schemaName), - name: name ? `CONSTRAINT ${wrapInQuotes(name)}` : '', - foreignKey: areKeysActivated ? foreignKeysToString(foreignKey) : foreignActiveKeysToString(foreignKey), - primaryKey: areKeysActivated ? foreignKeysToString(primaryKey) : foreignActiveKeysToString(primaryKey), - onDelete: foreignOnDelete ? ` ON DELETE ${foreignOnDelete}` : '', - onUpdate: foreignOnUpdate ? ` ON UPDATE ${foreignOnUpdate}` : '', - match: foreignMatch ? ` MATCH ${foreignMatch}` : '', - }); - - return { - statement: _.trim(foreignKeyStatement), - isActivated: areKeysActivated && isActivated, - }; - }, - - /** - * @param name {string} - * @param isActivated {boolean} - * @param customProperties {{ - * relationshipOnDelete?: string, - * relationshipOnUpdate?: string, - * relationshipMatch?: string, - * }} - * @param primaryTableActivated {boolean} - * @param foreignTableActivated {boolean} - * @param foreignSchemaName {string} - * @param foreignTable {string} - * @param primarySchemaName {string} - * @param primaryTable {string} - * @param primaryKey {Array<{ - * isActivated: boolean, - * name: string, - * }>} - * @param foreignKey {Array<{ - * isActivated: boolean, - * name: string, - * }>} - * @param schemaData {{ - * schemaName: string - * }} - * @param dbData {any} - * @return {{ - * statement: string, - * isActivated: boolean, - * }} - * */ - createForeignKey( - { - name, - foreignTable, - foreignKey, - primaryTable, - primaryKey, - primaryTableActivated, - foreignTableActivated, - foreignSchemaName, - primarySchemaName, - customProperties, - isActivated - }, - dbData, - schemaData, - ) { - const isAllPrimaryKeysDeactivated = checkAllKeysDeactivated(primaryKey); - const isAllForeignKeysDeactivated = checkAllKeysDeactivated(foreignKey); - const areKeysActivated = - !isAllPrimaryKeysDeactivated && - !isAllForeignKeysDeactivated && - primaryTableActivated && - foreignTableActivated; - - const { foreignOnDelete, foreignOnUpdate, foreignMatch } = - additionalPropertiesForForeignKey(customProperties); - - const foreignKeyStatement = assignTemplates(templates.createForeignKey, { - primaryTable: getNamePrefixedWithSchemaName(primaryTable, primarySchemaName || schemaData.schemaName), - foreignTable: getNamePrefixedWithSchemaName(foreignTable, foreignSchemaName || schemaData.schemaName), - name: name ? wrapInQuotes(name) : '', - foreignKey: areKeysActivated ? foreignKeysToString(foreignKey) : foreignActiveKeysToString(foreignKey), - primaryKey: areKeysActivated ? foreignKeysToString(primaryKey) : foreignActiveKeysToString(primaryKey), - onDelete: foreignOnDelete ? ` ON DELETE ${foreignOnDelete}` : '', - onUpdate: foreignOnUpdate ? ` ON UPDATE ${foreignOnUpdate}` : '', - match: foreignMatch ? ` MATCH ${foreignMatch}` : '', - }); - - return { - statement: _.trim(foreignKeyStatement), - isActivated: areKeysActivated && isActivated, - }; - }, - - createView(viewData, dbData, isActivated) { - const viewName = getNamePrefixedWithSchemaName(viewData.name, viewData.schemaName); - - const comment = assignTemplates(templates.comment, { - object: 'VIEW', - objectName: viewName, - comment: wrapComment(viewData.comment), - }); - - const allDeactivated = checkAllKeysDeactivated(viewData.keys || []); - const deactivatedWholeStatement = allDeactivated || !isActivated; - const { columns, tables } = getViewData(viewData.keys); - let columnsAsString = columns.map(column => column.statement).join(',\n\t\t'); - - if (!deactivatedWholeStatement) { - const dividedColumns = divideIntoActivatedAndDeactivated(columns, column => column.statement); - const deactivatedColumnsString = dividedColumns.deactivatedItems.length - ? commentIfDeactivated(dividedColumns.deactivatedItems.join(',\n\t\t'), { - isActivated: false, - isPartOfLine: true, - }) - : ''; - columnsAsString = dividedColumns.activatedItems.join(',\n\t\t') + deactivatedColumnsString; - } - - const selectStatement = _.trim(viewData.selectStatement) - ? _.trim(tab(viewData.selectStatement)) - : assignTemplates(templates.viewSelectStatement, { - tableName: tables.join(', '), - keys: columnsAsString, - }); - - const check_option = viewData.viewOptions?.check_option - ? `check_option=${viewData.viewOptions?.check_option}` - : ''; - const security_barrier = viewData.viewOptions?.security_barrier ? `security_barrier` : ''; - const dbVersionWhereSecurityInvokerAppeared = 15; - const { getDbVersion } = require('../utils/general')(_); - const security_invoker = - viewData.viewOptions?.security_invoker && - getDbVersion(dbData.dbVersion) >= dbVersionWhereSecurityInvokerAppeared - ? 'security_invoker' - : ''; - const withOptions = - check_option || security_barrier || security_invoker - ? `\n\tWITH (${_.compact([check_option, security_barrier, security_invoker]).join(',')})` - : ''; - - const getCheckOption = viewData => { - if (viewData.withCheckOption && viewData.checkTestingScope) { - return `\n\tWITH ${viewData.checkTestingScope} CHECK OPTION`; - } else if (viewData.withCheckOption) { - return '\n\tWITH CHECK OPTION'; - } else { - return ''; - } - }; - - const createViewScript = commentIfDeactivated( - assignTemplates(templates.createView, { - name: viewName, - orReplace: viewData.orReplace ? ' OR REPLACE' : '', - temporary: viewData.temporary ? ' TEMPORARY' : '', - checkOption: getCheckOption(viewData), - comment: viewData.comment ? comment : '', - withOptions, - selectStatement, - }), - { isActivated: !deactivatedWholeStatement }, - ); - - return [createViewScript].map(_.trim).join('\n\n').trim() + '\n'; - }, - - /** - * @param viewName {string} - * @return string - * */ - dropView(viewName) { - const templatesConfig = { - viewName, - } - return assignTemplates(templates.dropView, templatesConfig); - }, - - createViewIndex() { - return ''; - }, - - createUdt(udt) { - const columns = _.map(udt.properties, this.convertColumnDefinition); - - return getUserDefinedType(udt, columns); - }, - - getDefaultType(type) { - return defaultTypes[type]; - }, - - getTypesDescriptors() { - return descriptors; - }, - - hasType(type) { - return hasType(descriptors, type); - }, - - hydrateDatabase({ modelData }) { - modelData = _.get(modelData, '0', {}); - - return { - databaseName: modelData.database_name, - encoding: modelData.encoding, - template: modelData.template, - collate: modelData.LC_COLLATE, - characterClassification: modelData.LC_CTYPE, - dbVersion: modelData.dbVersion, - }; - }, - - hydrateColumn({ columnDefinition, jsonSchema, schemaData, definitionJsonSchema = {}, parentJsonSchema }) { - const collationRule = _.includes(['char', 'varchar', 'text'], columnDefinition.type) - ? jsonSchema.collationRule - : ''; - const timeTypes = ['time', 'timestamp']; - const timePrecision = _.includes(timeTypes, columnDefinition.type) ? jsonSchema.timePrecision : ''; - const timezone = _.includes(timeTypes, columnDefinition.type) ? jsonSchema.timezone : ''; - const intervalOptions = columnDefinition.type === 'interval' ? jsonSchema.intervalOptions : ''; - const { getDbVersion } = require('../utils/general')(_); - const dbVersion = getDbVersion(schemaData.dbVersion) - const primaryKeyOptions = _.omit( - keyHelper.hydratePrimaryKeyOptions( - _.first(jsonSchema.primaryKeyOptions) || {}, - columnDefinition.name, - columnDefinition.isActivated, - parentJsonSchema, - ), - 'columns', - ); - const uniqueKeyOptions = _.omit( - keyHelper.hydrateUniqueOptions({ - options: _.first(jsonSchema.uniqueKeyOptions) || {}, - columnName: columnDefinition.name, - isActivated: columnDefinition.isActivated, - jsonSchema: parentJsonSchema, - dbVersion, - }), - 'columns', - ); - - return { - name: columnDefinition.name, - type: columnDefinition.type, - primaryKey: keyHelper.isInlinePrimaryKey(jsonSchema), - primaryKeyOptions, - unique: keyHelper.isInlineUnique(jsonSchema), - uniqueKeyOptions, - nullable: columnDefinition.nullable, - default: columnDefinition.default, - comment: jsonSchema.refDescription || jsonSchema.description || definitionJsonSchema.description, - isActivated: columnDefinition.isActivated, - scale: columnDefinition.scale, - precision: columnDefinition.precision, - length: columnDefinition.length, - enum: jsonSchema.enum, - array_type: jsonSchema.array_type, - unit: jsonSchema.unit, - rangeSubtype: jsonSchema.rangeSubtype, - operatorClass: jsonSchema.operatorClass, - collation: jsonSchema.collation, - canonicalFunction: jsonSchema.canonicalFunction, - subtypeDiffFunction: jsonSchema.subtypeDiffFunction, - multiRangeType: jsonSchema.multiRangeType, - schemaName: schemaData.schemaName, - underlyingType: jsonSchema.underlyingType, - checkConstraints: jsonSchema.checkConstraints, - typeModifier: jsonSchema.typeModifier, - srid: jsonSchema.srid, - collationRule, - timePrecision, - timezone, - intervalOptions, - dbVersion, - generatedColumn: Boolean(jsonSchema.generatedColumn), - columnGenerationExpression: jsonSchema.columnGenerationExpression, - }; - }, - - hydrateJsonSchemaColumn(jsonSchema, definitionJsonSchema) { - if (!jsonSchema.$ref || _.isEmpty(definitionJsonSchema) || isNotPlainType(definitionJsonSchema)) { - return jsonSchema; - } - - jsonSchema = _.omit(jsonSchema, '$ref'); - return { ...definitionJsonSchema, ...jsonSchema }; - }, - - hydrateIndex(indexData, tableData, schemaData) { - return { ...indexData, schemaName: schemaData.schemaName }; - }, - - hydrateViewIndex(indexData) { - return {}; - }, - - hydrateCheckConstraint(checkConstraint) { - return { - name: checkConstraint.chkConstrName, - expression: checkConstraint.constrExpression, - notValid: checkConstraint.notValid, - }; - }, - - hydrateSchema(containerData, data) { - const dbVersion = _.get(data, 'modelData.0.dbVersion'); - - return { - schemaName: containerData.name, - ifNotExist: containerData.ifNotExist, - comments: containerData.description, - udfs: data?.udfs || [], - procedures: data?.procedures || [], - dbVersion, - }; - }, - - hydrateTable({ tableData, entityData, jsonSchema }) { - const detailsTab = entityData[0]; - const parentTables = _.chain(detailsTab.inherits) - .map(({ parentTable }) => _.get(tableData, `relatedSchemas[${parentTable}]`, '')) - .compact() - .map(table => table.code || table.collectionName) - .join(', ') - .thru(value => (value ? `(${value})` : '')) - .value(); - - const partitioning = _.first(detailsTab.partitioning) || {}; - const compositePartitionKey = keyHelper.getKeys(partitioning.compositePartitionKey, jsonSchema); - const partitionParent = _.get(tableData, `relatedSchemas[${detailsTab.partitionOf}]`); - const partitionOf = partitionParent - ? getNamePrefixedWithSchemaName(partitionParent.collectionName, partitionParent.bucketName) - : ''; - const { getDbVersion } = require('../utils/general')(_); - const dbVersion = getDbVersion(_.get(tableData, 'dbData.dbVersion', '')); - - return { - ...tableData, - partitionOf, - keyConstraints: keyHelper.getTableKeyConstraints(jsonSchema, dbVersion), - inherits: parentTables, - selectStatement: _.trim(detailsTab.selectStatement), - partitioning: _.assign({}, partitioning, { compositePartitionKey }), - ..._.pick( - detailsTab, - 'temporary', - 'unlogged', - 'description', - 'ifNotExist', - 'usingMethod', - 'on_commit', - 'storage_parameter', - 'partitionBounds', - ), - }; - }, - - hydrateViewColumn(data) { - return { - name: data.name, - tableName: data.entityName, - alias: data.alias, - isActivated: data.isActivated, - dbName: data.dbName, - }; - }, - - hydrateView({ viewData, entityData, relatedSchemas }) { - const detailsTab = entityData[0]; - - return { - name: viewData.name, - keys: viewData.keys, - comment: detailsTab.description, - orReplace: detailsTab.orReplace, - temporary: detailsTab.temporary, - recursive: detailsTab.recursive, - viewOptions: detailsTab.viewOptions, - selectStatement: detailsTab.selectStatement, - withCheckOption: detailsTab.withCheckOption, - checkTestingScope: detailsTab.withCheckOption ? detailsTab.checkTestingScope : '', - schemaName: viewData.schemaData.schemaName, - }; - }, - - commentIfDeactivated(statement, data, isPartOfLine) { - return statement; - }, - - /** - * @param tableName {string} - * @param columnName {string} - * @param dataType {string} - * @param dataTypeProperties {{ - * length?: number, - * scale?: number, - * precision?: number - * }} - * @return string - * */ - alterColumnType(tableName, columnName, dataType, dataTypeProperties) { - let dataTypeString = dataType; - if (dataTypeProperties.length) { - dataTypeString += `(${dataTypeProperties.length})`; - } else if (dataTypeProperties.precision && dataTypeProperties.scale) { - dataTypeString += `(${dataTypeProperties.precision},${dataTypeProperties.scale})`; - } else if (dataTypeProperties.precision) { - dataTypeString += `(${dataTypeProperties.precision})`; - } - - return assignTemplates(templates.alterColumnType, { - tableName, - columnName, - dataType: dataTypeString, - }) - }, - - /** - * @param tableName {string} - * @param columnName {string} - * @return string - * */ - setNotNullConstraint(tableName, columnName) { - return assignTemplates(templates.addNotNullConstraint, { - tableName, - columnName - }); - }, - - /** - * @param tableName {string} - * @param columnName {string} - * @return string - * */ - dropNotNullConstraint(tableName, columnName) { - return assignTemplates(templates.dropNotNullConstraint, { - tableName, - columnName - }); - }, - - /** - * @param tableName {string} - * @param oldColumnName {string} - * @param newColumnName {string} - * @return string - * */ - renameColumn(tableName, oldColumnName, newColumnName) { - return assignTemplates(templates.renameColumn, { - tableName, - oldColumnName, - newColumnName - }); - }, - - /** - * @param tableName {string} - * @param constraintName {string} - * @param expression {expression} - * @return string - * */ - addCheckConstraint(tableName, constraintName, expression) { - const templateConfig = { - tableName, - constraintName, - expression - }; - return assignTemplates(templates.addCheckConstraint, templateConfig); - }, - - /** - * @param tableName {string} - * @param constraintName {string} - * @return string - * */ - dropConstraint(tableName, constraintName) { - const templateConfig = { - tableName, - constraintName, - }; - return assignTemplates(templates.dropConstraint, templateConfig); - }, - - /** - * @param tableName {string} - * @param comment {string} - * @return string - * */ - updateTableComment(tableName, comment) { - const templateConfig = { - tableName, - comment - } - return assignTemplates(templates.updateCommentOnTable, templateConfig); - }, - - /** - * @param tableName {string} - * @return string - * */ - dropTableComment(tableName) { - const templateConfig = { - tableName, - comment: 'NULL' - } - return assignTemplates(templates.updateCommentOnTable, templateConfig); - }, - - /** - * @param columnName {string} - * @param comment {string} - * @return string - * */ - updateColumnComment(columnName, comment) { - const templateConfig = { - columnName, - comment - } - return assignTemplates(templates.updateCommentOnColumn, templateConfig); - }, - - /** - * @param columnName {string} - * @return string - * */ - dropColumnComment(columnName) { - const templateConfig = { - columnName, - comment: 'NULL' - } - return assignTemplates(templates.updateCommentOnColumn, templateConfig); - }, - - /** - * @param schemaName {string} - * @param comment {string} - * @return string - * */ - updateSchemaComment(schemaName, comment) { - const templateConfig = { - schemaName, - comment - } - return assignTemplates(templates.updateCommentOnSchema, templateConfig); - }, - - /** - * @param schemaName {string} - * @return string - * */ - dropSchemaComment(schemaName) { - const templateConfig = { - schemaName, - comment: 'NULL' - } - return assignTemplates(templates.updateCommentOnSchema, templateConfig); - }, - - /** - * @param viewName {string} - * @param comment {string} - * @return string - * */ - updateViewComment(viewName, comment) { - const templateConfig = { - viewName, - comment - } - return assignTemplates(templates.updateCommentOnView, templateConfig); - }, - - /** - * @param viewName {string} - * @return string - * */ - dropViewComment(viewName) { - const templateConfig = { - viewName, - comment: 'NULL' - } - return assignTemplates(templates.updateCommentOnView, templateConfig); - }, - - /** - * @param schemaName {string} - * @return string - * */ - createSchemaOnly(schemaName) { - const templateConfig = { - schemaName, - } - return assignTemplates(templates.createSchemaOnly, templateConfig); - }, - - /** - * @param schemaName {string} - * @return string - * */ - dropSchema(schemaName) { - const templateConfig = { - schemaName, - } - return assignTemplates(templates.dropSchema, templateConfig); - }, - - /** - * @param tableName {string} - * @return string - * */ - dropTable(tableName) { - const templateConfig = { - tableName, - } - return assignTemplates(templates.dropTable, templateConfig); - }, - - /** - * @param tableName {string} - * @param columnDefinition {string} - * @return string - * */ - addColumn(tableName, columnDefinition) { - const templateConfig = { - tableName, - columnDefinition, - } - return assignTemplates(templates.addColumn, templateConfig); - }, - - /** - * @param tableName {string} - * @param columnName {string} - * @return string - * */ - dropColumn(tableName, columnName) { - const templateConfig = { - tableName, - columnName, - } - return assignTemplates(templates.dropColumn, templateConfig); - }, - - /** - * @param udtName {string} - * @return string - * */ - dropDomain(udtName,) { - const templateConfig = { - udtName, - } - return assignTemplates(templates.dropDomain, templateConfig); - }, - - /** - * @param udtName {string} - * @return string - * */ - dropType(udtName,) { - const templateConfig = { - udtName, - } - return assignTemplates(templates.dropType, templateConfig); - }, - - /** - * @param udtName {string} - * @param columnDefinition {string} - * @return string - * */ - alterTypeAddAttribute(udtName, columnDefinition) { - const templateConfig = { - udtName, - columnDefinition, - } - return assignTemplates(templates.alterTypeAddAttribute, templateConfig); - }, - - /** - * @param udtName {string} - * @param attributeName {string} - * @return string - * */ - alterTypeDropAttribute(udtName, attributeName) { - const templateConfig = { - udtName, - attributeName, - } - return assignTemplates(templates.alterTypeDropAttribute, templateConfig); - }, - - /** - * @param udtName {string} - * @param oldAttributeName {string} - * @param newAttributeName {string} - * @return string - * */ - alterTypeRenameAttribute(udtName, oldAttributeName, newAttributeName) { - const templateConfig = { - udtName, - oldAttributeName, - newAttributeName, - } - return assignTemplates(templates.alterTypeRenameAttribute, templateConfig); - }, - - /** - * @param udtName {string} - * @param attributeName {string} - * @param newDataType {string} - * @return string - * */ - alterTypeChangeAttributeType(udtName, attributeName, newDataType) { - const templateConfig = { - udtName, - attributeName, - newDataType, - } - return assignTemplates(templates.alterTypeChangeAttributeType, templateConfig); - }, - - /** - * @param tableName {string} - * @param fkConstraintName {string} - * @return string - * */ - dropForeignKey(tableName, fkConstraintName) { - const templateConfig = { - tableName, - fkConstraintName, - } - return assignTemplates(templates.dropForeignKey, templateConfig); - }, - - /** - * @param tableName {string} - * @param isParentActivated {boolean} - * @param keyData {{ - * name: string, - * keyType: string, - * columns: Array<{ - * isActivated: boolean, - * name: string, - * }>, - * include: Array<{ - * isActivated: boolean, - * name: string, - * }>, - * storageParameters: string, - * }} - * @return {{ - * statement: string, - * isActivated: boolean, - * }} - * */ - createKeyConstraint(tableName, isParentActivated, keyData) { - const constraintStatementDto = createKeyConstraint(templates, isParentActivated)(keyData); - return { - statement: assignTemplates(templates.addPkConstraint, { - constraintStatement: (constraintStatementDto.statement || '').trim(), - tableName, - }), - isActivated: constraintStatementDto.isActivated, - } - }, - - /** - * @param tableName {string} - * @param constraintName {string} - * */ - dropPkConstraint(tableName, constraintName) { - const templatesConfig = { - tableName, - constraintName, - } - return assignTemplates(templates.dropConstraint, templatesConfig); - }, - }; -}; diff --git a/forward_engineering/ddlProvider/templates.js b/forward_engineering/ddlProvider/templates.js deleted file mode 100644 index 02ed3ae..0000000 --- a/forward_engineering/ddlProvider/templates.js +++ /dev/null @@ -1,108 +0,0 @@ -module.exports = { - createDatabase: - 'CREATE DATABASE ${name}${template}${encoding}${collate}${characterClassification};\n', - - createSchema: 'CREATE SCHEMA${ifNotExist} ${name};\nSET search_path TO ${name};\n\n${comment}\n', - - comment: 'COMMENT ON ${object} ${objectName} IS ${comment};\n', - - createTable: - 'CREATE${temporary} TABLE${ifNotExist} ${name} (\n' + - '${columnDefinitions}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n' + - ')${options};\n\n${comment}${columnDescriptions}', - - createTablePartitionOf: - 'CREATE${temporary} TABLE${ifNotExist} ${name}\n' + - '${partitionOf} ${openParenthesis}${keyConstraints}${checkConstraints}${foreignKeyConstraints}\n' + - '${closeParenthesis}${options};\n\n${comment}${columnDescriptions}', - - generatedColumnClause: ' GENERATED ALWAYS AS (${generationExpression}) STORED', - - columnDefinition: '${name} ${type}${collation}${generatedColumnClause}${primaryKey}${uniqueKey}${defaultValue}${notNull}', - - checkConstraint: '${name} CHECK (${expression})${notValid}', - - createForeignKeyConstraint: '${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable} (${primaryKey})${match}${onDelete}${onUpdate}', - - createKeyConstraint: '${constraintName}${keyType}${columns}${includeNonKey}${storageParameters}', - - alterColumnType: 'ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET DATA TYPE ${dataType};', - - addNotNullConstraint: 'ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} SET NOT NULL;', - - dropNotNullConstraint: 'ALTER TABLE IF EXISTS ${tableName} ALTER COLUMN ${columnName} DROP NOT NULL;', - - renameColumn: 'ALTER TABLE IF EXISTS ${tableName} RENAME COLUMN ${oldColumnName} TO ${newColumnName};', - - addCheckConstraint: 'ALTER TABLE IF EXISTS ${tableName} ADD CONSTRAINT ${constraintName} CHECK (${expression});', - - dropConstraint: 'ALTER TABLE IF EXISTS ${tableName} DROP CONSTRAINT IF EXISTS ${constraintName};', - - createForeignKey: - 'ALTER TABLE IF EXISTS ${foreignTable} ADD CONSTRAINT ${name} FOREIGN KEY (${foreignKey}) REFERENCES ${primaryTable}(${primaryKey})${match}${onDelete}${onUpdate};', - - dropForeignKey: 'ALTER TABLE ${tableName} DROP CONSTRAINT ${fkConstraintName};', - - addPkConstraint: 'ALTER TABLE IF EXISTS ${tableName} ADD ${constraintStatement};', - - dropTable: 'DROP TABLE IF EXISTS ${tableName};', - - addColumn: 'ALTER TABLE IF EXISTS ${tableName} ADD COLUMN IF NOT EXISTS ${columnDefinition};', - - dropColumn: 'ALTER TABLE IF EXISTS ${tableName} DROP COLUMN IF EXISTS ${columnName};', - - dropDomain: 'DROP DOMAIN IF EXISTS ${udtName};', - - dropType: 'DROP TYPE IF EXISTS ${udtName};', - - alterTypeAddAttribute: 'ALTER TYPE ${udtName} ADD ATTRIBUTE ${columnDefinition};', - - alterTypeDropAttribute: 'ALTER TYPE ${udtName} DROP ATTRIBUTE IF EXISTS ${attributeName};', - - alterTypeRenameAttribute: 'ALTER TYPE ${udtName} RENAME ATTRIBUTE ${oldAttributeName} TO ${newAttributeName};', - - alterTypeChangeAttributeType: 'ALTER TYPE ${udtName} ALTER ATTRIBUTE ${attributeName} SET DATA TYPE ${newDataType};', - - updateCommentOnTable: 'COMMENT ON TABLE ${tableName} IS ${comment};', - - updateCommentOnColumn: 'COMMENT ON COLUMN ${columnName} IS ${comment};', - - updateCommentOnSchema: 'COMMENT ON SCHEMA ${schemaName} IS ${comment};', - - updateCommentOnView: 'COMMENT ON VIEW ${viewName} IS ${comment};', - - createSchemaOnly: 'CREATE SCHEMA IF NOT EXISTS ${schemaName};', - - dropSchema: 'DROP SCHEMA IF EXISTS ${schemaName};', - - index: - 'CREATE${unique} INDEX${concurrently}${ifNotExist} ${name}\n' + - ' ON ${tableName}${using}${keys}${options};\n', - - createView: - 'CREATE${orReplace}${temporary} VIEW ${name}${withOptions}\nAS ${selectStatement}${checkOption};\n\n${comment}\n', - - viewSelectStatement: 'SELECT ${keys}\n\tFROM ${tableName}', - - dropView: 'DROP VIEW IF EXISTS ${viewName};', - - createFunction: - 'CREATE${orReplace} FUNCTION ${name}\n' + - '\t(${parameters})\n' + - '\tRETURNS ${returnType}\n' + - '\tLANGUAGE ${language}\n' + - '${properties}' + - 'AS $BODY$\n${definition}\n$BODY$;\n', - - createProcedure: - 'CREATE${orReplace} PROCEDURE ${name} (${parameters})\n' + - '\tLANGUAGE ${language}\n' + - 'AS $BODY$\n${body}\n$BODY$;\n', - - createCompositeType: 'CREATE TYPE ${name} AS (\n\t${columnDefinitions}\n);\n\n${comment}', - createEnumType: 'CREATE TYPE ${name} AS ENUM (${values});\n\n${comment}', - createRangeType: 'CREATE TYPE ${name} AS RANGE (\n\tSUBTYPE=${subtype}${options}\n);\n\n${comment}', - createDomainType: - 'CREATE DOMAIN ${name} AS ${underlyingType}${notNull}${collate}${default}${constraints};\n\n${comment}', - -}; diff --git a/forward_engineering/enums/reservedWords.js b/forward_engineering/enums/reservedWords.js deleted file mode 100644 index f1ee24f..0000000 --- a/forward_engineering/enums/reservedWords.js +++ /dev/null @@ -1,103 +0,0 @@ -const ReservedWords = Object.freeze({ - ALL: 'ALL', - ANALYSE: 'ANALYSE', - ANALYZE: 'ANALYZE', - AND: 'AND', - ANY: 'ANY', - ARRAY: 'ARRAY', - ASC: 'ASC', - ASYMMETRIC: 'ASYMMETRIC', - AUTHORIZATION: 'AUTHORIZATION', - BINARY: 'BINARY', - BOTH: 'BOTH', - CASE: 'CASE', - CAST: 'CAST', - CHECK: 'CHECK', - COLLATE: 'COLLATE', - COLUMN: 'COLUMN', - CONCURRENTLY: 'CONCURRENTLY', - CONSTRAINT: 'CONSTRAINT', - CREATE: 'CREATE', - CROSS: 'CROSS', - CURRENT_CATALOG: 'CURRENT_CATALOG', - CURRENT_DATE: 'CURRENT_DATE', - CURRENT_ROLE: 'CURRENT_ROLE', - CURRENT_SCHEMA: 'CURRENT_SCHEMA', - CURRENT_TIME: 'CURRENT_TIME', - CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP', - CURRENT_USER: 'CURRENT_USER', - DEFAULT: 'DEFAULT', - DEFERRABLE: 'DEFERRABLE', - DESC: 'DESC', - DISTINCT: 'DISTINCT', - DO: 'DO', - ELSE: 'ELSE', - END: 'END', - EXCEPT: 'EXCEPT', - FALSE: 'FALSE', - FOR: 'FOR', - FOREIGN: 'FOREIGN', - FREEZE: 'FREEZE', - FROM: 'FROM', - FULL: 'FULL', - GRANT: 'GRANT', - GROUP: 'GROUP', - HAVING: 'HAVING', - ILIKE: 'ILIKE', - IN: 'IN', - INITIALLY: 'INITIALLY', - INTERSECT: 'INTERSECT', - INTO: 'INTO', - IS: 'IS', - ISNULL: 'ISNULL', - JOIN: 'JOIN', - LATERAL: 'LATERAL', - LEADING: 'LEADING', - LEFT: 'LEFT', - LIKE: 'LIKE', - LIMIT: 'LIMIT', - LOCALTIME: 'LOCALTIME', - LOCALTIMESTAMP: 'LOCALTIMESTAMP', - NATURAL: 'NATURAL', - NOT: 'NOT', - NULL: 'NULL', - OFFSET: 'OFFSET', - ON: 'ON', - ONLY: 'ONLY', - OR: 'OR', - ORDER: 'ORDER', - OUTER: 'OUTER', - OVERLAPS: 'OVERLAPS', - PLACING: 'PLACING', - PRIMARY: 'PRIMARY', - REFERENCES: 'REFERENCES', - RETURNING: 'RETURNING', - RIGHT: 'RIGHT', - SELECT: 'SELECT', - SESSION_USER: 'SESSION_USER', - SIMILAR: 'SIMILAR', - SOME: 'SOME', - SYMMETRIC: 'SYMMETRIC', - TABLE: 'TABLE', - TABLESAMPLE: 'TABLESAMPLE', - THEN: 'THEN', - TO: 'TO', - TRAILING: 'TRAILING', - TRUE: 'TRUE', - UNION: 'UNION', - UNIQUE: 'UNIQUE', - USER: 'USER', - USING: 'USING', - VARIADIC: 'VARIADIC', - VERBOSE: 'VERBOSE', - WHEN: 'WHEN', - WHERE: 'WHERE', - WINDOW: 'WINDOW', - WITH: 'WITH', -}); - -const ReservedWordsAsArray = Object.values(ReservedWords); - -module.exports = { - ReservedWordsAsArray -} diff --git a/forward_engineering/types/coreApplicationDataTypes.js b/forward_engineering/types/coreApplicationDataTypes.js deleted file mode 100644 index 9f248bd..0000000 --- a/forward_engineering/types/coreApplicationDataTypes.js +++ /dev/null @@ -1,215 +0,0 @@ - -class ContainerJsonSchema { - /** - * @type {string} - */ - name - - /** - * @type {boolean} - */ - isActivated -} - -class ContainerStyles { - /** - * @type {Object} - * */ - backgroundColor -} - -class EntityData { - - /** - * @type {string | undefined} - */ - collectionName - - /** - * @type {boolean | undefined} - */ - isActivated - - /** - * @type {string | undefined} - */ - bucketId - - /** - * @type {any | undefined} - */ - additionalProperties - - /** - * @type {boolean | undefined} - */ - tableIfNotExists -} - -class InternalDefinitions { - - /** - * @type {string} - */ - $schema - - /** - * @type {"definitions"} - */ - type - - /** - * @type {string} - */ - GUID -} - -class ModelDefinitions { - - /** - * @type {string} - */ - $schema - - /** - * @type {"definitions"} - */ - type - - /** - * @type {string} - */ - GUID -} - -class ExternalDefinitions { - - /** - * @type {string} - */ - $schema - - /** - * @type {"externalDefinitions"} - */ - type - - /** - * @type {string} - */ - GUID -} - -class FieldJsonSchema { - - /** - * @type {string} - */ - type - - /** - * @type {boolean} - */ - isActivated - - /** - * @type {string} - */ - mode - - /** - * @type {string} - */ - subtype - - /** - * @type {[ - * "compositePartitionKey", - * "compositeClusteringKey", - * "compositePrimaryKey", - * "compositeUniqueKey", - * ]} - */ - compositeKey - - /** - * @type {boolean} - */ - compositePartitionKey - - /** - * @type {boolean} - */ - compositeClusteringKey - - /** - * @type {boolean} - */ - compositePrimaryKey - - /** - * @type {boolean} - */ - compositeUniqueKey - - /** - * @type {string} - */ - GUID -} - -class EntityJsonSchema { - - /** - * @type {string} - */ - $schema - - /** - * @type {"object"} - */ - type - - /** - * @type {string} - */ - title - - /** - * @type {{ - * [fieldName: string]: FieldJsonSchema - * }} - */ - properties - - /** - * @type {boolean} - */ - isActivated - - /** - * @type {boolean} - */ - additionalProperties - - /** - * @type {boolean} - */ - tableIfNotExists - - /** - * @type {string} - */ - GUID -} - -module.exports = { - ContainerJsonSchema, - ContainerStyles, - EntityData, - InternalDefinitions, - ModelDefinitions, - ExternalDefinitions, - FieldJsonSchema, - EntityJsonSchema, -} diff --git a/forward_engineering/types/coreApplicationTypes.js b/forward_engineering/types/coreApplicationTypes.js deleted file mode 100644 index d5a0b8a..0000000 --- a/forward_engineering/types/coreApplicationTypes.js +++ /dev/null @@ -1,158 +0,0 @@ -class PluginError { - /** - * @type string - */ - message - - /** - * @type {string | undefined} - */ - stack -} - -class App { - - /** - * @type {(library: string) => any} - * */ - require -} - -class Logger { - - /** - * @type {(level: string, additionalInfoDto: Object, message: string, hiddenKeys?: any) => void} - * */ - log - - /** - * @type {() => void} - * */ - clear -} - -class CoreData { - /** - * @type {string} - */ - jsonSchema - - /** - * @type {string} - */ - modelDefinitions - - /** - * @type {string} - */ - internalDefinitions - - /** - * @type {string} - */ - externalDefinitions - - /** - * @type {any} - */ - containerData - - /** - * @type {any} - */ - entityData - - /** - * @type {any} - */ - entities - - /** - * @type {Array} - */ - views - - /** - * @type {Object | undefined} - */ - viewData - - /** - * @type {Array} - */ - relationships - - /** - * @type {Object | undefined} - */ - collectionRefsDefinitionsMap - - /** - * @type {boolean} - */ - isUpdateScript - - /** - * @type {'container' | 'entity'} - */ - level - - /** - * @type {string | undefined} - */ - host - - /** - * @type {string | undefined} - */ - clusterId - - /** - * @type {string | undefined} - */ - accessToken - - /** - * @type {string | number | undefined} - */ - applyToInstanceQueryRequestTimeout - - /** - * @type {string | undefined} - */ - script - - /** - * @type {any | undefined} - */ - hiddenKeys - - /** - * @type {Array<{ - * id: string, - * value: any, - * }> | {separateBucket: boolean}} - */ - options - - /** - * @type {[ - * { - * modelName: string, - * dbVendor: string, - * dbVersion: string, - * isLineageEnabled: boolean - * }, - * { relationships: [] }, - * { sources: [] } - * ]} - * */ - modelData -} - -module.exports = { - App, - CoreData, - Logger, - PluginError, -} diff --git a/forward_engineering/utils/assignTemplates.js b/forward_engineering/utils/assignTemplates.js deleted file mode 100644 index ec2b098..0000000 --- a/forward_engineering/utils/assignTemplates.js +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright © 2016-2021 by IntegrIT S.A. dba Hackolade. All rights reserved. - * - * The copyright to the computer software herein is the property of IntegrIT S.A. - * The software may be used and/or copied only with the written permission of - * IntegrIT S.A. or in accordance with the terms and conditions stipulated in - * the agreement/contract under which the software has been supplied. - */ - -const template = (modifiers = '') => new RegExp('\\$\\{(.*?)\\}', modifiers); -const getAllTemplates = str => str.match(template('gi')) || []; -const parseTemplate = str => (str.match(template('i')) || [])[1]; - -const assignTemplates = (str, templates) => { - return getAllTemplates(str).reduce((result, item) => { - const templateName = parseTemplate(item); - - return result.replace(item, () => { - return templates[templateName] || templates[templateName] === 0 ? templates[templateName] : ''; - }); - }, str); -}; - -module.exports = assignTemplates; diff --git a/forward_engineering/utils/general.js b/forward_engineering/utils/general.js deleted file mode 100644 index 08ec368..0000000 --- a/forward_engineering/utils/general.js +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright © 2016-2021 by IntegrIT S.A. dba Hackolade. All rights reserved. - * - * The copyright to the computer software herein is the property of IntegrIT S.A. - * The software may be used and/or copied only with the written permission of - * IntegrIT S.A. or in accordance with the terms and conditions stipulated in - * the agreement/contract under which the software has been supplied. - */ - -const {AlterCollectionDto, AlterCollectionRoleDto} = require('../alterScript/types/AlterCollectionDto'); - -const {ReservedWordsAsArray} = require("../enums/reservedWords"); -const MUST_BE_ESCAPED = /\t|\n|'|\f|\r/gm; - -module.exports = _ => { - const getDbName = containerData => { - return _.get(containerData, '[0].code') || _.get(containerData, '[0].name', ''); - }; - - const getEntityName = entityData => { - return (entityData && (entityData.code || entityData.collectionName)) || ''; - }; - - const getViewName = view => { - return (view && (view.code || view.name)) || ''; - }; - - const getDbData = containerData => { - return Object.assign({}, _.get(containerData, '[0]', {}), { name: getDbName(containerData) }); - }; - - const getViewOn = viewData => _.get(viewData, '[0].viewOn'); - - const tab = (text, tab = '\t') => { - return text - .split('\n') - .map(line => tab + line) - .join('\n'); - }; - - const hasType = (types, type) => { - return Object.keys(types).map(_.toLower).includes(_.toLower(type)); - }; - - /** - * @param collection {AlterCollectionDto} - * @return {AlterCollectionDto & AlterCollectionRoleDto} - * */ - const getSchemaOfAlterCollection = (collection) => { - return {...collection, ...(_.omit(collection?.role, 'properties') || {})}; - } - - /** - * @param collectionSchema {AlterCollectionDto & AlterCollectionRoleDto} - * @return {string} - * */ - const getFullCollectionName = (collectionSchema) => { - const collectionName = getEntityName(collectionSchema); - const bucketName = collectionSchema.compMod?.keyspaceName; - return getNamePrefixedWithSchemaName(collectionName, bucketName); - } - - const clean = obj => - Object.entries(obj) - .filter(([name, value]) => !_.isNil(value)) - .reduce( - (result, [name, value]) => ({ - ...result, - [name]: value, - }), - {}, - ); - - const checkAllKeysActivated = keys => { - return keys.every(key => _.get(key, 'isActivated', true)); - }; - - /** - * @param keys {Array<{ - * isActivated: boolean, - * }>} - * */ - const checkAllKeysDeactivated = keys => { - return keys.length ? keys.every(key => !_.get(key, 'isActivated', true)) : false; - }; - - const divideIntoActivatedAndDeactivated = (items, mapFunction) => { - const activatedItems = items.filter(item => _.get(item, 'isActivated', true)).map(mapFunction); - const deactivatedItems = items.filter(item => !_.get(item, 'isActivated', true)).map(mapFunction); - - return { activatedItems, deactivatedItems }; - }; - - const commentIfDeactivated = (statement, { isActivated, isPartOfLine, inlineComment = '--' }) => { - if (!statement) { - return ''; - } - if (isActivated !== false) { - return statement; - } - if (isPartOfLine) { - return '/* ' + statement + ' */'; - } else if (statement.includes('\n')) { - return '/*\n' + statement + ' */\n'; - } else { - return inlineComment + ' ' + statement; - } - }; - - const wrap = (str, start = "'", end = "'") => { - const firstChar = str[0]; - const lastChar = str[str.length - 1]; - - if (lastChar === start && firstChar === end) { - return str; - } else { - return `${start}${str}${end}`; - } - }; - - const checkFieldPropertiesChanged = (compMod, propertiesToCheck) => { - return propertiesToCheck.some(prop => compMod?.oldField[prop] !== compMod?.newField[prop]); - }; - - const getFullTableName = (collection) => { - const collectionSchema = {...collection, ...(_.omit(collection?.role, 'properties') || {})}; - const tableName = getEntityName(collectionSchema); - const schemaName = collectionSchema.compMod?.keyspaceName; - return getNamePrefixedWithSchemaName(tableName, schemaName); - } - - const getFullColumnName = (collection, columnName) => { - const {wrapInQuotes} = require('../utils/general')(_); - - const fullTableName = getFullTableName(collection); - return `${fullTableName}.${wrapInQuotes(columnName)}`; - } - - const getFullViewName = (view) => { - const viewSchema = {...view, ...(_.omit(view?.role, 'properties') || {})}; - const viewName = getViewName(viewSchema); - const schemaName = viewSchema.compMod?.keyspaceName; - return getNamePrefixedWithSchemaName(viewName, schemaName); - } - - /** - * @param udt {Object} - * @return {string} - * */ - const getUdtName = (udt) => { - return udt.code || udt.name; - } - - const getDbVersion = (dbVersion = '') => { - const version = dbVersion.match(/\d+/); - - return Number(_.get(version, [0], 0)); - }; - - const prepareComment = (comment = '') => - comment.replace(MUST_BE_ESCAPED, character => `\\${character}`); - - const wrapComment = comment => `E'${prepareComment(JSON.stringify(comment)).slice(1, -1)}'`; - - const getFunctionArguments = functionArguments => { - return _.map(functionArguments, arg => { - const defaultExpression = arg.defaultExpression ? `DEFAULT ${arg.defaultExpression}` : ''; - - return _.trim(`${arg.argumentMode} ${arg.argumentName || ''} ${arg.argumentType} ${defaultExpression}`); - }).join(', '); - }; - - const getNamePrefixedWithSchemaName = (name, schemaName) => { - if (schemaName) { - return `${wrapInQuotes(schemaName)}.${wrapInQuotes(name)}`; - } - - return wrapInQuotes(name); - }; - - const wrapInQuotes = name => - /\s|\W/.test(name) || _.includes(ReservedWordsAsArray, _.toUpper(name)) ? `"${name}"` : name; - - const columnMapToString = ({ name }) => wrapInQuotes(name); - - const getColumnsList = (columns, isAllColumnsDeactivated, isParentActivated, mapColumn = columnMapToString) => { - const dividedColumns = divideIntoActivatedAndDeactivated(columns, mapColumn); - const deactivatedColumnsAsString = dividedColumns?.deactivatedItems?.length - ? commentIfDeactivated(dividedColumns.deactivatedItems.join(', '), { - isActivated: false, - isPartOfLine: true, - }) - : ''; - - return !isAllColumnsDeactivated && isParentActivated - ? ' (' + dividedColumns.activatedItems.join(', ') + deactivatedColumnsAsString + ')' - : ' (' + columns.map(mapColumn).join(', ') + ')'; - }; - - const getKeyWithAlias = key => { - if (!key) { - return ''; - } - - if (key.alias) { - return `${wrapInQuotes(key.name)} as ${wrapInQuotes(key.alias)}`; - } else { - return wrapInQuotes(key.name); - } - }; - - const getViewData = keys => { - if (!Array.isArray(keys)) { - return { tables: [], columns: [] }; - } - - return keys.reduce( - (result, key) => { - if (!key.tableName) { - result.columns.push(getKeyWithAlias(key)); - - return result; - } - - const tableName = `${wrapInQuotes(key.dbName)}.${wrapInQuotes(key.tableName)}`; - - if (!result.tables.includes(tableName)) { - result.tables.push(tableName); - } - - result.columns.push({ - statement: `${tableName}.${getKeyWithAlias(key)}`, - isActivated: key.isActivated, - }); - - return result; - }, - { - tables: [], - columns: [], - }, - ); - }; - - return { - getDbName, - getDbData, - getEntityName, - getViewName, - getViewOn, - tab, - hasType, - clean, - checkAllKeysActivated, - checkAllKeysDeactivated, - divideIntoActivatedAndDeactivated, - commentIfDeactivated, - wrap, - checkFieldPropertiesChanged, - getFullTableName, - getFullColumnName, - getFullViewName, - getUdtName, - getDbVersion, - wrapComment, - getFunctionArguments, - getNamePrefixedWithSchemaName, - wrapInQuotes, - getColumnsList, - getViewData, - getSchemaOfAlterCollection, - getFullCollectionName - }; -}; diff --git a/jsonSchemaProperties.json b/jsonSchemaProperties.json index 32a8e13..560355b 100644 --- a/jsonSchemaProperties.json +++ b/jsonSchemaProperties.json @@ -1,4 +1,15 @@ { - "unneededFieldProps": ["collectionName", "name", "users", "indexes", "collectionUsers", "additionalPropertieserties", "compositeClusteringKey", "compositePartitionKey", "SecIDxs", "compositeKey"], + "unneededFieldProps": [ + "collectionName", + "name", + "users", + "indexes", + "collectionUsers", + "additionalPropertieserties", + "compositeClusteringKey", + "compositePartitionKey", + "SecIDxs", + "compositeKey" + ], "removeIfPropsNegative": ["partitionKey", "sortKey"] -} \ No newline at end of file +} diff --git a/package.json b/package.json index 8ef1873..7b1e147 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,6 @@ { "name": "CockroachDB", - "version": "0.1.4", - "versionDate": "2024-01-26", + "version": "0.2.1", "author": "hackolade", "engines": { "hackolade": "6.1.2", @@ -26,8 +25,8 @@ "enableJsonType": true, "useJsonTypesWithComplexTypes": true, "reverseSchemaIntoOneColumn": true, - "disableDenormalization": true, - "enableComplexTypesNormalization": true, + "disableDenormalization": true, + "enableComplexTypesNormalization": true, "views": { "enabled": true, "viewLevel": "model", @@ -43,5 +42,44 @@ }, "description": "Hackolade plugin for CockroachDB", "icon_url": "logo.jpg", - "disabled": false -} + "disabled": false, + "dependencies": { + "lodash": "4.17.21", + "pg": "8.11.5", + "tunnel-ssh": "4.1.6" + }, + "lint-staged": { + "*.{js,json}": "prettier --write" + }, + "simple-git-hooks": { + "pre-commit": "npx lint-staged", + "pre-push": "npx eslint ." + }, + "scripts": { + "lint": "eslint . --max-warnings=0", + "package": "node esbuild.package.js" + }, + "devDependencies": { + "@hackolade/hck-esbuild-plugins-pack": "0.0.1", + "@typescript-eslint/eslint-plugin": "7.11.0", + "@typescript-eslint/parser": "7.11.0", + "esbuild": "0.20.2", + "esbuild-plugin-clean": "1.0.1", + "eslint": "8.57.0", + "eslint-config-prettier": "9.1.0", + "eslint-formatter-teamcity": "^1.0.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-prettier": "5.1.3", + "eslint-plugin-unused-imports": "3.2.0", + "lint-staged": "14.0.1", + "prettier": "3.2.5", + "simple-git-hooks": "2.11.1" + }, + "overrides": { + "tunnel-ssh": { + "cpu-features": "npm:-@0.0.1", + "ssh2": "npm:-@0.0.1" + } + }, + "release": true +} \ No newline at end of file diff --git a/polyglot/convertAdapter.json b/polyglot/convertAdapter.json index 20d4c9d..ceb88d1 100644 --- a/polyglot/convertAdapter.json +++ b/polyglot/convertAdapter.json @@ -39,10 +39,10 @@ * }, * } */ - { - "modify": { - "field": [ - { +{ + "modify": { + "field": [ + { "from": { "type": "numeric", "mode": "int" @@ -53,6 +53,6 @@ "mode": "bigint" } } - ] - } + ] + } } diff --git a/properties_pane/defaultData.json b/properties_pane/defaultData.json index 04ea0ea..961aa05 100644 --- a/properties_pane/defaultData.json +++ b/properties_pane/defaultData.json @@ -58,4 +58,4 @@ "SecIndxFunction": "", "SecIndxComments": "" } -} \ No newline at end of file +} diff --git a/properties_pane/entity_level/entityLevelConfig.json b/properties_pane/entity_level/entityLevelConfig.json index d4230b5..19b9ef6 100644 --- a/properties_pane/entity_level/entityLevelConfig.json +++ b/properties_pane/entity_level/entityLevelConfig.json @@ -589,7 +589,7 @@ making sure that you maintain a proper JSON format. "propertyTooltip": "", "propertyType": "select", "defaultValue": "btree", - "options": ["","btree", "gist", "gin"] + "options": ["", "btree", "gist", "gin"] }, { "propertyName": "Unique", @@ -795,11 +795,7 @@ making sure that you maintain a proper JSON format. "propertyKeyword": "visibility", "propertyTooltip": "An optional VISIBLE or NOT VISIBLE clause that indicates whether an index is visible to the cost-based optimizer.", "propertyType": "select", - "options": [ - "", - "VISIBLE", - "NOT VISIBLE" - ] + "options": ["", "VISIBLE", "NOT VISIBLE"] }, { "propertyName": "Comment", diff --git a/properties_pane/field_level/fieldLevelConfig.json b/properties_pane/field_level/fieldLevelConfig.json index 8babcec..4b86394 100644 --- a/properties_pane/field_level/fieldLevelConfig.json +++ b/properties_pane/field_level/fieldLevelConfig.json @@ -125,15 +125,7 @@ making sure that you maintain a proper JSON format. "propertyName": "Subtype", "propertyKeyword": "mode", "propertyType": "select", - "options": [ - "char", - "varchar", - "text", - "bit", - "varbit", - "tsvector", - "tsquery" - ], + "options": ["char", "varchar", "text", "bit", "varbit", "tsvector", "tsquery"], "data": "options", "valueType": "string", "cleanDependency": true @@ -150,12 +142,7 @@ making sure that you maintain a proper JSON format. "typeDecorator": true, "dependency": { "key": "mode", - "value": [ - "char", - "varchar", - "bit", - "varbit" - ] + "value": ["char", "varchar", "bit", "varbit"] } }, { @@ -182,11 +169,7 @@ making sure that you maintain a proper JSON format. "propertyType": "text", "dependency": { "key": "mode", - "value": [ - "char", - "varchar", - "text" - ] + "value": ["char", "varchar", "text"] } }, { @@ -344,29 +327,33 @@ making sure that you maintain a proper JSON format. }, { "type": "not", - "values": [{ - "level": "siblings", - "value": { - "type": "and", - "values": [{ - "key": "primaryKey", - "value": true - }, - { - "type": "or", + "values": [ + { + "level": "siblings", + "value": { + "type": "and", "values": [ { - "key": "compositeUniqueKey", - "value": false + "key": "primaryKey", + "value": true }, { - "key": "compositeUniqueKey", - "exist": false + "type": "or", + "values": [ + { + "key": "compositeUniqueKey", + "value": false + }, + { + "key": "compositeUniqueKey", + "exist": false + } + ] } ] - }] + } } - }] + ] }, { "type": "and", @@ -637,15 +624,7 @@ making sure that you maintain a proper JSON format. "propertyName": "Subtype", "propertyKeyword": "mode", "propertyType": "select", - "options": [ - "int", - "int2", - "int4", - "decimal", - "float", - "real", - "double precision" - ], + "options": ["int", "int2", "int4", "decimal", "float", "real", "double precision"], "data": "options", "valueType": "string" }, @@ -658,9 +637,7 @@ making sure that you maintain a proper JSON format. "typeDecorator": true, "dependency": { "key": "mode", - "value": [ - "decimal" - ] + "value": ["decimal"] } }, { @@ -672,9 +649,7 @@ making sure that you maintain a proper JSON format. "typeDecorator": true, "dependency": { "key": "mode", - "value": [ - "decimal" - ] + "value": ["decimal"] } }, { @@ -687,11 +662,7 @@ making sure that you maintain a proper JSON format. "values": [ { "key": "mode", - "value": [ - "smallserial", - "serial", - "bigserial" - ] + "value": ["smallserial", "serial", "bigserial"] } ] }, @@ -836,29 +807,33 @@ making sure that you maintain a proper JSON format. }, { "type": "not", - "values": [{ - "level": "siblings", - "value": { - "type": "and", - "values": [{ - "key": "primaryKey", - "value": true - }, - { - "type": "or", + "values": [ + { + "level": "siblings", + "value": { + "type": "and", "values": [ { - "key": "compositeUniqueKey", - "value": false + "key": "primaryKey", + "value": true }, { - "key": "compositeUniqueKey", - "exist": false + "type": "or", + "values": [ + { + "key": "compositeUniqueKey", + "value": false + }, + { + "key": "compositeUniqueKey", + "exist": false + } + ] } ] - }] + } } - }] + ] }, { "type": "and", @@ -1135,9 +1110,7 @@ making sure that you maintain a proper JSON format. "propertyName": "Subtype", "propertyKeyword": "mode", "propertyType": "select", - "options": [ - "bytea" - ], + "options": ["bytea"], "data": "options", "valueType": "string" }, @@ -1286,29 +1259,33 @@ making sure that you maintain a proper JSON format. }, { "type": "not", - "values": [{ - "level": "siblings", - "value": { - "type": "and", - "values": [{ - "key": "primaryKey", - "value": true - }, - { - "type": "or", + "values": [ + { + "level": "siblings", + "value": { + "type": "and", "values": [ { - "key": "compositeUniqueKey", - "value": false + "key": "primaryKey", + "value": true }, { - "key": "compositeUniqueKey", - "exist": false + "type": "or", + "values": [ + { + "key": "compositeUniqueKey", + "value": false + }, + { + "key": "compositeUniqueKey", + "exist": false + } + ] } ] - }] + } } - }] + ] }, { "type": "and", @@ -1572,12 +1549,7 @@ making sure that you maintain a proper JSON format. "propertyName": "Subtype", "propertyKeyword": "mode", "propertyType": "select", - "options": [ - "date", - "time", - "timestamp", - "interval" - ], + "options": ["date", "time", "timestamp", "interval"], "data": "options", "valueType": "string" }, @@ -1593,28 +1565,17 @@ making sure that you maintain a proper JSON format. "typeDecorator": true, "dependency": { "key": "mode", - "value": [ - "time", - "timestamp", - "interval" - ] + "value": ["time", "timestamp", "interval"] } }, { "propertyName": "Timezone", "propertyKeyword": "timezone", "propertyType": "select", - "options": [ - "", - "WITH TIME ZONE", - "WITHOUT TIME ZONE" - ], + "options": ["", "WITH TIME ZONE", "WITHOUT TIME ZONE"], "dependency": { "key": "mode", - "value": [ - "time", - "timestamp" - ] + "value": ["time", "timestamp"] } }, { @@ -1789,29 +1750,33 @@ making sure that you maintain a proper JSON format. }, { "type": "not", - "values": [{ - "level": "siblings", - "value": { - "type": "and", - "values": [{ - "key": "primaryKey", - "value": true - }, - { - "type": "or", + "values": [ + { + "level": "siblings", + "value": { + "type": "and", "values": [ { - "key": "compositeUniqueKey", - "value": false + "key": "primaryKey", + "value": true }, { - "key": "compositeUniqueKey", - "exist": false + "type": "or", + "values": [ + { + "key": "compositeUniqueKey", + "value": false + }, + { + "key": "compositeUniqueKey", + "exist": false + } + ] } ] - }] + } } - }] + ] }, { "type": "and", @@ -2154,12 +2119,7 @@ making sure that you maintain a proper JSON format. "propertyName": "Subtype", "propertyKeyword": "mode", "propertyType": "select", - "options": [ - "inet", - "cidr", - "macaddr", - "macaddr8" - ], + "options": ["inet", "cidr", "macaddr", "macaddr8"], "data": "options", "valueType": "string" }, @@ -2308,29 +2268,33 @@ making sure that you maintain a proper JSON format. }, { "type": "not", - "values": [{ - "level": "siblings", - "value": { - "type": "and", - "values": [{ - "key": "primaryKey", - "value": true - }, - { - "type": "or", + "values": [ + { + "level": "siblings", + "value": { + "type": "and", "values": [ { - "key": "compositeUniqueKey", - "value": false + "key": "primaryKey", + "value": true }, { - "key": "compositeUniqueKey", - "exist": false + "type": "or", + "values": [ + { + "key": "compositeUniqueKey", + "value": false + }, + { + "key": "compositeUniqueKey", + "exist": false + } + ] } ] - }] + } } - }] + ] }, { "type": "and", @@ -2742,29 +2706,33 @@ making sure that you maintain a proper JSON format. }, { "type": "not", - "values": [{ - "level": "siblings", - "value": { - "type": "and", - "values": [{ - "key": "primaryKey", - "value": true - }, - { - "type": "or", + "values": [ + { + "level": "siblings", + "value": { + "type": "and", "values": [ { - "key": "compositeUniqueKey", - "value": false + "key": "primaryKey", + "value": true }, { - "key": "compositeUniqueKey", - "exist": false + "type": "or", + "values": [ + { + "key": "compositeUniqueKey", + "value": false + }, + { + "key": "compositeUniqueKey", + "exist": false + } + ] } ] - }] + } } - }] + ] }, { "type": "and", @@ -3197,29 +3165,33 @@ making sure that you maintain a proper JSON format. }, { "type": "not", - "values": [{ - "level": "siblings", - "value": { - "type": "and", - "values": [{ - "key": "primaryKey", - "value": true - }, - { - "type": "or", + "values": [ + { + "level": "siblings", + "value": { + "type": "and", "values": [ { - "key": "compositeUniqueKey", - "value": false + "key": "primaryKey", + "value": true }, { - "key": "compositeUniqueKey", - "exist": false + "type": "or", + "values": [ + { + "key": "compositeUniqueKey", + "value": false + }, + { + "key": "compositeUniqueKey", + "exist": false + } + ] } ] - }] + } } - }] + ] }, { "type": "and", @@ -3489,10 +3461,7 @@ making sure that you maintain a proper JSON format. "propertyName": "Subtype", "propertyKeyword": "mode", "propertyType": "select", - "options": [ - "json", - "jsonb" - ], + "options": ["json", "jsonb"], "data": "options", "valueType": "string" }, diff --git a/properties_pane/model_level/modelLevelConfig.json b/properties_pane/model_level/modelLevelConfig.json index cdba564..47fc816 100644 --- a/properties_pane/model_level/modelLevelConfig.json +++ b/properties_pane/model_level/modelLevelConfig.json @@ -61,9 +61,7 @@ making sure that you maintain a proper JSON format. "shouldValidate": false, "propertyTooltip": "DB vendor", "propertyType": "select", - "options": [ - "CockroachDB" - ], + "options": ["CockroachDB"], "disabledOption": true }, { @@ -72,10 +70,7 @@ making sure that you maintain a proper JSON format. "shouldValidate": false, "propertyTooltip": "DB version", "propertyType": "select", - "options": [ - "v22.x", - "v23.x" - ], + "options": ["v22.x", "v23.x"], "disabledOption": false }, { @@ -89,10 +84,7 @@ making sure that you maintain a proper JSON format. "propertyKeyword": "encoding", "propertyTooltip": "Select from list of options", "propertyType": "select", - "options": [ - "", - "UTF-8" - ] + "options": ["", "UTF-8"] }, { "propertyName": "Template", @@ -133,37 +125,19 @@ making sure that you maintain a proper JSON format. "propertyName": "On Delete", "propertyKeyword": "relationshipOnDelete", "propertyType": "select", - "options": [ - "", - "NO ACTION", - "RESTRICT", - "CASCADE", - "SET NULL", - "SET DEFAULT" - ] + "options": ["", "NO ACTION", "RESTRICT", "CASCADE", "SET NULL", "SET DEFAULT"] }, { "propertyName": "On Update", "propertyKeyword": "relationshipOnUpdate", "propertyType": "select", - "options": [ - "", - "NO ACTION", - "RESTRICT", - "CASCADE", - "SET NULL", - "SET DEFAULT" - ] + "options": ["", "NO ACTION", "RESTRICT", "CASCADE", "SET NULL", "SET DEFAULT"] }, { "propertyName": "Match", "propertyKeyword": "relationshipMatch", "propertyType": "select", - "options": [ - "", - "SIMPLE", - "FULL" - ] + "options": ["", "SIMPLE", "FULL"] } ] } diff --git a/properties_pane/samples.json b/properties_pane/samples.json index 3f0bc84..ff5ddec 100644 --- a/properties_pane/samples.json +++ b/properties_pane/samples.json @@ -23,7 +23,7 @@ ] } }, - { + { "validateAs": "string", "dependency": { "type": "and", diff --git a/properties_pane/view_level/viewLevelConfig.json b/properties_pane/view_level/viewLevelConfig.json index f3abf95..cebb6fc 100644 --- a/properties_pane/view_level/viewLevelConfig.json +++ b/properties_pane/view_level/viewLevelConfig.json @@ -154,11 +154,7 @@ making sure that you maintain a proper JSON format. "propertyKeyword": "check_option", "propertyTooltip": "This option controls the behavior of automatically updatable views. When this option is specified, INSERT and UPDATE commands on the view will be checked to ensure that new rows satisfy the view-defining condition (that is, the new rows are checked to ensure that they are visible through the view). If they are not, the update will be rejected.", "propertyType": "select", - "options": [ - "", - "local", - "cascaded" - ] + "options": ["", "local", "cascaded"] }, { "propertyName": "Security barrier", @@ -196,17 +192,15 @@ making sure that you maintain a proper JSON format. "propertyKeyword": "checkTestingScope", "propertyTooltip": "This option controls the behavior of automatically updatable views. When this option is specified, INSERT and UPDATE commands on the view will be checked to ensure that new rows satisfy the view-defining condition (that is, the new rows are checked to ensure that they are visible through the view). If they are not, the update will be rejected.", "propertyType": "select", - "options": [ - "", - "LOCAL", - "CASCADED" - ], + "options": ["", "LOCAL", "CASCADED"], "dependency": { "type": "or", - "values": [{ - "key": "withCheckOption", - "value": true - }] + "values": [ + { + "key": "withCheckOption", + "value": true + } + ] } }, { diff --git a/reverse_engineering/api.js b/reverse_engineering/api.js index f9fc9c8..1a0c2b4 100644 --- a/reverse_engineering/api.js +++ b/reverse_engineering/api.js @@ -1,232 +1,249 @@ -'use strict'; - -const { createLogger } = require('./helpers/loggerHelper'); -const cockroachDBService = require('./helpers/cockroachDBService'); - -module.exports = { - async disconnect(connectionInfo, logger, callback, app) { - await cockroachDBService.disconnect(); - - callback(); - }, - - async testConnection(connectionInfo, logger, callback, app) { - try { - logInfo('Test connection', connectionInfo, logger); - - const cockroachDBLogger = createLogger({ - title: 'Test connection instance log', - hiddenKeys: connectionInfo.hiddenKeys, - logger, - }); - - cockroachDBService.setDependencies(app); - await cockroachDBService.connect(connectionInfo, cockroachDBLogger); - await cockroachDBService.pingDb(); - await cockroachDBService.logVersion(); - callback(); - } catch (error) { - logger.log('error', prepareError(error), 'Test connection instance log'); - callback(prepareError(error)); - } finally { - await cockroachDBService.disconnect(); - } - }, - - async getDatabases(connectionInfo, logger, cb, app) { - try { - logInfo('Get databases', connectionInfo, logger); - - const cockroachDBLogger = createLogger({ - title: 'Get DB names', - hiddenKeys: connectionInfo.hiddenKeys, - logger, - }); - - cockroachDBService.setDependencies(app); - await cockroachDBService.connect(connectionInfo, cockroachDBLogger); - await cockroachDBService.logVersion(); - - const dbs = await cockroachDBService.getDatabaseNames(); - logger.log('info', dbs, 'All databases list', connectionInfo.hiddenKeys); - return cb(null, dbs); - } catch (err) { - logger.log('error', err); - return cb(prepareError(err)); - } - }, - - getDocumentKinds: function (connectionInfo, logger, cb) { - cb(null, []); - }, - - async getDbCollectionsNames(connectionInfo, logger, callback, app) { - try { - logInfo('Get DB table names', connectionInfo, logger); - - const cockroachDBLogger = createLogger({ - title: 'Get DB collections names', - hiddenKeys: connectionInfo.hiddenKeys, - logger, - }); - - cockroachDBService.setDependencies(app); - await cockroachDBService.connect(connectionInfo, cockroachDBLogger); - await cockroachDBService.logVersion(); - const schemasNames = await cockroachDBService.getAllSchemasNames(); - - const collections = await schemasNames.reduce(async (next, dbName) => { - const result = await next; - try { - const dbCollections = await cockroachDBService.getTablesNames(dbName); - - return result.concat({ - dbName, - dbCollections, - isEmpty: dbCollections.length === 0, - }); - } catch (error) { - cockroachDBLogger.info(`Error reading database "${dbName}"`); - cockroachDBLogger.error(error); - - return result.concat({ - dbName, - dbCollections: [], - isEmpty: true, - status: true, - }); - } - }, Promise.resolve([])); - - callback(null, collections); - } catch (error) { - logger.log('error', prepareError(error), 'Get DB collections names'); - callback(prepareError(error)); - await cockroachDBService.disconnect(); - } - }, - - async getDbCollectionsData(data, logger, callback, app) { - try { - logger.log('info', data, 'Retrieve tables data:', data.hiddenKeys); - - const cockroachDBLogger = createLogger({ - title: 'Get DB collections data log', - hiddenKeys: data.hiddenKeys, - logger, - }); - - cockroachDBLogger.progress('Start reverse engineering...'); - - const collections = data.collectionData.collections; - const schemasNames = data.collectionData.dataBaseNames; - - const modelData = await cockroachDBService.getDbLevelData(); - - const { packages, relationships } = await Promise.all( - schemasNames.map(async schemaName => { - const { tables, views, modelDefinitions } = await cockroachDBService.retrieveEntitiesData( - schemaName, - collections[schemaName], - data.recordSamplingSettings, - ); - const { functions, procedures } = await cockroachDBService.retrieveSchemaLevelData( - schemaName, - data.ignoreUdfUdpTriggers, - ); - - cockroachDBLogger.progress('Schema data fetched successfully', schemaName); - - return { - schemaName, - tables, - views, - functions, - procedures, - modelDefinitions, - }; - }), - ) - .then(schemaData => { - const relationships = schemaData - .flatMap(({ tables }) => tables.map(entityData => entityData.relationships)) - .flat(); - - const packages = schemaData.flatMap( - ({ schemaName, tables, views, functions, procedures, modelDefinitions }) => { - const bucketInfo = { - UDFs: functions, - Procedures: procedures, - }; - - const tablePackages = tables - .map(entityData => ({ - dbName: schemaName, - collectionName: entityData.name, - documents: entityData.documents, - views: [], - emptyBucket: false, - entityLevel: entityData.entityLevel, - validation: { - jsonSchema: entityData.jsonSchema, - }, - bucketInfo, - modelDefinitions, - })) - .sort(data => (app.require('lodash').isEmpty(data.entityLevel.inherits) ? -1 : 1)); - - if (views?.length) { - const viewPackage = { - dbName: schemaName, - views: views, - emptyBucket: false, - }; - - return [...tablePackages, viewPackage]; - } - - return tablePackages; - }, - ); - return { packages, relationships }; - }) - .then(({ packages, relationships }) => ({ packages: orderPackages(packages), relationships })); - - cockroachDBLogger.info('The data is processed and sent to the application', { - packagesLength: packages?.length, - relationshipsLength: relationships?.length, - }); - callback(null, packages, modelData, relationships); - } catch (error) { - logger.log('error', prepareError(error), 'Retrieve tables data'); - callback(prepareError(error)); - } finally { - await cockroachDBService.disconnect(); - } - }, -}; - -const prepareError = error => { - error = JSON.stringify(error, Object.getOwnPropertyNames(error)); - error = JSON.parse(error); - return error; -}; - -const logInfo = (step, connectionInfo, logger) => { - logger.clear(); - logger.log('info', connectionInfo, 'connectionInfo', connectionInfo.hiddenKeys); -}; - -const orderPackages = packages => { - return packages.sort((packA, packB) => { - if (!packA.collectionName && !packB.collectionName) { - return 0; - } else if (!packA.collectionName) { - return 1; - } else if (!packB.collectionName) { - return -1; - } else { - return packA.collectionName.localeCompare(packB.collectionName); - } - }); -}; +"use strict";var Ce=Object.defineProperty;var $i=Object.getOwnPropertyDescriptor;var zi=Object.getOwnPropertyNames;var Yi=Object.prototype.hasOwnProperty;var i=(t,e)=>Ce(t,"name",{value:e,configurable:!0});var Ji=(t,e)=>()=>(t&&(e=t(t=0)),e);var h=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Zi=(t,e)=>{for(var r in e)Ce(t,r,{get:e[r],enumerable:!0})},Xi=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of zi(e))!Yi.call(t,s)&&s!==r&&Ce(t,s,{get:()=>e[s],enumerable:!(n=$i(e,s))||n.enumerable});return t};var ea=t=>Xi(Ce({},"__esModule",{value:!0}),t);var Yr=h((Th,zr)=>{"use strict";var ta=i(({title:t,logger:e,hiddenKeys:r})=>({info(n,s={}){e.log("info",{message:n,...s},t,r)},progress(n,s="",a=""){e.progress({message:n,containerName:s,entityName:a})},error(n){e.log("error",ra(n),t)}}),"createLogger"),ra=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError");zr.exports={createLogger:ta}});var Zr=h((bh,Jr)=>{var ie=1e3,ae=ie*60,oe=ae*60,ce=oe*24,na=ce*365.25;Jr.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return sa(t);if(r==="number"&&isNaN(t)===!1)return e.long?aa(t):ia(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function sa(t){if(t=String(t),!(t.length>100)){var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*na;case"days":case"day":case"d":return r*ce;case"hours":case"hour":case"hrs":case"hr":case"h":return r*oe;case"minutes":case"minute":case"mins":case"min":case"m":return r*ae;case"seconds":case"second":case"secs":case"sec":case"s":return r*ie;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}i(sa,"parse");function ia(t){return t>=ce?Math.round(t/ce)+"d":t>=oe?Math.round(t/oe)+"h":t>=ae?Math.round(t/ae)+"m":t>=ie?Math.round(t/ie)+"s":t+"ms"}i(ia,"fmtShort");function aa(t){return Oe(t,ce,"day")||Oe(t,oe,"hour")||Oe(t,ae,"minute")||Oe(t,ie,"second")||t+" ms"}i(aa,"fmtLong");function Oe(t,e,r){if(!(t{g=Xr.exports=et.debug=et.default=et;g.coerce=pa;g.disable=ua;g.enable=ca;g.enabled=la;g.humanize=Zr();g.names=[];g.skips=[];g.formatters={};var Xe;function oa(t){var e=0,r;for(r in t)e=(e<<5)-e+t.charCodeAt(r),e|=0;return g.colors[Math.abs(e)%g.colors.length]}i(oa,"selectColor");function et(t){function e(){if(e.enabled){var r=e,n=+new Date,s=n-(Xe||n);r.diff=s,r.prev=Xe,r.curr=n,Xe=n;for(var a=new Array(arguments.length),o=0;o{I=tn.exports=tt();I.log=da;I.formatArgs=fa;I.save=ma;I.load=en;I.useColors=ha;I.storage=typeof chrome<"u"&&typeof chrome.storage<"u"?chrome.storage.local:_a();I.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function ha(){return typeof window<"u"&&window.process&&window.process.type==="renderer"?!0:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}i(ha,"useColors");I.formatters.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}};function fa(t){var e=this.useColors;if(t[0]=(e?"%c":"")+this.namespace+(e?" %c":" ")+t[0]+(e?"%c ":" ")+"+"+I.humanize(this.diff),!!e){var r="color: "+this.color;t.splice(1,0,r,"color: inherit");var n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,function(a){a!=="%%"&&(n++,a==="%c"&&(s=n))}),t.splice(s,0,r)}}i(fa,"formatArgs");function da(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}i(da,"log");function ma(t){try{t==null?I.storage.removeItem("debug"):I.storage.debug=t}catch{}}i(ma,"save");function en(){var t;try{t=I.storage.debug}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}i(en,"load");I.enable(en());function _a(){try{return window.localStorage}catch{}}i(_a,"localstorage")});var on=h((C,an)=>{var nn=require("tty"),ue=require("util");C=an.exports=tt();C.init=ba;C.log=Sa;C.formatArgs=Ea;C.save=Ta;C.load=sn;C.useColors=ga;C.colors=[6,2,3,4,5,1];C.inspectOpts=Object.keys(process.env).filter(function(t){return/^debug_/i.test(t)}).reduce(function(t,e){var r=e.substring(6).toLowerCase().replace(/_([a-z])/g,function(s,a){return a.toUpperCase()}),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});var $=parseInt(process.env.DEBUG_FD,10)||2;$!==1&&$!==2&&ue.deprecate(function(){},"except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)")();var ya=$===1?process.stdout:$===2?process.stderr:va($);function ga(){return"colors"in C.inspectOpts?!!C.inspectOpts.colors:nn.isatty($)}i(ga,"useColors");C.formatters.o=function(t){return this.inspectOpts.colors=this.useColors,ue.inspect(t,this.inspectOpts).split(` +`).map(function(e){return e.trim()}).join(" ")};C.formatters.O=function(t){return this.inspectOpts.colors=this.useColors,ue.inspect(t,this.inspectOpts)};function Ea(t){var e=this.namespace,r=this.useColors;if(r){var n=this.color,s=" \x1B[3"+n+";1m"+e+" \x1B[0m";t[0]=s+t[0].split(` +`).join(` +`+s),t.push("\x1B[3"+n+"m+"+C.humanize(this.diff)+"\x1B[0m")}else t[0]=new Date().toUTCString()+" "+e+" "+t[0]}i(Ea,"formatArgs");function Sa(){return ya.write(ue.format.apply(ue,arguments)+` +`)}i(Sa,"log");function Ta(t){t==null?delete process.env.DEBUG:process.env.DEBUG=t}i(Ta,"save");function sn(){return process.env.DEBUG}i(sn,"load");function va(t){var e,r=process.binding("tty_wrap");switch(r.guessHandleType(t)){case"TTY":e=new nn.WriteStream(t),e._type="tty",e._handle&&e._handle.unref&&e._handle.unref();break;case"FILE":var n=require("fs");e=new n.SyncWriteStream(t,{autoClose:!1}),e._type="fs";break;case"PIPE":case"TCP":var s=require("net");e=new s.Socket({fd:t,readable:!1,writable:!0}),e.readable=!1,e.read=null,e._type="pipe",e._handle&&e._handle.unref&&e._handle.unref();break;default:throw new Error("Implement me. Unknown stream file type!")}return e.fd=t,e._isStdio=!0,e}i(va,"createWritableStdioStream");function ba(t){t.inspectOpts={};for(var e=Object.keys(C.inspectOpts),r=0;r{typeof process<"u"&&process.type==="renderer"?rt.exports=rn():rt.exports=on()});var cn=h(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.default=null});var _n=h((Nh,mn)=>{var ln=9007199254740991,wa="[object Arguments]",Aa="[object Function]",Ca="[object GeneratorFunction]",Oa=/^(?:0|[1-9]\d*)$/;function pn(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}i(pn,"apply");function Ra(t,e){for(var r=-1,n=Array(t);++r1?r[s-1]:void 0,o=s>2?r[2]:void 0;for(a=t.length>3&&typeof a=="function"?(s--,a):void 0,o&&Da(r[0],r[1],o)&&(a=s<3?void 0:a,s=1),e=Object(e);++n-1&&t%1==0&&t-1&&t%1==0&&t<=ln}i(Ha,"isLength");function ot(t){var e=typeof t;return!!t&&(e=="object"||e=="function")}i(ot,"isObject");function Wa(t){return!!t&&typeof t=="object"}i(Wa,"isObjectLike");var ja=qa(function(t,e,r,n){Ma(e,Ka(e),t,n)}),Va=fn(function(t){return t.push(void 0,xa),pn(ja,void 0,t)});function Ka(t){return at(t)?Na(t,!0):La(t)}i(Ka,"keysIn");mn.exports=Va});var gn=h((Ph,yn)=>{var $a=require("util"),za=_n(),Ya=nt()("tunnel-ssh-config"),ct=i(function(t,e){Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=t,this.extra=e},"ConfigError");$a.inherits(ct,Error);function Ja(t){var e=process.env;if(za(t||{},{username:e.TUNNELSSH_USER||e.USER||e.USERNAME||"root",port:22,host:null,srcPort:0,srcHost:"127.0.0.1",dstPort:null,dstHost:"127.0.0.1",localHost:"127.0.0.1",localPort:t.dstPort,agent:process.env.SSH_AUTH_SOCK}),!t.host)throw new ct("host not set");if(!t.dstPort)throw new ct("dstPort not set");return Ya("ssh-config",function(){var r=["password","privateKey"];return Object.keys(t).reduce(function(n,s){return r.indexOf(s)===-1?n[s]=t[s]:n[s]="***HIDDEN***",n},{})}()),t}i(Ja,"createConfig");yn.exports=Ja});var Sn=h((Mh,En)=>{var Za=require("net"),ut=nt()("tunnel-ssh"),Xa=cn().Client,eo=gn(),to=require("events"),ro=i(function(){},"noop");function no(t,e){var r=new Xa;return e.on("close",r.end.bind(r)),r.on("ready",function(){ut("sshConnection:ready"),e.emit("sshConnection",r,e),r.forwardOut(t.srcHost,t.srcPort,t.dstHost,t.dstPort,function(n,s){if(n){e.emit("error",n),ut("Destination port:",n);return}ut("sshStream:create"),e.emit("sshStream",s),e.pipe(s).pipe(e)})}),r}i(no,"bindSSHConnection");function so(t,e){return e.reduce(function(r,n){return delete r[n],r},Object.assign({},t))}i(so,"omit");function io(t){var e,r=[],n=0;return e=Za.createServer(function(s){var a;n++,s.on("error",e.emit.bind(e,"error")),s.on("close",function(){n--,n===0&&(t.keepAlive||setTimeout(function(){n===0&&e.close()},2))}),e.emit("netConnection",s,e),a=no(t,s),a.on("error",e.emit.bind(e,"error")),s.on("sshStream",function(o){o.on("error",function(){e.close()})}),r.push(a,s);try{a.connect(so(t,["localPort","localHost"]))}catch(o){e.emit("error",o)}}),e.on("close",function(){r.forEach(function(s){s.end()})}),e}i(io,"createServer");function ao(t,e){var r,n;e||(e=ro);try{n=eo(t),r=io(n),r.listen(n.localPort,n.localHost,function(s){e(s,r)})}catch(s){r=new to.EventEmitter,setImmediate(function(){e(s),r.emit("error",s)})}return r}i(ao,"tunnel");En.exports=ao});var pt=h(Tn=>{"use strict";Tn.parse=function(t,e){return new lt(t,e).parse()};var Re=class Re{constructor(e,r){this.source=e,this.transform=r||oo,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var r;(this.recorded.length>0||e)&&(r=this.recorded.join(""),r==="NULL"&&!e&&(r=null),r!==null&&(r=this.transform(r)),this.entries.push(r),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var r,n,s;for(this.consumeDimensions();!this.isEof();)if(r=this.nextCharacter(),r.value==="{"&&!s)this.dimension++,this.dimension>1&&(n=new Re(this.source.substr(this.position-1),this.transform),this.entries.push(n.parse(!0)),this.position+=n.position-2);else if(r.value==="}"&&!s){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else r.value==='"'&&!r.escaped?(s&&this.newEntry(!0),s=!s):r.value===","&&!s?this.newEntry():this.record(r.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};i(Re,"ArrayParser");var lt=Re;function oo(t){return t}i(oo,"identity")});var ht=h((kh,vn)=>{var co=pt();vn.exports={create:function(t,e){return{parse:function(){return co.parse(t,e)}}}}});var An=h((Bh,wn)=>{"use strict";var uo=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,lo=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,po=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,ho=/^-?infinity$/;wn.exports=i(function(e){if(ho.test(e))return Number(e.replace("i","I"));var r=uo.exec(e);if(!r)return fo(e)||null;var n=!!r[8],s=parseInt(r[1],10);n&&(s=bn(s));var a=parseInt(r[2],10)-1,o=r[3],c=parseInt(r[4],10),l=parseInt(r[5],10),u=parseInt(r[6],10),p=r[7];p=p?1e3*parseFloat(p):0;var f,m=mo(e);return m!=null?(f=new Date(Date.UTC(s,a,o,c,l,u,p)),ft(s)&&f.setUTCFullYear(s),m!==0&&f.setTime(f.getTime()-m)):(f=new Date(s,a,o,c,l,u,p),ft(s)&&f.setFullYear(s)),f},"parseDate");function fo(t){var e=lo.exec(t);if(e){var r=parseInt(e[1],10),n=!!e[4];n&&(r=bn(r));var s=parseInt(e[2],10)-1,a=e[3],o=new Date(r,s,a);return ft(r)&&o.setFullYear(r),o}}i(fo,"getDate");function mo(t){if(t.endsWith("+00"))return 0;var e=po.exec(t.split(" ")[1]);if(e){var r=e[1];if(r==="Z")return 0;var n=r==="-"?-1:1,s=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return s*n*1e3}}i(mo,"timeZoneOffset");function bn(t){return-(t-1)}i(bn,"bcYearToNegativeYear");function ft(t){return t>=0&&t<100}i(ft,"is0To99")});var On=h((Gh,Cn)=>{Cn.exports=yo;var _o=Object.prototype.hasOwnProperty;function yo(t){for(var e=1;e{"use strict";var go=On();In.exports=z;function z(t){if(!(this instanceof z))return new z(t);go(this,No(t))}i(z,"PostgresInterval");var Eo=["seconds","minutes","hours","days","months","years"];z.prototype.toPostgres=function(){var t=Eo.filter(this.hasOwnProperty,this);return this.milliseconds&&t.indexOf("seconds")<0&&t.push("seconds"),t.length===0?"0":t.map(function(e){var r=this[e]||0;return e==="seconds"&&this.milliseconds&&(r=(r+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),r+" "+e},this).join(" ")};var So={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},To=["years","months","days"],vo=["hours","minutes","seconds"];z.prototype.toISOString=z.prototype.toISO=function(){var t=To.map(r,this).join(""),e=vo.map(r,this).join("");return"P"+t+"T"+e;function r(n){var s=this[n]||0;return n==="seconds"&&this.milliseconds&&(s=(s+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),s+So[n]}};var dt="([+-]?\\d+)",bo=dt+"\\s+years?",wo=dt+"\\s+mons?",Ao=dt+"\\s+days?",Co="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",Oo=new RegExp([bo,wo,Ao,Co].map(function(t){return"("+t+")?"}).join("\\s*")),Rn={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},Ro=["hours","minutes","seconds","milliseconds"];function Io(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}i(Io,"parseMilliseconds");function No(t){if(!t)return{};var e=Oo.exec(t),r=e[8]==="-";return Object.keys(Rn).reduce(function(n,s){var a=Rn[s],o=e[a];return!o||(o=s==="milliseconds"?Io(o):parseInt(o,10),!o)||(r&&~Ro.indexOf(s)&&(o*=-1),n[s]=o),n},{})}i(No,"parse")});var Pn=h((jh,xn)=>{"use strict";xn.exports=i(function(e){if(/^\\x/.test(e))return new Buffer(e.substr(2),"hex");for(var r="",n=0;n{var he=pt(),fe=ht(),Ie=An(),Mn=Nn(),qn=Pn();function Ne(t){return i(function(r){return r===null?r:t(r)},"nullAllowed")}i(Ne,"allowNull");function Dn(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}i(Dn,"parseBool");function xo(t){return t?he.parse(t,Dn):null}i(xo,"parseBoolArray");function Po(t){return parseInt(t,10)}i(Po,"parseBaseTenInt");function mt(t){return t?he.parse(t,Ne(Po)):null}i(mt,"parseIntegerArray");function Lo(t){return t?he.parse(t,Ne(function(e){return Fn(e).trim()})):null}i(Lo,"parseBigIntegerArray");var Mo=i(function(t){if(!t)return null;var e=fe.create(t,function(r){return r!==null&&(r=Et(r)),r});return e.parse()},"parsePointArray"),_t=i(function(t){if(!t)return null;var e=fe.create(t,function(r){return r!==null&&(r=parseFloat(r)),r});return e.parse()},"parseFloatArray"),q=i(function(t){if(!t)return null;var e=fe.create(t);return e.parse()},"parseStringArray"),yt=i(function(t){if(!t)return null;var e=fe.create(t,function(r){return r!==null&&(r=Ie(r)),r});return e.parse()},"parseDateArray"),qo=i(function(t){if(!t)return null;var e=fe.create(t,function(r){return r!==null&&(r=Mn(r)),r});return e.parse()},"parseIntervalArray"),Do=i(function(t){return t?he.parse(t,Ne(qn)):null},"parseByteAArray"),gt=i(function(t){return parseInt(t,10)},"parseInteger"),Fn=i(function(t){var e=String(t);return/^\d+$/.test(e)?e:t},"parseBigInteger"),Ln=i(function(t){return t?he.parse(t,Ne(JSON.parse)):null},"parseJsonArray"),Et=i(function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},"parsePoint"),Fo=i(function(t){if(t[0]!=="<"&&t[1]!=="(")return null;for(var e="(",r="",n=!1,s=2;s{"use strict";var P=1e6;function Bo(t){var e=t.readInt32BE(0),r=t.readUInt32BE(4),n="";e<0&&(e=~e+(r===0),r=~r+1>>>0,n="-");var s="",a,o,c,l,u,p;{if(a=e%P,e=e/P>>>0,o=4294967296*a+r,r=o/P>>>0,c=""+(o-P*r),r===0&&e===0)return n+c+s;for(l="",u=6-c.length,p=0;p>>0,o=4294967296*a+r,r=o/P>>>0,c=""+(o-P*r),r===0&&e===0)return n+c+s;for(l="",u=6-c.length,p=0;p>>0,o=4294967296*a+r,r=o/P>>>0,c=""+(o-P*r),r===0&&e===0)return n+c+s;for(l="",u=6-c.length,p=0;p{var Uo=Gn(),T=i(function(t,e,r,n,s){r=r||0,n=n||!1,s=s||function(E,M,x){return E*Math.pow(2,x)+M};var a=r>>3,o=i(function(E){return n?~E&255:E},"inv"),c=255,l=8-r%8;e>r%8);var u=0;r%8+e>=8&&(u=s(0,o(t[a])&c,l));for(var p=e+r>>3,f=a+1;f0&&(u=s(u,o(t[p])>>8-m,m)),u},"parseBits"),Wn=i(function(t,e,r){var n=Math.pow(2,r-1)-1,s=T(t,1),a=T(t,r,1);if(a===0)return 0;var o=1,c=i(function(u,p,f){u===0&&(u=1);for(var m=1;m<=f;m++)o/=2,(p&1<0&&(u+=o);return u},"parsePrecisionBits"),l=T(t,e,r+1,!1,c);return a==Math.pow(2,r+1)-1?l===0?s===0?1/0:-1/0:NaN:(s===0?1:-1)*Math.pow(2,a-n)*l},"parseFloatFromBits"),Go=i(function(t){return T(t,1)==1?-1*(T(t,15,1,!0)+1):T(t,15,1)},"parseInt16"),Qn=i(function(t){return T(t,1)==1?-1*(T(t,31,1,!0)+1):T(t,31,1)},"parseInt32"),Qo=i(function(t){return Wn(t,23,8)},"parseFloat32"),Ho=i(function(t){return Wn(t,52,11)},"parseFloat64"),Wo=i(function(t){var e=T(t,16,32);if(e==49152)return NaN;for(var r=Math.pow(1e4,T(t,16,16)),n=0,s=[],a=T(t,16),o=0;o>3,(s+=p<<3)>>3),f;console.log("ERROR: ElementType not implemented: "+u)},"parseElement"),l=i(function(u,p){var f=[],m;if(u.length>1){var E=u.shift();for(m=0;m0},"parseBool"),Ko=i(function(t){t(20,Uo),t(21,Go),t(23,Qn),t(26,Qn),t(1700,Wo),t(700,Qo),t(701,Ho),t(16,Vo),t(1114,Hn.bind(null,!1)),t(1184,Hn.bind(null,!0)),t(1e3,de),t(1007,de),t(1016,de),t(1008,de),t(1009,de),t(25,jo)},"init");jn.exports={init:Ko}});var $n=h((Xh,Kn)=>{Kn.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var ye=h(_e=>{var $o=Bn(),zo=Vn(),Yo=ht(),Jo=$n();_e.getTypeParser=Zo;_e.setTypeParser=Xo;_e.arrayParser=Yo;_e.builtins=Jo;var me={text:{},binary:{}};function zn(t){return String(t)}i(zn,"noParse");function Zo(t,e){return e=e||"text",me[e]&&me[e][t]||zn}i(Zo,"getTypeParser");function Xo(t,e,r){typeof e=="function"&&(r=e,e="text"),me[e][t]=r}i(Xo,"setTypeParser");$o.init(function(t,e){me.text[t]=e});zo.init(function(t,e){me.binary[t]=e})});var ge=h((rf,St)=>{"use strict";St.exports={host:"localhost",user:process.platform==="win32"?process.env.USERNAME:process.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var Y=ye(),ec=Y.getTypeParser(20,"text"),tc=Y.getTypeParser(1016,"text");St.exports.__defineSetter__("parseInt8",function(t){Y.setTypeParser(20,"text",t?Y.getTypeParser(23,"text"):ec),Y.setTypeParser(1016,"text",t?Y.getTypeParser(1007,"text"):tc)})});var Ee=h((nf,Jn)=>{"use strict";var rc=ge();function nc(t){var e=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return'"'+e+'"'}i(nc,"escapeElement");function Yn(t){for(var e="{",r=0;r0&&(e=e+","),t[r]===null||typeof t[r]>"u")e=e+"NULL";else if(Array.isArray(t[r]))e=e+Yn(t[r]);else if(ArrayBuffer.isView(t[r])){var n=t[r];if(!(n instanceof Buffer)){var s=Buffer.from(n.buffer,n.byteOffset,n.byteLength);s.length===n.byteLength?n=s:n=s.slice(n.byteOffset,n.byteOffset+n.byteLength)}e+="\\\\x"+n.toString("hex")}else e+=nc(xe(t[r]));return e=e+"}",e}i(Yn,"arrayString");var xe=i(function(t,e){if(t==null)return null;if(t instanceof Buffer)return t;if(ArrayBuffer.isView(t)){var r=Buffer.from(t.buffer,t.byteOffset,t.byteLength);return r.length===t.byteLength?r:r.slice(t.byteOffset,t.byteOffset+t.byteLength)}return t instanceof Date?rc.parseInputDatesAsUTC?ac(t):ic(t):Array.isArray(t)?Yn(t):typeof t=="object"?sc(t,e):t.toString()},"prepareValue");function sc(t,e){if(t&&typeof t.toPostgres=="function"){if(e=e||[],e.indexOf(t)!==-1)throw new Error('circular reference detected while preparing "'+t+'" for query');return e.push(t),xe(t.toPostgres(xe),e)}return JSON.stringify(t)}i(sc,"prepareObject");function R(t,e){for(t=""+t;t.length{"use strict";var Se=require("crypto");function Tt(t){return Se.createHash("md5").update(t,"utf-8").digest("hex")}i(Tt,"md5");function lc(t,e,r){var n=Tt(e+t),s=Tt(Buffer.concat([Buffer.from(n),r]));return"md5"+s}i(lc,"postgresMd5PasswordHash");function pc(t){return Se.createHash("sha256").update(t).digest()}i(pc,"sha256");function hc(t,e){return Se.createHmac("sha256",t).update(e).digest()}i(hc,"hmacSha256");async function fc(t,e,r){return Se.pbkdf2Sync(t,e,r,32,"sha256")}i(fc,"deriveKey");Zn.exports={postgresMd5PasswordHash:lc,randomBytes:Se.randomBytes,deriveKey:fc,sha256:pc,hmacSha256:hc,md5:Tt}});var ns=h((cf,rs)=>{var es=require("crypto");rs.exports={postgresMd5PasswordHash:mc,randomBytes:dc,deriveKey:gc,sha256:_c,hmacSha256:yc,md5:vt};var ts=es.webcrypto||globalThis.crypto,J=ts.subtle,bt=new TextEncoder;function dc(t){return ts.getRandomValues(Buffer.alloc(t))}i(dc,"randomBytes");async function vt(t){try{return es.createHash("md5").update(t,"utf-8").digest("hex")}catch{let r=typeof t=="string"?bt.encode(t):t,n=await J.digest("MD5",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}}i(vt,"md5");async function mc(t,e,r){var n=await vt(e+t),s=await vt(Buffer.concat([Buffer.from(n),r]));return"md5"+s}i(mc,"postgresMd5PasswordHash");async function _c(t){return await J.digest("SHA-256",t)}i(_c,"sha256");async function yc(t,e){let r=await J.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await J.sign("HMAC",r,bt.encode(e))}i(yc,"hmacSha256");async function gc(t,e,r){let n=await J.importKey("raw",bt.encode(t),"PBKDF2",!1,["deriveBits"]),s={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:r};return await J.deriveBits(s,n,32*8,["deriveBits"])}i(gc,"deriveKey")});var At=h((lf,wt)=>{"use strict";var Ec=parseInt(process.versions&&process.versions.node&&process.versions.node.split(".")[0])<15;Ec?wt.exports=Xn():wt.exports=ns()});var os=h((pf,as)=>{"use strict";var H=At();function Sc(t){if(t.indexOf("SCRAM-SHA-256")===-1)throw new Error("SASL: Only mechanism SCRAM-SHA-256 is currently supported");let e=H.randomBytes(18).toString("base64");return{mechanism:"SCRAM-SHA-256",clientNonce:e,response:"n,,n=*,r="+e,message:"SASLInitialResponse"}}i(Sc,"startSession");async function Tc(t,e,r){if(t.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof r!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let n=wc(r);if(n.nonce.startsWith(t.clientNonce)){if(n.nonce.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var s="n=*,r="+t.clientNonce,a="r="+n.nonce+",s="+n.salt+",i="+n.iteration,o="c=biws,r="+n.nonce,c=s+","+a+","+o,l=Buffer.from(n.salt,"base64"),u=await H.deriveKey(e,l,n.iteration),p=await H.hmacSha256(u,"Client Key"),f=await H.sha256(p),m=await H.hmacSha256(f,c),E=Cc(Buffer.from(p),Buffer.from(m)).toString("base64"),M=await H.hmacSha256(u,"Server Key"),x=await H.hmacSha256(M,c);t.message="SASLResponse",t.serverSignature=Buffer.from(x).toString("base64"),t.response=o+",p="+E}i(Tc,"continueSession");function vc(t,e){if(t.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:r}=Ac(e);if(r!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}i(vc,"finalizeSession");function bc(t){if(typeof t!="string")throw new TypeError("SASL: text must be a string");return t.split("").map((e,r)=>t.charCodeAt(r)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}i(bc,"isPrintableChars");function ss(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}i(ss,"isBase64");function is(t){if(typeof t!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(t.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let r=e[0],n=e.substring(2);return[r,n]}))}i(is,"parseAttributePairs");function wc(t){let e=is(t),r=e.get("r");if(r){if(!bc(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let n=e.get("s");if(n){if(!ss(n))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let s=e.get("i");if(s){if(!/^[1-9][0-9]*$/.test(s))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let a=parseInt(s,10);return{nonce:r,salt:n,iteration:a}}i(wc,"parseServerFirstMessage");function Ac(t){let r=is(t).get("v");if(r){if(!ss(r))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:r}}i(Ac,"parseServerFinalMessage");function Cc(t,e){if(!Buffer.isBuffer(t))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(t.length!==e.length)throw new Error("Buffer lengths must match");if(t.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(t.map((r,n)=>t[n]^e[n]))}i(Cc,"xorBuffers");as.exports={startSession:Sc,continueSession:Tc,finalizeSession:vc}});var Ct=h((ff,cs)=>{"use strict";var Oc=ye();function Pe(t){this._types=t||Oc,this.text={},this.binary={}}i(Pe,"TypeOverrides");Pe.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};Pe.prototype.setTypeParser=function(t,e,r){typeof e=="function"&&(r=e,e="text"),this.getOverrides(e)[t]=r};Pe.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};cs.exports=Pe});var ls=h((mf,us)=>{"use strict";function Ot(t){if(t.charAt(0)==="/"){let c=t.split(" ");return{host:c[0],database:c[1]}}let e={},r,n=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(t)&&(t=encodeURI(t).replace(/\%25(\d\d)/g,"%$1"));try{r=new URL(t,"postgres://base")}catch{r=new URL(t.replace("@/","@___DUMMY___/"),"postgres://base"),n=!0}for(let c of r.searchParams.entries())e[c[0]]=c[1];if(e.user=e.user||decodeURIComponent(r.username),e.password=e.password||decodeURIComponent(r.password),r.protocol=="socket:")return e.host=decodeURI(r.pathname),e.database=r.searchParams.get("db"),e.client_encoding=r.searchParams.get("encoding"),e;let s=n?"":r.hostname;e.host?s&&/^%2f/i.test(s)&&(r.pathname=s+r.pathname):e.host=decodeURIComponent(s),e.port||(e.port=r.port);let a=r.pathname.slice(1)||null;e.database=a?decodeURI(a):null,(e.ssl==="true"||e.ssl==="1")&&(e.ssl=!0),e.ssl==="0"&&(e.ssl=!1),(e.sslcert||e.sslkey||e.sslrootcert||e.sslmode)&&(e.ssl={});let o=e.sslcert||e.sslkey||e.sslrootcert?require("fs"):null;switch(e.sslcert&&(e.ssl.cert=o.readFileSync(e.sslcert).toString()),e.sslkey&&(e.ssl.key=o.readFileSync(e.sslkey).toString()),e.sslrootcert&&(e.ssl.ca=o.readFileSync(e.sslrootcert).toString()),e.sslmode){case"disable":{e.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{e.ssl.rejectUnauthorized=!1;break}}return e}i(Ot,"parse");us.exports=Ot;Ot.parse=Ot});var Nt=h((yf,fs)=>{"use strict";var Rc=require("dns"),hs=ge(),ps=ls().parse,N=i(function(t,e,r){return r===void 0?r=process.env["PG"+t.toUpperCase()]:r===!1||(r=process.env[r]),e[t]||r||hs[t]},"val"),Ic=i(function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return hs.ssl},"readSSLConfigFromEnvironment"),Z=i(function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},"quoteParamValue"),D=i(function(t,e,r){var n=e[r];n!=null&&t.push(r+"="+Z(n))},"add"),It=class It{constructor(e){e=typeof e=="string"?ps(e):e||{},e.connectionString&&(e=Object.assign({},e,ps(e.connectionString))),this.user=N("user",e),this.database=N("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(N("port",e),10),this.host=N("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:N("password",e)}),this.binary=N("binary",e),this.options=N("options",e),this.ssl=typeof e.ssl>"u"?Ic():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=N("client_encoding",e),this.replication=N("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=N("application_name",e,"PGAPPNAME"),this.fallback_application_name=N("fallback_application_name",e,!1),this.statement_timeout=N("statement_timeout",e,!1),this.lock_timeout=N("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=N("idle_in_transaction_session_timeout",e,!1),this.query_timeout=N("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){var r=[];D(r,this,"user"),D(r,this,"password"),D(r,this,"port"),D(r,this,"application_name"),D(r,this,"fallback_application_name"),D(r,this,"connect_timeout"),D(r,this,"options");var n=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(D(r,n,"sslmode"),D(r,n,"sslca"),D(r,n,"sslkey"),D(r,n,"sslcert"),D(r,n,"sslrootcert"),this.database&&r.push("dbname="+Z(this.database)),this.replication&&r.push("replication="+Z(this.replication)),this.host&&r.push("host="+Z(this.host)),this.isDomainSocket)return e(null,r.join(" "));this.client_encoding&&r.push("client_encoding="+Z(this.client_encoding)),Rc.lookup(this.host,function(s,a){return s?e(s,null):(r.push("hostaddr="+Z(a)),e(null,r.join(" ")))})}};i(It,"ConnectionParameters");var Rt=It;fs.exports=Rt});var _s=h((Ef,ms)=>{"use strict";var Nc=ye(),ds=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,Pt=class Pt{constructor(e,r){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=r,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){var r;e.text?r=ds.exec(e.text):r=ds.exec(e.command),r&&(this.command=r[1],r[3]?(this.oid=parseInt(r[2],10),this.rowCount=parseInt(r[3],10)):r[2]&&(this.rowCount=parseInt(r[2],10)))}_parseRowAsArray(e){for(var r=new Array(e.length),n=0,s=e.length;n{"use strict";var{EventEmitter:xc}=require("events"),ys=_s(),gs=Ee(),Mt=class Mt extends xc{constructor(e,r,n){super(),e=gs.normalizeQueryConfig(e,r,n),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new ys(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new ys(this._rowMode,this.types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let r;if(!this._canceledDueToError){try{r=this._result.parseRow(e.fields)}catch(n){this._canceledDueToError=n;return}this.emit("row",r,this._result),this._accumulateRows&&this._result.addRow(r)}}handleCommandComplete(e,r){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&r.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,r){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(r){process.nextTick(()=>{throw r})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let r=e.parsedStatements[this.name];return this.text&&r&&this.text!==r?new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`):this.values&&!Array.isArray(this.values)?new Error("Query values must be an array"):(this.requiresPreparation()?this.prepare(e):e.query(this.text),null)}hasBeenParsed(e){return this.name&&e.parsedStatements[this.name]}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,r){e.execute({portal:this.portal,rows:r}),r?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||e.parse({text:this.text,name:this.name,types:this.types});try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:gs.prepareValue})}catch(r){this.handleError(r,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,r){}};i(Mt,"Query");var Lt=Mt;Es.exports=Lt});var ur=h(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.NoticeMessage=d.DataRowMessage=d.CommandCompleteMessage=d.ReadyForQueryMessage=d.NotificationResponseMessage=d.BackendKeyDataMessage=d.AuthenticationMD5Password=d.ParameterStatusMessage=d.ParameterDescriptionMessage=d.RowDescriptionMessage=d.Field=d.CopyResponse=d.CopyDataMessage=d.DatabaseError=d.copyDone=d.emptyQuery=d.replicationStart=d.portalSuspended=d.noData=d.closeComplete=d.bindComplete=d.parseComplete=void 0;d.parseComplete={name:"parseComplete",length:5};d.bindComplete={name:"bindComplete",length:5};d.closeComplete={name:"closeComplete",length:5};d.noData={name:"noData",length:5};d.portalSuspended={name:"portalSuspended",length:5};d.replicationStart={name:"replicationStart",length:4};d.emptyQuery={name:"emptyQuery",length:4};d.copyDone={name:"copyDone",length:4};var zt=class zt extends Error{constructor(e,r,n){super(e),this.length=r,this.name=n}};i(zt,"DatabaseError");var qt=zt;d.DatabaseError=qt;var Yt=class Yt{constructor(e,r){this.length=e,this.chunk=r,this.name="copyData"}};i(Yt,"CopyDataMessage");var Dt=Yt;d.CopyDataMessage=Dt;var Jt=class Jt{constructor(e,r,n,s){this.length=e,this.name=r,this.binary=n,this.columnTypes=new Array(s)}};i(Jt,"CopyResponse");var Ft=Jt;d.CopyResponse=Ft;var Zt=class Zt{constructor(e,r,n,s,a,o,c){this.name=e,this.tableID=r,this.columnID=n,this.dataTypeID=s,this.dataTypeSize=a,this.dataTypeModifier=o,this.format=c}};i(Zt,"Field");var kt=Zt;d.Field=kt;var Xt=class Xt{constructor(e,r){this.length=e,this.fieldCount=r,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};i(Xt,"RowDescriptionMessage");var Bt=Xt;d.RowDescriptionMessage=Bt;var er=class er{constructor(e,r){this.length=e,this.parameterCount=r,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};i(er,"ParameterDescriptionMessage");var Ut=er;d.ParameterDescriptionMessage=Ut;var tr=class tr{constructor(e,r,n){this.length=e,this.parameterName=r,this.parameterValue=n,this.name="parameterStatus"}};i(tr,"ParameterStatusMessage");var Gt=tr;d.ParameterStatusMessage=Gt;var rr=class rr{constructor(e,r){this.length=e,this.salt=r,this.name="authenticationMD5Password"}};i(rr,"AuthenticationMD5Password");var Qt=rr;d.AuthenticationMD5Password=Qt;var nr=class nr{constructor(e,r,n){this.length=e,this.processID=r,this.secretKey=n,this.name="backendKeyData"}};i(nr,"BackendKeyDataMessage");var Ht=nr;d.BackendKeyDataMessage=Ht;var sr=class sr{constructor(e,r,n,s){this.length=e,this.processId=r,this.channel=n,this.payload=s,this.name="notification"}};i(sr,"NotificationResponseMessage");var Wt=sr;d.NotificationResponseMessage=Wt;var ir=class ir{constructor(e,r){this.length=e,this.status=r,this.name="readyForQuery"}};i(ir,"ReadyForQueryMessage");var jt=ir;d.ReadyForQueryMessage=jt;var ar=class ar{constructor(e,r){this.length=e,this.text=r,this.name="commandComplete"}};i(ar,"CommandCompleteMessage");var Vt=ar;d.CommandCompleteMessage=Vt;var or=class or{constructor(e,r){this.length=e,this.fields=r,this.name="dataRow",this.fieldCount=r.length}};i(or,"DataRowMessage");var Kt=or;d.DataRowMessage=Kt;var cr=class cr{constructor(e,r){this.length=e,this.message=r,this.name="notice"}};i(cr,"NoticeMessage");var $t=cr;d.NoticeMessage=$t});var Ts=h(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.Writer=void 0;var pr=class pr{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){var r=this.buffer.length-this.offset;if(r>1)+e;this.buffer=Buffer.allocUnsafe(s),n.copy(this.buffer)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{var r=Buffer.byteLength(e);this.ensure(r+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=r}return this.buffer[this.offset++]=0,this}addString(e=""){var r=Buffer.byteLength(e);return this.ensure(r),this.buffer.write(e,this.offset),this.offset+=r,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let r=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(r,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){var r=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),r}};i(pr,"Writer");var lr=pr;Le.Writer=lr});var bs=h(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.serialize=void 0;var hr=Ts(),v=new hr.Writer,Pc=i(t=>{v.addInt16(3).addInt16(0);for(let n of Object.keys(t))v.addCString(n).addCString(t[n]);v.addCString("client_encoding").addCString("UTF8");var e=v.addCString("").flush(),r=e.length+4;return new hr.Writer().addInt32(r).add(e).flush()},"startup"),Lc=i(()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},"requestSsl"),Mc=i(t=>v.addCString(t).flush(112),"password"),qc=i(function(t,e){return v.addCString(t).addInt32(Buffer.byteLength(e)).addString(e),v.flush(112)},"sendSASLInitialResponseMessage"),Dc=i(function(t){return v.addString(t).flush(112)},"sendSCRAMClientFinalMessage"),Fc=i(t=>v.addCString(t).flush(81),"query"),vs=[],kc=i(t=>{let e=t.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let r=t.types||vs;for(var n=r.length,s=v.addCString(e).addCString(t.text).addInt16(n),a=0;a{let e=t.portal||"",r=t.statement||"",n=t.binary||!1,s=t.values||vs,a=s.length;return v.addCString(e).addCString(r),v.addInt16(a),Bc(s,t.valueMapper),v.addInt16(a),v.add(X.flush()),v.addInt16(n?1:0),v.flush(66)},"bind"),Gc=Buffer.from([69,0,0,0,9,0,0,0,0,0]),Qc=i(t=>{if(!t||!t.portal&&!t.rows)return Gc;let e=t.portal||"",r=t.rows||0,n=Buffer.byteLength(e),s=4+n+1+4,a=Buffer.allocUnsafe(1+s);return a[0]=69,a.writeInt32BE(s,1),a.write(e,5,"utf-8"),a[n+5]=0,a.writeUInt32BE(r,a.length-4),a},"execute"),Hc=i((t,e)=>{let r=Buffer.allocUnsafe(16);return r.writeInt32BE(16,0),r.writeInt16BE(1234,4),r.writeInt16BE(5678,6),r.writeInt32BE(t,8),r.writeInt32BE(e,12),r},"cancel"),fr=i((t,e)=>{let n=4+Buffer.byteLength(e)+1,s=Buffer.allocUnsafe(1+n);return s[0]=t,s.writeInt32BE(n,1),s.write(e,5,"utf-8"),s[n]=0,s},"cstringMessage"),Wc=v.addCString("P").flush(68),jc=v.addCString("S").flush(68),Vc=i(t=>t.name?fr(68,`${t.type}${t.name||""}`):t.type==="P"?Wc:jc,"describe"),Kc=i(t=>{let e=`${t.type}${t.name||""}`;return fr(67,e)},"close"),$c=i(t=>v.add(t).flush(100),"copyData"),zc=i(t=>fr(102,t),"copyFail"),Me=i(t=>Buffer.from([t,0,0,0,4]),"codeOnlyBuffer"),Yc=Me(72),Jc=Me(83),Zc=Me(88),Xc=Me(99),eu={startup:Pc,password:Mc,requestSsl:Lc,sendSASLInitialResponseMessage:qc,sendSCRAMClientFinalMessage:Dc,query:Fc,parse:kc,bind:Uc,execute:Qc,describe:Vc,close:Kc,flush:()=>Yc,sync:()=>Jc,end:()=>Zc,copyData:$c,copyDone:()=>Xc,copyFail:zc,cancel:Hc};qe.serialize=eu});var ws=h(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.BufferReader=void 0;var tu=Buffer.allocUnsafe(0),mr=class mr{constructor(e=0){this.offset=e,this.buffer=tu,this.encoding="utf-8"}setBuffer(e,r){this.offset=e,this.buffer=r}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}string(e){let r=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,r}cstring(){let e=this.offset,r=e;for(;this.buffer[r++]!==0;);return this.offset=r,this.buffer.toString(this.encoding,e,r-1)}bytes(e){let r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}};i(mr,"BufferReader");var dr=mr;De.BufferReader=dr});var Os=h(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.Parser=void 0;var b=ur(),ru=ws(),_r=1,nu=4,As=_r+nu,Cs=Buffer.allocUnsafe(0),gr=class gr{constructor(e){if(this.buffer=Cs,this.bufferLength=0,this.bufferOffset=0,this.reader=new ru.BufferReader,(e==null?void 0:e.mode)==="binary")throw new Error("Binary mode not supported yet");this.mode=(e==null?void 0:e.mode)||"text"}parse(e,r){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,s=this.bufferOffset;for(;s+As<=n;){let a=this.buffer[s],o=this.buffer.readUInt32BE(s+_r),c=_r+o;if(c+s<=n){let l=this.handlePacket(s+As,a,o,this.buffer);r(l),s+=c}else break}s===n?(this.buffer=Cs,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=n-s,this.bufferOffset=s)}mergeBuffer(e){if(this.bufferLength>0){let r=this.bufferLength+e.byteLength;if(r+this.bufferOffset>this.buffer.byteLength){let s;if(r<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)s=this.buffer;else{let a=this.buffer.byteLength*2;for(;r>=a;)a*=2;s=Buffer.allocUnsafe(a)}this.buffer.copy(s,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=s,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=r}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,r,n,s){switch(r){case 50:return b.bindComplete;case 49:return b.parseComplete;case 51:return b.closeComplete;case 110:return b.noData;case 115:return b.portalSuspended;case 99:return b.copyDone;case 87:return b.replicationStart;case 73:return b.emptyQuery;case 68:return this.parseDataRowMessage(e,n,s);case 67:return this.parseCommandCompleteMessage(e,n,s);case 90:return this.parseReadyForQueryMessage(e,n,s);case 65:return this.parseNotificationMessage(e,n,s);case 82:return this.parseAuthenticationResponse(e,n,s);case 83:return this.parseParameterStatusMessage(e,n,s);case 75:return this.parseBackendKeyData(e,n,s);case 69:return this.parseErrorMessage(e,n,s,"error");case 78:return this.parseErrorMessage(e,n,s,"notice");case 84:return this.parseRowDescriptionMessage(e,n,s);case 116:return this.parseParameterDescriptionMessage(e,n,s);case 71:return this.parseCopyInMessage(e,n,s);case 72:return this.parseCopyOutMessage(e,n,s);case 100:return this.parseCopyData(e,n,s);default:return new b.DatabaseError("received invalid response: "+r.toString(16),n,"error")}}parseReadyForQueryMessage(e,r,n){this.reader.setBuffer(e,n);let s=this.reader.string(1);return new b.ReadyForQueryMessage(r,s)}parseCommandCompleteMessage(e,r,n){this.reader.setBuffer(e,n);let s=this.reader.cstring();return new b.CommandCompleteMessage(r,s)}parseCopyData(e,r,n){let s=n.slice(e,e+(r-4));return new b.CopyDataMessage(r,s)}parseCopyInMessage(e,r,n){return this.parseCopyMessage(e,r,n,"copyInResponse")}parseCopyOutMessage(e,r,n){return this.parseCopyMessage(e,r,n,"copyOutResponse")}parseCopyMessage(e,r,n,s){this.reader.setBuffer(e,n);let a=this.reader.byte()!==0,o=this.reader.int16(),c=new b.CopyResponse(r,s,a,o);for(let l=0;l{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.DatabaseError=G.serialize=G.parse=void 0;var su=ur();Object.defineProperty(G,"DatabaseError",{enumerable:!0,get:function(){return su.DatabaseError}});var iu=bs();Object.defineProperty(G,"serialize",{enumerable:!0,get:function(){return iu.serialize}});var au=Os();function ou(t,e){let r=new au.Parser;return t.on("data",n=>r.parse(n,e)),new Promise(n=>t.on("end",()=>n()))}i(ou,"parse");G.parse=ou});var Rs={};Zi(Rs,{default:()=>cu});var cu,Is=Ji(()=>{cu={}});var Ns=h((qf,Sr)=>{Sr.exports.getStream=i(function(e){let r=require("net");if(typeof r.Socket=="function")return new r.Socket;{let{CloudflareSocket:n}=(Is(),ea(Rs));return new n(e)}},"getStream");Sr.exports.getSecureStream=i(function(e){var r=require("tls");return r.connect?r.connect(e):(e.socket.startTls(e),e.socket)},"getSecureStream")});var br=h((kf,xs)=>{"use strict";var Ff=require("net"),uu=require("events").EventEmitter,{parse:lu,serialize:O}=Er(),{getStream:pu,getSecureStream:hu}=Ns(),fu=O.flush(),du=O.sync(),mu=O.end(),vr=class vr extends uu{constructor(e){super(),e=e||{},this.stream=e.stream||pu(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=e.ssl||!1,this._ending=!1,this._emitMessage=!1;var r=this;this.on("newListener",function(n){n==="message"&&(r._emitMessage=!0)})}connect(e,r){var n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,r),this.stream.once("connect",function(){n._keepAlive&&n.stream.setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit("connect")});let s=i(function(a){n._ending&&(a.code==="ECONNRESET"||a.code==="EPIPE")||n.emit("error",a)},"reportStreamError");if(this.stream.on("error",s),this.stream.on("close",function(){n.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(a){var o=a.toString("utf8");switch(o){case"S":break;case"N":return n.stream.end(),n.emit("error",new Error("The server does not support SSL connections"));default:return n.stream.end(),n.emit("error",new Error("There was an error establishing an SSL connection"))}let c={socket:n.stream};n.ssl!==!0&&(Object.assign(c,n.ssl),"key"in n.ssl&&(c.key=n.ssl.key));var l=require("net");l.isIP&&l.isIP(r)===0&&(c.servername=r);try{n.stream=hu(c)}catch(u){return n.emit("error",u)}n.attachListeners(n.stream),n.stream.on("error",s),n.emit("sslconnect")})}attachListeners(e){lu(e,r=>{var n=r.name==="error"?"errorMessage":r.name;this._emitMessage&&this.emit("message",r),this.emit(n,r)})}requestSsl(){this.stream.write(O.requestSsl())}startup(e){this.stream.write(O.startup(e))}cancel(e,r){this._send(O.cancel(e,r))}password(e){this._send(O.password(e))}sendSASLInitialResponseMessage(e,r){this._send(O.sendSASLInitialResponseMessage(e,r))}sendSCRAMClientFinalMessage(e){this._send(O.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(O.query(e))}parse(e){this._send(O.parse(e))}bind(e){this._send(O.bind(e))}execute(e){this._send(O.execute(e))}flush(){this.stream.writable&&this.stream.write(fu)}sync(){this._ending=!0,this._send(du)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(mu,()=>{this.stream.end()})}close(e){this._send(O.close(e))}describe(e){this._send(O.describe(e))}sendCopyFromChunk(e){this._send(O.copyData(e))}endCopyFrom(){this._send(O.copyDone())}sendCopyFail(e){this._send(O.copyFail(e))}};i(vr,"Connection");var Tr=vr;xs.exports=Tr});var qs=h((Uf,Ms)=>{"use strict";var{Transform:_u}=require("stream"),{StringDecoder:yu}=require("string_decoder"),Q=Symbol("last"),ke=Symbol("decoder");function gu(t,e,r){let n;if(this.overflow){if(n=this[ke].write(t).split(this.matcher),n.length===1)return r();n.shift(),this.overflow=!1}else this[Q]+=this[ke].write(t),n=this[Q].split(this.matcher);this[Q]=n.pop();for(let s=0;sthis.maxLength,this.overflow&&!this.skipOverflow){r(new Error("maximum buffer reached"));return}r()}i(gu,"transform");function Eu(t){if(this[Q]+=this[ke].end(),this[Q])try{Ls(this,this.mapper(this[Q]))}catch(e){return t(e)}t()}i(Eu,"flush");function Ls(t,e){e!==void 0&&t.push(e)}i(Ls,"push");function Ps(t){return t}i(Ps,"noop");function Su(t,e,r){switch(t=t||/\r?\n/,e=e||Ps,r=r||{},arguments.length){case 1:typeof t=="function"?(e=t,t=/\r?\n/):typeof t=="object"&&!(t instanceof RegExp)&&!t[Symbol.split]&&(r=t,t=/\r?\n/);break;case 2:typeof t=="function"?(r=e,e=t,t=/\r?\n/):typeof e=="object"&&(r=e,e=Ps)}r=Object.assign({},r),r.autoDestroy=!0,r.transform=gu,r.flush=Eu,r.readableObjectMode=!0;let n=new _u(r);return n[Q]="",n[ke]=new yu("utf8"),n.matcher=t,n.mapper=e,n.maxLength=r.maxLength,n.skipOverflow=r.skipOverflow||!1,n.overflow=!1,n._destroy=function(s,a){this._writableState.errorEmitted=!1,a(s)},n}i(Su,"split");Ms.exports=Su});var ks=h((Qf,B)=>{"use strict";var Ds=require("path"),Tu=require("stream").Stream,vu=qs(),Fs=require("util"),bu=5432,Be=process.platform==="win32",Te=process.stderr,wu=56,Au=7,Cu=61440,Ou=32768;function Ru(t){return(t&Cu)==Ou}i(Ru,"isRegFile");var ee=["host","port","database","user","password"],wr=ee.length,Iu=ee[wr-1];function Ar(){var t=Te instanceof Tu&&Te.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(` +`);Te.write(Fs.format.apply(Fs,e))}}i(Ar,"warn");Object.defineProperty(B.exports,"isWin",{get:function(){return Be},set:function(t){Be=t}});B.exports.warnTo=function(t){var e=Te;return Te=t,e};B.exports.getFileName=function(t){var e=t||process.env,r=e.PGPASSFILE||(Be?Ds.join(e.APPDATA||"./","postgresql","pgpass.conf"):Ds.join(e.HOME||"./",".pgpass"));return r};B.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Be?!0:(e=e||"",Ru(t.mode)?t.mode&(wu|Au)?(Ar('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(Ar('WARNING: password file "%s" is not a plain file',e),!1))};var Nu=B.exports.match=function(t,e){return ee.slice(0,-1).reduce(function(r,n,s){return s==1&&Number(t[n]||bu)===Number(e[n])?r&&!0:r&&(e[n]==="*"||e[n]===t[n])},!0)};B.exports.getPassword=function(t,e,r){var n,s=e.pipe(vu());function a(l){var u=xu(l);u&&Pu(u)&&Nu(t,u)&&(n=u[Iu],s.end())}i(a,"onLine");var o=i(function(){e.destroy(),r(n)},"onEnd"),c=i(function(l){e.destroy(),Ar("WARNING: error on reading file: %s",l),r(void 0)},"onErr");e.on("error",c),s.on("data",a).on("end",o).on("error",c)};var xu=B.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",r="",n=0,s=0,a=0,o={},c=!1,l=i(function(p,f,m){var E=t.substring(f,m);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(E=E.replace(/\\([:\\])/g,"$1")),o[ee[p]]=E},"addToObj"),u=0;u=0&&e==":"&&r!=="\\"&&(l(n,s,u+1),s=u+2,n+=1)}return o=Object.keys(o).length===wr?o:null,o},Pu=B.exports.isValidEntry=function(t){for(var e={0:function(o){return o.length>0},1:function(o){return o==="*"?!0:(o=Number(o),isFinite(o)&&o>0&&o<9007199254740992&&Math.floor(o)===o)},2:function(o){return o.length>0},3:function(o){return o.length>0},4:function(o){return o.length>0}},r=0;r{"use strict";var Wf=require("path"),Bs=require("fs"),Ue=ks();Cr.exports=function(t,e){var r=Ue.getFileName();Bs.stat(r,function(n,s){if(n||!Ue.usePgPass(s,r))return e(void 0);var a=Bs.createReadStream(r);Ue.getPassword(t,a,e)})};Cr.exports.warnTo=Ue.warnTo});var Ws=h((Vf,Hs)=>{"use strict";var Lu=require("events").EventEmitter,Gs=Ee(),Or=os(),Mu=Ct(),qu=Nt(),Qs=Ss(),Du=ge(),Fu=br(),ku=At(),Rr=class Rr extends Lu{constructor(e){super(),this.connectionParameters=new qu(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var r=e||{};this._Promise=r.Promise||global.Promise,this._types=new Mu(r.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=r.connection||new Fu({stream:r.stream,ssl:this.connectionParameters.ssl,keepAlive:r.keepAlive||!1,keepAliveInitialDelayMillis:r.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=r.binary||Du.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=r.connectionTimeoutMillis||0}_errorAllQueries(e){let r=i(n=>{process.nextTick(()=>{n.handleError(e,this.connection)})},"enqueueError");this.activeQuery&&(r(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(r),this.queryQueue.length=0}_connect(e){var r=this,n=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let s=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(s)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{n._ending=!0,n.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){r.ssl?n.requestSsl():n.startup(r.getStartupConf())}),n.on("sslconnect",function(){n.startup(r.getStartupConf())}),this._attachListeners(n),n.once("end",()=>{let s=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(s),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(s):this._handleErrorEvent(s):this._connectionError||this._handleErrorEvent(s)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((r,n)=>{this._connect(s=>{s?n(s):r()})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_checkPgPass(e){let r=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password()).then(n=>{if(n!==void 0){if(typeof n!="string"){r.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(n=>{r.emit("error",n)});else if(this.password!==null)e();else try{Us()(this.connectionParameters,s=>{s!==void 0&&(this.connectionParameters.password=this.password=s),e()})}catch(n){this.emit("error",n)}}_handleAuthCleartextPassword(e){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._checkPgPass(async()=>{try{let r=await ku.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(r)}catch(r){this.emit("error",r)}})}_handleAuthSASL(e){this._checkPgPass(()=>{try{this.saslSession=Or.startSession(e.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(r){this.connection.emit("error",r)}})}async _handleAuthSASLContinue(e){try{await Or.continueSession(this.saslSession,this.password,e.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(r){this.connection.emit("error",r)}}_handleAuthSASLFinal(e){try{Or.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(r){this.connection.emit("error",r)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:r}=this;this.activeQuery=null,this.readyForQuery=!0,r&&r.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let r=this.activeQuery;if(!r){this._handleErrorEvent(e);return}this.activeQuery=null,r.handleError(e,this.connection)}_handleRowDescription(e){this.activeQuery.handleRowDescription(e)}_handleDataRow(e){this.activeQuery.handleDataRow(e)}_handlePortalSuspended(e){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(e){this.activeQuery.handleCommandComplete(e,this.connection)}_handleParseComplete(e){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(e){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(e){this.activeQuery.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){var e=this.connectionParameters,r={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(r.application_name=n),e.replication&&(r.replication=""+e.replication),e.statement_timeout&&(r.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(r.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(r.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(r.options=e.options),r}cancel(e,r){if(e.activeQuery===r){var n=this.connection;this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){n.cancel(e.processID,e.secretKey)})}else e.queryQueue.indexOf(r)!==-1&&e.queryQueue.splice(e.queryQueue.indexOf(r),1)}setTypeParser(e,r,n){return this._types.setTypeParser(e,r,n)}getTypeParser(e,r){return this._types.getTypeParser(e,r)}escapeIdentifier(e){return Gs.escapeIdentifier(e)}escapeLiteral(e){return Gs.escapeLiteral(e)}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let e=this.activeQuery.submit(this.connection);e&&process.nextTick(()=>{this.activeQuery.handleError(e,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(e,r,n){var s,a,o,c,l;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,a=s=e,typeof r=="function"&&(s.callback=s.callback||r)):(o=this.connectionParameters.query_timeout,s=new Qs(e,r,n),s.callback||(a=new this._Promise((u,p)=>{s.callback=(f,m)=>f?p(f):u(m)}).catch(u=>{throw Error.captureStackTrace(u),u}))),o&&(l=s.callback,c=setTimeout(()=>{var u=new Error("Query read timeout");process.nextTick(()=>{s.handleError(u,this.connection)}),l(u),s.callback=()=>{};var p=this.queryQueue.indexOf(s);p>-1&&this.queryQueue.splice(p,1),this._pulseQueryQueue()},o),s.callback=(u,p)=>{clearTimeout(c),l(u,p)}),this.binary&&!s.binary&&(s.binary=!0),s._result&&!s._result._types&&(s._result._types=this._types),this._queryable?this._ending?(process.nextTick(()=>{s.handleError(new Error("Client was closed and is not queryable"),this.connection)}),a):(this.queryQueue.push(s),this._pulseQueryQueue(),a):(process.nextTick(()=>{s.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),a)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e)e();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),e)this.connection.once("end",e);else return new this._Promise(r=>{this.connection.once("end",r)})}};i(Rr,"Client");var Ge=Rr;Ge.Query=Qs;Hs.exports=Ge});var $s=h(($f,Ks)=>{"use strict";var Bu=require("events").EventEmitter,js=i(function(){},"NOOP"),Vs=i((t,e)=>{let r=t.findIndex(e);return r===-1?void 0:t.splice(r,1)[0]},"removeWhere"),xr=class xr{constructor(e,r,n){this.client=e,this.idleListener=r,this.timeoutId=n}};i(xr,"IdleItem");var Ir=xr,Pr=class Pr{constructor(e){this.callback=e}};i(Pr,"PendingItem");var te=Pr;function Uu(){throw new Error("Release called on client which has already been released to the pool.")}i(Uu,"throwOnDoubleRelease");function Qe(t,e){if(e)return{callback:e,result:void 0};let r,n,s=i(function(o,c){o?r(o):n(c)},"cb"),a=new t(function(o,c){n=o,r=c}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:s,result:a}}i(Qe,"promisify");function Gu(t,e){return i(function r(n){n.client=e,e.removeListener("error",r),e.on("error",()=>{t.log("additional client error after disconnection due to error",n)}),t._remove(e),t.emit("error",n,e)},"idleListener")}i(Gu,"makeIdleListener");var Lr=class Lr extends Bu{constructor(e,r){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||r||Mr().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(r=>{this._remove(r.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let r=this._idle.pop();clearTimeout(r.timeoutId);let n=r.client;n.ref&&n.ref();let s=r.idleListener;return this._acquireClient(n,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e){let r=Vs(this._idle,n=>n.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(n=>n!==e),e.end(),this.emit("remove",e)}connect(e){if(this.ending){let s=new Error("Cannot use a pool after calling end on the pool");return e?e(s):this.Promise.reject(s)}let r=Qe(this.Promise,e),n=r.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new te(r.callback)),n;let s=i((c,l,u)=>{clearTimeout(o),r.callback(c,l,u)},"queueCallback"),a=new te(s),o=setTimeout(()=>{Vs(this._pendingQueue,c=>c.callback===s),a.timedOut=!0,r.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return this._pendingQueue.push(a),n}return this.newClient(new te(r.callback)),n}newClient(e){let r=new this.Client(this.options);this._clients.push(r);let n=Gu(this,r);this.log("checking client timeout");let s,a=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{this.log("ending client due to timeout"),a=!0,r.connection?r.connection.stream.destroy():r.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),r.connect(o=>{if(s&&clearTimeout(s),r.on("error",n),o)this.log("client failed to connect",o),this._clients=this._clients.filter(c=>c!==r),a&&(o.message="Connection terminated due to connection timeout"),this._pulseQueue(),e.timedOut||e.callback(o,void 0,js);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let c=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(r),this._idle.findIndex(u=>u.client===r)!==-1&&this._acquireClient(r,new te((u,p,f)=>f()),n,!1)},this.options.maxLifetimeSeconds*1e3);c.unref(),r.once("end",()=>clearTimeout(c))}return this._acquireClient(r,e,n,!0)}})}_acquireClient(e,r,n,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n),e.removeListener("error",n),r.timedOut?s&&this.options.verify?this.options.verify(e,e.release):e.release():s&&this.options.verify?this.options.verify(e,a=>{if(a)return e.release(a),r.callback(a,void 0,js);r.callback(void 0,e,e.release)}):r.callback(void 0,e,e.release)}_releaseOnce(e,r){let n=!1;return s=>{n&&Uu(),n=!0,this._release(e,r,s)}}_release(e,r,n){if(e.on("error",r),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",n,e),n||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses){e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e),this._pulseQueue();return}if(this._expired.has(e)){this.log("remove expired client"),this._expired.delete(e),this._remove(e),this._pulseQueue();return}let a;this.options.idleTimeoutMillis&&(a=setTimeout(()=>{this.log("remove idle client"),this._remove(e)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&a.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new Ir(e,r,a)),this._pulseQueue()}query(e,r,n){if(typeof e=="function"){let a=Qe(this.Promise,e);return setImmediate(function(){return a.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),a.result}typeof r=="function"&&(n=r,r=void 0);let s=Qe(this.Promise,n);return n=s.callback,this.connect((a,o)=>{if(a)return n(a);let c=!1,l=i(u=>{c||(c=!0,o.release(u),n(u))},"onError");o.once("error",l),this.log("dispatching query");try{o.query(e,r,(u,p)=>{if(this.log("query dispatched"),o.removeListener("error",l),!c)return c=!0,o.release(u),u?n(u):n(void 0,p)})}catch(u){return o.release(u),n(u)}}),s.result}end(e){if(this.log("ending"),this.ending){let n=new Error("Called end on pool more than once");return e?e(n):this.Promise.reject(n)}this.ending=!0;let r=Qe(this.Promise,e);return this._endCallback=r.callback,this._pulseQueue(),r.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,r)=>e+(this._expired.has(r)?1:0),0)}get totalCount(){return this._clients.length}};i(Lr,"Pool");var Nr=Lr;Ks.exports=Nr});var Js=h((Yf,Ys)=>{"use strict";var zs=require("events").EventEmitter,Qu=require("util"),qr=Ee(),re=Ys.exports=function(t,e,r){zs.call(this),t=qr.normalizeQueryConfig(t,e,r),this.text=t.text,this.values=t.values,this.name=t.name,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};Qu.inherits(re,zs);var Hu={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};re.prototype.handleError=function(t){var e=this.native.pq.resultErrorFields();if(e)for(var r in e){var n=Hu[r]||r;t[n]=e[r]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};re.prototype.then=function(t,e){return this._getPromise().then(t,e)};re.prototype.catch=function(t){return this._getPromise().catch(t)};re.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};re.prototype.submit=function(t){this.state="running";var e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;var r=i(function(a,o,c){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),a)return e.handleError(a);e._emitRowEvents&&(c.length>1?o.forEach((l,u)=>{l.forEach(p=>{e.emit("row",p,c[u])})}):o.forEach(function(l){e.emit("row",l,c)})),e.state="end",e.emit("end",c),e.callback&&e.callback(null,c)},"after");if(process.domain&&(r=process.domain.bind(r)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var n=(this.values||[]).map(qr.prepareValue);if(t.namedQueries[this.name]){if(this.text&&t.namedQueries[this.name]!==this.text){let a=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return r(a)}return t.native.execute(this.name,n,r)}return t.native.prepare(this.name,this.text,n.length,function(a){return a?r(a):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,n,r))})}else if(this.values){if(!Array.isArray(this.values)){let a=new Error("Query values must be an array");return r(a)}var s=this.values.map(qr.prepareValue);t.native.query(this.text,s,r)}else t.native.query(this.text,r)}});var ri=h((Zf,ti)=>{"use strict";var Zs;try{Zs=require("pg-native")}catch(t){throw t}var Wu=Ct(),Xs=require("events").EventEmitter,ju=require("util"),Vu=Nt(),ei=Js(),L=ti.exports=function(t){Xs.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new Wu(t.types),this.native=new Zs({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var e=this.connectionParameters=new Vu(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};L.Query=ei;ju.inherits(L,Xs);L.prototype._errorAllQueries=function(t){let e=i(r=>{process.nextTick(()=>{r.native=this.native,r.handleError(t)})},"enqueueError");this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};L.prototype._connect=function(t){var e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(r,n){if(e.connectionParameters.nativeConnectionString&&(n=e.connectionParameters.nativeConnectionString),r)return t(r);e.native.connect(n,function(s){if(s)return e.native.end(),t(s);e._connected=!0,e.native.on("error",function(a){e._queryable=!1,e._errorAllQueries(a),e.emit("error",a)}),e.native.on("notification",function(a){e.emit("notification",{channel:a.relname,payload:a.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t()})})};L.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,r)=>{this._connect(n=>{n?r(n):e()})})};L.prototype.query=function(t,e,r){var n,s,a,o,c;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")a=t.query_timeout||this.connectionParameters.query_timeout,s=n=t,typeof e=="function"&&(t.callback=e);else if(a=this.connectionParameters.query_timeout,n=new ei(t,e,r),!n.callback){let l,u;s=new this._Promise((p,f)=>{l=p,u=f}).catch(p=>{throw Error.captureStackTrace(p),p}),n.callback=(p,f)=>p?u(p):l(f)}return a&&(c=n.callback,o=setTimeout(()=>{var l=new Error("Query read timeout");process.nextTick(()=>{n.handleError(l,this.connection)}),c(l),n.callback=()=>{};var u=this._queryQueue.indexOf(n);u>-1&&this._queryQueue.splice(u,1),this._pulseQueryQueue()},a),n.callback=(l,u)=>{clearTimeout(o),c(l,u)}),this._queryable?this._ending?(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client was closed and is not queryable"))}),s):(this._queryQueue.push(n),this._pulseQueryQueue(),s):(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client has encountered a connection error and is not queryable"))}),s)};L.prototype.end=function(t){var e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,t));var r;return t||(r=new this._Promise(function(n,s){t=i(a=>a?s(a):n(),"cb")})),this.native.end(function(){e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})}),r};L.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};L.prototype._pulseQueryQueue=function(t){if(this._connected&&!this._hasActiveQuery()){var e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);var r=this;e.once("_done",function(){r._pulseQueryQueue()})}};L.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};L.prototype.ref=function(){};L.prototype.unref=function(){};L.prototype.setTypeParser=function(t,e,r){return this._types.setTypeParser(t,e,r)};L.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)}});var Dr=h((ed,ni)=>{"use strict";ni.exports=ri()});var Mr=h((td,ve)=>{"use strict";var Ku=Ws(),$u=ge(),zu=br(),Yu=$s(),{DatabaseError:Ju}=Er(),{escapeIdentifier:Zu,escapeLiteral:Xu}=Ee(),el=i(t=>{var e;return e=class extends Yu{constructor(n){super(n,t)}},i(e,"BoundPool"),e},"poolFactory"),Fr=i(function(t){this.defaults=$u,this.Client=t,this.Query=this.Client.Query,this.Pool=el(this.Client),this._pools=[],this.Connection=zu,this.types=ye(),this.DatabaseError=Ju,this.escapeIdentifier=Zu,this.escapeLiteral=Xu},"PG");typeof process.env.NODE_PG_FORCE_NATIVE<"u"?ve.exports=new Fr(Dr()):(ve.exports=new Fr(Ku),Object.defineProperty(ve.exports,"native",{configurable:!0,enumerable:!1,get(){var t=null;try{t=new Fr(Dr())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(ve.exports,"native",{value:t}),t}}))});var ii=h((nd,si)=>{"use strict";var W=require("fs"),tl=Sn(),rl=Mr(),nl="The server does not support SSL connections",sl="28000",il=i(t=>{let e={username:t.ssh_user,host:t.ssh_host,port:t.ssh_port,dstHost:t.host,dstPort:t.port,localHost:"127.0.0.1",localPort:t.port,keepAlive:!0};return t.ssh_method==="privateKey"?Object.assign({},e,{privateKey:W.readFileSync(t.ssh_key_file),passphrase:t.ssh_key_passphrase}):Object.assign({},e,{password:t.ssh_password})},"getSshConfig"),al=i(t=>new Promise((e,r)=>{tl(il(t),(n,s)=>{n?r(n):e({tunnel:s,info:Object.assign({},t,{host:"127.0.0.1"})})})}),"connectViaSsh"),ol=i((t,e)=>{let r=t.sslType;if(!r||r==="disable"||r==="allow")return!1;if(["require","prefer"].includes(r)&&!t.certAuthority)return{rejectUnauthorized:!1};let n={checkServerIdentity(s,a){e.info("Certificate",{hostname:s,cert:{subject:a.subject,issuer:a.issuer,valid_from:a.valid_from,valid_to:a.valid_to}})}};return W.existsSync(t.certAuthority)&&(n.ca=W.readFileSync(t.certAuthority).toString()),W.existsSync(t.clientCert)&&(n.cert=W.readFileSync(t.clientCert).toString()),W.existsSync(t.clientPrivateKey)&&(n.key=W.readFileSync(t.clientPrivateKey).toString()),n},"getSslOptions"),cl=i(t=>({Off:"disable",TRUST_ALL_CERTIFICATES:"allow",TRUST_CUSTOM_CA_SIGNED_CERTIFICATES:"prefer",TRUST_SERVER_CLIENT_CERTIFICATES:"verify-full"})[t]||t,"mapSslType"),ul=i(async(t,e)=>{let r=null;if(t.ssh){let{info:a,tunnel:o}=await al(t);r=o,t=a}t=Object.assign({},t,{sslType:cl(t.sslType)});let n={host:t.host,user:t.userName,password:t.userPassword,port:t.port,keepAlive:!0,ssl:ol(t,e),connectionTimeoutMillis:Number(t.queryRequestTimeout)||6e4,query_timeout:Number(t.queryRequestTimeout)||6e4,statement_timeout:Number(t.queryRequestTimeout)||6e4,database:t.database||t.maintenanceDatabase,application_name:"Hackolade",idleTimeoutMillis:Number(t.queryRequestTimeout)||1e4,sslType:t.sslType};return{client:await kr(n,e),sshTunnel:r}},"createClient"),ll=i((t,e,r)=>{var n;if(r.message===nl&&t.sslType==="prefer")return e.info("Retry connection without SSL (SSL mode 'prefer')"),e.error(r),kr({...t,isRetry:!0,ssl:!1},e);if(((n=r.code)==null?void 0:n.toString())===sl&&t.sslType==="allow")return e.info("Retry connection with SSL (SSL mode 'allow')"),e.error(r),kr({...t,isRetry:!0,ssl:{rejectUnauthorized:!1}},e);throw r},"retryOnSslError"),kr=i((t,e)=>{let r=new rl.Pool(t);return r.connect().then(n=>(n.release(),r)).catch(async n=>{if(await r.end(),t.isRetry)throw n;return ll(t,e,n)})},"createConnectionPool");si.exports={createClient:ul}});var Br=h((id,ci)=>{"use strict";var ai=i(t=>` + SELECT obj_description(oid, 'pg_proc') AS description, + proname AS function_name, + provolatile AS volatility, + proparallel AS parallel, + proisstrict AS strict, + proretset AS returns_set, + proleakproof AS leak_proof, + procost AS estimated_cost, + prorows AS estimated_rows, + prosrc AS body, + ${t===10?"CASE WHEN proiswindow is true THEN 'w' ELSE '' END AS kind":"prokind AS kind"} + FROM pg_catalog.pg_proc WHERE pronamespace = $1;`,"getGET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL"),oi={PING:"SELECT schema_name FROM information_schema.schemata LIMIT 1;",GET_VERSION:"SELECT version()",GET_VERSION_AS_NUM:"SHOW server_version_num;",GET_SCHEMA_NAMES:"SELECT schema_name FROM information_schema.schemata;",GET_TABLE_NAMES:` + SELECT tables.table_name, tables.table_type + FROM information_schema.tables AS tables + INNER JOIN ( + SELECT pg_class.relname AS table_name, + pg_namespace.nspname AS table_schema + FROM pg_catalog.pg_class AS pg_class + INNER JOIN pg_catalog.pg_namespace AS pg_namespace + ON (pg_namespace.oid = pg_class.relnamespace) + WHERE (pg_class.relispartition = false OR pg_class.relispartition IS NULL) AND pg_class.relkind = ANY ('{"r","v","t","m","p"}') + ) AS catalog_table_data + ON (catalog_table_data.table_name = tables.table_name AND catalog_table_data.table_schema = tables.table_schema) + WHERE tables.table_schema = $1; + `,GET_NAMESPACE_OID:"SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = $1",GET_TABLE_LEVEL_DATA:` + SELECT pc.oid, pc.relpersistence, pc.reloptions, pg_get_expr(pc.relpartbound, pc.oid) AS partition_expr + FROM pg_catalog.pg_class AS pc + WHERE pc.relname = $1 AND pc.relnamespace = $2;`,GET_TABLE_TOAST_OPTIONS:` + SELECT reloptions AS toast_options + FROM pg_catalog.pg_class + WHERE oid = + (SELECT reltoastrelid + FROM pg_catalog.pg_class + WHERE relname=$1 AND relnamespace = $2 + LIMIT 1)`,GET_TABLE_COLUMNS:` + SELECT * FROM information_schema.columns + WHERE table_name = $1 AND table_schema = $2 + ORDER BY ordinal_position`,GET_TABLE_COLUMNS_ADDITIONAL_DATA:` + SELECT pg_attribute.attname AS name, + pg_attribute.attndims AS number_of_array_dimensions, + pg_description.description, + pg_attribute.atttypmod AS attribute_mode + FROM pg_catalog.pg_attribute AS pg_attribute + LEFT JOIN pg_catalog.pg_description AS pg_description ON (pg_description.objsubid=pg_attribute.attnum + AND pg_description.objoid = pg_attribute.attrelid) + WHERE pg_attribute.attrelid = $1;`,GET_DESCRIPTION_BY_OID:"SELECT obj_description($1, $2)",GET_ROWS_COUNT:t=>`SELECT COUNT(*) AS quantity FROM ${t};`,GET_SAMPLED_DATA:(t,e)=>`SELECT ${e} FROM ${t} LIMIT $1;`,GET_SAMPLED_DATA_SIZE:(t,e)=>` + SELECT sum(pg_column_size(_hackolade_tmp_sampling_tbl.*)) AS _hackolade_tmp_sampling_tbl_size + FROM (SELECT ${e} FROM ${t} LIMIT $1) AS _hackolade_tmp_sampling_tbl;`,GET_TABLE_CONSTRAINTS:` + SELECT pcon.conname AS constraint_name, + pcon.contype AS constraint_type, + pcon.conkey AS constraint_keys, + pg_catalog.pg_get_expr(pcon.conbin, pcon.conrelid) AS expression, + obj_description(pcon.oid, 'pg_constraint') AS description, + pc.reloptions AS storage_parameters + FROM pg_catalog.pg_constraint AS pcon + LEFT JOIN pg_catalog.pg_class AS pc + ON pcon.conindid = pc.oid + WHERE pcon.conrelid = $1;`,GET_TABLE_INDEXES:` + SELECT indexname, + index_id, + index_method, + index_unique, + number_of_keys, + where_expression, + array_agg(attname ORDER BY ord)::text[] AS columns, + array_agg(coll ORDER BY ord) AS collations, + array_agg(opclass ORDER BY ord) AS opclasses, + array_agg(expression ORDER BY ord) AS expressions, + array_agg(ascending ORDER BY ord) AS ascendings, + array_agg(nulls_first ORDER BY ord) AS nulls_first, + reloptions AS storage_parameters + FROM ( + SELECT ct.oid AS table_oid, + c.relname AS indexname, + m.amname AS index_method, + indexes.indisunique AS index_unique, + indexes.ord, + attribute.attname, + c.reloptions, + indexes.indnkeyatts AS number_of_keys, + ti.index_id AS index_id, + pg_catalog.pg_get_expr(indpred, indrelid) AS where_expression, + CASE + WHEN collation_namespace.nspname is not null THEN format('%I.%I',collation_namespace.nspname,collation_t.collname) + END AS coll, + CASE + WHEN opclass_t.opcname is not null THEN format('%I.%I',opclas_namespace.nspname,opclass_t.opcname) + END AS opclass, + CASE + WHEN NOT m.amcanorder THEN '' + WHEN indexes.indoption[indexes.ord - 1] & 1 = 1 THEN 'DESC' ELSE 'ASC' + END AS ascending, + CASE + WHEN NOT m.amcanorder THEN '' + WHEN indexes.indoption[indexes.ord - 1] & 2 = 2 THEN 'NULLS FIRST' ELSE 'NULLS LAST' + END AS nulls_first, + pg_catalog.pg_get_indexdef(indexes.indexrelid, ord, false) AS expression + FROM + ( + SELECT *, + generate_series(1,array_length(i.indkey,1)) AS ord, + unnest(i.indkey) AS key, + unnest(i.indcollation) AS coll, + unnest(i.indclass) AS class, + unnest(i.indoption) AS option + FROM pg_catalog.pg_index i + ) indexes + JOIN pg_catalog.pg_class c ON (c.oid=indexes.indexrelid) + JOIN pg_catalog.pg_class ct ON (ct.oid=indexes.indrelid) + JOIN pg_catalog.pg_am m ON (m.oid=c.relam) + LEFT JOIN pg_catalog.pg_attribute attribute + ON (attribute.attrelid=indexes.indrelid AND attribute.attnum=indexes.key) + LEFT JOIN pg_catalog.pg_collation collation_t ON (collation_t.oid=indexes.coll) + LEFT JOIN pg_catalog.pg_namespace collation_namespace ON (collation_namespace.oid=collation_t.collnamespace) + LEFT JOIN pg_catalog.pg_opclass opclass_t ON (opclass_t.oid=indexes.class) + LEFT JOIN pg_catalog.pg_namespace opclas_namespace ON (opclas_namespace.oid=opclass_t.opcnamespace) + INNER JOIN crdb_internal.table_indexes ti ON ( + indexes.indrelid = ti.descriptor_id + AND c.relname = ti.index_name + ) + ) s2 + WHERE table_oid = $1 + GROUP BY + indexname, + index_id, + index_method, + index_unique, + reloptions, + number_of_keys, + where_expression; + `,GET_TABLE_INDEX_PARTITIONING_DATA:` + SELECT + partitions.name AS partition_name, + partitions.index_id, + parent_name, + column_names, + list_value, + range_value, + index_name + FROM crdb_internal.partitions + INNER JOIN crdb_internal.table_indexes + ON partitions.table_id = table_indexes.descriptor_id + AND partitions.index_id = table_indexes.index_id + WHERE table_indexes.descriptor_id = $1; + `,GET_TABLE_INDEX_CREATE_INFO:` + SELECT index_name, + is_sharded, + is_visible, + create_statement + FROM crdb_internal.table_indexes WHERE descriptor_id = $1; + `,GET_TABLE_FOREIGN_KEYS:` + SELECT pcon.conname AS relationship_name, + pcon.conkey AS table_columns_positions, + pcon.confdeltype AS relationship_on_delete, + pcon.confupdtype AS relationship_on_update, + pcon.confmatchtype AS relationship_match, + pc_foreign_table.relname AS foreign_table_name, + ARRAY( + SELECT column_name::text FROM unnest(pcon.confkey) AS column_position + JOIN information_schema.columns ON (ordinal_position = column_position) + WHERE table_name = pc_foreign_table.relname AND table_schema = foreign_table_namespace.nspname)::text[] AS foreign_columns, + foreign_table_namespace.nspname AS foreign_table_schema + FROM pg_catalog.pg_constraint AS pcon + LEFT JOIN pg_catalog.pg_class AS pc ON pcon.conindid = pc.oid + LEFT JOIN pg_catalog.pg_class AS pc_foreign_table ON (pcon.confrelid = pc_foreign_table.oid) + JOIN pg_catalog.pg_namespace AS foreign_table_namespace ON (pc_foreign_table.relnamespace = foreign_table_namespace.oid) + WHERE pcon.conrelid = $1 AND pcon.contype = 'f';`,GET_VIEW_DATA:"SELECT * FROM information_schema.views WHERE table_name = $1 AND table_schema = $2;",GET_VIEW_SELECT_STMT_FALLBACK:"SELECT definition FROM pg_views WHERE viewname = $1 AND schemaname = $2;",GET_VIEW_OPTIONS:` + SELECT oid, + reloptions AS view_options, + relpersistence AS persistence, + obj_description(oid, 'pg_class') AS description + FROM pg_catalog.pg_class + WHERE relname = $1 AND relnamespace = $2;`,GET_FUNCTIONS_WITH_PROCEDURES:` + SELECT specific_name, + routine_name AS name, + routine_type, + routine_definition, + external_language, + security_type, + type_udt_name AS return_data_type + FROM information_schema.routines + WHERE specific_schema=$1;`,GET_FUNCTIONS_WITH_PROCEDURES_ARGS:` + SELECT parameter_name, + parameter_mode, + parameter_default, + data_type, + udt_name + FROM information_schema.parameters + WHERE specific_name = $1 + ORDER BY ordinal_position;`,GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL:ai(),GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:ai(10),GET_USER_DEFINED_TYPES:` + SELECT pg_type.typrelid AS pg_class_oid, + pg_type.typname AS name, + pg_type.typtype AS type, + pg_catalog.array_agg(pg_enum.enumlabel)::text[] AS enum_values, + range_subtype_type.typname AS range_subtype, + range_collation.collname AS range_collation_name, + range_opclass.opcname AS range_opclass_name, + range_canonical_proc.proname AS range_canonical_proc, + range_diff_proc.proname AS range_diff_proc + FROM pg_catalog.pg_type AS pg_type + LEFT JOIN pg_catalog.pg_class AS pg_class ON (pg_class.oid = pg_type.typrelid) + LEFT JOIN pg_catalog.pg_namespace AS pg_namespace ON (pg_namespace.oid = pg_type.typnamespace) + LEFT JOIN pg_catalog.pg_enum AS pg_enum ON (pg_enum.enumtypid = pg_type.oid) + LEFT JOIN pg_catalog.pg_range AS pg_range ON (pg_range.rngtypid = pg_type.oid) + LEFT JOIN pg_catalog.pg_type AS range_subtype_type ON (range_subtype_type.oid = pg_range.rngsubtype) + LEFT JOIN pg_catalog.pg_collation AS range_collation ON (range_collation.oid = pg_range.rngcollation) + LEFT JOIN pg_catalog.pg_opclass AS range_opclass ON (range_opclass.oid = pg_range.rngsubopc) + LEFT JOIN pg_catalog.pg_proc AS range_canonical_proc ON (range_canonical_proc.oid = pg_range.rngcanonical) + LEFT JOIN pg_catalog.pg_proc AS range_diff_proc ON (range_diff_proc.oid = pg_range.rngsubdiff) + WHERE pg_namespace.nspname = $1 + AND ( + (pg_type.typtype = 'c' AND (pg_class.relkind = 'c' OR pg_class.relkind IS NULL)) + OR pg_type.typtype = 'e' + OR pg_type.typtype = 'r' + ) + GROUP BY pg_class_oid, + pg_type.typname, + pg_type.typtype, + pg_class.oid, + range_subtype, + range_collation_name, + range_opclass_name, + range_canonical_proc, + range_diff_proc;`,GET_COMPOSITE_TYPE_COLUMNS:` + SELECT pg_attribute.attname AS column_name, + pg_type.typname AS data_type, + pg_get_expr(pg_attrdef.adbin, pg_attrdef.adrelid) AS columns_default, + pg_attribute.attnotnull AS not_null, + pg_collation.collname AS collation_name, + pg_attribute.attndims AS number_of_array_dimensions, + pg_attribute.atttypmod AS character_maximum_length + FROM pg_catalog.pg_attribute AS pg_attribute + LEFT JOIN pg_catalog.pg_type AS pg_type ON (pg_type.oid = pg_attribute.atttypid) + LEFT JOIN pg_catalog.pg_attrdef AS pg_attrdef ON (pg_attrdef.adrelid = pg_attribute.attrelid + AND pg_attrdef.adnum = pg_attribute.attnum) + LEFT JOIN pg_catalog.pg_collation AS pg_collation ON (pg_collation.oid = pg_attribute.attcollation) + WHERE pg_attribute.attrelid = $1`,GET_DB_NAME:"SELECT current_database();",GET_DB_ENCODING:"SHOW SERVER_ENCODING;",GET_DB_COLLATE_NAME:"SELECT default_collate_name FROM information_schema.character_sets;",GET_DATABASES:"SELECT datname AS database_name FROM pg_catalog.pg_database WHERE datistemplate != TRUE AND datallowconn = TRUE;"},pl=i(t=>(Object.entries(oi).find(([r,n])=>t===n)||[])[0]||"Custom query","getQueryName");ci.exports={getQueryName:pl,...oi}});var li=h((od,ui)=>{"use strict";var hl=Br(),j=null,He=null;ui.exports={initializeClient(t,e){j=t,He=e,j.on("error",r=>e.error(r))},isClientInitialized(){return!!j},releaseClient(){return j?new Promise(t=>{j.end(()=>{j=null,t()})}):Promise.resolve()},async query(t,e,r=!1){let n=hl.getQueryName(t);He.info("Execute query",{queryName:n,params:e});let s=Date.now(),a=await j.query(t,e),o=Date.now()-s;He.info("Query executed",{queryName:n,params:e,duration:o,rowsCount:a.rowCount});let c=a.rows||[];return r?c[0]:c},async queryTolerant(t,e,r=!1){try{return await this.query(t,e,r)}catch(n){return n.query=t,n.params=e,He.error(n),null}}}});var fi=h((cd,hi)=>{"use strict";var pi=i(t=>{let e=t.reduce((n,s)=>s.properties?{...n,[s.name]:{...s,...pi(s.properties)}}:{...n,[s.name]:s},{}),r=Object.entries(e).filter(([n,s])=>s.required).map(([n])=>n);return{properties:e,required:r}},"getJsonSchema");hi.exports={getJsonSchema:pi}});var Qr=h((ld,di)=>{"use strict";var V=null,fl=i(t=>{V=t.require("lodash")},"setDependencies"),Ur={column_default:"default",is_nullable:{keyword:"required",map:(t,e,r)=>({YES:!1,NO:!0})[r]},not_null:"required",data_type:"type",numeric_precision:"precision",numeric_scale:"scale",datetime_precision:"timePrecision",attribute_mode:{keyword:"timePrecision",check:(t,e,r)=>r!==-1&&vl(t.data_type)},interval_type:"intervalOptions",collation_name:"collationRule",column_name:"name",number_of_array_dimensions:"numberOfArrayDimensions",udt_name:"udt_name",character_maximum_length:{keyword:"length",map:(t,e,r)=>Number(r)},description:"description"},dl=i((t,e,r)=>{let n=Ur[e];if(!n||typeof n=="string")return r;let s=n.check||((c,l,u)=>!0),a=n.map||((c,l,u)=>u),o="";return s(t,e,r)&&(o=r),a(t,e,o)},"getColumnValue"),ml=i(t=>e=>V.chain(e).toPairs().map(([r,n])=>{var s;return[((s=Ur[r])==null?void 0:s.keyword)||Ur[r],dl(e,r,n)]}).filter(([r,n])=>r&&!V.isNil(n)).fromPairs().thru(_l(t)).value(),"mapColumnData"),_l=i(t=>e=>({...e,...yl(t,e)}),"setColumnType"),yl=i((t,e)=>e.type==="ARRAY"?gl(t,e):e.type==="USER-DEFINED"?Gr(t,e.udt_name):Gr(t,e.type),"getType"),gl=i((t,e)=>({...Gr(t,e.udt_name.slice(1)),array_type:V.fill(Array(e.numberOfArrayDimensions),"")}),"getArrayType"),Gr=i((t,e)=>{switch(e){case"bigserial":case"real":case"double precision":case"smallserial":case"serial":case"money":return{type:"numeric",mode:e};case"numeric":case"dec":case"decimal":return{type:"numeric",mode:"decimal"};case"int2":case"smallint":return{type:"numeric",mode:"int2"};case"int4":case"integer":return{type:"numeric",mode:"int4"};case"int":case"int8":case"int64":case"bigint":return{type:"numeric",mode:"int"};case"float4":return{type:"numeric",mode:"real"};case"float8":return{type:"numeric",mode:"double precision"};case"bit":case"char":case"text":case"tsvector":case"tsquery":return{type:"char",mode:e};case"bit varying":return{type:"char",mode:"varbit"};case"character":return{type:"char",mode:"char"};case"character varying":return{type:"char",mode:"varchar"};case"bpchar":return{type:"char",mode:"char"};case"point":case"line":case"lseg":case"box":case"path":case"polygon":case"circle":case"box2d":case"box3d":case"geometry":case"geometry_dump":case"geography":return{type:"geometry",mode:e};case"bytea":return{type:"binary",mode:e};case"inet":case"cidr":case"macaddr":case"macaddr8":return{type:"inet",mode:e};case"date":case"time":case"timestamp":case"interval":return{type:"datetime",mode:e};case"timestamptz":case"timestamp with time zone":return{type:"datetime",mode:"timestamp",timezone:"WITH TIME ZONE"};case"timestamp without time zone":return{type:"datetime",mode:"timestamp",timezone:"WITHOUT TIME ZONE"};case"timetz":case"time with time zone":return{type:"datetime",mode:"time",timezone:"WITH TIME ZONE"};case"time without time zone":return{type:"datetime",mode:"time",timezone:"WITHOUT TIME ZONE"};case"json":case"jsonb":return{type:"json",mode:e,subtype:"object"};case"int4range":case"int8range":case"numrange":case"daterange":case"tsrange":case"tstzrange":return{type:"range",mode:e};case"int4multirange":case"int8multirange":case"nummultirange":case"tsmultirange":case"tstzmultirange":case"datemultirange":return{type:"multirange",mode:e};case"uuid":case"xml":case"boolean":return{type:e};case"bool":return{type:"boolean"};case"oid":case"regclass":case"regcollation":case"regconfig":case"regdictionary":case"regnamespace":case"regoper":case"regoperator":case"regproc":case"regprocedure":case"regrole":case"regtype":return{type:"oid",mode:e};default:return V.some(t,{name:e})?{$ref:`#/definitions/${e}`}:{type:"char",mode:"varchar"}}},"mapType"),El=i((t,e)=>{let r=V.first(e)||{};return t.map(n=>{if(n.type!=="json")return n;let s=r[n.name],a=Sl(s),o=Tl(a);return{...n,subtype:o}})},"setSubtypeFromSampledJsonValues"),Sl=i(t=>{try{return JSON.parse(t)}catch{return{}}},"safeParse"),Tl=i(t=>{if(Array.isArray(t))return"array";let e=typeof t;return e==="undefined"?"object":e},"getParsedJsonValueType"),vl=i(t=>V.includes(["timestamp with time zone","timestamp without time zone","time with time zone","time without time zone"],t),"canHaveTimePrecision");di.exports={setDependencies:fl,mapColumnData:ml,setSubtypeFromSampledJsonValues:El}});var be=h((hd,mi)=>{"use strict";var bl=["ALL","ANALYSE","ANALYZE","AND","ANY","ARRAY","ASC","ASYMMETRIC","AUTHORIZATION","BINARY","BOTH","CASE","CAST","CHECK","COLLATE","COLUMN","CONCURRENTLY","CONSTRAINT","CREATE","CROSS","CURRENT_CATALOG","CURRENT_DATE","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DEFAULT","DEFERRABLE","DESC","DISTINCT","DO","ELSE","END","EXCEPT","FALSE","FOR","FOREIGN","FREEZE","FROM","FULL","GRANT","GROUP","HAVING","ILIKE","IN","INITIALLY","INTERSECT","INTO","IS","ISNULL","JOIN","LATERAL","LEADING","LEFT","LIKE","LIMIT","LOCALTIME","LOCALTIMESTAMP","NATURAL","NOT","NULL","OFFSET","ON","ONLY","OR","ORDER","OUTER","OVERLAPS","PLACING","PRIMARY","REFERENCES","RETURNING","RIGHT","SELECT","SESSION_USER","SIMILAR","SOME","SYMMETRIC","TABLE","TABLESAMPLE","THEN","TO","TRAILING","TRUE","UNION","UNIQUE","USER","USING","VARIADIC","VERBOSE","WHEN","WHERE","WINDOW","WITH"],ne=null,wl=i(t=>{ne=t.require("lodash")},"setDependencies"),Al=i(t=>ne.chain(t).toPairs().reject(([e,r])=>ne.isNil(r)).fromPairs().value(),"clearEmptyPropertiesInObject"),Cl=i(t=>e=>{var r;return(r=ne.find(t,{ordinal_position:e}))==null?void 0:r.column_name},"getColumnNameByPosition"),Ol=i(t=>/\s|\W/.test(t)||ne.includes(bl,ne.toUpper(t))?`"${t}"`:t,"wrapInQuotes");mi.exports={clearEmptyPropertiesInObject:Al,setDependencies:wl,getColumnNameByPosition:Cl,wrapInQuotes:Ol}});var gi=h((dd,yi)=>{"use strict";var{getColumnNameByPosition:Rl}=be(),Hr=null,Il=i(t=>{Hr=t.require("lodash")},"setDependencies"),_i=i(t=>{switch(t){case"a":return"NO ACTION";case"r":return"RESTRICT";case"c":return"CASCADE";case"n":return"SET NULL";case"d":return"SET DEFAULT";default:return""}},"prepareDeleteAndUpdate"),Nl=i(t=>{switch(t){case"f":return"FULL";case"s":return"SIMPLE";default:return""}},"prepareMatch"),xl=i((t,e,r,n)=>Hr.map(t,s=>({relationshipName:s.relationship_name,dbName:s.foreign_table_schema,parentCollection:s.foreign_table_name,parentField:s.foreign_columns,childDbName:r,childCollection:e,childField:Hr.map(s.table_columns_positions,Rl(n)),relationshipType:"Foreign Key",relationshipInfo:{relationshipOnDelete:_i(s.relationship_on_delete),relationshipOnUpdate:_i(s.relationship_on_update),relationshipMatch:Nl(s.relationship_match)}})),"prepareForeignKeys");yi.exports={setDependencies:Il,prepareForeignKeys:xl}});var Ti=h((_d,Si)=>{"use strict";var We=null,Pl=i(t=>{We=t.require("lodash")},"setDependencies"),Ei=i(t=>We.map(t,e=>({argumentMode:e.parameter_mode,argumentName:e.parameter_name,argumentType:Ll(e.data_type,e.udt_name),defaultExpression:e.parameter_default})),"mapFunctionArgs"),Ll=i((t,e)=>t==="USER-DEFINED"?e:t==="ARRAY"?e.slice(1)+"[]":t,"getArgType"),Ml=i(t=>{switch(t){case"i":return"IMMUTABLE";case"s":return"STABLE";case"v":default:return"VOLATILE"}},"getVolatility"),ql=i(t=>{switch(t){case"s":return"SAFE";case"r":return"RESTICTED";case"u":return"UNSAFE";default:return""}},"getParallel"),Dl=i(t=>t?"STRICT":"CALLED ON NULL INPUT","getNullArgs"),Fl=i((t,e,r)=>({name:t.name,functionDescription:r==null?void 0:r.description,functionArguments:Ei(e),functionReturnsSetOf:r==null?void 0:r.returns_set,functionReturnType:t.return_data_type,functionLanguage:We.toLower(t.external_language),functionBody:t.routine_definition??(r==null?void 0:r.body),functionWindow:(r==null?void 0:r.kind)==="w",functionVolatility:Ml(r==null?void 0:r.volatility),functionLeakProof:r==null?void 0:r.leak_proof,functionNullArgs:Dl(r==null?void 0:r.strict),functionSqlSecurity:t.security_type,functionParallel:ql(t.parallel),functionExecutionCost:t.estimated_cost,functionExecutionRows:t.estimated_rows}),"mapFunctionData"),kl=i((t,e,r)=>({name:t.name,description:r==null?void 0:r.description,language:We.toLower(t.external_language),inputArgs:Ei(e),body:t.routine_definition}),"mapProcedureData");Si.exports={setDependencies:Pl,mapFunctionData:Fl,mapProcedureData:kl}});var Ai=h((gd,wi)=>{"use strict";var Bl=i(t=>e=>{if(!e)return null;let r=Gl(e),n=Ql(t)(e),s=Hl(e);return[{partitionMethod:r,compositePartitionKey:n,partitioning_expression:s}]},"preparePartition"),Wr=i((t={})=>t.list_value?"LIST":t.range_value?"RANGE":"","getPartitionMethodByRow"),vi=i((t=[])=>t.filter(e=>!e.parent_name),"getParentPartitionRows"),Ul=i((t=[],e=null)=>t.filter(r=>r.parent_name===e),"getChildPartitionRows"),Gl=i((t=[])=>{let e=vi(t);if(!e.length)return"";let r=e[0];return Wr(r)},"getPartitionMethod"),Ql=i(t=>(e=[])=>{let n=e.filter(s=>!s.parent_name).flatMap(s=>(s.column_names||"").split(",").map(o=>o.trim()));return t.uniq(n)},"getCompositePartitionKey"),Hl=i(t=>{let e=vi(t);if(!e.length)return"";let r=e[0],n=Wr(r),s=r.column_names||"",a=e.map(o=>bi({partition:o,paddingFactor:1,partitionResult:t})).join(`, +`);return`PARTITION BY ${n} (${s}) ( +${a} +)`},"getPartitionExpression"),bi=i(({partition:t,partitionResult:e,paddingFactor:r})=>{let n=t.list_value?"VALUES IN":"VALUES FROM",s=t.list_value||t.range_value||"",a=" ".repeat(r),o=`${a}PARTITION ${t.partition_name} ${n} ${s}`,c=Ul(e,t.partition_name);if(c.length){let l=c.map(m=>bi({partition:m,partitionResult:e,paddingFactor:r+1})).join(`, +`),u=c[0],p=Wr(u),f=u.column_names||"";return o+` PARTITION BY ${p} (${f}) ( +`+l+` +`+a+")"}return o},"getSinglePartitionExpression");wi.exports={preparePartition:Bl}});var Ni=h((Sd,Ii)=>{"use strict";var{clearEmptyPropertiesInObject:je,getColumnNameByPosition:Ci}=be(),{preparePartition:Wl}=Ai(),S=null,jl=i(t=>{S=t.require("lodash")},"setDependencies"),Vl=i(t=>{let e={};for(let r of Object.keys(t))r.startsWith("ttl")?(e.ttl_storage_parameters||(e.ttl_storage_parameters={}),e.ttl_storage_parameters[r]=t[r]):e[r]=t[r];return e},"groupTtlStorageParams"),Oi=i((t,e)=>{if(!t&&!e)return null;let r=fp(t),n=je(r),s=Vl(n);return je(s)},"prepareStorageParameters"),jr=i(t=>S.split(t,"="),"splitByEqualitySymbol"),Kl=i(t=>S.find(t,{type:"json"}),"checkHaveJsonTypes"),$l=i((t,e)=>{if(e.active==="absolute")return Number(e.absolute.value);let r=Math.ceil(t*e.relative.value/100);return Math.min(r,e.maxValue)},"getSampleDocSize"),zl=i((t,e,r)=>S.reduce(t,(n,s)=>{switch(s.constraint_type){case"c":return{...n,chkConstr:[...n.chkConstr,Zl(s)]};case"p":return{...n,primaryKey:[...n.primaryKey,Yl(s,e)]};case"u":return{...n,uniqueKey:[...n.uniqueKey,Jl(s,e)]};default:return n}},{chkConstr:[],uniqueKey:[],primaryKey:[]}),"prepareTableConstraints"),Yl=i((t,e)=>({constraintName:t.constraint_name,compositePrimaryKey:S.map(t.constraint_keys,Ci(e)),indexStorageParameters:S.join(t.storage_parameters,",")}),"getPrimaryKeyConstraint"),Jl=i((t,e)=>({constraintName:t.constraint_name,compositeUniqueKey:S.map(t.constraint_keys,Ci(e)),indexStorageParameters:S.join(t.storage_parameters,","),indexComment:t.description}),"getUniqueKeyConstraint"),Zl=i(t=>({chkConstrName:t.constraint_name,constrExpression:t.expression,notValid:t.notValid,constrDescription:t.description}),"getCheckConstraint"),Xl=i((t,e=[])=>e.find(n=>n.index_name===t)||{}||{},"getIndexCreateInfoRowByName"),ep=i(t=>{switch(t.toUpperCase()){case"INVERTED":return"gin";case"PREFIX":return"btree";default:return t}},"parseIndexMethod"),tp=i((t,e)=>(t||[]).filter(r=>r.index_name===e.indexname&&r.index_id===e.index_id),"getIndexPartitioningRows"),rp=i(({tableIndexesResult:t,tableIndexesCreateInfoResult:e=[],tableIndexesPartitioningResult:r})=>S.map(t,n=>{let s=Xl(n.indexname,e),a=s.create_statement,o=op(n,a),c=S.slice(o,0,n.number_of_keys),l=S.chain(o).slice(n.number_of_keys).map(x=>S.pick(x,"name")).value(),u=s.is_visible?"VISIBLE":"NOT VISIBLE",p=!!s.is_sharded,f=tp(r,n),E=(Wl(S)(f)||[{}])[0].partitioning_expression,M={indxName:n.indexname,index_method:ep(n.index_method),unique:n.index_unique??!1,index_storage_parameter:up(n.storage_parameters,a),where:n.where_expression||"",partitioning_expression:E,include:l,columns:c,using_hash:p,visibility:u};return je(M)}),"prepareTableIndexes"),np=i(({createStatement:t,columnName:e})=>{let r=["(",","],n=0;for(;n{let r=t.substring(e),n=r.indexOf(","),s=r.indexOf(")");return n===-1?e+s:e+Math.min(n,s)},"getColumnDefinitionEnd"),ip=i(({createStatement:t,columnName:e})=>{let r=np({columnName:e,createStatement:t});if(r===-1)return"";let n=sp({columnDefinitionStart:r,createStatement:t});return n===-1?"":t.substring(r,n)},"getIndexColumnQueryDefinition"),ap=i(({indexData:t,itemIndex:e,columnName:r,createStatement:n})=>{let s=S.get(t,`opclasses.${e}`,"");if(s)return s;let a=ip({columnName:r,createStatement:n});if(!a)return"";let o=a.substring(r.length).trim();return o?o.toUpperCase().replaceAll("ASC","").replaceAll("DESC","").replaceAll("NULLS FIRST","").replaceAll("NULLS LAST","").toLowerCase().trim():""},"getIndexColumnOpClass"),op=i((t,e)=>S.chain(t.columns).map((r,n)=>{if(!r)return;let s=S.get(t,`ascendings.${n}`,"ASC"),a=S.get(t,`nulls_first.${n}`,"NULLS FIRST"),o=ap({columnName:r,createStatement:e,itemIndex:n,indexData:t}),c=S.get(t,`collations.${n}`,"");return{name:r,sortOrder:s,nullsOrder:a,opclass:o,collation:c}}).compact().value(),"mapIndexColumns"),Ri=i(t=>{let e={fillfactor:t.fillfactor,bucket_count:t.bucket_count,geometry_max_x:t.geometry_max_x,geometry_max_y:t.geometry_max_y,geometry_min_x:t.geometry_min_x,geometry_min_y:t.geometry_min_y,s2_level_mod:t.s2_level_mod,s2_max_cells:t.s2_max_cells,s2_max_level:t.s2_max_level};return je(e)},"hydrateIndexStorageParameters"),cp=i(t=>{let e=/\s+with\s+\(.*?\)/im,r=t.match(e);if(!(r!=null&&r.length))return null;let n=r[0],s=7,a=n.length-1,o=n.substring(s,a).split(",").map(l=>l.trim()),c=S.fromPairs(S.map(o,l=>jr(l)));return Ri(c)},"parseIndexStorageParametersFromDdl"),up=i((t,e)=>{if(!t)return cp(e);let r=S.fromPairs(S.map(t,n=>jr(n)));return Ri(r)},"getIndexStorageParameters"),lp=i((t,e)=>{let r=(t==null?void 0:t.relpersistence)==="t",n=(t==null?void 0:t.relpersistence)==="u",s=Oi(t==null?void 0:t.reloptions,e),a=t.partition_expr;return{temporary:r,unlogged:n,storage_parameter:s,partitionBounds:a}},"prepareTableLevelData"),pp=i(t=>{switch(hp(t)){case"number":case"boolean":return JSON.parse(t);case"string":default:return t}},"convertValueToType"),hp=i(t=>{try{let e=typeof JSON.parse(t);return e==="object"?"string":e}catch{return"string"}},"getTypeOfValue"),fp=i(t=>S.chain(t).map(jr).map(([e,r])=>[e,pp(r)]).fromPairs().value()||{},"prepareOptions"),dp=i((t,e)=>S.map(e,({parent_table_name:r})=>({parentTable:[t,r]})),"prepareTableInheritance");Ii.exports={prepareStorageParameters:Oi,setDependencies:jl,checkHaveJsonTypes:Kl,prepareTableConstraints:zl,prepareTableLevelData:lp,prepareTableIndexes:rp,getSampleDocSize:$l,prepareTableInheritance:dp}});var Pi=h((vd,xi)=>{"use strict";var{mapColumnData:mp}=Qr(),Vr=null,_p=i(t=>{Vr=t.require("lodash")},"setDependencies"),yp=i(t=>Vr.chain(t).map(e=>{switch(e.type){case"e":return gp(e);case"r":return Ep(e);case"c":return Sp(e);default:return null}}).compact().value(),"getUserDefinedTypes"),gp=i(t=>({name:t.name,type:"enum",enum:t.enum_values||[]}),"getEnumType"),Ep=i(t=>({name:t.name,type:"range_udt",rangeSubtype:t.range_subtype||"",operatorClass:t.range_opclass_name||"",collation:t.range_collation_name||"",canonicalFunction:t.range_canonical_proc||"",subtypeDiffFunction:t.range_diff_proc||""}),"getRangeType"),Sp=i(t=>{let e=Vr.map(t.columns,mp([]));return{name:t.name,type:"composite",properties:e}},"getCompositeType"),Tp=i(t=>t.type==="c","isTypeComposite");xi.exports={setDependencies:_p,getUserDefinedTypes:yp,isTypeComposite:Tp}});var Mi=h((wd,Li)=>{"use strict";var{clearEmptyPropertiesInObject:vp,wrapInQuotes:bp}=be(),U=null,wp=i(t=>{U=t.require("lodash")},"setDependencies"),Kr=" (v)",Ap=i(t=>t==="VIEW","isViewByTableType"),Cp=i(t=>U.endsWith(t,Kr),"isViewByName"),Op=i(t=>t.slice(0,-Kr.length),"removeViewNameSuffix"),Rp=i(t=>`${t}${Kr}`,"setViewSuffix"),Ip=i((t,e,r={})=>{let n=U.trim(e.view_definition||r.definition||"");return n?`CREATE VIEW ${bp(t)} AS ${n}`:""},"generateCreateViewScript"),Np=i((t,e)=>{let r={withCheckOption:t.check_option!=="NONE"||U.isNil(t.check_option),checkTestingScope:xp(t.check_option),viewOptions:U.fromPairs(U.map(e==null?void 0:e.view_options,Lp)),temporary:(e==null?void 0:e.persistence)==="t",recursive:Pp(t),description:e==null?void 0:e.description};return vp(r)},"prepareViewData"),xp=i(t=>t==="NONE"?"":t,"getCheckTestingScope"),Pp=i(t=>U.startsWith(U.trim(t.view_definition),"WITH RECURSIVE"),"isViewRecursive"),Lp=i(t=>U.split(t,"="),"splitByEqualitySymbol");Li.exports={setDependencies:wp,isViewByTableType:Ap,isViewByName:Cp,removeViewNameSuffix:Op,generateCreateViewScript:Ip,setViewSuffix:Rp,prepareViewData:Np}});var Fi=h((Cd,Di)=>{"use strict";var Mp=i((t,e)=>[qp,Dp].reduce(({attributes:r,entityLevel:n},s)=>s(r,n),{attributes:t,entityLevel:e}),"reorganizeConstraints"),qp=i((t,e)=>{var a,o,c;if(((c=(o=(a=e.primaryKey)==null?void 0:a[0])==null?void 0:o.compositePrimaryKey)==null?void 0:c.length)!==1)return{attributes:t,entityLevel:e};let n=e.primaryKey[0],s=n.compositePrimaryKey[0];return{attributes:Fp(t,s,n),entityLevel:Gp(e)}},"reorganizePrimaryKeys"),Dp=i((t,e)=>(e.uniqueKey||[]).reduce(({attributes:r,entityLevel:n},s)=>{if(!(s.compositeUniqueKey.length===1))return{attributes:r,entityLevel:n};let o=s.compositeUniqueKey[0];return{attributes:Bp(r,o,s),entityLevel:Qp(n,s)}},{attributes:t,entityLevel:e}),"reorganizeUniqueKeys"),Fp=i((t,e,r)=>t.map(n=>n.name!==e?n:kp(n,r)),"setAttributesPrimaryKeyData"),kp=i((t,e)=>({...t,primaryKey:!0,primaryKeyOptions:qi(e)}),"setPrimaryKeyData"),Bp=i((t,e,r)=>t.map(n=>n.name!==e?n:Up(n,r)),"setAttributesUniqueKeyData"),Up=i((t,e)=>({...t,unique:!0,uniqueKeyOptions:qi(e)}),"setUniqueKeyData"),qi=i(t=>[{constraintName:t.constraintName,indexInclude:t.indexInclude,indexStorageParameters:t.indexStorageParameters,indexComment:t.indexComment}],"getOptions"),Gp=i(t=>({...t,primaryKey:[]}),"clearPrimaryKeys"),Qp=i((t,e)=>{let r=t.uniqueKey.filter(n=>n.constraintName!==e.constraintName);return{...t,uniqueKey:r}},"filterUniqueKeys");Di.exports={reorganizeConstraints:Mp}});var Qi=h((Rd,Gi)=>{"use strict";var{createClient:Hp}=ii(),_=li(),{getJsonSchema:ki}=fi(),{setDependencies:Wp,mapColumnData:jp,setSubtypeFromSampledJsonValues:Vp}=Qr(),{setDependencies:Kp,clearEmptyPropertiesInObject:Bi}=be(),{setDependencies:$p,prepareForeignKeys:zp}=gi(),{setDependencies:Yp,mapFunctionData:Jp,mapProcedureData:Zp}=Ti(),{setDependencies:Xp,checkHaveJsonTypes:eh,prepareTableConstraints:th,getSampleDocSize:rh,prepareTableLevelData:nh,prepareTableIndexes:sh}=Ni(),{setDependencies:ih,getUserDefinedTypes:ah,isTypeComposite:oh}=Pi(),{setDependencies:ch,isViewByTableType:uh,isViewByName:lh,removeViewNameSuffix:ph,generateCreateViewScript:hh,setViewSuffix:fh,prepareViewData:dh}=Mi(),y=Br(),{reorganizeConstraints:mh}=Fi(),Ve=null,A=null,F=null,Ui=14;Gi.exports={setDependencies(t){A=t.require("lodash"),Kp(t),Xp(t),Wp(t),$p(t),ch(t),Yp(t),ih(t)},async connect(t,e){_.isClientInitialized()&&await this.disconnect();let{client:r,sshTunnel:n}=await Hp(t,e);_.initializeClient(r,e),Ve=n,F=e,Ui=await this._getServerVersion()},async disconnect(){Ve&&(Ve.close(),Ve=null),await _.releaseClient()},pingDb(){return _.query(y.PING)},applyScript(t){return _.query(t)},async getDatabaseNames(){return A.map(await _.query(y.GET_DATABASES),"database_name")},async logVersion(){let t=await _.queryTolerant(y.GET_VERSION,[],!0),e=(t==null?void 0:t.version)||"Version not retrieved"},async getAllSchemasNames(){return(await _.query(y.GET_SCHEMA_NAMES)).map(({schema_name:e})=>e).filter(e=>!_h(e))},async getTablesNames(t){let e=await _.query(y.GET_TABLE_NAMES,[t]),r=["FOREIGN TABLE"];return e.filter(({table_type:n})=>!A.includes(r,n)).map(({table_name:n,table_type:s})=>uh(s)?fh(n):n)},async getDbLevelData(){var n,s,a;F.progress("Get database data");let t=(n=await _.queryTolerant(y.GET_DB_NAME,[],!0))==null?void 0:n.current_database,e=(s=await _.queryTolerant(y.GET_DB_ENCODING,[],!0))==null?void 0:s.server_encoding,r=(a=await _.queryTolerant(y.GET_DB_COLLATE_NAME,[],!0))==null?void 0:a.default_collate_name;return Bi({database_name:t,encoding:e,LC_COLLATE:r,LC_CTYPE:r})},async retrieveEntitiesData(t,e,r){let n=await this._retrieveUserDefinedTypes(t),s=await _.queryTolerant(y.GET_NAMESPACE_OID,[t],!0),a=s==null?void 0:s.oid,[o,c]=A.partition(e,lh),l=c.map(f=>({tableName:f})),u=await we(A.uniq(l),A.bind(this._retrieveSingleTableData,this,r,a,t,n));return{views:await we(o,A.bind(this._retrieveSingleViewData,this,a,t)),tables:u,modelDefinitions:ki(n)}},async retrieveSchemaLevelData(t,e){var u;if(e)return F.info("Functions and procedures ignored"),{functions:[],procedures:[]};F.progress("Get Functions and Procedures",t);let r=(u=await _.queryTolerant(y.GET_NAMESPACE_OID,[t],!0))==null?void 0:u.oid,n=await _.queryTolerant(y.GET_FUNCTIONS_WITH_PROCEDURES,[t]),s=await _.queryTolerant(yh(Ui),[r]),[a,o]=A.partition(A.filter(n,"routine_type"),{routine_type:"FUNCTION"}),c=await we(a,async p=>{let f=await _.queryTolerant(y.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[p.specific_name]),m=A.find(s,{function_name:p.name});return Jp(p,f,m)}),l=await we(o,async p=>{let f=await _.queryTolerant(y.GET_FUNCTIONS_WITH_PROCEDURES_ARGS,[p.specific_name]),m=A.find(s,{function_name:p.name});return Zp(p,f,m)});return{functions:c,procedures:l}},async _retrieveUserDefinedTypes(t){F.progress("Get User-Defined Types",t);let e=await _.queryTolerant(y.GET_USER_DEFINED_TYPES,[t]),r=await we(e,async n=>oh(n)?{...n,columns:await _.queryTolerant(y.GET_COMPOSITE_TYPE_COLUMNS,[n.pg_class_oid])}:n);return ah(r)},async _retrieveSingleTableData(t,e,r,n,{tableName:s}){F.progress("Get table data",r,s);let a=await _.queryTolerant(y.GET_TABLE_LEVEL_DATA,[s,e],!0),o=a==null?void 0:a.oid,c=await _.queryTolerant(y.GET_TABLE_TOAST_OPTIONS,[s,e],!0),l=await this._getTableColumns(s,r,o),p=await _.queryTolerant(y.GET_DESCRIPTION_BY_OID,[o,"pg_class"],!0),f=await _.queryTolerant(y.GET_TABLE_CONSTRAINTS,[o]),m=await _.queryTolerant(y.GET_TABLE_INDEXES,[o]),E=await _.queryTolerant(y.GET_TABLE_INDEX_PARTITIONING_DATA,[o]),M=await _.queryTolerant(y.GET_TABLE_INDEX_CREATE_INFO,[o]),x=await _.queryTolerant(y.GET_TABLE_FOREIGN_KEYS,[o]);F.info("Table data retrieved",{schemaName:r,tableName:s,columnTypes:l.map(Ki=>Ki.data_type)});let $e=nh(a,c),ze=gh(p),Ye=th(f,l,m),Je=sh({tableIndexesResult:m,tableIndexesCreateInfoResult:M,tableIndexesPartitioningResult:E}),Ae=zp(x,s,r,l),k={description:ze,Indxs:Je,...$e,...Ye},Hi=Bi(k),se=l.map(jp(n)),Wi=eh(se),Ze=[];Wi&&(Ze=await this._getDocuments(r,s,se,t),se=Vp(se,Ze));let{attributes:ji,entityLevel:Vi}=mh(se,Hi);return{name:s,entityLevel:Vi,jsonSchema:ki(ji),documents:Ze,relationships:Ae}},async _getTableColumns(t,e,r){F.progress("Get columns",e,t);let n=await _.query(y.GET_TABLE_COLUMNS,[t,e]),s=await _.queryTolerant(y.GET_TABLE_COLUMNS_ADDITIONAL_DATA,[r]);return A.map(n,a=>({...a,ordinal_position:Number(a.ordinal_position),...A.find(s,{name:a.column_name})||{}}))},async _getDocuments(t,e,r,n){var p;F.progress("Sampling table",t,e);let s=`${t}.${e}`,a=((p=await _.queryTolerant(y.GET_ROWS_COUNT(s),[],!0))==null?void 0:p.quantity)||0,o=rh(a,n),c=r.filter(({type:f})=>A.includes(["json","jsonb"],f)),l=A.map(c,"name").join(", "),u=await _.queryTolerant(y.GET_SAMPLED_DATA_SIZE(s,l),[o],!0);return F.info("Sampling table",{tableName:e,jsonColumnsNumber:c.length,samplingDataSize:u==null?void 0:u._hackolade_tmp_sampling_tbl_size}),await _.queryTolerant(y.GET_SAMPLED_DATA(s,l),[o])},async _retrieveSingleViewData(t,e,r){F.progress("Get view data",e,r),r=ph(r);let n=await _.query(y.GET_VIEW_DATA,[r,e],!0),s=!n.view_definition&&await _.queryTolerant(y.GET_VIEW_SELECT_STMT_FALLBACK,[r,e],!0),a=await _.queryTolerant(y.GET_VIEW_OPTIONS,[r,t],!0),o=hh(r,n,s),c=dh(n,a);return o?{name:r,data:c,ddl:{script:o,type:"postgres"}}:(F.info("View select statement was not retrieved",{schemaName:e,viewName:r}),{name:r,data:c,jsonSchema:{properties:[]}})},async _getServerVersion(){let t=await _.queryTolerant(y.GET_VERSION_AS_NUM,[],!0),e=A.toNumber(t==null?void 0:t.server_version_num);return e>=1e5&&e<11e4?10:e>=11e4&&e<12e4?11:e>=12e4&&e<13e4?12:e>=13e4&&e<14e4?13:(e>=14e4&&e<15e4,14)}};var _h=i(t=>!!(A.startsWith(t,"pg_")||A.includes(["information_schema"],t)),"isSystemSchema"),yh=i(t=>t===10?y.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10:y.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL,"getGetFunctionsAdditionalDataQuery"),gh=i(t=>t==null?void 0:t.obj_description,"getDescriptionFromResult"),we=i((t,e)=>Promise.all(A.map(t,e)),"mapPromises")});var{createLogger:Ke}=Yr(),w=Qi();module.exports={async disconnect(t,e,r,n){await w.disconnect(),r()},async testConnection(t,e,r,n){try{$r("Test connection",t,e);let s=Ke({title:"Test connection instance log",hiddenKeys:t.hiddenKeys,logger:e});w.setDependencies(n),await w.connect(t,s),await w.pingDb(),await w.logVersion(),r()}catch(s){e.log("error",K(s),"Test connection instance log"),r(K(s))}finally{await w.disconnect()}},async getDatabases(t,e,r,n){try{$r("Get databases",t,e);let s=Ke({title:"Get DB names",hiddenKeys:t.hiddenKeys,logger:e});w.setDependencies(n),await w.connect(t,s),await w.logVersion();let a=await w.getDatabaseNames();return e.log("info",a,"All databases list",t.hiddenKeys),r(null,a)}catch(s){return e.log("error",s),r(K(s))}},getDocumentKinds:function(t,e,r){r(null,[])},async getDbCollectionsNames(t,e,r,n){try{$r("Get DB table names",t,e);let s=Ke({title:"Get DB collections names",hiddenKeys:t.hiddenKeys,logger:e});w.setDependencies(n),await w.connect(t,s),await w.logVersion();let o=await(await w.getAllSchemasNames()).reduce(async(c,l)=>{let u=await c;try{let p=await w.getTablesNames(l);return u.concat({dbName:l,dbCollections:p,isEmpty:p.length===0})}catch(p){return s.info(`Error reading database "${l}"`),s.error(p),u.concat({dbName:l,dbCollections:[],isEmpty:!0,status:!0})}},Promise.resolve([]));r(null,o)}catch(s){e.log("error",K(s),"Get DB collections names"),r(K(s)),await w.disconnect()}},async getDbCollectionsData(t,e,r,n){try{e.log("info",t,"Retrieve tables data:",t.hiddenKeys);let s=Ke({title:"Get DB collections data log",hiddenKeys:t.hiddenKeys,logger:e});s.progress("Start reverse engineering...");let a=t.collectionData.collections,o=t.collectionData.dataBaseNames,c=await w.getDbLevelData(),{packages:l,relationships:u}=await Promise.all(o.map(async p=>{let{tables:f,views:m,modelDefinitions:E}=await w.retrieveEntitiesData(p,a[p],t.recordSamplingSettings),{functions:M,procedures:x}=await w.retrieveSchemaLevelData(p,t.ignoreUdfUdpTriggers);return s.progress("Schema data fetched successfully",p),{schemaName:p,tables:f,views:m,functions:M,procedures:x,modelDefinitions:E}})).then(p=>{let f=p.flatMap(({tables:E})=>E.map(M=>M.relationships)).flat();return{packages:p.flatMap(({schemaName:E,tables:M,views:x,functions:$e,procedures:ze,modelDefinitions:Ye})=>{let Je={UDFs:$e,Procedures:ze},Ae=M.map(k=>({dbName:E,collectionName:k.name,documents:k.documents,views:[],emptyBucket:!1,entityLevel:k.entityLevel,validation:{jsonSchema:k.jsonSchema},bucketInfo:Je,modelDefinitions:Ye})).sort(k=>n.require("lodash").isEmpty(k.entityLevel.inherits)?-1:1);if(x!=null&&x.length){let k={dbName:E,views:x,emptyBucket:!1};return[...Ae,k]}return Ae}),relationships:f}}).then(({packages:p,relationships:f})=>({packages:Eh(p),relationships:f}));s.info("The data is processed and sent to the application",{packagesLength:l==null?void 0:l.length,relationshipsLength:u==null?void 0:u.length}),r(null,l,c,u)}catch(s){e.log("error",K(s),"Retrieve tables data"),r(K(s))}finally{await w.disconnect()}}};var K=i(t=>(t=JSON.stringify(t,Object.getOwnPropertyNames(t)),t=JSON.parse(t),t),"prepareError"),$r=i((t,e,r)=>{r.clear(),r.log("info",e,"connectionInfo",e.hiddenKeys)},"logInfo"),Eh=i(t=>t.sort((e,r)=>!e.collectionName&&!r.collectionName?0:e.collectionName?r.collectionName?e.collectionName.localeCompare(r.collectionName):-1:1),"orderPackages"); diff --git a/reverse_engineering/config.json b/reverse_engineering/config.json index 469f82b..0e570f3 100644 --- a/reverse_engineering/config.json +++ b/reverse_engineering/config.json @@ -5,15 +5,8 @@ }, "defaultDdlType": "postgres", "scenario": "getDatabases", - "excludeDocKind": [ - "id" - ], - "connectionList": [ - "name", - "host", - "port", - "userName" - ], + "excludeDocKind": ["id"], + "connectionList": ["name", "host", "port", "userName"], "helpUrl": "https://hackolade.com/help/ConnecttoaCockroachDBinstance.html", "options": [ { diff --git a/reverse_engineering/connection_settings_modal/connectionSettingsModalConfig.json b/reverse_engineering/connection_settings_modal/connectionSettingsModalConfig.json index 8c21f62..e94ab0d 100644 --- a/reverse_engineering/connection_settings_modal/connectionSettingsModalConfig.json +++ b/reverse_engineering/connection_settings_modal/connectionSettingsModalConfig.json @@ -98,19 +98,10 @@ "inputKeyword": "certAuthority", "inputType": "file", "inputPlaceholder": "Certificate Authority", - "extensions": [ - "pem", - "crt", - "key" - ], + "extensions": ["pem", "crt", "key"], "dependency": { "key": "sslType", - "value": [ - "prefer", - "require", - "verify-ca", - "verify-full" - ] + "value": ["prefer", "require", "verify-ca", "verify-full"] } }, { @@ -118,19 +109,10 @@ "inputKeyword": "clientCert", "inputType": "file", "inputPlaceholder": "Client Certificate", - "extensions": [ - "pem", - "crt", - "key" - ], + "extensions": ["pem", "crt", "key"], "dependency": { "key": "sslType", - "value": [ - "prefer", - "require", - "verify-ca", - "verify-full" - ] + "value": ["prefer", "require", "verify-ca", "verify-full"] } }, { @@ -138,19 +120,10 @@ "inputKeyword": "clientPrivateKey", "inputType": "file", "inputPlaceholder": "Client Private Key", - "extensions": [ - "pem", - "crt", - "key" - ], + "extensions": ["pem", "crt", "key"], "dependency": { "key": "sslType", - "value": [ - "prefer", - "require", - "verify-ca", - "verify-full" - ] + "value": ["prefer", "require", "verify-ca", "verify-full"] } } ] @@ -221,15 +194,10 @@ "inputKeyword": "ssh_key_file", "inputType": "file", "inputPlaceholder": "Private Key", - "extensions": [ - "*" - ], + "extensions": ["*"], "dependency": { "key": "ssh_method", - "value": [ - "privateKey", - "" - ] + "value": ["privateKey", ""] }, "disable": { "key": "ssh", @@ -244,10 +212,7 @@ "isHiddenKey": true, "dependency": { "key": "ssh_method", - "value": [ - "privateKey", - "" - ] + "value": ["privateKey", ""] }, "disable": { "key": "ssh", @@ -262,10 +227,7 @@ "isHiddenKey": true, "dependency": { "key": "ssh_method", - "value": [ - "password", - "" - ] + "value": ["password", ""] }, "disable": { "key": "ssh", @@ -274,4 +236,4 @@ } ] } -] \ No newline at end of file +] diff --git a/reverse_engineering/helpers/cockroachDBHelpers/columnHelper.js b/reverse_engineering/helpers/cockroachDBHelpers/columnHelper.js deleted file mode 100644 index eb8dae0..0000000 --- a/reverse_engineering/helpers/cockroachDBHelpers/columnHelper.js +++ /dev/null @@ -1,270 +0,0 @@ -let _ = null; - -const setDependencies = app => { - _ = app.require('lodash'); -}; - -const columnPropertiesMapper = { - column_default: 'default', - is_nullable: { - keyword: 'required', - map: (column, key, value) => { - return { - YES: false, - NO: true, - }[value]; - }, - }, - not_null: 'required', - data_type: 'type', - numeric_precision: 'precision', - numeric_scale: 'scale', - datetime_precision: 'timePrecision', - attribute_mode: { - keyword: 'timePrecision', - check: (column, key, value) => value !== -1 && canHaveTimePrecision(column.data_type), - }, - interval_type: 'intervalOptions', - collation_name: 'collationRule', - column_name: 'name', - number_of_array_dimensions: 'numberOfArrayDimensions', - udt_name: 'udt_name', - character_maximum_length: { - keyword: 'length', - map: (column, key, value) => Number(value), - }, - description: 'description', -}; -const getColumnValue = (column, key, value) => { - const appropriateMapperConfig = columnPropertiesMapper[key]; - if (!appropriateMapperConfig || typeof appropriateMapperConfig === 'string') { - return value; - } - - const checkFunction = appropriateMapperConfig.check || ((column, key, value) => true); - const mapFunction = appropriateMapperConfig.map || ((column, key, value) => value); - - let resultValue = ''; - if (checkFunction(column, key, value)) { - resultValue = value; - } - - return mapFunction(column, key, resultValue); -}; - -const mapColumnData = userDefinedTypes => column => { - return _.chain(column) - .toPairs() - .map(([key, value]) => [ - columnPropertiesMapper[key]?.keyword || columnPropertiesMapper[key], - getColumnValue(column, key, value), - ]) - .filter(([key, value]) => key && !_.isNil(value)) - .fromPairs() - .thru(setColumnType(userDefinedTypes)) - .value(); -}; - -const setColumnType = userDefinedTypes => column => ({ - ...column, - ...getType(userDefinedTypes, column), -}); - -const getType = (userDefinedTypes, column) => { - if (column.type === 'ARRAY') { - return getArrayType(userDefinedTypes, column); - } - - if (column.type === 'USER-DEFINED') { - return mapType(userDefinedTypes, column.udt_name); - } - - return mapType(userDefinedTypes, column.type); -}; - -const getArrayType = (userDefinedTypes, column) => { - const typeData = mapType(userDefinedTypes, column.udt_name.slice(1)); - - return { - ...typeData, - array_type: _.fill(Array(column.numberOfArrayDimensions), ''), - }; -}; - -const mapType = (userDefinedTypes, type) => { - switch (type) { - case 'bigserial': - case 'real': - case 'double precision': - case 'smallserial': - case 'serial': - case 'money': - return { type: 'numeric', mode: type }; - case 'numeric': - case 'dec': - case 'decimal': - return { type: 'numeric', mode: 'decimal' }; - case 'int2': - case 'smallint': - return { type: 'numeric', mode: 'int2' }; - case 'int4': - case 'integer': - return { type: 'numeric', mode: 'int4' }; - case 'int': - case 'int8': - case 'int64': - case 'bigint': - return { type: 'numeric', mode: 'int' }; - case 'float4': - return { type: 'numeric', mode: 'real' }; - case 'float8': - return { type: 'numeric', mode: 'double precision' }; - case 'bit': - case 'char': - case 'text': - case 'tsvector': - case 'tsquery': - return { type: 'char', mode: type }; - case 'bit varying': - return { type: 'char', mode: 'varbit' }; - case 'character': - return { type: 'char', mode: 'char' }; - case 'character varying': - return { type: 'char', mode: 'varchar' }; - case 'bpchar': - return { type: 'char', mode: 'char' }; - case 'point': - case 'line': - case 'lseg': - case 'box': - case 'path': - case 'polygon': - case 'circle': - case 'box2d': - case 'box3d': - case 'geometry': - case 'geometry_dump': - case 'geography': - return { type: 'geometry', mode: type }; - case 'bytea': - return { type: 'binary', mode: type }; - case 'inet': - case 'cidr': - case 'macaddr': - case 'macaddr8': - return { type: 'inet', mode: type }; - case 'date': - case 'time': - case 'timestamp': - case 'interval': - return { type: 'datetime', mode: type }; - case 'timestamptz': - case 'timestamp with time zone': - return { type: 'datetime', mode: 'timestamp', timezone: 'WITH TIME ZONE' }; - case 'timestamp without time zone': - return { type: 'datetime', mode: 'timestamp', timezone: 'WITHOUT TIME ZONE' }; - case 'timetz': - case 'time with time zone': - return { type: 'datetime', mode: 'time', timezone: 'WITH TIME ZONE' }; - case 'time without time zone': - return { type: 'datetime', mode: 'time', timezone: 'WITHOUT TIME ZONE' }; - case 'json': - case 'jsonb': - return { type: 'json', mode: type, subtype: 'object' }; - case 'int4range': - case 'int8range': - case 'numrange': - case 'daterange': - case 'tsrange': - case 'tstzrange': - return { type: 'range', mode: type }; - case 'int4multirange': - case 'int8multirange': - case 'nummultirange': - case 'tsmultirange': - case 'tstzmultirange': - case 'datemultirange': - return { type: 'multirange', mode: type }; - case 'uuid': - case 'xml': - case 'boolean': - return { type }; - case 'bool': - return { type: 'boolean' }; - case 'oid': - case 'regclass': - case 'regcollation': - case 'regconfig': - case 'regdictionary': - case 'regnamespace': - case 'regoper': - case 'regoperator': - case 'regproc': - case 'regprocedure': - case 'regrole': - case 'regtype': - return { type: 'oid', mode: type }; - - default: { - if (_.some(userDefinedTypes, { name: type })) { - return { $ref: `#/definitions/${type}` }; - } - - return { type: 'char', mode: 'varchar' }; - } - } -}; - -const setSubtypeFromSampledJsonValues = (columns, documents) => { - const sampleDocument = _.first(documents) || {}; - - return columns.map(column => { - if (column.type !== 'json') { - return column; - } - - const sampleValue = sampleDocument[column.name]; - const parsedValue = safeParse(sampleValue); - const jsonType = getParsedJsonValueType(parsedValue); - - return { - ...column, - subtype: jsonType, - }; - }); -}; - -const safeParse = json => { - try { - return JSON.parse(json); - } catch (error) { - return {}; - } -}; - -const getParsedJsonValueType = value => { - if (Array.isArray(value)) { - return 'array'; - } - - const type = typeof value; - - if (type === 'undefined') { - return 'object'; - } - - return type; -}; - -const canHaveTimePrecision = columnDataType => { - return _.includes( - ['timestamp with time zone', 'timestamp without time zone', 'time with time zone', 'time without time zone'], - columnDataType, - ); -}; - -module.exports = { - setDependencies, - mapColumnData, - setSubtypeFromSampledJsonValues, -}; diff --git a/reverse_engineering/helpers/cockroachDBHelpers/common.js b/reverse_engineering/helpers/cockroachDBHelpers/common.js deleted file mode 100644 index 45c31ba..0000000 --- a/reverse_engineering/helpers/cockroachDBHelpers/common.js +++ /dev/null @@ -1,121 +0,0 @@ -const COCKROACHDB_RESERVED_WORDS = [ - 'ALL', - 'ANALYSE', - 'ANALYZE', - 'AND', - 'ANY', - 'ARRAY', - 'ASC', - 'ASYMMETRIC', - 'AUTHORIZATION', - 'BINARY', - 'BOTH', - 'CASE', - 'CAST', - 'CHECK', - 'COLLATE', - 'COLUMN', - 'CONCURRENTLY', - 'CONSTRAINT', - 'CREATE', - 'CROSS', - 'CURRENT_CATALOG', - 'CURRENT_DATE', - 'CURRENT_ROLE', - 'CURRENT_SCHEMA', - 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', - 'CURRENT_USER', - 'DEFAULT', - 'DEFERRABLE', - 'DESC', - 'DISTINCT', - 'DO', - 'ELSE', - 'END', - 'EXCEPT', - 'FALSE', - 'FOR', - 'FOREIGN', - 'FREEZE', - 'FROM', - 'FULL', - 'GRANT', - 'GROUP', - 'HAVING', - 'ILIKE', - 'IN', - 'INITIALLY', - 'INTERSECT', - 'INTO', - 'IS', - 'ISNULL', - 'JOIN', - 'LATERAL', - 'LEADING', - 'LEFT', - 'LIKE', - 'LIMIT', - 'LOCALTIME', - 'LOCALTIMESTAMP', - 'NATURAL', - 'NOT', - 'NULL', - 'OFFSET', - 'ON', - 'ONLY', - 'OR', - 'ORDER', - 'OUTER', - 'OVERLAPS', - 'PLACING', - 'PRIMARY', - 'REFERENCES', - 'RETURNING', - 'RIGHT', - 'SELECT', - 'SESSION_USER', - 'SIMILAR', - 'SOME', - 'SYMMETRIC', - 'TABLE', - 'TABLESAMPLE', - 'THEN', - 'TO', - 'TRAILING', - 'TRUE', - 'UNION', - 'UNIQUE', - 'USER', - 'USING', - 'VARIADIC', - 'VERBOSE', - 'WHEN', - 'WHERE', - 'WINDOW', - 'WITH', -]; - -let _ = null; - -const setDependencies = app => { - _ = app.require('lodash'); -}; - -const clearEmptyPropertiesInObject = obj => - _.chain(obj) - .toPairs() - .reject(([key, value]) => _.isNil(value)) - .fromPairs() - .value(); - -const getColumnNameByPosition = columns => position => _.find(columns, { ordinal_position: position })?.column_name; -const wrapInQuotes = name => - /\s|\W/.test(name) || _.includes(COCKROACHDB_RESERVED_WORDS, _.toUpper(name)) ? `"${name}"` : name; - -module.exports = { - clearEmptyPropertiesInObject, - setDependencies, - getColumnNameByPosition, - wrapInQuotes, -}; diff --git a/reverse_engineering/helpers/cockroachDBHelpers/foreignKeysHelper.js b/reverse_engineering/helpers/cockroachDBHelpers/foreignKeysHelper.js deleted file mode 100644 index 93a6cf2..0000000 --- a/reverse_engineering/helpers/cockroachDBHelpers/foreignKeysHelper.js +++ /dev/null @@ -1,60 +0,0 @@ -const { getColumnNameByPosition } = require('./common'); - -let _ = null; - -const setDependencies = app => { - _ = app.require('lodash'); -}; - -const prepareDeleteAndUpdate = value => { - switch (value) { - case 'a': - return 'NO ACTION'; - case 'r': - return 'RESTRICT'; - case 'c': - return 'CASCADE'; - case 'n': - return 'SET NULL'; - case 'd': - return 'SET DEFAULT'; - default: - return ''; - } -}; - -const prepareMatch = value => { - switch (value) { - case 'f': - return 'FULL'; - case 's': - return 'SIMPLE'; - default: - return ''; - } -}; - -const prepareForeignKeys = (tableForeignKeys, tableName, schemaName, columns) => { - return _.map(tableForeignKeys, foreignKeyData => { - return { - relationshipName: foreignKeyData.relationship_name, - dbName: foreignKeyData.foreign_table_schema, - parentCollection: foreignKeyData.foreign_table_name, - parentField: foreignKeyData.foreign_columns, - childDbName: schemaName, - childCollection: tableName, - childField: _.map(foreignKeyData.table_columns_positions, getColumnNameByPosition(columns)), - relationshipType: 'Foreign Key', - relationshipInfo: { - relationshipOnDelete: prepareDeleteAndUpdate(foreignKeyData.relationship_on_delete), - relationshipOnUpdate: prepareDeleteAndUpdate(foreignKeyData.relationship_on_update), - relationshipMatch: prepareMatch(foreignKeyData.relationship_match), - } - }; - }); -}; - -module.exports = { - setDependencies, - prepareForeignKeys, -}; diff --git a/reverse_engineering/helpers/cockroachDBHelpers/functionHelper.js b/reverse_engineering/helpers/cockroachDBHelpers/functionHelper.js deleted file mode 100644 index 212f2f8..0000000 --- a/reverse_engineering/helpers/cockroachDBHelpers/functionHelper.js +++ /dev/null @@ -1,95 +0,0 @@ -let _ = null; - -const setDependencies = app => { - _ = app.require('lodash'); -}; - -const mapFunctionArgs = args => { - return _.map(args, arg => ({ - argumentMode: arg.parameter_mode, - argumentName: arg.parameter_name, - argumentType: getArgType(arg.data_type, arg.udt_name), - defaultExpression: arg.parameter_default, - })); -}; - -const getArgType = (argType, argUdt) => { - if (argType === 'USER-DEFINED') { - return argUdt; - } - - if (argType === 'ARRAY') { - return argUdt.slice(1) + '[]'; - } - - return argType; -}; - -const getVolatility = volatility => { - switch (volatility) { - case 'i': - return 'IMMUTABLE'; - case 's': - return 'STABLE'; - case 'v': - default: - return 'VOLATILE'; - } -}; - -const getParallel = parallel => { - switch (parallel) { - case 's': - return 'SAFE'; - case 'r': - return 'RESTICTED'; - case 'u': - return 'UNSAFE'; - default: - return ''; - } -}; - -const getNullArgs = strict => { - if (strict) { - return 'STRICT'; - } - - return 'CALLED ON NULL INPUT'; -}; - -const mapFunctionData = (functionData, functionArgs, additionalData) => { - return { - name: functionData.name, - functionDescription: additionalData?.description, - functionArguments: mapFunctionArgs(functionArgs), - functionReturnsSetOf: additionalData?.returns_set, - functionReturnType: functionData.return_data_type, - functionLanguage: _.toLower(functionData.external_language), - functionBody: functionData.routine_definition ?? additionalData?.body, - functionWindow: additionalData?.kind === 'w', - functionVolatility: getVolatility(additionalData?.volatility), - functionLeakProof: additionalData?.leak_proof, - functionNullArgs: getNullArgs(additionalData?.strict), - functionSqlSecurity: functionData.security_type, - functionParallel: getParallel(functionData.parallel), - functionExecutionCost: functionData.estimated_cost, - functionExecutionRows: functionData.estimated_rows, - }; -}; - -const mapProcedureData = (functionData, functionArgs, additionalData) => { - return { - name: functionData.name, - description: additionalData?.description, - language: _.toLower(functionData.external_language), - inputArgs: mapFunctionArgs(functionArgs), - body: functionData.routine_definition, - }; -}; - -module.exports = { - setDependencies, - mapFunctionData, - mapProcedureData, -}; diff --git a/reverse_engineering/helpers/cockroachDBHelpers/partitioningHelper.js b/reverse_engineering/helpers/cockroachDBHelpers/partitioningHelper.js deleted file mode 100644 index 6ac429f..0000000 --- a/reverse_engineering/helpers/cockroachDBHelpers/partitioningHelper.js +++ /dev/null @@ -1,152 +0,0 @@ - -/** - * @return {( - * partitionResult: Array - * ) => (Array<{ - * partitionMethod: string, - * compositePartitionKey: Array, - * partitioning_expression: string, - * }> | null)} - * */ -const preparePartition = (_) => (partitionResult) => { - if (!partitionResult) { - return null; - } - - const partitionMethod = getPartitionMethod(partitionResult); - const compositePartitionKey = getCompositePartitionKey(_)(partitionResult); - const partitioning_expression = getPartitionExpression(partitionResult); - - return [ - { - partitionMethod, - compositePartitionKey, - partitioning_expression, - }, - ]; -}; - -/** - * @return {string} - */ -const getPartitionMethodByRow = (row = {}) => { - if (row.list_value) { - return 'LIST'; - } - if (row.range_value) { - return 'RANGE'; - } - return ''; -}; - -/** - * @param partitionResult {Array} - * @return {Array} - * */ -const getParentPartitionRows = (partitionResult = []) => { - return partitionResult.filter(row => !row.parent_name); -} - -/** - * @param partitionResult {Array} - * @param parentName {string | null} - * @return {Array} - * */ -const getChildPartitionRows = (partitionResult = [], parentName = null) => { - return partitionResult.filter(row => row.parent_name === parentName); -} - -/** - * @return {string} - */ -const getPartitionMethod = (partitionResult = []) => { - const parentPartitionRows = getParentPartitionRows(partitionResult); - if (!parentPartitionRows.length) { - return ''; - } - const firstRow = parentPartitionRows[0]; - return getPartitionMethodByRow(firstRow); -}; - -/** - * @return {(partitionResult: Array) => Array} - * */ -const getCompositePartitionKey = (_) => (partitionResult = []) => { - const parentPartitionRows = partitionResult.filter(row => !row.parent_name); - const columnNames = parentPartitionRows - .flatMap(row => { - const columnNames = row.column_names || ''; - return columnNames.split(',').map(name => name.trim()); - }) - return _.uniq(columnNames); -} - -/** - * @param partitionResult {Array} - * @return {string} - * */ -const getPartitionExpression = (partitionResult) => { - const parentPartitionRows = getParentPartitionRows(partitionResult); - if (!parentPartitionRows.length) { - return ''; - } - const firstRow = parentPartitionRows[0]; - const partitionMethod = getPartitionMethodByRow(firstRow); - const columnNames = firstRow.column_names || ''; - - const parentPartitions = parentPartitionRows - .map(row => getSinglePartitionExpression({ - partition: row, - paddingFactor: 1, - partitionResult - })) - .join(',\n'); - return `PARTITION BY ${partitionMethod} (${columnNames}) ( -${parentPartitions} -)` -}; - -/** - * @param partition {Object} - * @param partitionResult {Array} - * @param paddingFactor {number} - * @return {string} - * */ -const getSinglePartitionExpression = ({ - partition, - partitionResult, - paddingFactor - }) => { - const valuesClause = partition.list_value ? 'VALUES IN' : 'VALUES FROM'; - const value = partition.list_value || partition.range_value || ''; - const baseDdlPadding = '\t'.repeat(paddingFactor); - const baseDdl = `${baseDdlPadding}PARTITION ${partition.partition_name} ${valuesClause} ${value}`; - - const children = getChildPartitionRows(partitionResult, partition.partition_name); - if (children.length) { - const childPartitions = children.map(child => getSinglePartitionExpression({ - partition: child, - partitionResult, - paddingFactor: paddingFactor + 1, - })) - .join(',\n'); - - const firstChildRow = children[0]; - const partitionMethod = getPartitionMethodByRow(firstChildRow); - const columnNames = firstChildRow.column_names || ''; - return baseDdl + ` PARTITION BY ${partitionMethod} (${columnNames}) (\n` - + childPartitions + '\n' - + baseDdlPadding + ')' - } - return baseDdl; -} - -/** - * @param item {string} - * @return {Array} - * */ -const splitByEqualitySymbol = item => item ? item.split('=') : []; - -module.exports = { - preparePartition, -} diff --git a/reverse_engineering/helpers/cockroachDBHelpers/reorganizeConstraints.js b/reverse_engineering/helpers/cockroachDBHelpers/reorganizeConstraints.js deleted file mode 100644 index 2afed64..0000000 --- a/reverse_engineering/helpers/cockroachDBHelpers/reorganizeConstraints.js +++ /dev/null @@ -1,100 +0,0 @@ -const reorganizeConstraints = (attributes, entityLevel) => { - return [reorganizePrimaryKeys, reorganizeUniqueKeys].reduce( - ({ attributes, entityLevel }, reorganize) => reorganize(attributes, entityLevel), - { attributes, entityLevel }, - ); -}; - -const reorganizePrimaryKeys = (attributes, entityLevel) => { - const isSinglePrimaryKey = entityLevel.primaryKey?.[0]?.compositePrimaryKey?.length !== 1; - - if (isSinglePrimaryKey) { - return { attributes, entityLevel }; - } - - const primaryKey = entityLevel.primaryKey[0]; - const attributeName = primaryKey.compositePrimaryKey[0]; - - return { - attributes: setAttributesPrimaryKeyData(attributes, attributeName, primaryKey), - entityLevel: clearPrimaryKeys(entityLevel), - }; -}; - -const reorganizeUniqueKeys = (attributes, entityLevel) => { - return (entityLevel.uniqueKey || []).reduce( - ({ attributes, entityLevel }, uniqueKey) => { - const hasSingleUniqueKey = uniqueKey.compositeUniqueKey.length === 1; - if (!hasSingleUniqueKey) { - return { attributes, entityLevel }; - } - - const attributeName = uniqueKey.compositeUniqueKey[0]; - - return { - attributes: setAttributesUniqueKeyData(attributes, attributeName, uniqueKey), - entityLevel: filterUniqueKeys(entityLevel, uniqueKey), - }; - }, - { attributes, entityLevel }, - ); -}; - -const setAttributesPrimaryKeyData = (attributes, attributeName, primaryKey) => { - return attributes.map(attribute => { - if (attribute.name !== attributeName) { - return attribute; - } - - return setPrimaryKeyData(attribute, primaryKey); - }); -}; - -const setPrimaryKeyData = (attribute, primaryKey) => { - return { - ...attribute, - primaryKey: true, - primaryKeyOptions: getOptions(primaryKey), - }; -}; - -const setAttributesUniqueKeyData = (attributes, attributeName, uniqueKey) => { - return attributes.map(attribute => { - if (attribute.name !== attributeName) { - return attribute; - } - - return setUniqueKeyData(attribute, uniqueKey); - }); -}; - -const setUniqueKeyData = (attribute, uniqueKey) => { - return { - ...attribute, - unique: true, - uniqueKeyOptions: getOptions(uniqueKey), - }; -}; - -const getOptions = key => { - return [ - { - constraintName: key.constraintName, - indexInclude: key.indexInclude, - indexStorageParameters: key.indexStorageParameters, - indexComment: key.indexComment, - }, - ]; -}; - -const clearPrimaryKeys = entityLevel => { - return { ...entityLevel, primaryKey: [] }; -}; - -const filterUniqueKeys = (entityLevel, uniqueKey) => { - const filteredKeys = entityLevel.uniqueKey.filter(key => key.constraintName !== uniqueKey.constraintName); - - return { ...entityLevel, uniqueKey: filteredKeys }; -}; - -module.exports = { reorganizeConstraints }; diff --git a/reverse_engineering/helpers/cockroachDBHelpers/tableHelper.js b/reverse_engineering/helpers/cockroachDBHelpers/tableHelper.js deleted file mode 100644 index 35d3c0c..0000000 --- a/reverse_engineering/helpers/cockroachDBHelpers/tableHelper.js +++ /dev/null @@ -1,433 +0,0 @@ -const {clearEmptyPropertiesInObject, getColumnNameByPosition} = require('./common'); -const {preparePartition} = require("./partitioningHelper"); - -let _ = null; - -const setDependencies = app => { - _ = app.require('lodash'); -}; - -const groupTtlStorageParams = (options) => { - const result = {}; - for (const key of Object.keys(options)) { - if (key.startsWith('ttl')) { - if (!result.ttl_storage_parameters) { - result.ttl_storage_parameters = {}; - } - - result.ttl_storage_parameters[key] = options[key]; - } else { - result[key] = options[key]; - } - } - return result; -} - -const prepareStorageParameters = (reloptions, tableToastOptions) => { - if (!reloptions && !tableToastOptions) { - return null; - } - - const options = prepareOptions(reloptions); - const nonEmptyOptions = clearEmptyPropertiesInObject(options); - const optionsWithGroupedTtl = groupTtlStorageParams(nonEmptyOptions); - return clearEmptyPropertiesInObject(optionsWithGroupedTtl); -}; - -const splitByEqualitySymbol = item => _.split(item, '='); - -const checkHaveJsonTypes = columns => { - return _.find(columns, {type: 'json'}); -}; - -const getSampleDocSize = (count, recordSamplingSettings) => { - if (recordSamplingSettings.active === 'absolute') { - return Number(recordSamplingSettings.absolute.value); - } - - const limit = Math.ceil((count * recordSamplingSettings.relative.value) / 100); - - return Math.min(limit, recordSamplingSettings.maxValue); -}; - -const prepareTableConstraints = (constraintsResult, attributesWithPositions, tableIndexes) => { - return _.reduce( - constraintsResult, - (entityConstraints, constraint) => { - switch (constraint.constraint_type) { - case 'c': - return { - ...entityConstraints, - chkConstr: [...entityConstraints.chkConstr, getCheckConstraint(constraint)], - }; - case 'p': - return { - ...entityConstraints, - primaryKey: [ - ...entityConstraints.primaryKey, - getPrimaryKeyConstraint(constraint, attributesWithPositions), - ], - }; - case 'u': - return { - ...entityConstraints, - uniqueKey: [ - ...entityConstraints.uniqueKey, - getUniqueKeyConstraint(constraint, attributesWithPositions), - ], - }; - default: - return entityConstraints; - } - }, - { - chkConstr: [], - uniqueKey: [], - primaryKey: [], - }, - ); -}; - -const getPrimaryKeyConstraint = (constraint, tableColumns) => { - return { - constraintName: constraint.constraint_name, - compositePrimaryKey: _.map(constraint.constraint_keys, getColumnNameByPosition(tableColumns)), - indexStorageParameters: _.join(constraint.storage_parameters, ','), - }; -}; - -const getUniqueKeyConstraint = (constraint, tableColumns) => { - return { - constraintName: constraint.constraint_name, - compositeUniqueKey: _.map(constraint.constraint_keys, getColumnNameByPosition(tableColumns)), - indexStorageParameters: _.join(constraint.storage_parameters, ','), - indexComment: constraint.description, - }; -}; - -const getCheckConstraint = constraint => { - return { - chkConstrName: constraint.constraint_name, - constrExpression: constraint.expression, - notValid: constraint.notValid, - constrDescription: constraint.description, - }; -}; - -/** - * @return {Object} - * */ -const getIndexCreateInfoRowByName = ( - indexName, - tableIndexesCreateInfoResult = [] -) => { - const createStatementResultRow = tableIndexesCreateInfoResult - .find(result => result.index_name === indexName) || {}; - return createStatementResultRow || {}; -} - -/** - * @param method {string} - * @return {string} - * */ -const parseIndexMethod = (method) => { - switch (method.toUpperCase()){ - case 'INVERTED': - return 'gin'; - case 'PREFIX': - return 'btree'; - default: - return method; - } -} - -/** - * @param tableIndexesPartitioningResult {Array} - * @param index {Object} - * @return {Array} - * */ -const getIndexPartitioningRows = (tableIndexesPartitioningResult, index) => { - return (tableIndexesPartitioningResult || []) - .filter(row => row.index_name === index.indexname && row.index_id === index.index_id); -} - -const prepareTableIndexes = ({ - tableIndexesResult, - tableIndexesCreateInfoResult = [], - tableIndexesPartitioningResult, - }) => { - return _.map(tableIndexesResult, indexData => { - const createInfoRow = getIndexCreateInfoRowByName(indexData.indexname, tableIndexesCreateInfoResult); - const createStatement = createInfoRow.create_statement; - - const allColumns = mapIndexColumns(indexData, createStatement); - const columns = _.slice(allColumns, 0, indexData.number_of_keys); - const include = _.chain(allColumns) - .slice(indexData.number_of_keys) - .map(column => _.pick(column, 'name')) - .value(); - - const visibility = createInfoRow.is_visible ? 'VISIBLE' : 'NOT VISIBLE'; - const using_hash = Boolean(createInfoRow.is_sharded); - - const partitionRowsForCurrentIndex = getIndexPartitioningRows(tableIndexesPartitioningResult, indexData); - const partitioning = preparePartition(_)(partitionRowsForCurrentIndex) || [{}]; - const partitioning_expression = partitioning[0].partitioning_expression; - - const index = { - indxName: indexData.indexname, - index_method: parseIndexMethod(indexData.index_method), - unique: indexData.index_unique ?? false, - index_storage_parameter: getIndexStorageParameters(indexData.storage_parameters, createStatement), - where: indexData.where_expression || '', - partitioning_expression, - include, - columns, - using_hash, - visibility, - }; - - return clearEmptyPropertiesInObject(index); - }); -}; - -/** - * @param columnName {string} - * @param createStatement {string} - * @return {number} - * */ -const getIndexColumnDefinitionStart = ({createStatement, columnName}) => { - // Index column definition follows either a "(" if it is the first column - // or a "," if it is not the first column - const allowedPreviousChars = ['(', ',']; - - let indexOfColumnNamePosition = 0; - - while(indexOfColumnNamePosition < createStatement.length) { - const indexOfColumnName = createStatement.indexOf(columnName, indexOfColumnNamePosition); - if (indexOfColumnName === -1) { - return -1; - } - const previousChar = createStatement.charAt(indexOfColumnName - 1); - const nextChar = createStatement.charAt(indexOfColumnName + columnName.length); - if (nextChar.match(/\s/) && allowedPreviousChars.includes(previousChar)) { - return indexOfColumnName; - } - indexOfColumnNamePosition = indexOfColumnName + columnName.length; - } -} - -/** - * @param createStatement {string} - * @param columnDefinitionStart {number} - * @return {number} - * */ -const getColumnDefinitionEnd = ({createStatement, columnDefinitionStart}) => { - const columnDefinitionWithRestOfTheQuery = createStatement.substring(columnDefinitionStart); - const indexOfFirstComma = columnDefinitionWithRestOfTheQuery.indexOf(','); - const indexOfFirstClosedParenthesis = columnDefinitionWithRestOfTheQuery.indexOf(')'); - if (indexOfFirstComma === -1) { - return columnDefinitionStart + indexOfFirstClosedParenthesis; - } - return columnDefinitionStart + Math.min(indexOfFirstComma, indexOfFirstClosedParenthesis); -} - -/** - * @param columnName {string} - * @param createStatement {string} - * @return {string} - * */ -const getIndexColumnQueryDefinition = ({createStatement, columnName}) => { - const columnDefinitionStart = getIndexColumnDefinitionStart({ columnName, createStatement }); - if (columnDefinitionStart === -1) { - return ''; - } - const columnDefinitionEnd = getColumnDefinitionEnd({columnDefinitionStart, createStatement}); - if (columnDefinitionEnd === -1) { - return ''; - } - - return createStatement.substring(columnDefinitionStart, columnDefinitionEnd); -} - -/** - * @param indexData {Object} - * @param itemIndex {number} - * @param columnName {string} - * @param createStatement {string} - * @return {string} - * */ -const getIndexColumnOpClass = ({indexData, itemIndex, columnName, createStatement}) => { - const opclass = _.get(indexData, `opclasses.${itemIndex}`, ''); - if (opclass) { - return opclass; - } - const columnDefinition = getIndexColumnQueryDefinition({ columnName, createStatement }); - if (!columnDefinition) { - return ''; - } - - const definitionNoColumnName = columnDefinition.substring(columnName.length).trim(); - if (!definitionNoColumnName) { - return ''; - } - return definitionNoColumnName - .toUpperCase() - .replaceAll('ASC', '') - .replaceAll('DESC', '') - .replaceAll('NULLS FIRST', '') - .replaceAll('NULLS LAST', '') - .toLowerCase() - .trim(); -} - -const mapIndexColumns = (indexData, createStatement) => { - return _.chain(indexData.columns) - .map((columnName, itemIndex) => { - if (!columnName) { - return; - } - - const sortOrder = _.get(indexData, `ascendings.${itemIndex}`, 'ASC'); - const nullsOrder = _.get(indexData, `nulls_first.${itemIndex}`, 'NULLS FIRST'); - const opclass = getIndexColumnOpClass({ - columnName, - createStatement, - itemIndex, - indexData - }); - const collation = _.get(indexData, `collations.${itemIndex}`, ''); - - return { - name: columnName, - sortOrder, - nullsOrder, - opclass, - collation, - }; - }) - .compact() - .value(); -}; - -/** - * @return {Object} - */ -const hydrateIndexStorageParameters = (parameters) => { - const data = { - fillfactor: parameters.fillfactor, - bucket_count: parameters.bucket_count, - geometry_max_x: parameters.geometry_max_x, - geometry_max_y: parameters.geometry_max_y, - geometry_min_x: parameters.geometry_min_x, - geometry_min_y: parameters.geometry_min_y, - s2_level_mod: parameters.s2_level_mod, - s2_max_cells: parameters.s2_max_cells, - s2_max_level: parameters.s2_max_level, - }; - - return clearEmptyPropertiesInObject(data); -} - -/** - * @param createStatement {string} - * @return {Object | null} - * */ -const parseIndexStorageParametersFromDdl = (createStatement) => { - const storageParamsRegex = /\s+with\s+\(.*?\)/mi; - const match = createStatement.match(storageParamsRegex); - if (!match?.length) { - return null; - } - // In the form of " WITH (param1=1,param2=2)" - const rawStorageParamsClause = match[0]; - // Remove " WITH (" - const indexToSubstringFrom = " WITH (".length; - // Remove the last ")" - const indexToSubstringTo = rawStorageParamsClause.length - 1; - - const keyValuePairs = rawStorageParamsClause.substring(indexToSubstringFrom, indexToSubstringTo) - .split(',') - .map(pair => pair.trim()); - - const storageParameters = _.fromPairs(_.map(keyValuePairs, param => splitByEqualitySymbol(param))); - return hydrateIndexStorageParameters(storageParameters); -} - -/** - * @param storageParameters {Object | undefined} - * @param createStatement {string} - * @return {Object | null} - * */ -const getIndexStorageParameters = (storageParameters, createStatement) => { - if (!storageParameters) { - return parseIndexStorageParametersFromDdl(createStatement); - } - - const params = _.fromPairs(_.map(storageParameters, param => splitByEqualitySymbol(param))); - return hydrateIndexStorageParameters(params); -}; - -const prepareTableLevelData = (tableLevelData, tableToastOptions) => { - const temporary = tableLevelData?.relpersistence === 't'; - const unlogged = tableLevelData?.relpersistence === 'u'; - const storage_parameter = prepareStorageParameters(tableLevelData?.reloptions, tableToastOptions); - const partitionBounds = tableLevelData.partition_expr; - - return { - temporary, - unlogged, - storage_parameter, - partitionBounds, - }; -}; - -const convertValueToType = value => { - switch (getTypeOfValue(value)) { - case 'number': - case 'boolean': - return JSON.parse(value); - case 'string': - default: - return value; - } -}; - -const getTypeOfValue = value => { - try { - const type = typeof JSON.parse(value); - - if (type === 'object') { - return 'string'; - } - - return type; - } catch (error) { - return 'string'; - } -}; - -const prepareOptions = options => { - return ( - _.chain(options) - .map(splitByEqualitySymbol) - .map(([key, value]) => [key, convertValueToType(value)]) - .fromPairs() - .value() || {} - ); -}; - -const prepareTableInheritance = (schemaName, inheritanceResult) => { - return _.map(inheritanceResult, ({parent_table_name}) => ({parentTable: [schemaName, parent_table_name]})); -}; - -module.exports = { - prepareStorageParameters, - setDependencies, - checkHaveJsonTypes, - prepareTableConstraints, - prepareTableLevelData, - prepareTableIndexes, - getSampleDocSize, - prepareTableInheritance, -}; diff --git a/reverse_engineering/helpers/cockroachDBHelpers/userDefinedTypesHelper.js b/reverse_engineering/helpers/cockroachDBHelpers/userDefinedTypesHelper.js deleted file mode 100644 index 1741918..0000000 --- a/reverse_engineering/helpers/cockroachDBHelpers/userDefinedTypesHelper.js +++ /dev/null @@ -1,64 +0,0 @@ -const { mapColumnData } = require('./columnHelper'); - -let _ = null; - -const setDependencies = app => { - _ = app.require('lodash'); -}; - -const getUserDefinedTypes = (udtResponse) => { - return _.chain(udtResponse) - .map(typeData => { - switch (typeData.type) { - case 'e': - return getEnumType(typeData); - case 'r': - return getRangeType(typeData); - case 'c': - return getCompositeType(typeData); - default: - return null; - } - }) - .compact() - .value(); -}; - -const getEnumType = typeData => { - return { - name: typeData.name, - type: 'enum', - enum: typeData.enum_values || [], - }; -}; - -const getRangeType = typeData => { - return { - name: typeData.name, - type: 'range_udt', - rangeSubtype: typeData.range_subtype || '', - operatorClass: typeData.range_opclass_name || '', - collation: typeData.range_collation_name || '', - canonicalFunction: typeData.range_canonical_proc || '', - subtypeDiffFunction: typeData.range_diff_proc || '', - }; -}; - -const getCompositeType = typeData => { - const columns = _.map(typeData.columns, mapColumnData([])); - - return { - name: typeData.name, - type: 'composite', - properties: columns, - }; -}; - -const isTypeComposite = typeData => typeData.type === 'c'; - - -module.exports = { - setDependencies, - getUserDefinedTypes, - isTypeComposite, -}; diff --git a/reverse_engineering/helpers/cockroachDBHelpers/viewHelper.js b/reverse_engineering/helpers/cockroachDBHelpers/viewHelper.js deleted file mode 100644 index 138ca43..0000000 --- a/reverse_engineering/helpers/cockroachDBHelpers/viewHelper.js +++ /dev/null @@ -1,61 +0,0 @@ -const { clearEmptyPropertiesInObject, wrapInQuotes } = require('./common'); - -let _ = null; - -const setDependencies = app => { - _ = app.require('lodash'); -}; - -const VIEW_SUFFIX = ' (v)'; - -const isViewByTableType = table_type => table_type === 'VIEW'; -const isViewByName = name => _.endsWith(name, VIEW_SUFFIX); -const removeViewNameSuffix = name => name.slice(0, -VIEW_SUFFIX.length); -const setViewSuffix = name => `${name}${VIEW_SUFFIX}`; - -const generateCreateViewScript = (viewName, viewData, viewDefinitionFallback = {}) => { - const selectStatement = _.trim(viewData.view_definition || viewDefinitionFallback.definition || ''); - - if (!selectStatement) { - return ''; - } - - return `CREATE VIEW ${wrapInQuotes(viewName)} AS ${selectStatement}`; -}; - -const prepareViewData = (viewData, viewOptions) => { - const data = { - withCheckOption: viewData.check_option !== 'NONE' || _.isNil(viewData.check_option), - checkTestingScope: getCheckTestingScope(viewData.check_option), - viewOptions: _.fromPairs(_.map(viewOptions?.view_options, splitByEqualitySymbol)), - temporary: viewOptions?.persistence === 't', - recursive: isViewRecursive(viewData), - description: viewOptions?.description, - }; - - return clearEmptyPropertiesInObject(data); -}; - -const getCheckTestingScope = check_option => { - if (check_option === 'NONE') { - return ''; - } - - return check_option; -}; - -const isViewRecursive = viewData => { - return _.startsWith(_.trim(viewData.view_definition), 'WITH RECURSIVE'); -}; - -const splitByEqualitySymbol = item => _.split(item, '='); - -module.exports = { - setDependencies, - isViewByTableType, - isViewByName, - removeViewNameSuffix, - generateCreateViewScript, - setViewSuffix, - prepareViewData, -}; diff --git a/reverse_engineering/helpers/cockroachDBService.js b/reverse_engineering/helpers/cockroachDBService.js deleted file mode 100644 index 10fc836..0000000 --- a/reverse_engineering/helpers/cockroachDBService.js +++ /dev/null @@ -1,428 +0,0 @@ -const { createClient } = require('./connectionHelper'); -const db = require('./db'); -const { getJsonSchema } = require('./getJsonSchema'); -const { - setDependencies: setDependenciesInColumnHelper, - mapColumnData, - setSubtypeFromSampledJsonValues, -} = require('./cockroachDBHelpers/columnHelper'); -const { - setDependencies: setDependenciesInCommonHelper, - clearEmptyPropertiesInObject, -} = require('./cockroachDBHelpers/common'); -const { - setDependencies: setDependenciesInForeignKeysHelper, - prepareForeignKeys, -} = require('./cockroachDBHelpers/foreignKeysHelper'); -const { - setDependencies: setFunctionHelperDependencies, - mapFunctionData, - mapProcedureData, -} = require('./cockroachDBHelpers/functionHelper'); -const { - setDependencies: setDependenciesInTableHelper, - checkHaveJsonTypes, - prepareTableConstraints, - getSampleDocSize, - prepareTableLevelData, - prepareTableIndexes, -} = require('./cockroachDBHelpers/tableHelper'); -const { - setDependencies: setDependenciesInUserDefinedTypesHelper, - getUserDefinedTypes, - isTypeComposite, -} = require('./cockroachDBHelpers/userDefinedTypesHelper'); -const { - setDependencies: setViewDependenciesInViewHelper, - isViewByTableType, - isViewByName, - removeViewNameSuffix, - generateCreateViewScript, - setViewSuffix, - prepareViewData, -} = require('./cockroachDBHelpers/viewHelper'); -const queryConstants = require('./queryConstants'); -const { reorganizeConstraints } = require('./cockroachDBHelpers/reorganizeConstraints'); - -let currentSshTunnel = null; -let _ = null; -let logger = null; -let version = 14; - -module.exports = { - setDependencies(app) { - _ = app.require('lodash'); - setDependenciesInCommonHelper(app); - setDependenciesInTableHelper(app); - setDependenciesInColumnHelper(app); - setDependenciesInForeignKeysHelper(app); - setViewDependenciesInViewHelper(app); - setFunctionHelperDependencies(app); - setDependenciesInUserDefinedTypesHelper(app); - }, - - async connect(connectionInfo, specificLogger) { - if (db.isClientInitialized()) { - await this.disconnect(); - } - - const { client, sshTunnel } = await createClient(connectionInfo, specificLogger); - - db.initializeClient(client, specificLogger); - currentSshTunnel = sshTunnel; - logger = specificLogger; - version = await this._getServerVersion(); - }, - - async disconnect() { - if (currentSshTunnel) { - currentSshTunnel.close(); - currentSshTunnel = null; - } - - await db.releaseClient(); - }, - - pingDb() { - return db.query(queryConstants.PING); - }, - - applyScript(script) { - return db.query(script); - }, - - async getDatabaseNames() { - return _.map(await db.query(queryConstants.GET_DATABASES), 'database_name'); - }, - - async logVersion() { - const versionRow = await db.queryTolerant(queryConstants.GET_VERSION, [], true); - const version = versionRow?.version || 'Version not retrieved'; - - // logger.info(`CockroachDB version: ${version}`); - }, - - async getAllSchemasNames() { - const schemaNames = await db.query(queryConstants.GET_SCHEMA_NAMES); - - return schemaNames.map(({ schema_name }) => schema_name).filter(schemaName => !isSystemSchema(schemaName)); - }, - - async getTablesNames(schemaName) { - const tables = await db.query(queryConstants.GET_TABLE_NAMES, [schemaName]); - - const tableTypesToExclude = ['FOREIGN TABLE']; - - return tables - .filter(({ table_type }) => !_.includes(tableTypesToExclude, table_type)) - .map(({ table_name, table_type }) => { - if (isViewByTableType(table_type)) { - return setViewSuffix(table_name); - } else { - return table_name; - } - }); - }, - - async getDbLevelData() { - logger.progress('Get database data'); - - const database_name = (await db.queryTolerant(queryConstants.GET_DB_NAME, [], true))?.current_database; - const encoding = (await db.queryTolerant(queryConstants.GET_DB_ENCODING, [], true))?.server_encoding; - const LC_COLLATE = (await db.queryTolerant(queryConstants.GET_DB_COLLATE_NAME, [], true))?.default_collate_name; - - return clearEmptyPropertiesInObject({ - database_name, - encoding, - LC_COLLATE, - LC_CTYPE: LC_COLLATE, - }); - }, - - async retrieveEntitiesData( - schemaName, - entitiesNames, - recordSamplingSettings, - ) { - const userDefinedTypes = await this._retrieveUserDefinedTypes(schemaName); - const schemaOidResult = await db.queryTolerant(queryConstants.GET_NAMESPACE_OID, [schemaName], true); - const schemaOid = schemaOidResult?.oid; - - const [viewsNames, tablesNames] = _.partition(entitiesNames, isViewByName); - - const allTablesList = tablesNames.map(tableName => ({ tableName })); - - const tables = await mapPromises( - _.uniq(allTablesList), - _.bind( - this._retrieveSingleTableData, - this, - recordSamplingSettings, - schemaOid, - schemaName, - userDefinedTypes, - ), - ); - - const views = await mapPromises( - viewsNames, - _.bind(this._retrieveSingleViewData, this, schemaOid, schemaName), - ); - - return { views, tables, modelDefinitions: getJsonSchema(userDefinedTypes) }; - }, - - async retrieveSchemaLevelData(schemaName, ignoreUdfUdpTriggers) { - if (ignoreUdfUdpTriggers) { - logger.info('Functions and procedures ignored'); - - return { functions: [], procedures: [] }; - } - - logger.progress('Get Functions and Procedures', schemaName); - - const schemaOid = (await db.queryTolerant(queryConstants.GET_NAMESPACE_OID, [schemaName], true))?.oid; - - const functionsWithProcedures = await db.queryTolerant(queryConstants.GET_FUNCTIONS_WITH_PROCEDURES, [ - schemaName, - ]); - const functionAdditionalData = await db.queryTolerant(getGetFunctionsAdditionalDataQuery(version), [schemaOid]); - const [functions, procedures] = _.partition(_.filter(functionsWithProcedures, 'routine_type'), { - routine_type: 'FUNCTION', - }); - - const userDefinedFunctions = await mapPromises(functions, async functionData => { - const functionArgs = await db.queryTolerant(queryConstants.GET_FUNCTIONS_WITH_PROCEDURES_ARGS, [ - functionData.specific_name, - ]); - const additionalData = _.find(functionAdditionalData, { function_name: functionData.name }); - - return mapFunctionData(functionData, functionArgs, additionalData); - }); - - const userDefinedProcedures = await mapPromises(procedures, async functionData => { - const functionArgs = await db.queryTolerant(queryConstants.GET_FUNCTIONS_WITH_PROCEDURES_ARGS, [ - functionData.specific_name, - ]); - const additionalData = _.find(functionAdditionalData, { function_name: functionData.name }); - - return mapProcedureData(functionData, functionArgs, additionalData); - }); - - return { functions: userDefinedFunctions, procedures: userDefinedProcedures }; - }, - - async _retrieveUserDefinedTypes(schemaName) { - logger.progress('Get User-Defined Types', schemaName); - - const userDefinedTypes = await db.queryTolerant(queryConstants.GET_USER_DEFINED_TYPES, [schemaName]); - - const udtsWithColumns = await mapPromises(userDefinedTypes, async typeData => { - if (isTypeComposite(typeData)) { - return { - ...typeData, - columns: await db.queryTolerant(queryConstants.GET_COMPOSITE_TYPE_COLUMNS, [typeData.pg_class_oid]), - }; - } - - return typeData; - }); - - return getUserDefinedTypes(udtsWithColumns); - }, - - async _retrieveSingleTableData( - recordSamplingSettings, - schemaOid, - schemaName, - userDefinedTypes, - { tableName }, - ) { - logger.progress('Get table data', schemaName, tableName); - - const tableLevelData = await db.queryTolerant( - queryConstants.GET_TABLE_LEVEL_DATA, - [tableName, schemaOid], - true, - ); - const tableOid = tableLevelData?.oid; - - const tableToastOptions = await db.queryTolerant( - queryConstants.GET_TABLE_TOAST_OPTIONS, - [tableName, schemaOid], - true, - ); - const tableColumns = await this._getTableColumns(tableName, schemaName, tableOid); - const tableCommentsCatalog = 'pg_class'; - const descriptionResult = await db.queryTolerant(queryConstants.GET_DESCRIPTION_BY_OID, [tableOid, tableCommentsCatalog], true); - const tableConstraintsResult = await db.queryTolerant(queryConstants.GET_TABLE_CONSTRAINTS, [tableOid]); - const tableIndexesResult = await db.queryTolerant(queryConstants.GET_TABLE_INDEXES, [tableOid]); - const tableIndexesPartitioningResult = await db.queryTolerant(queryConstants.GET_TABLE_INDEX_PARTITIONING_DATA, [tableOid]); - const tableIndexesCreateInfoResult = await db.queryTolerant(queryConstants.GET_TABLE_INDEX_CREATE_INFO, [tableOid]); - const tableForeignKeys = await db.queryTolerant(queryConstants.GET_TABLE_FOREIGN_KEYS, [tableOid]); - - logger.info('Table data retrieved', { - schemaName, - tableName, - columnTypes: tableColumns.map(column => column.data_type), - }); - - const tableLevelProperties = prepareTableLevelData(tableLevelData, tableToastOptions); - const description = getDescriptionFromResult(descriptionResult); - const tableConstraint = prepareTableConstraints(tableConstraintsResult, tableColumns, tableIndexesResult); - const tableIndexes = prepareTableIndexes({ - tableIndexesResult, - tableIndexesCreateInfoResult, - tableIndexesPartitioningResult, - }); - const relationships = prepareForeignKeys(tableForeignKeys, tableName, schemaName, tableColumns); - - const tableData = { - description, - Indxs: tableIndexes, - ...tableLevelProperties, - ...tableConstraint, - }; - - const entityLevel = clearEmptyPropertiesInObject(tableData); - - let targetAttributes = tableColumns.map(mapColumnData(userDefinedTypes)); - - const hasJsonTypes = checkHaveJsonTypes(targetAttributes); - let documents = []; - - if (hasJsonTypes) { - documents = await this._getDocuments(schemaName, tableName, targetAttributes, recordSamplingSettings); - targetAttributes = setSubtypeFromSampledJsonValues(targetAttributes, documents); - } - - const { attributes, entityLevel: updatedEntityLevel } = reorganizeConstraints(targetAttributes, entityLevel); - - return { - name: tableName, - entityLevel: updatedEntityLevel, - jsonSchema: getJsonSchema(attributes), - documents, - relationships, - }; - }, - - async _getTableColumns(tableName, schemaName, tableOid) { - logger.progress('Get columns', schemaName, tableName); - - const tableColumns = await db.query(queryConstants.GET_TABLE_COLUMNS, [tableName, schemaName]); - const tableColumnsAdditionalData = await db.queryTolerant(queryConstants.GET_TABLE_COLUMNS_ADDITIONAL_DATA, [ - tableOid, - ]); - - return _.map(tableColumns, columnData => { - return { - ...columnData, - ordinal_position: Number(columnData.ordinal_position), - ...(_.find(tableColumnsAdditionalData, { name: columnData.column_name }) || {}), - }; - }); - }, - - async _getDocuments(schemaName, tableName, attributes, recordSamplingSettings) { - logger.progress('Sampling table', schemaName, tableName); - - const fullTableName = `${schemaName}.${tableName}`; - const quantity = - (await db.queryTolerant(queryConstants.GET_ROWS_COUNT(fullTableName), [], true))?.quantity || 0; - const limit = getSampleDocSize(quantity, recordSamplingSettings); - - const jsonColumns = attributes.filter(({ type }) => _.includes(['json', 'jsonb'], type)); - - const jsonColumnsString = _.map(jsonColumns, 'name').join(', '); - - const samplingDataSize = await db.queryTolerant( - queryConstants.GET_SAMPLED_DATA_SIZE(fullTableName, jsonColumnsString), - [limit], - true, - ); - - logger.info('Sampling table', { - tableName, - jsonColumnsNumber: jsonColumns.length, - samplingDataSize: samplingDataSize?._hackolade_tmp_sampling_tbl_size, - }); - - return await db.queryTolerant(queryConstants.GET_SAMPLED_DATA(fullTableName, jsonColumnsString), [limit]); - }, - - async _retrieveSingleViewData(schemaOid, schemaName, viewName) { - logger.progress('Get view data', schemaName, viewName); - - viewName = removeViewNameSuffix(viewName); - - const viewData = await db.query(queryConstants.GET_VIEW_DATA, [viewName, schemaName], true); - const viewDefinitionFallback = - !viewData.view_definition && - (await db.queryTolerant(queryConstants.GET_VIEW_SELECT_STMT_FALLBACK, [viewName, schemaName], true)); - const viewOptions = await db.queryTolerant(queryConstants.GET_VIEW_OPTIONS, [viewName, schemaOid], true); - - const script = generateCreateViewScript(viewName, viewData, viewDefinitionFallback); - const data = prepareViewData(viewData, viewOptions); - - if (!script) { - logger.info('View select statement was not retrieved', { schemaName, viewName }); - - return { - name: viewName, - data, - jsonSchema: { properties: [] }, - }; - } - - return { - name: viewName, - data, - ddl: { - script, - type: 'postgres', - }, - }; - }, - - async _getServerVersion() { - const result = await db.queryTolerant(queryConstants.GET_VERSION_AS_NUM, [], true); - const serverVersionNum = _.toNumber(result?.server_version_num); - - if (serverVersionNum >= 100000 && serverVersionNum < 110000) { - return 10; - } else if (serverVersionNum >= 110000 && serverVersionNum < 120000) { - return 11; - } else if (serverVersionNum >= 120000 && serverVersionNum < 130000) { - return 12; - } else if (serverVersionNum >= 130000 && serverVersionNum < 140000) { - return 13; - } else if (serverVersionNum >= 140000 && serverVersionNum < 150000) { - return 14; - } - - return 14; - }, -}; - -const isSystemSchema = schema_name => { - if (_.startsWith(schema_name, 'pg_')) { - return true; - } - - if (_.includes(['information_schema'], schema_name)) { - return true; - } - - return false; -}; - -const getGetFunctionsAdditionalDataQuery = postgreVersion => { - return postgreVersion === 10 - ? queryConstants.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10 - : queryConstants.GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL; -}; - -const getDescriptionFromResult = result => result?.obj_description; - -const mapPromises = (items, asyncFunc) => Promise.all(_.map(items, asyncFunc)); diff --git a/reverse_engineering/helpers/connectionHelper.js b/reverse_engineering/helpers/connectionHelper.js deleted file mode 100644 index 397253e..0000000 --- a/reverse_engineering/helpers/connectionHelper.js +++ /dev/null @@ -1,188 +0,0 @@ -const fs = require('fs'); -const ssh = require('tunnel-ssh'); -const pg = require('pg'); - -const SSL_NOT_SUPPORTED_MESSAGE = 'The server does not support SSL connections'; -const COCKROACHDB_SSL_REQUIRED_ERROR_CODE = '28000'; - -const getSshConfig = info => { - const config = { - username: info.ssh_user, - host: info.ssh_host, - port: info.ssh_port, - dstHost: info.host, - dstPort: info.port, - localHost: '127.0.0.1', - localPort: info.port, - keepAlive: true, - }; - - if (info.ssh_method === 'privateKey') { - return Object.assign({}, config, { - privateKey: fs.readFileSync(info.ssh_key_file), - passphrase: info.ssh_key_passphrase, - }); - } else { - return Object.assign({}, config, { - password: info.ssh_password, - }); - } -}; - -const connectViaSsh = info => - new Promise((resolve, reject) => { - ssh(getSshConfig(info), (err, tunnel) => { - if (err) { - reject(err); - } else { - resolve({ - tunnel, - info: Object.assign({}, info, { - host: '127.0.0.1', - }), - }); - } - }); - }); - -const getSslOptions = (connectionInfo, logger) => { - const sslType = connectionInfo.sslType; - - if (!sslType || sslType === 'disable' || sslType === 'allow') { - return false; - } - - if (['require', 'prefer'].includes(sslType) && !connectionInfo.certAuthority) { - return { - rejectUnauthorized: false, - }; - } - - let sslOptions = { - checkServerIdentity(hostname, cert) { - logger.info('Certificate', { - hostname, - cert: { - subject: cert.subject, - issuer: cert.issuer, - valid_from: cert.valid_from, - valid_to: cert.valid_to, - }, - }); - }, - }; - - if (fs.existsSync(connectionInfo.certAuthority)) { - sslOptions.ca = fs.readFileSync(connectionInfo.certAuthority).toString(); - } - - if (fs.existsSync(connectionInfo.clientCert)) { - sslOptions.cert = fs.readFileSync(connectionInfo.clientCert).toString(); - } - - if (fs.existsSync(connectionInfo.clientPrivateKey)) { - sslOptions.key = fs.readFileSync(connectionInfo.clientPrivateKey).toString(); - } - - return sslOptions; -}; - -const mapSslType = sslType => { - const oldToNewSslType = { - Off: 'disable', - TRUST_ALL_CERTIFICATES: 'allow', - TRUST_CUSTOM_CA_SIGNED_CERTIFICATES: 'prefer', - TRUST_SERVER_CLIENT_CERTIFICATES: 'verify-full', - }; - - return oldToNewSslType[sslType] || sslType; -}; - -const createClient = async (connectionInfo, logger) => { - let sshTunnel = null; - - if (connectionInfo.ssh) { - const { info, tunnel } = await connectViaSsh(connectionInfo); - sshTunnel = tunnel; - connectionInfo = info; - } - - connectionInfo = Object.assign({}, connectionInfo, { sslType: mapSslType(connectionInfo.sslType) }); - - const config = { - host: connectionInfo.host, - user: connectionInfo.userName, - password: connectionInfo.userPassword, - port: connectionInfo.port, - keepAlive: true, - ssl: getSslOptions(connectionInfo, logger), - connectionTimeoutMillis: Number(connectionInfo.queryRequestTimeout) || 60000, - query_timeout: Number(connectionInfo.queryRequestTimeout) || 60000, - statement_timeout: Number(connectionInfo.queryRequestTimeout) || 60000, - database: connectionInfo.database || connectionInfo.maintenanceDatabase, - application_name: 'Hackolade', - idleTimeoutMillis: Number(connectionInfo.queryRequestTimeout) || 10000, - sslType: connectionInfo.sslType, - }; - - const client = await createConnectionPool(config, logger); - - return { client, sshTunnel }; -}; - -const retryOnSslError = (config, logger, error) => { - if (error.message === SSL_NOT_SUPPORTED_MESSAGE && config.sslType === 'prefer') { - logger.info("Retry connection without SSL (SSL mode 'prefer')"); - logger.error(error); - - return createConnectionPool( - { - ...config, - isRetry: true, - ssl: false, - }, - logger, - ); - } - - if (error.code?.toString() === COCKROACHDB_SSL_REQUIRED_ERROR_CODE && config.sslType === 'allow') { - logger.info("Retry connection with SSL (SSL mode 'allow')"); - logger.error(error); - - return createConnectionPool( - { - ...config, - isRetry: true, - ssl: { rejectUnauthorized: false }, - }, - logger, - ); - } - - throw error; -}; - -const createConnectionPool = (config, logger) => { - const pool = new pg.Pool(config); - - return pool - .connect() - .then(client => { - client.release(); - - return pool; - }) - .catch(async error => { - await pool.end(); - - if (config.isRetry) { - throw error; - } - - return retryOnSslError(config, logger, error); - }); -}; - -module.exports = { - createClient, -}; diff --git a/reverse_engineering/helpers/db.js b/reverse_engineering/helpers/db.js deleted file mode 100644 index be4ebd7..0000000 --- a/reverse_engineering/helpers/db.js +++ /dev/null @@ -1,59 +0,0 @@ -const queryConstants = require('./queryConstants'); - -let client = null; -let logger = null; - -module.exports = { - initializeClient(newClient, newLogger) { - client = newClient; - logger = newLogger; - - client.on('error', error => newLogger.error(error)); - }, - - isClientInitialized() { - return Boolean(client); - }, - - releaseClient() { - if (client) { - return new Promise(resolve => { - client.end(() => { - client = null; - resolve(); - }); - }); - } - - return Promise.resolve(); - }, - - async query(query, params, firstRow = false) { - const queryName = queryConstants.getQueryName(query); - - logger.info('Execute query', { queryName, params }); - - const start = Date.now(); - const result = await client.query(query, params); - const duration = Date.now() - start; - - logger.info('Query executed', { queryName, params, duration, rowsCount: result.rowCount }); - - const rows = result.rows || []; - - return firstRow ? rows[0] : rows; - }, - - async queryTolerant(query, params, firstRow = false) { - try { - return await this.query(query, params, firstRow); - } catch (error) { - error.query = query; - error.params = params; - - logger.error(error); - - return null; - } - }, -}; diff --git a/reverse_engineering/helpers/getJsonSchema.js b/reverse_engineering/helpers/getJsonSchema.js deleted file mode 100644 index 1d3fbc3..0000000 --- a/reverse_engineering/helpers/getJsonSchema.js +++ /dev/null @@ -1,28 +0,0 @@ -const getJsonSchema = columns => { - const properties = columns.reduce((properties, column) => { - if (column.properties) { - return { - ...properties, - [column.name]: { - ...column, - ...getJsonSchema(column.properties), - }, - }; - } - - return { - ...properties, - [column.name]: column, - }; - }, {}); - - const required = Object.entries(properties) - .filter(([filedName, field]) => field.required) - .map(([fieldName]) => fieldName); - - return { properties, required }; -}; - -module.exports = { - getJsonSchema, -}; diff --git a/reverse_engineering/helpers/loggerHelper.js b/reverse_engineering/helpers/loggerHelper.js deleted file mode 100644 index e487736..0000000 --- a/reverse_engineering/helpers/loggerHelper.js +++ /dev/null @@ -1,25 +0,0 @@ -const createLogger = ({ title, logger, hiddenKeys }) => { - return { - info(message, additionalData = {}) { - logger.log('info', { message, ...additionalData }, title, hiddenKeys); - }, - - progress(message, dbName = '', tableName = '') { - logger.progress({ message, containerName: dbName, entityName: tableName }); - }, - - error(error) { - logger.log('error', prepareError(error), title); - }, - }; -}; - -const prepareError = error => { - error = JSON.stringify(error, Object.getOwnPropertyNames(error)); - error = JSON.parse(error); - return error; -}; - -module.exports = { - createLogger, -}; diff --git a/reverse_engineering/helpers/queryConstants.js b/reverse_engineering/helpers/queryConstants.js deleted file mode 100644 index 6effffc..0000000 --- a/reverse_engineering/helpers/queryConstants.js +++ /dev/null @@ -1,324 +0,0 @@ - -const getGET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL = postgresVersion => { - const kindQuery = - postgresVersion === 10 ? `CASE WHEN proiswindow is true THEN 'w' ELSE '' END AS kind` : 'prokind AS kind'; - - return ` - SELECT obj_description(oid, 'pg_proc') AS description, - proname AS function_name, - provolatile AS volatility, - proparallel AS parallel, - proisstrict AS strict, - proretset AS returns_set, - proleakproof AS leak_proof, - procost AS estimated_cost, - prorows AS estimated_rows, - prosrc AS body, - ${kindQuery} - FROM pg_catalog.pg_proc WHERE pronamespace = $1;`; -}; - -const queryConstants = { - PING: 'SELECT schema_name FROM information_schema.schemata LIMIT 1;', - - GET_VERSION: 'SELECT version()', - - GET_VERSION_AS_NUM: 'SHOW server_version_num;', - - GET_SCHEMA_NAMES: 'SELECT schema_name FROM information_schema.schemata;', - - GET_TABLE_NAMES: ` - SELECT tables.table_name, tables.table_type - FROM information_schema.tables AS tables - INNER JOIN ( - SELECT pg_class.relname AS table_name, - pg_namespace.nspname AS table_schema - FROM pg_catalog.pg_class AS pg_class - INNER JOIN pg_catalog.pg_namespace AS pg_namespace - ON (pg_namespace.oid = pg_class.relnamespace) - WHERE (pg_class.relispartition = false OR pg_class.relispartition IS NULL) AND pg_class.relkind = ANY ('{"r","v","t","m","p"}') - ) AS catalog_table_data - ON (catalog_table_data.table_name = tables.table_name AND catalog_table_data.table_schema = tables.table_schema) - WHERE tables.table_schema = $1; - `, - - GET_NAMESPACE_OID: 'SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = $1', - - GET_TABLE_LEVEL_DATA: ` - SELECT pc.oid, pc.relpersistence, pc.reloptions, pg_get_expr(pc.relpartbound, pc.oid) AS partition_expr - FROM pg_catalog.pg_class AS pc - WHERE pc.relname = $1 AND pc.relnamespace = $2;`, - - GET_TABLE_TOAST_OPTIONS: ` - SELECT reloptions AS toast_options - FROM pg_catalog.pg_class - WHERE oid = - (SELECT reltoastrelid - FROM pg_catalog.pg_class - WHERE relname=$1 AND relnamespace = $2 - LIMIT 1)`, - - GET_TABLE_COLUMNS: ` - SELECT * FROM information_schema.columns - WHERE table_name = $1 AND table_schema = $2 - ORDER BY ordinal_position`, - - GET_TABLE_COLUMNS_ADDITIONAL_DATA: ` - SELECT pg_attribute.attname AS name, - pg_attribute.attndims AS number_of_array_dimensions, - pg_description.description, - pg_attribute.atttypmod AS attribute_mode - FROM pg_catalog.pg_attribute AS pg_attribute - LEFT JOIN pg_catalog.pg_description AS pg_description ON (pg_description.objsubid=pg_attribute.attnum - AND pg_description.objoid = pg_attribute.attrelid) - WHERE pg_attribute.attrelid = $1;`, - - GET_DESCRIPTION_BY_OID: `SELECT obj_description($1, $2)`, - - GET_ROWS_COUNT: fullTableName => `SELECT COUNT(*) AS quantity FROM ${fullTableName};`, - - GET_SAMPLED_DATA: (fullTableName, jsonColumns) => `SELECT ${jsonColumns} FROM ${fullTableName} LIMIT $1;`, - - GET_SAMPLED_DATA_SIZE: (fullTableName, jsonColumns) => ` - SELECT sum(pg_column_size(_hackolade_tmp_sampling_tbl.*)) AS _hackolade_tmp_sampling_tbl_size - FROM (SELECT ${jsonColumns} FROM ${fullTableName} LIMIT $1) AS _hackolade_tmp_sampling_tbl;`, - - GET_TABLE_CONSTRAINTS: ` - SELECT pcon.conname AS constraint_name, - pcon.contype AS constraint_type, - pcon.conkey AS constraint_keys, - pg_catalog.pg_get_expr(pcon.conbin, pcon.conrelid) AS expression, - obj_description(pcon.oid, 'pg_constraint') AS description, - pc.reloptions AS storage_parameters - FROM pg_catalog.pg_constraint AS pcon - LEFT JOIN pg_catalog.pg_class AS pc - ON pcon.conindid = pc.oid - WHERE pcon.conrelid = $1;`, - - GET_TABLE_INDEXES: ` - SELECT indexname, - index_id, - index_method, - index_unique, - number_of_keys, - where_expression, - array_agg(attname ORDER BY ord)::text[] AS columns, - array_agg(coll ORDER BY ord) AS collations, - array_agg(opclass ORDER BY ord) AS opclasses, - array_agg(expression ORDER BY ord) AS expressions, - array_agg(ascending ORDER BY ord) AS ascendings, - array_agg(nulls_first ORDER BY ord) AS nulls_first, - reloptions AS storage_parameters - FROM ( - SELECT ct.oid AS table_oid, - c.relname AS indexname, - m.amname AS index_method, - indexes.indisunique AS index_unique, - indexes.ord, - attribute.attname, - c.reloptions, - indexes.indnkeyatts AS number_of_keys, - ti.index_id AS index_id, - pg_catalog.pg_get_expr(indpred, indrelid) AS where_expression, - CASE - WHEN collation_namespace.nspname is not null THEN format('%I.%I',collation_namespace.nspname,collation_t.collname) - END AS coll, - CASE - WHEN opclass_t.opcname is not null THEN format('%I.%I',opclas_namespace.nspname,opclass_t.opcname) - END AS opclass, - CASE - WHEN NOT m.amcanorder THEN '' - WHEN indexes.indoption[indexes.ord - 1] & 1 = 1 THEN 'DESC' ELSE 'ASC' - END AS ascending, - CASE - WHEN NOT m.amcanorder THEN '' - WHEN indexes.indoption[indexes.ord - 1] & 2 = 2 THEN 'NULLS FIRST' ELSE 'NULLS LAST' - END AS nulls_first, - pg_catalog.pg_get_indexdef(indexes.indexrelid, ord, false) AS expression - FROM - ( - SELECT *, - generate_series(1,array_length(i.indkey,1)) AS ord, - unnest(i.indkey) AS key, - unnest(i.indcollation) AS coll, - unnest(i.indclass) AS class, - unnest(i.indoption) AS option - FROM pg_catalog.pg_index i - ) indexes - JOIN pg_catalog.pg_class c ON (c.oid=indexes.indexrelid) - JOIN pg_catalog.pg_class ct ON (ct.oid=indexes.indrelid) - JOIN pg_catalog.pg_am m ON (m.oid=c.relam) - LEFT JOIN pg_catalog.pg_attribute attribute - ON (attribute.attrelid=indexes.indrelid AND attribute.attnum=indexes.key) - LEFT JOIN pg_catalog.pg_collation collation_t ON (collation_t.oid=indexes.coll) - LEFT JOIN pg_catalog.pg_namespace collation_namespace ON (collation_namespace.oid=collation_t.collnamespace) - LEFT JOIN pg_catalog.pg_opclass opclass_t ON (opclass_t.oid=indexes.class) - LEFT JOIN pg_catalog.pg_namespace opclas_namespace ON (opclas_namespace.oid=opclass_t.opcnamespace) - INNER JOIN crdb_internal.table_indexes ti ON ( - indexes.indrelid = ti.descriptor_id - AND c.relname = ti.index_name - ) - ) s2 - WHERE table_oid = $1 - GROUP BY - indexname, - index_id, - index_method, - index_unique, - reloptions, - number_of_keys, - where_expression; - `, - - GET_TABLE_INDEX_PARTITIONING_DATA: ` - SELECT - partitions.name AS partition_name, - partitions.index_id, - parent_name, - column_names, - list_value, - range_value, - index_name - FROM crdb_internal.partitions - INNER JOIN crdb_internal.table_indexes - ON partitions.table_id = table_indexes.descriptor_id - AND partitions.index_id = table_indexes.index_id - WHERE table_indexes.descriptor_id = $1; - `, - - GET_TABLE_INDEX_CREATE_INFO: ` - SELECT index_name, - is_sharded, - is_visible, - create_statement - FROM crdb_internal.table_indexes WHERE descriptor_id = $1; - `, - - GET_TABLE_FOREIGN_KEYS: ` - SELECT pcon.conname AS relationship_name, - pcon.conkey AS table_columns_positions, - pcon.confdeltype AS relationship_on_delete, - pcon.confupdtype AS relationship_on_update, - pcon.confmatchtype AS relationship_match, - pc_foreign_table.relname AS foreign_table_name, - ARRAY( - SELECT column_name::text FROM unnest(pcon.confkey) AS column_position - JOIN information_schema.columns ON (ordinal_position = column_position) - WHERE table_name = pc_foreign_table.relname AND table_schema = foreign_table_namespace.nspname)::text[] AS foreign_columns, - foreign_table_namespace.nspname AS foreign_table_schema - FROM pg_catalog.pg_constraint AS pcon - LEFT JOIN pg_catalog.pg_class AS pc ON pcon.conindid = pc.oid - LEFT JOIN pg_catalog.pg_class AS pc_foreign_table ON (pcon.confrelid = pc_foreign_table.oid) - JOIN pg_catalog.pg_namespace AS foreign_table_namespace ON (pc_foreign_table.relnamespace = foreign_table_namespace.oid) - WHERE pcon.conrelid = $1 AND pcon.contype = 'f';`, - - GET_VIEW_DATA: `SELECT * FROM information_schema.views WHERE table_name = $1 AND table_schema = $2;`, - - GET_VIEW_SELECT_STMT_FALLBACK: `SELECT definition FROM pg_views WHERE viewname = $1 AND schemaname = $2;`, - - GET_VIEW_OPTIONS: ` - SELECT oid, - reloptions AS view_options, - relpersistence AS persistence, - obj_description(oid, 'pg_class') AS description - FROM pg_catalog.pg_class - WHERE relname = $1 AND relnamespace = $2;`, - - GET_FUNCTIONS_WITH_PROCEDURES: ` - SELECT specific_name, - routine_name AS name, - routine_type, - routine_definition, - external_language, - security_type, - type_udt_name AS return_data_type - FROM information_schema.routines - WHERE specific_schema=$1;`, - - GET_FUNCTIONS_WITH_PROCEDURES_ARGS: ` - SELECT parameter_name, - parameter_mode, - parameter_default, - data_type, - udt_name - FROM information_schema.parameters - WHERE specific_name = $1 - ORDER BY ordinal_position;`, - - GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL: getGET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL(), - - GET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL_V_10: getGET_FUNCTIONS_WITH_PROCEDURES_ADDITIONAL(10), - - GET_USER_DEFINED_TYPES: ` - SELECT pg_type.typrelid AS pg_class_oid, - pg_type.typname AS name, - pg_type.typtype AS type, - pg_catalog.array_agg(pg_enum.enumlabel)::text[] AS enum_values, - range_subtype_type.typname AS range_subtype, - range_collation.collname AS range_collation_name, - range_opclass.opcname AS range_opclass_name, - range_canonical_proc.proname AS range_canonical_proc, - range_diff_proc.proname AS range_diff_proc - FROM pg_catalog.pg_type AS pg_type - LEFT JOIN pg_catalog.pg_class AS pg_class ON (pg_class.oid = pg_type.typrelid) - LEFT JOIN pg_catalog.pg_namespace AS pg_namespace ON (pg_namespace.oid = pg_type.typnamespace) - LEFT JOIN pg_catalog.pg_enum AS pg_enum ON (pg_enum.enumtypid = pg_type.oid) - LEFT JOIN pg_catalog.pg_range AS pg_range ON (pg_range.rngtypid = pg_type.oid) - LEFT JOIN pg_catalog.pg_type AS range_subtype_type ON (range_subtype_type.oid = pg_range.rngsubtype) - LEFT JOIN pg_catalog.pg_collation AS range_collation ON (range_collation.oid = pg_range.rngcollation) - LEFT JOIN pg_catalog.pg_opclass AS range_opclass ON (range_opclass.oid = pg_range.rngsubopc) - LEFT JOIN pg_catalog.pg_proc AS range_canonical_proc ON (range_canonical_proc.oid = pg_range.rngcanonical) - LEFT JOIN pg_catalog.pg_proc AS range_diff_proc ON (range_diff_proc.oid = pg_range.rngsubdiff) - WHERE pg_namespace.nspname = $1 - AND ( - (pg_type.typtype = 'c' AND (pg_class.relkind = 'c' OR pg_class.relkind IS NULL)) - OR pg_type.typtype = 'e' - OR pg_type.typtype = 'r' - ) - GROUP BY pg_class_oid, - pg_type.typname, - pg_type.typtype, - pg_class.oid, - range_subtype, - range_collation_name, - range_opclass_name, - range_canonical_proc, - range_diff_proc;`, - - GET_COMPOSITE_TYPE_COLUMNS: ` - SELECT pg_attribute.attname AS column_name, - pg_type.typname AS data_type, - pg_get_expr(pg_attrdef.adbin, pg_attrdef.adrelid) AS columns_default, - pg_attribute.attnotnull AS not_null, - pg_collation.collname AS collation_name, - pg_attribute.attndims AS number_of_array_dimensions, - pg_attribute.atttypmod AS character_maximum_length - FROM pg_catalog.pg_attribute AS pg_attribute - LEFT JOIN pg_catalog.pg_type AS pg_type ON (pg_type.oid = pg_attribute.atttypid) - LEFT JOIN pg_catalog.pg_attrdef AS pg_attrdef ON (pg_attrdef.adrelid = pg_attribute.attrelid - AND pg_attrdef.adnum = pg_attribute.attnum) - LEFT JOIN pg_catalog.pg_collation AS pg_collation ON (pg_collation.oid = pg_attribute.attcollation) - WHERE pg_attribute.attrelid = $1`, - - GET_DB_NAME: 'SELECT current_database();', - - GET_DB_ENCODING: 'SHOW SERVER_ENCODING;', - - GET_DB_COLLATE_NAME: 'SELECT default_collate_name FROM information_schema.character_sets;', - - GET_DATABASES: - 'SELECT datname AS database_name FROM pg_catalog.pg_database WHERE datistemplate != TRUE AND datallowconn = TRUE;', - -}; - -const getQueryName = query => { - const queryEntry = - Object.entries(queryConstants).find(([queryName, constantQuery]) => query === constantQuery) || []; - - return queryEntry[0] || 'Custom query'; -}; - -module.exports = { - getQueryName, - ...queryConstants, -}; diff --git a/reverse_engineering/node_modules/asn1/Jenkinsfile b/reverse_engineering/node_modules/asn1/Jenkinsfile deleted file mode 100644 index d1b4593..0000000 --- a/reverse_engineering/node_modules/asn1/Jenkinsfile +++ /dev/null @@ -1,65 +0,0 @@ -@Library('jenkins-joylib@v1.0.8') _ - -pipeline { - - agent none - - options { - buildDiscarder(logRotator(numToKeepStr: '45')) - timestamps() - } - - stages { - stage('top') { - parallel { - stage('v4-zone') { - agent { - label joyCommonLabels(image_ver: '15.4.1') - } - tools { - nodejs 'sdcnode-v4-zone' - } - stages { - stage('check') { - steps{ - sh('make check') - } - } - stage('test') { - steps{ - sh('make test') - } - } - } - } - - stage('v6-zone64') { - agent { - label joyCommonLabels(image_ver: '18.4.0') - } - tools { - nodejs 'sdcnode-v6-zone64' - } - stages { - stage('check') { - steps{ - sh('make check') - } - } - stage('test') { - steps{ - sh('make test') - } - } - } - } - } - } - } - - post { - always { - joySlackNotifications() - } - } -} diff --git a/reverse_engineering/node_modules/asn1/LICENSE b/reverse_engineering/node_modules/asn1/LICENSE deleted file mode 100644 index 9b5dcdb..0000000 --- a/reverse_engineering/node_modules/asn1/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011 Mark Cavage, All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE diff --git a/reverse_engineering/node_modules/asn1/README.md b/reverse_engineering/node_modules/asn1/README.md deleted file mode 100644 index 2208210..0000000 --- a/reverse_engineering/node_modules/asn1/README.md +++ /dev/null @@ -1,50 +0,0 @@ -node-asn1 is a library for encoding and decoding ASN.1 datatypes in pure JS. -Currently BER encoding is supported; at some point I'll likely have to do DER. - -## Usage - -Mostly, if you're *actually* needing to read and write ASN.1, you probably don't -need this readme to explain what and why. If you have no idea what ASN.1 is, -see this: ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc - -The source is pretty much self-explanatory, and has read/write methods for the -common types out there. - -### Decoding - -The following reads an ASN.1 sequence with a boolean. - - var Ber = require('asn1').Ber; - - var reader = new Ber.Reader(Buffer.from([0x30, 0x03, 0x01, 0x01, 0xff])); - - reader.readSequence(); - console.log('Sequence len: ' + reader.length); - if (reader.peek() === Ber.Boolean) - console.log(reader.readBoolean()); - -### Encoding - -The following generates the same payload as above. - - var Ber = require('asn1').Ber; - - var writer = new Ber.Writer(); - - writer.startSequence(); - writer.writeBoolean(true); - writer.endSequence(); - - console.log(writer.buffer); - -## Installation - - npm install asn1 - -## License - -MIT. - -## Bugs - -See . diff --git a/reverse_engineering/node_modules/asn1/lib/ber/errors.js b/reverse_engineering/node_modules/asn1/lib/ber/errors.js deleted file mode 100644 index 4557b8a..0000000 --- a/reverse_engineering/node_modules/asn1/lib/ber/errors.js +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - - -module.exports = { - - newInvalidAsn1Error: function (msg) { - var e = new Error(); - e.name = 'InvalidAsn1Error'; - e.message = msg || ''; - return e; - } - -}; diff --git a/reverse_engineering/node_modules/asn1/lib/ber/index.js b/reverse_engineering/node_modules/asn1/lib/ber/index.js deleted file mode 100644 index 387d132..0000000 --- a/reverse_engineering/node_modules/asn1/lib/ber/index.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - -var errors = require('./errors'); -var types = require('./types'); - -var Reader = require('./reader'); -var Writer = require('./writer'); - - -// --- Exports - -module.exports = { - - Reader: Reader, - - Writer: Writer - -}; - -for (var t in types) { - if (types.hasOwnProperty(t)) - module.exports[t] = types[t]; -} -for (var e in errors) { - if (errors.hasOwnProperty(e)) - module.exports[e] = errors[e]; -} diff --git a/reverse_engineering/node_modules/asn1/lib/ber/reader.js b/reverse_engineering/node_modules/asn1/lib/ber/reader.js deleted file mode 100644 index 8a7e4ca..0000000 --- a/reverse_engineering/node_modules/asn1/lib/ber/reader.js +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - -var assert = require('assert'); -var Buffer = require('safer-buffer').Buffer; - -var ASN1 = require('./types'); -var errors = require('./errors'); - - -// --- Globals - -var newInvalidAsn1Error = errors.newInvalidAsn1Error; - - - -// --- API - -function Reader(data) { - if (!data || !Buffer.isBuffer(data)) - throw new TypeError('data must be a node Buffer'); - - this._buf = data; - this._size = data.length; - - // These hold the "current" state - this._len = 0; - this._offset = 0; -} - -Object.defineProperty(Reader.prototype, 'length', { - enumerable: true, - get: function () { return (this._len); } -}); - -Object.defineProperty(Reader.prototype, 'offset', { - enumerable: true, - get: function () { return (this._offset); } -}); - -Object.defineProperty(Reader.prototype, 'remain', { - get: function () { return (this._size - this._offset); } -}); - -Object.defineProperty(Reader.prototype, 'buffer', { - get: function () { return (this._buf.slice(this._offset)); } -}); - - -/** - * Reads a single byte and advances offset; you can pass in `true` to make this - * a "peek" operation (i.e., get the byte, but don't advance the offset). - * - * @param {Boolean} peek true means don't move offset. - * @return {Number} the next byte, null if not enough data. - */ -Reader.prototype.readByte = function (peek) { - if (this._size - this._offset < 1) - return null; - - var b = this._buf[this._offset] & 0xff; - - if (!peek) - this._offset += 1; - - return b; -}; - - -Reader.prototype.peek = function () { - return this.readByte(true); -}; - - -/** - * Reads a (potentially) variable length off the BER buffer. This call is - * not really meant to be called directly, as callers have to manipulate - * the internal buffer afterwards. - * - * As a result of this call, you can call `Reader.length`, until the - * next thing called that does a readLength. - * - * @return {Number} the amount of offset to advance the buffer. - * @throws {InvalidAsn1Error} on bad ASN.1 - */ -Reader.prototype.readLength = function (offset) { - if (offset === undefined) - offset = this._offset; - - if (offset >= this._size) - return null; - - var lenB = this._buf[offset++] & 0xff; - if (lenB === null) - return null; - - if ((lenB & 0x80) === 0x80) { - lenB &= 0x7f; - - if (lenB === 0) - throw newInvalidAsn1Error('Indefinite length not supported'); - - if (lenB > 4) - throw newInvalidAsn1Error('encoding too long'); - - if (this._size - offset < lenB) - return null; - - this._len = 0; - for (var i = 0; i < lenB; i++) - this._len = (this._len << 8) + (this._buf[offset++] & 0xff); - - } else { - // Wasn't a variable length - this._len = lenB; - } - - return offset; -}; - - -/** - * Parses the next sequence in this BER buffer. - * - * To get the length of the sequence, call `Reader.length`. - * - * @return {Number} the sequence's tag. - */ -Reader.prototype.readSequence = function (tag) { - var seq = this.peek(); - if (seq === null) - return null; - if (tag !== undefined && tag !== seq) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + seq.toString(16)); - - var o = this.readLength(this._offset + 1); // stored in `length` - if (o === null) - return null; - - this._offset = o; - return seq; -}; - - -Reader.prototype.readInt = function () { - return this._readTag(ASN1.Integer); -}; - - -Reader.prototype.readBoolean = function () { - return (this._readTag(ASN1.Boolean) === 0 ? false : true); -}; - - -Reader.prototype.readEnumeration = function () { - return this._readTag(ASN1.Enumeration); -}; - - -Reader.prototype.readString = function (tag, retbuf) { - if (!tag) - tag = ASN1.OctetString; - - var b = this.peek(); - if (b === null) - return null; - - if (b !== tag) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + b.toString(16)); - - var o = this.readLength(this._offset + 1); // stored in `length` - - if (o === null) - return null; - - if (this.length > this._size - o) - return null; - - this._offset = o; - - if (this.length === 0) - return retbuf ? Buffer.alloc(0) : ''; - - var str = this._buf.slice(this._offset, this._offset + this.length); - this._offset += this.length; - - return retbuf ? str : str.toString('utf8'); -}; - -Reader.prototype.readOID = function (tag) { - if (!tag) - tag = ASN1.OID; - - var b = this.readString(tag, true); - if (b === null) - return null; - - var values = []; - var value = 0; - - for (var i = 0; i < b.length; i++) { - var byte = b[i] & 0xff; - - value <<= 7; - value += byte & 0x7f; - if ((byte & 0x80) === 0) { - values.push(value); - value = 0; - } - } - - value = values.shift(); - values.unshift(value % 40); - values.unshift((value / 40) >> 0); - - return values.join('.'); -}; - - -Reader.prototype._readTag = function (tag) { - assert.ok(tag !== undefined); - - var b = this.peek(); - - if (b === null) - return null; - - if (b !== tag) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + b.toString(16)); - - var o = this.readLength(this._offset + 1); // stored in `length` - if (o === null) - return null; - - if (this.length > 4) - throw newInvalidAsn1Error('Integer too long: ' + this.length); - - if (this.length > this._size - o) - return null; - this._offset = o; - - var fb = this._buf[this._offset]; - var value = 0; - - for (var i = 0; i < this.length; i++) { - value <<= 8; - value |= (this._buf[this._offset++] & 0xff); - } - - if ((fb & 0x80) === 0x80 && i !== 4) - value -= (1 << (i * 8)); - - return value >> 0; -}; - - - -// --- Exported API - -module.exports = Reader; diff --git a/reverse_engineering/node_modules/asn1/lib/ber/types.js b/reverse_engineering/node_modules/asn1/lib/ber/types.js deleted file mode 100644 index 8aea000..0000000 --- a/reverse_engineering/node_modules/asn1/lib/ber/types.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - - -module.exports = { - EOC: 0, - Boolean: 1, - Integer: 2, - BitString: 3, - OctetString: 4, - Null: 5, - OID: 6, - ObjectDescriptor: 7, - External: 8, - Real: 9, // float - Enumeration: 10, - PDV: 11, - Utf8String: 12, - RelativeOID: 13, - Sequence: 16, - Set: 17, - NumericString: 18, - PrintableString: 19, - T61String: 20, - VideotexString: 21, - IA5String: 22, - UTCTime: 23, - GeneralizedTime: 24, - GraphicString: 25, - VisibleString: 26, - GeneralString: 28, - UniversalString: 29, - CharacterString: 30, - BMPString: 31, - Constructor: 32, - Context: 128 -}; diff --git a/reverse_engineering/node_modules/asn1/lib/ber/writer.js b/reverse_engineering/node_modules/asn1/lib/ber/writer.js deleted file mode 100644 index 3515acf..0000000 --- a/reverse_engineering/node_modules/asn1/lib/ber/writer.js +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - -var assert = require('assert'); -var Buffer = require('safer-buffer').Buffer; -var ASN1 = require('./types'); -var errors = require('./errors'); - - -// --- Globals - -var newInvalidAsn1Error = errors.newInvalidAsn1Error; - -var DEFAULT_OPTS = { - size: 1024, - growthFactor: 8 -}; - - -// --- Helpers - -function merge(from, to) { - assert.ok(from); - assert.equal(typeof (from), 'object'); - assert.ok(to); - assert.equal(typeof (to), 'object'); - - var keys = Object.getOwnPropertyNames(from); - keys.forEach(function (key) { - if (to[key]) - return; - - var value = Object.getOwnPropertyDescriptor(from, key); - Object.defineProperty(to, key, value); - }); - - return to; -} - - - -// --- API - -function Writer(options) { - options = merge(DEFAULT_OPTS, options || {}); - - this._buf = Buffer.alloc(options.size || 1024); - this._size = this._buf.length; - this._offset = 0; - this._options = options; - - // A list of offsets in the buffer where we need to insert - // sequence tag/len pairs. - this._seq = []; -} - -Object.defineProperty(Writer.prototype, 'buffer', { - get: function () { - if (this._seq.length) - throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); - - return (this._buf.slice(0, this._offset)); - } -}); - -Writer.prototype.writeByte = function (b) { - if (typeof (b) !== 'number') - throw new TypeError('argument must be a Number'); - - this._ensure(1); - this._buf[this._offset++] = b; -}; - - -Writer.prototype.writeInt = function (i, tag) { - if (typeof (i) !== 'number') - throw new TypeError('argument must be a Number'); - if (typeof (tag) !== 'number') - tag = ASN1.Integer; - - var sz = 4; - - while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && - (sz > 1)) { - sz--; - i <<= 8; - } - - if (sz > 4) - throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); - - this._ensure(2 + sz); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = sz; - - while (sz-- > 0) { - this._buf[this._offset++] = ((i & 0xff000000) >>> 24); - i <<= 8; - } - -}; - - -Writer.prototype.writeNull = function () { - this.writeByte(ASN1.Null); - this.writeByte(0x00); -}; - - -Writer.prototype.writeEnumeration = function (i, tag) { - if (typeof (i) !== 'number') - throw new TypeError('argument must be a Number'); - if (typeof (tag) !== 'number') - tag = ASN1.Enumeration; - - return this.writeInt(i, tag); -}; - - -Writer.prototype.writeBoolean = function (b, tag) { - if (typeof (b) !== 'boolean') - throw new TypeError('argument must be a Boolean'); - if (typeof (tag) !== 'number') - tag = ASN1.Boolean; - - this._ensure(3); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = 0x01; - this._buf[this._offset++] = b ? 0xff : 0x00; -}; - - -Writer.prototype.writeString = function (s, tag) { - if (typeof (s) !== 'string') - throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); - if (typeof (tag) !== 'number') - tag = ASN1.OctetString; - - var len = Buffer.byteLength(s); - this.writeByte(tag); - this.writeLength(len); - if (len) { - this._ensure(len); - this._buf.write(s, this._offset); - this._offset += len; - } -}; - - -Writer.prototype.writeBuffer = function (buf, tag) { - if (typeof (tag) !== 'number') - throw new TypeError('tag must be a number'); - if (!Buffer.isBuffer(buf)) - throw new TypeError('argument must be a buffer'); - - this.writeByte(tag); - this.writeLength(buf.length); - this._ensure(buf.length); - buf.copy(this._buf, this._offset, 0, buf.length); - this._offset += buf.length; -}; - - -Writer.prototype.writeStringArray = function (strings) { - if ((!strings instanceof Array)) - throw new TypeError('argument must be an Array[String]'); - - var self = this; - strings.forEach(function (s) { - self.writeString(s); - }); -}; - -// This is really to solve DER cases, but whatever for now -Writer.prototype.writeOID = function (s, tag) { - if (typeof (s) !== 'string') - throw new TypeError('argument must be a string'); - if (typeof (tag) !== 'number') - tag = ASN1.OID; - - if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) - throw new Error('argument is not a valid OID string'); - - function encodeOctet(bytes, octet) { - if (octet < 128) { - bytes.push(octet); - } else if (octet < 16384) { - bytes.push((octet >>> 7) | 0x80); - bytes.push(octet & 0x7F); - } else if (octet < 2097152) { - bytes.push((octet >>> 14) | 0x80); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); - } else if (octet < 268435456) { - bytes.push((octet >>> 21) | 0x80); - bytes.push(((octet >>> 14) | 0x80) & 0xFF); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); - } else { - bytes.push(((octet >>> 28) | 0x80) & 0xFF); - bytes.push(((octet >>> 21) | 0x80) & 0xFF); - bytes.push(((octet >>> 14) | 0x80) & 0xFF); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); - } - } - - var tmp = s.split('.'); - var bytes = []; - bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); - tmp.slice(2).forEach(function (b) { - encodeOctet(bytes, parseInt(b, 10)); - }); - - var self = this; - this._ensure(2 + bytes.length); - this.writeByte(tag); - this.writeLength(bytes.length); - bytes.forEach(function (b) { - self.writeByte(b); - }); -}; - - -Writer.prototype.writeLength = function (len) { - if (typeof (len) !== 'number') - throw new TypeError('argument must be a Number'); - - this._ensure(4); - - if (len <= 0x7f) { - this._buf[this._offset++] = len; - } else if (len <= 0xff) { - this._buf[this._offset++] = 0x81; - this._buf[this._offset++] = len; - } else if (len <= 0xffff) { - this._buf[this._offset++] = 0x82; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else if (len <= 0xffffff) { - this._buf[this._offset++] = 0x83; - this._buf[this._offset++] = len >> 16; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else { - throw newInvalidAsn1Error('Length too long (> 4 bytes)'); - } -}; - -Writer.prototype.startSequence = function (tag) { - if (typeof (tag) !== 'number') - tag = ASN1.Sequence | ASN1.Constructor; - - this.writeByte(tag); - this._seq.push(this._offset); - this._ensure(3); - this._offset += 3; -}; - - -Writer.prototype.endSequence = function () { - var seq = this._seq.pop(); - var start = seq + 3; - var len = this._offset - start; - - if (len <= 0x7f) { - this._shift(start, len, -2); - this._buf[seq] = len; - } else if (len <= 0xff) { - this._shift(start, len, -1); - this._buf[seq] = 0x81; - this._buf[seq + 1] = len; - } else if (len <= 0xffff) { - this._buf[seq] = 0x82; - this._buf[seq + 1] = len >> 8; - this._buf[seq + 2] = len; - } else if (len <= 0xffffff) { - this._shift(start, len, 1); - this._buf[seq] = 0x83; - this._buf[seq + 1] = len >> 16; - this._buf[seq + 2] = len >> 8; - this._buf[seq + 3] = len; - } else { - throw newInvalidAsn1Error('Sequence too long'); - } -}; - - -Writer.prototype._shift = function (start, len, shift) { - assert.ok(start !== undefined); - assert.ok(len !== undefined); - assert.ok(shift); - - this._buf.copy(this._buf, start + shift, start, start + len); - this._offset += shift; -}; - -Writer.prototype._ensure = function (len) { - assert.ok(len); - - if (this._size - this._offset < len) { - var sz = this._size * this._options.growthFactor; - if (sz - this._offset < len) - sz += len; - - var buf = Buffer.alloc(sz); - - this._buf.copy(buf, 0, 0, this._offset); - this._buf = buf; - this._size = sz; - } -}; - - - -// --- Exported API - -module.exports = Writer; diff --git a/reverse_engineering/node_modules/asn1/lib/index.js b/reverse_engineering/node_modules/asn1/lib/index.js deleted file mode 100644 index ede3ab2..0000000 --- a/reverse_engineering/node_modules/asn1/lib/index.js +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2011 Mark Cavage All rights reserved. - -// If you have no idea what ASN.1 or BER is, see this: -// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc - -var Ber = require('./ber/index'); - - - -// --- Exported API - -module.exports = { - - Ber: Ber, - - BerReader: Ber.Reader, - - BerWriter: Ber.Writer - -}; diff --git a/reverse_engineering/node_modules/asn1/package.json b/reverse_engineering/node_modules/asn1/package.json deleted file mode 100644 index 3d9906e..0000000 --- a/reverse_engineering/node_modules/asn1/package.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "_from": "asn1@^0.2.4", - "_id": "asn1@0.2.6", - "_inBundle": false, - "_integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", - "_location": "/asn1", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "asn1@^0.2.4", - "name": "asn1", - "escapedName": "asn1", - "rawSpec": "^0.2.4", - "saveSpec": null, - "fetchSpec": "^0.2.4" - }, - "_requiredBy": [ - "/ssh2" - ], - "_resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", - "_shasum": "0d3a7bb6e64e02a90c0303b31f292868ea09a08d", - "_spec": "asn1@^0.2.4", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/ssh2", - "author": { - "name": "Joyent", - "url": "joyent.com" - }, - "bugs": { - "url": "https://github.com/joyent/node-asn1/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Mark Cavage", - "email": "mcavage@gmail.com" - }, - { - "name": "David Gwynne", - "email": "loki@animata.net" - }, - { - "name": "Yunong Xiao", - "email": "yunong@joyent.com" - }, - { - "name": "Alex Wilson", - "email": "alex.wilson@joyent.com" - } - ], - "dependencies": { - "safer-buffer": "~2.1.0" - }, - "deprecated": false, - "description": "Contains parsers and serializers for ASN.1 (currently BER only)", - "devDependencies": { - "eslint": "2.13.1", - "eslint-plugin-joyent": "~1.3.0", - "faucet": "0.0.1", - "istanbul": "^0.3.6", - "tape": "^3.5.0" - }, - "homepage": "https://github.com/joyent/node-asn1#readme", - "license": "MIT", - "main": "lib/index.js", - "name": "asn1", - "repository": { - "type": "git", - "url": "git+https://github.com/joyent/node-asn1.git" - }, - "scripts": { - "test": "tape ./test/ber/*.test.js" - }, - "version": "0.2.6" -} diff --git a/reverse_engineering/node_modules/bcrypt-pbkdf/CONTRIBUTING.md b/reverse_engineering/node_modules/bcrypt-pbkdf/CONTRIBUTING.md deleted file mode 100644 index 401d34e..0000000 --- a/reverse_engineering/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +++ /dev/null @@ -1,13 +0,0 @@ -# Contributing - -This repository uses [cr.joyent.us](https://cr.joyent.us) (Gerrit) for new -changes. Anyone can submit changes. To get started, see the [cr.joyent.us user -guide](https://github.com/joyent/joyent-gerrit/blob/master/docs/user/README.md). -This repo does not use GitHub pull requests. - -See the [Joyent Engineering -Guidelines](https://github.com/joyent/eng/blob/master/docs/index.md) for general -best practices expected in this repository. - -If you're changing something non-trivial or user-facing, you may want to submit -an issue first. diff --git a/reverse_engineering/node_modules/bcrypt-pbkdf/LICENSE b/reverse_engineering/node_modules/bcrypt-pbkdf/LICENSE deleted file mode 100644 index fc58d2a..0000000 --- a/reverse_engineering/node_modules/bcrypt-pbkdf/LICENSE +++ /dev/null @@ -1,66 +0,0 @@ -The Blowfish portions are under the following license: - -Blowfish block cipher for OpenBSD -Copyright 1997 Niels Provos -All rights reserved. - -Implementation advice by David Mazieres . - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -3. The name of the author may not be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - - -The bcrypt_pbkdf portions are under the following license: - -Copyright (c) 2013 Ted Unangst - -Permission to use, copy, modify, and distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - - - -Performance improvements (Javascript-specific): - -Copyright 2016, Joyent Inc -Author: Alex Wilson - -Permission to use, copy, modify, and distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/bcrypt-pbkdf/README.md b/reverse_engineering/node_modules/bcrypt-pbkdf/README.md deleted file mode 100644 index 7551f33..0000000 --- a/reverse_engineering/node_modules/bcrypt-pbkdf/README.md +++ /dev/null @@ -1,45 +0,0 @@ -Port of the OpenBSD `bcrypt_pbkdf` function to pure Javascript. `npm`-ified -version of [Devi Mandiri's port](https://github.com/devi/tmp/blob/master/js/bcrypt_pbkdf.js), -with some minor performance improvements. The code is copied verbatim (and -un-styled) from Devi's work. - -This product includes software developed by Niels Provos. - -## API - -### `bcrypt_pbkdf.pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds)` - -Derive a cryptographic key of arbitrary length from a given password and salt, -using the OpenBSD `bcrypt_pbkdf` function. This is a combination of Blowfish and -SHA-512. - -See [this article](http://www.tedunangst.com/flak/post/bcrypt-pbkdf) for -further information. - -Parameters: - - * `pass`, a Uint8Array of length `passlen` - * `passlen`, an integer Number - * `salt`, a Uint8Array of length `saltlen` - * `saltlen`, an integer Number - * `key`, a Uint8Array of length `keylen`, will be filled with output - * `keylen`, an integer Number - * `rounds`, an integer Number, number of rounds of the PBKDF to run - -### `bcrypt_pbkdf.hash(sha2pass, sha2salt, out)` - -Calculate a Blowfish hash, given SHA2-512 output of a password and salt. Used as -part of the inner round function in the PBKDF. - -Parameters: - - * `sha2pass`, a Uint8Array of length 64 - * `sha2salt`, a Uint8Array of length 64 - * `out`, a Uint8Array of length 32, will be filled with output - -## License - -This source form is a 1:1 port from the OpenBSD `blowfish.c` and `bcrypt_pbkdf.c`. -As a result, it retains the original copyright and license. The two files are -under slightly different (but compatible) licenses, and are here combined in -one file. For each of the full license texts see `LICENSE`. diff --git a/reverse_engineering/node_modules/bcrypt-pbkdf/index.js b/reverse_engineering/node_modules/bcrypt-pbkdf/index.js deleted file mode 100644 index b1b5ad4..0000000 --- a/reverse_engineering/node_modules/bcrypt-pbkdf/index.js +++ /dev/null @@ -1,556 +0,0 @@ -'use strict'; - -var crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash; - -/* - * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a - * result, it retains the original copyright and license. The two files are - * under slightly different (but compatible) licenses, and are here combined in - * one file. - * - * Credit for the actual porting work goes to: - * Devi Mandiri - */ - -/* - * The Blowfish portions are under the following license: - * - * Blowfish block cipher for OpenBSD - * Copyright 1997 Niels Provos - * All rights reserved. - * - * Implementation advice by David Mazieres . - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * The bcrypt_pbkdf portions are under the following license: - * - * Copyright (c) 2013 Ted Unangst - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* - * Performance improvements (Javascript-specific): - * - * Copyright 2016, Joyent Inc - * Author: Alex Wilson - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -// Ported from OpenBSD bcrypt_pbkdf.c v1.9 - -var BLF_J = 0; - -var Blowfish = function() { - this.S = [ - new Uint32Array([ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, - 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, - 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, - 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, - 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, - 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, - 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, - 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, - 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, - 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, - 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, - 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, - 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, - 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, - 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, - 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, - 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, - 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, - 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, - 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, - 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, - 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, - 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, - 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, - 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, - 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, - 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, - 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, - 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, - 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, - 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, - 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, - 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, - 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, - 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, - 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, - 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, - 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, - 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, - 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, - 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, - 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, - 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), - new Uint32Array([ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, - 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, - 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, - 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, - 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, - 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, - 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, - 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, - 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, - 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, - 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, - 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, - 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, - 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, - 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, - 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, - 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, - 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, - 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, - 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, - 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, - 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, - 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, - 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, - 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, - 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, - 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, - 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, - 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, - 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, - 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, - 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, - 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, - 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, - 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, - 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, - 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, - 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, - 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, - 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, - 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, - 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, - 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), - new Uint32Array([ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, - 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, - 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, - 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, - 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, - 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, - 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, - 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, - 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, - 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, - 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, - 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, - 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, - 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, - 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, - 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, - 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, - 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, - 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, - 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, - 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, - 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, - 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, - 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, - 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, - 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, - 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, - 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, - 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, - 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, - 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, - 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, - 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, - 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, - 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, - 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, - 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, - 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, - 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, - 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, - 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, - 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, - 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), - new Uint32Array([ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, - 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, - 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, - 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, - 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, - 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, - 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, - 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, - 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, - 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, - 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, - 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, - 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, - 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, - 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, - 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, - 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, - 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, - 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, - 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, - 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, - 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, - 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, - 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, - 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, - 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, - 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, - 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, - 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, - 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, - 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, - 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, - 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, - 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, - 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, - 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, - 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, - 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, - 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, - 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, - 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, - 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, - 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) - ]; - this.P = new Uint32Array([ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, - 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, - 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, - 0x9216d5d9, 0x8979fb1b]); -}; - -function F(S, x8, i) { - return (((S[0][x8[i+3]] + - S[1][x8[i+2]]) ^ - S[2][x8[i+1]]) + - S[3][x8[i]]); -}; - -Blowfish.prototype.encipher = function(x, x8) { - if (x8 === undefined) { - x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - } - x[0] ^= this.P[0]; - for (var i = 1; i < 16; i += 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[17]; - x[1] = t; -}; - -Blowfish.prototype.decipher = function(x) { - var x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - x[0] ^= this.P[17]; - for (var i = 16; i > 0; i -= 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[0]; - x[1] = t; -}; - -function stream2word(data, databytes){ - var i, temp = 0; - for (i = 0; i < 4; i++, BLF_J++) { - if (BLF_J >= databytes) BLF_J = 0; - temp = (temp << 8) | data[BLF_J]; - } - return temp; -}; - -Blowfish.prototype.expand0state = function(key, keybytes) { - var d = new Uint32Array(2), i, k; - var d8 = new Uint8Array(d.buffer); - - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } - BLF_J = 0; - - for (i = 0; i < 18; i += 2) { - this.encipher(d, d8); - this.P[i] = d[0]; - this.P[i+1] = d[1]; - } - - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - this.encipher(d, d8); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; - } - } -}; - -Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { - var d = new Uint32Array(2), i, k; - - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } - - for (i = 0, BLF_J = 0; i < 18; i += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.P[i] = d[0]; - this.P[i+1] = d[1]; - } - - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; - } - } - BLF_J = 0; -}; - -Blowfish.prototype.enc = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.encipher(data.subarray(i*2)); - } -}; - -Blowfish.prototype.dec = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.decipher(data.subarray(i*2)); - } -}; - -var BCRYPT_BLOCKS = 8, - BCRYPT_HASHSIZE = 32; - -function bcrypt_hash(sha2pass, sha2salt, out) { - var state = new Blowfish(), - cdata = new Uint32Array(BCRYPT_BLOCKS), i, - ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, - 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, - 105,116,101]); //"OxychromaticBlowfishSwatDynamite" - - state.expandstate(sha2salt, 64, sha2pass, 64); - for (i = 0; i < 64; i++) { - state.expand0state(sha2salt, 64); - state.expand0state(sha2pass, 64); - } - - for (i = 0; i < BCRYPT_BLOCKS; i++) - cdata[i] = stream2word(ciphertext, ciphertext.byteLength); - for (i = 0; i < 64; i++) - state.enc(cdata, cdata.byteLength / 8); - - for (i = 0; i < BCRYPT_BLOCKS; i++) { - out[4*i+3] = cdata[i] >>> 24; - out[4*i+2] = cdata[i] >>> 16; - out[4*i+1] = cdata[i] >>> 8; - out[4*i+0] = cdata[i]; - } -}; - -function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { - var sha2pass = new Uint8Array(64), - sha2salt = new Uint8Array(64), - out = new Uint8Array(BCRYPT_HASHSIZE), - tmpout = new Uint8Array(BCRYPT_HASHSIZE), - countsalt = new Uint8Array(saltlen+4), - i, j, amt, stride, dest, count, - origkeylen = keylen; - - if (rounds < 1) - return -1; - if (passlen === 0 || saltlen === 0 || keylen === 0 || - keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) - return -1; - - stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); - amt = Math.floor((keylen + stride - 1) / stride); - - for (i = 0; i < saltlen; i++) - countsalt[i] = salt[i]; - - crypto_hash_sha512(sha2pass, pass, passlen); - - for (count = 1; keylen > 0; count++) { - countsalt[saltlen+0] = count >>> 24; - countsalt[saltlen+1] = count >>> 16; - countsalt[saltlen+2] = count >>> 8; - countsalt[saltlen+3] = count; - - crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (i = out.byteLength; i--;) - out[i] = tmpout[i]; - - for (i = 1; i < rounds; i++) { - crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (j = 0; j < out.byteLength; j++) - out[j] ^= tmpout[j]; - } - - amt = Math.min(amt, keylen); - for (i = 0; i < amt; i++) { - dest = i * stride + (count - 1); - if (dest >= origkeylen) - break; - key[dest] = out[i]; - } - keylen -= i; - } - - return 0; -}; - -module.exports = { - BLOCKS: BCRYPT_BLOCKS, - HASHSIZE: BCRYPT_HASHSIZE, - hash: bcrypt_hash, - pbkdf: bcrypt_pbkdf -}; diff --git a/reverse_engineering/node_modules/bcrypt-pbkdf/package.json b/reverse_engineering/node_modules/bcrypt-pbkdf/package.json deleted file mode 100644 index 6939b23..0000000 --- a/reverse_engineering/node_modules/bcrypt-pbkdf/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "_from": "bcrypt-pbkdf@^1.0.2", - "_id": "bcrypt-pbkdf@1.0.2", - "_inBundle": false, - "_integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", - "_location": "/bcrypt-pbkdf", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "bcrypt-pbkdf@^1.0.2", - "name": "bcrypt-pbkdf", - "escapedName": "bcrypt-pbkdf", - "rawSpec": "^1.0.2", - "saveSpec": null, - "fetchSpec": "^1.0.2" - }, - "_requiredBy": [ - "/ssh2" - ], - "_resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", - "_shasum": "a4301d389b6a43f9b67ff3ca11a3f6637e360e9e", - "_spec": "bcrypt-pbkdf@^1.0.2", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/ssh2", - "bugs": { - "url": "https://github.com/joyent/node-bcrypt-pbkdf/issues" - }, - "bundleDependencies": false, - "dependencies": { - "tweetnacl": "^0.14.3" - }, - "deprecated": false, - "description": "Port of the OpenBSD bcrypt_pbkdf function to pure JS", - "devDependencies": {}, - "homepage": "https://github.com/joyent/node-bcrypt-pbkdf#readme", - "license": "BSD-3-Clause", - "main": "index.js", - "name": "bcrypt-pbkdf", - "repository": { - "type": "git", - "url": "git://github.com/joyent/node-bcrypt-pbkdf.git" - }, - "version": "1.0.2" -} diff --git a/reverse_engineering/node_modules/buffer-writer/.travis.yml b/reverse_engineering/node_modules/buffer-writer/.travis.yml deleted file mode 100644 index 8e59bb3..0000000 --- a/reverse_engineering/node_modules/buffer-writer/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: node_js -node_js: - - 4 - - 6 - - 8 - - 10 - - 11 diff --git a/reverse_engineering/node_modules/buffer-writer/LICENSE b/reverse_engineering/node_modules/buffer-writer/LICENSE deleted file mode 100644 index 72dc60d..0000000 --- a/reverse_engineering/node_modules/buffer-writer/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -The MIT License (MIT) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/buffer-writer/README.md b/reverse_engineering/node_modules/buffer-writer/README.md deleted file mode 100644 index 81eccc0..0000000 --- a/reverse_engineering/node_modules/buffer-writer/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# buffer-writer - -[![Build Status](https://secure.travis-ci.org/brianc/node-buffer-writer.png?branch=master)](http://travis-ci.org/brianc/node-buffer-writer) - -Fast & efficient buffer writer used to keep memory usage low by internally recycling a single large buffer. - -Used as the binary protocol writer in [node-postgres](https://github.com/brianc/node-postgres) - -Since postgres requires big endian encoding, this only writes big endian numbers for now, but can & probably will easily be extended to write little endian as well. - -I'll admit this has a few postgres specific things I might need to take out in the future, such as `addHeader` - -## api - -`var writer = new (require('buffer-writer')());` - -### writer.addInt32(num) - -Writes a 4-byte big endian binary encoded number to the end of the buffer. - -### writer.addInt16(num) - -Writes a 2-byte big endian binary encoded number to the end of the buffer. - -### writer.addCString(string) - -Writes a string to the buffer `utf8` encoded and adds a null character (`\0`) at the end. - -### var buffer = writer.addHeader(char) - -Writes the 5 byte PostgreSQL required header to the beginning of the buffer. (1 byte for character, 1 BE Int32 for length of the buffer) - -### var buffer = writer.join() - -Collects all data in the writer and joins it into a single, new buffer. - -### var buffer = writer.flush(char) - -Writes the 5 byte postgres required message header, collects all data in the writer and joins it into a single, new buffer, and then resets the writer. - -## thoughts - -This is kind of node-postgres specific. If you're interested in using this for a more general purpose thing, lemme know. -I would love to work with you on getting this more reusable for your needs. - -## license - -MIT diff --git a/reverse_engineering/node_modules/buffer-writer/index.js b/reverse_engineering/node_modules/buffer-writer/index.js deleted file mode 100644 index f3c119e..0000000 --- a/reverse_engineering/node_modules/buffer-writer/index.js +++ /dev/null @@ -1,129 +0,0 @@ -//binary data writer tuned for creating -//postgres message packets as effeciently as possible by reusing the -//same buffer to avoid memcpy and limit memory allocations -var Writer = module.exports = function (size) { - this.size = size || 1024; - this.buffer = Buffer.alloc(this.size + 5); - this.offset = 5; - this.headerPosition = 0; -}; - -//resizes internal buffer if not enough size left -Writer.prototype._ensure = function (size) { - var remaining = this.buffer.length - this.offset; - if (remaining < size) { - var oldBuffer = this.buffer; - // exponential growth factor of around ~ 1.5 - // https://stackoverflow.com/questions/2269063/buffer-growth-strategy - var newSize = oldBuffer.length + (oldBuffer.length >> 1) + size; - this.buffer = Buffer.alloc(newSize); - oldBuffer.copy(this.buffer); - } -}; - -Writer.prototype.addInt32 = function (num) { - this._ensure(4); - this.buffer[this.offset++] = (num >>> 24 & 0xFF); - this.buffer[this.offset++] = (num >>> 16 & 0xFF); - this.buffer[this.offset++] = (num >>> 8 & 0xFF); - this.buffer[this.offset++] = (num >>> 0 & 0xFF); - return this; -}; - -Writer.prototype.addInt16 = function (num) { - this._ensure(2); - this.buffer[this.offset++] = (num >>> 8 & 0xFF); - this.buffer[this.offset++] = (num >>> 0 & 0xFF); - return this; -}; - -//for versions of node requiring 'length' as 3rd argument to buffer.write -var writeString = function (buffer, string, offset, len) { - buffer.write(string, offset, len); -}; - -//overwrite function for older versions of node -if (Buffer.prototype.write.length === 3) { - writeString = function (buffer, string, offset, len) { - buffer.write(string, offset); - }; -} - -Writer.prototype.addCString = function (string) { - //just write a 0 for empty or null strings - if (!string) { - this._ensure(1); - } else { - var len = Buffer.byteLength(string); - this._ensure(len + 1); //+1 for null terminator - writeString(this.buffer, string, this.offset, len); - this.offset += len; - } - - this.buffer[this.offset++] = 0; // null terminator - return this; -}; - -Writer.prototype.addChar = function (c) { - this._ensure(1); - writeString(this.buffer, c, this.offset, 1); - this.offset++; - return this; -}; - -Writer.prototype.addString = function (string) { - string = string || ""; - var len = Buffer.byteLength(string); - this._ensure(len); - this.buffer.write(string, this.offset); - this.offset += len; - return this; -}; - -Writer.prototype.getByteLength = function () { - return this.offset - 5; -}; - -Writer.prototype.add = function (otherBuffer) { - this._ensure(otherBuffer.length); - otherBuffer.copy(this.buffer, this.offset); - this.offset += otherBuffer.length; - return this; -}; - -Writer.prototype.clear = function () { - this.offset = 5; - this.headerPosition = 0; - this.lastEnd = 0; -}; - -//appends a header block to all the written data since the last -//subsequent header or to the beginning if there is only one data block -Writer.prototype.addHeader = function (code, last) { - var origOffset = this.offset; - this.offset = this.headerPosition; - this.buffer[this.offset++] = code; - //length is everything in this packet minus the code - this.addInt32(origOffset - (this.headerPosition + 1)); - //set next header position - this.headerPosition = origOffset; - //make space for next header - this.offset = origOffset; - if (!last) { - this._ensure(5); - this.offset += 5; - } -}; - -Writer.prototype.join = function (code) { - if (code) { - this.addHeader(code, true); - } - return this.buffer.slice(code ? 0 : 5, this.offset); -}; - -Writer.prototype.flush = function (code) { - var result = this.join(code); - this.clear(); - return result; -}; diff --git a/reverse_engineering/node_modules/buffer-writer/package.json b/reverse_engineering/node_modules/buffer-writer/package.json deleted file mode 100644 index d0a9343..0000000 --- a/reverse_engineering/node_modules/buffer-writer/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "_from": "buffer-writer@2.0.0", - "_id": "buffer-writer@2.0.0", - "_inBundle": false, - "_integrity": "sha512-a7ZpuTZU1TRtnwyCNW3I5dc0wWNC3VR9S++Ewyk2HHZdrO3CQJqSpd+95Us590V6AL7JqUAH2IwZ/398PmNFgw==", - "_location": "/buffer-writer", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "buffer-writer@2.0.0", - "name": "buffer-writer", - "escapedName": "buffer-writer", - "rawSpec": "2.0.0", - "saveSpec": null, - "fetchSpec": "2.0.0" - }, - "_requiredBy": [ - "/pg" - ], - "_resolved": "https://registry.npmjs.org/buffer-writer/-/buffer-writer-2.0.0.tgz", - "_shasum": "ce7eb81a38f7829db09c873f2fbb792c0c98ec04", - "_spec": "buffer-writer@2.0.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg", - "author": { - "name": "Brian M. Carlson" - }, - "bugs": { - "url": "https://github.com/brianc/node-buffer-writer/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "a fast, efficient buffer writer", - "devDependencies": { - "mocha": "5.2.0" - }, - "engines": { - "node": ">=4" - }, - "homepage": "https://github.com/brianc/node-buffer-writer#readme", - "keywords": [ - "buffer", - "writer", - "builder" - ], - "license": "MIT", - "main": "index.js", - "name": "buffer-writer", - "repository": { - "type": "git", - "url": "git://github.com/brianc/node-buffer-writer.git" - }, - "scripts": { - "test": "mocha --throw-deprecation" - }, - "version": "2.0.0" -} diff --git a/reverse_engineering/node_modules/buffer-writer/test/mocha.opts b/reverse_engineering/node_modules/buffer-writer/test/mocha.opts deleted file mode 100644 index 5efaf24..0000000 --- a/reverse_engineering/node_modules/buffer-writer/test/mocha.opts +++ /dev/null @@ -1 +0,0 @@ ---ui tdd diff --git a/reverse_engineering/node_modules/buffer-writer/test/writer-tests.js b/reverse_engineering/node_modules/buffer-writer/test/writer-tests.js deleted file mode 100644 index ded91c8..0000000 --- a/reverse_engineering/node_modules/buffer-writer/test/writer-tests.js +++ /dev/null @@ -1,218 +0,0 @@ -var Writer = require(__dirname + "/../"); - -var assert = require('assert'); -var util = require('util'); - -assert.equalBuffers = function (actual, expected) { - var spit = function (actual, expected) { - console.log(""); - console.log("actual " + util.inspect(actual)); - console.log("expect " + util.inspect(expected)); - console.log(""); - }; - if (actual.length != expected.length) { - spit(actual, expected); - assert.strictEqual(actual.length, expected.length); - } - for (var i = 0; i < actual.length; i++) { - if (actual[i] != expected[i]) { - spit(actual, expected); - } - assert.strictEqual(actual[i], expected[i]); - } -}; - -suite('adding int32', function () { - var testAddingInt32 = function (int, expectedBuffer) { - test('writes ' + int, function () { - var subject = new Writer(); - var result = subject.addInt32(int).join(); - assert.equalBuffers(result, expectedBuffer); - }); - }; - - testAddingInt32(0, [0, 0, 0, 0]); - testAddingInt32(1, [0, 0, 0, 1]); - testAddingInt32(256, [0, 0, 1, 0]); - test('writes largest int32', function () { - //todo need to find largest int32 when I have internet access - return false; - }); - - test('writing multiple int32s', function () { - var subject = new Writer(); - var result = subject.addInt32(1).addInt32(10).addInt32(0).join(); - assert.equalBuffers(result, [0, 0, 0, 1, 0, 0, 0, 0x0a, 0, 0, 0, 0]); - }); - - suite('having to resize the buffer', function () { - test('after resize correct result returned', function () { - var subject = new Writer(10); - subject.addInt32(1).addInt32(1).addInt32(1); - assert.equalBuffers(subject.join(), [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]); - }); - }); -}); - -suite('int16', function () { - test('writes 0', function () { - var subject = new Writer(); - var result = subject.addInt16(0).join(); - assert.equalBuffers(result, [0, 0]); - }); - - test('writes 400', function () { - var subject = new Writer(); - var result = subject.addInt16(400).join(); - assert.equalBuffers(result, [1, 0x90]); - }); - - test('writes many', function () { - var subject = new Writer(); - var result = subject.addInt16(0).addInt16(1).addInt16(2).join(); - assert.equalBuffers(result, [0, 0, 0, 1, 0, 2]); - }); - - test('resizes if internal buffer fills up', function () { - var subject = new Writer(3); - var result = subject.addInt16(2).addInt16(3).join(); - assert.equalBuffers(result, [0, 2, 0, 3]); - }); - -}); - -suite('cString', function () { - test('writes empty cstring', function () { - var subject = new Writer(); - var result = subject.addCString().join(); - assert.equalBuffers(result, [0]); - }); - - test('writes two empty cstrings', function () { - var subject = new Writer(); - var result = subject.addCString("").addCString("").join(); - assert.equalBuffers(result, [0, 0]); - }); - - - test('writes non-empty cstring', function () { - var subject = new Writer(); - var result = subject.addCString("!!!").join(); - assert.equalBuffers(result, [33, 33, 33, 0]); - }); - - test('resizes if reached end', function () { - var subject = new Writer(3); - var result = subject.addCString("!!!").join(); - assert.equalBuffers(result, [33, 33, 33, 0]); - }); - - test('writes multiple cstrings', function () { - var subject = new Writer(); - var result = subject.addCString("!").addCString("!").join(); - assert.equalBuffers(result, [33, 0, 33, 0]); - }); - -}); - -test('writes char', function () { - var subject = new Writer(2); - var result = subject.addChar('a').addChar('b').addChar('c').join(); - assert.equalBuffers(result, [0x61, 0x62, 0x63]); -}); - -test('gets correct byte length', function () { - var subject = new Writer(5); - assert.strictEqual(subject.getByteLength(), 0); - subject.addInt32(0); - assert.strictEqual(subject.getByteLength(), 4); - subject.addCString("!"); - assert.strictEqual(subject.getByteLength(), 6); -}); - -test('can add arbitrary buffer to the end', function () { - var subject = new Writer(4); - subject.addCString("!!!") - var result = subject.add(Buffer.from("@@@")).join(); - assert.equalBuffers(result, [33, 33, 33, 0, 0x40, 0x40, 0x40]); -}); - -suite('can write normal string', function () { - var subject = new Writer(4); - var result = subject.addString("!").join(); - assert.equalBuffers(result, [33]); - test('can write cString too', function () { - var result = subject.addCString("!").join(); - assert.equalBuffers(result, [33, 33, 0]); - }); - test('can resize', function () { - var result = subject.addString("!!").join(); - assert.equalBuffers(result, [33, 33, 0, 33, 33]); - }); -}); - - -suite('clearing', function () { - var subject = new Writer(); - subject.addCString("@!!#!#"); - subject.addInt32(10401); - test('clears', function () { - subject.clear(); - assert.equalBuffers(subject.join(), []); - }); - test('writing more', function () { - var joinedResult = subject.addCString("!").addInt32(9).addInt16(2).join(); - assert.equalBuffers(joinedResult, [33, 0, 0, 0, 0, 9, 0, 2]); - }); - test('returns result', function () { - var flushedResult = subject.flush(); - assert.equalBuffers(flushedResult, [33, 0, 0, 0, 0, 9, 0, 2]) - }); - test('clears the writer', function () { - assert.equalBuffers(subject.join(), []) - assert.equalBuffers(subject.flush(), []) - }); -}); - -test("resizing to much larger", function () { - var subject = new Writer(2); - var string = "!!!!!!!!"; - var result = subject.addCString(string).flush(); - assert.equalBuffers(result, [33, 33, 33, 33, 33, 33, 33, 33, 0]); -}); - -suite("flush", function () { - test('added as a hex code to a full writer', function () { - var subject = new Writer(2); - var result = subject.addCString("!").flush(0x50); - assert.equalBuffers(result, [0x50, 0, 0, 0, 6, 33, 0]); - }); - - test('added as a hex code to a non-full writer', function () { - var subject = new Writer(10).addCString("!"); - var joinedResult = subject.join(0x50); - var result = subject.flush(0x50); - assert.equalBuffers(result, [0x50, 0, 0, 0, 6, 33, 0]); - }); - - test('added as a hex code to a buffer which requires resizing', function () { - var result = new Writer(2).addCString("!!!!!!!!").flush(0x50); - assert.equalBuffers(result, [0x50, 0, 0, 0, 0x0D, 33, 33, 33, 33, 33, 33, 33, 33, 0]); - }); -}); - -suite("header", function () { - test('adding two packets with headers', function () { - var subject = new Writer(10).addCString("!"); - subject.addHeader(0x50); - subject.addCString("!!"); - subject.addHeader(0x40); - subject.addCString("!"); - var result = subject.flush(0x10); - assert.equalBuffers(result, [0x50, 0, 0, 0, 6, 33, 0, 0x40, 0, 0, 0, 7, 33, 33, 0, 0x10, 0, 0, 0, 6, 33, 0]); - }); -}); - - - - diff --git a/reverse_engineering/node_modules/cpu-features/LICENSE b/reverse_engineering/node_modules/cpu-features/LICENSE deleted file mode 100644 index 290762e..0000000 --- a/reverse_engineering/node_modules/cpu-features/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright Brian White. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. \ No newline at end of file diff --git a/reverse_engineering/node_modules/cpu-features/README.md b/reverse_engineering/node_modules/cpu-features/README.md deleted file mode 100644 index c3b1244..0000000 --- a/reverse_engineering/node_modules/cpu-features/README.md +++ /dev/null @@ -1,60 +0,0 @@ - -Description -=========== - -A simple [node.js](https://nodejs.org) binding to [cpu_features](https://github.com/google/cpu_features) for obtaining information about installed CPU(s). - - -Requirements -============ - -* [node.js](http://nodejs.org/) -- v8.0.0 or newer -* An appropriate build environment -- see [node-gyp's documentation](https://github.com/nodejs/node-gyp/blob/master/README.md) -* CMake -- any modern version (v3.14+ required for Windows and must be available in %PATH%) - - -Install -======= - - npm install cpu-features - - -Example -======= - -```js - // Generally it's a good idea to just call this once and - // reuse the result since `cpu-features` does not cache - // the result itself. - const features = require('cpu-features')(); - - console.log(features); - // example output: - // { arch: 'x86', - // brand: 'Intel(R) Core(TM) i7-3770K CPU @ 3.50GHz', - // family: 6, - // model: 58, - // stepping: 9, - // uarch: 'INTEL_IVB', - // flags: - // { fpu: true, - // tsc: true, - // cx8: true, - // clfsh: true, - // mmx: true, - // aes: true, - // erms: true, - // f16c: true, - // sse: true, - // sse2: true, - // sse3: true, - // ssse3: true, - // sse4_1: true, - // sse4_2: true, - // avx: true, - // pclmulqdq: true, - // cx16: true, - // popcnt: true, - // rdrnd: true, - // ss: true } } -``` diff --git a/reverse_engineering/node_modules/cpu-features/binding.gyp b/reverse_engineering/node_modules/cpu-features/binding.gyp deleted file mode 100644 index 58e26fd..0000000 --- a/reverse_engineering/node_modules/cpu-features/binding.gyp +++ /dev/null @@ -1,91 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'cpufeatures', - 'dependencies': [ 'build_deps' ], - 'include_dirs': [ - 'deps/cpu_features/include', - 'src', - "> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = AR($(TOOLSET)) $@ -cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) - -quiet_cmd_alink_thin = AR($(TOOLSET)) $@ -cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) - -# Due to circular dependencies between libraries :(, we wrap the -# special "figure out circular dependencies" flags around the entire -# input list during linking. -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) $(LIBS) -Wl,--end-group - -# We support two kinds of shared objects (.so): -# 1) shared_library, which is just bundling together many dependent libraries -# into a link line. -# 2) loadable_module, which is generating a module intended for dlopen(). -# -# They differ only slightly: -# In the former case, we want to package all dependent code into the .so. -# In the latter case, we want to package just the API exposed by the -# outermost module. -# This means shared_library uses --whole-archive, while loadable_module doesn't. -# (Note that --whole-archive is incompatible with the --start-group used in -# normal linking.) - -# Other shared-object link notes: -# - Set SONAME to the library filename so our binaries don't reference -# the local, absolute paths used on the link command-line. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 1,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,build_deps.target.mk)))),) - include build_deps.target.mk -endif -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,config_deps.target.mk)))),) - include config_deps.target.mk -endif -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,cpufeatures.target.mk)))),) - include cpufeatures.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/build/config.gypi -I/usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/vitalii/.cache/node-gyp/14.17.6/include/node/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/vitalii/.cache/node-gyp/14.17.6" "-Dnode_gyp_dir=/usr/lib/node_modules/npm/node_modules/node-gyp" "-Dnode_lib_file=/home/vitalii/.cache/node-gyp/14.17.6/<(target_arch)/node.lib" "-Dmodule_root_dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features" "-Dnode_engine=v8" binding.gyp -Makefile: $(srcdir)/../../../../../../../.cache/node-gyp/14.17.6/include/node/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/cpufeatures.node.d b/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/cpufeatures.node.d deleted file mode 100644 index 34c83d2..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/cpufeatures.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/cpufeatures.node := rm -rf "Release/cpufeatures.node" && cp -af "Release/obj.target/cpufeatures.node" "Release/cpufeatures.node" diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/build_deps.stamp.d b/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/build_deps.stamp.d deleted file mode 100644 index 3b4e8b5..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/build_deps.stamp.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/build_deps.stamp := touch Release/obj.target/build_deps.stamp diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/config_deps.stamp.d b/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/config_deps.stamp.d deleted file mode 100644 index b1b2243..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/config_deps.stamp.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/config_deps.stamp := touch Release/obj.target/config_deps.stamp diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/cpufeatures.node.d b/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/cpufeatures.node.d deleted file mode 100644 index cb65a82..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/cpufeatures.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/cpufeatures.node := g++ -shared -pthread -rdynamic -m64 -Wl,-soname=cpufeatures.node -o Release/obj.target/cpufeatures.node -Wl,--start-group Release/obj.target/cpufeatures/src/binding.o -Wl,--end-group /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/cpufeatures/src/binding.o.d b/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/cpufeatures/src/binding.o.d deleted file mode 100644 index a79a929..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/Release/obj.target/cpufeatures/src/binding.o.d +++ /dev/null @@ -1,72 +0,0 @@ -cmd_Release/obj.target/cpufeatures/src/binding.o := g++ '-DNODE_GYP_MODULE_NAME=cpufeatures' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__STDC_FORMAT_MACROS' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-DBUILDING_NODE_EXTENSION' -I/home/vitalii/.cache/node-gyp/14.17.6/include/node -I/home/vitalii/.cache/node-gyp/14.17.6/src -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/config -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/openssl/include -I/home/vitalii/.cache/node-gyp/14.17.6/deps/uv/include -I/home/vitalii/.cache/node-gyp/14.17.6/deps/zlib -I/home/vitalii/.cache/node-gyp/14.17.6/deps/v8/include -I../deps/cpu_features/include -I../src -I../../nan -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O2 -O3 -fno-omit-frame-pointer -fno-rtti -fno-exceptions -std=gnu++1y -MMD -MF ./Release/.deps/Release/obj.target/cpufeatures/src/binding.o.d.raw -c -o Release/obj.target/cpufeatures/src/binding.o ../src/binding.cc -Release/obj.target/cpufeatures/src/binding.o: ../src/binding.cc \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/cppgc/common.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8config.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-internal.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-version.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8config.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-platform.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node_version.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node_buffer.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node.h \ - ../../nan/nan.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node_version.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/errno.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/version.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/unix.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/threadpool.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/linux.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node_object_wrap.h \ - ../../nan/nan_callbacks.h ../../nan/nan_callbacks_12_inl.h \ - ../../nan/nan_maybe_43_inl.h ../../nan/nan_converters.h \ - ../../nan/nan_converters_43_inl.h ../../nan/nan_new.h \ - ../../nan/nan_implementation_12_inl.h ../../nan/nan_persistent_12_inl.h \ - ../../nan/nan_weak.h ../../nan/nan_object_wrap.h ../../nan/nan_private.h \ - ../../nan/nan_typedarray_contents.h ../../nan/nan_json.h \ - ../../nan/nan_scriptorigin.h \ - ../deps/cpu_features/include/cpu_features_macros.h \ - ../deps/cpu_features/include/cpuinfo_x86.h \ - ../deps/cpu_features/include/cpu_features_cache_info.h \ - ../deps/cpu_features/include/cpu_features_macros.h -../src/binding.cc: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/cppgc/common.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8config.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-internal.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-version.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8config.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-platform.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node_version.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node_buffer.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node.h: -../../nan/nan.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node_version.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/errno.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/version.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/unix.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/threadpool.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/linux.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node_object_wrap.h: -../../nan/nan_callbacks.h: -../../nan/nan_callbacks_12_inl.h: -../../nan/nan_maybe_43_inl.h: -../../nan/nan_converters.h: -../../nan/nan_converters_43_inl.h: -../../nan/nan_new.h: -../../nan/nan_implementation_12_inl.h: -../../nan/nan_persistent_12_inl.h: -../../nan/nan_weak.h: -../../nan/nan_object_wrap.h: -../../nan/nan_private.h: -../../nan/nan_typedarray_contents.h: -../../nan/nan_json.h: -../../nan/nan_scriptorigin.h: -../deps/cpu_features/include/cpu_features_macros.h: -../deps/cpu_features/include/cpuinfo_x86.h: -../deps/cpu_features/include/cpu_features_cache_info.h: -../deps/cpu_features/include/cpu_features_macros.h: diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile.d b/reverse_engineering/node_modules/cpu-features/build/Release/.deps/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile.d deleted file mode 100644 index b094fbb..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile.d +++ /dev/null @@ -1 +0,0 @@ -cmd_/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile := LD_LIBRARY_PATH=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/build/Release/lib.host:/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/build/Release/lib.target:$$LD_LIBRARY_PATH; export LD_LIBRARY_PATH; cd ../.; mkdir -p /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build; cmake "-DCMAKE_BUILD_TYPE=Release" "-DBUILD_PIC=ON" -B/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build -H/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a.d b/reverse_engineering/node_modules/cpu-features/build/Release/.deps/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a.d deleted file mode 100644 index 90c5a6b..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/Release/.deps/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a.d +++ /dev/null @@ -1 +0,0 @@ -cmd_/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a := LD_LIBRARY_PATH=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/build/Release/lib.host:/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/build/Release/lib.target:$$LD_LIBRARY_PATH; export LD_LIBRARY_PATH; cd ../.; mkdir -p /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build; cmake --build /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build --config Release diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/cpufeatures.node b/reverse_engineering/node_modules/cpu-features/build/Release/cpufeatures.node deleted file mode 100644 index a72e99b..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/build/Release/cpufeatures.node and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/obj.target/build_deps.stamp b/reverse_engineering/node_modules/cpu-features/build/Release/obj.target/build_deps.stamp deleted file mode 100644 index e69de29..0000000 diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/obj.target/config_deps.stamp b/reverse_engineering/node_modules/cpu-features/build/Release/obj.target/config_deps.stamp deleted file mode 100644 index e69de29..0000000 diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/obj.target/cpufeatures.node b/reverse_engineering/node_modules/cpu-features/build/Release/obj.target/cpufeatures.node deleted file mode 100644 index a72e99b..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/build/Release/obj.target/cpufeatures.node and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/build/Release/obj.target/cpufeatures/src/binding.o b/reverse_engineering/node_modules/cpu-features/build/Release/obj.target/cpufeatures/src/binding.o deleted file mode 100644 index 9e0c164..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/build/Release/obj.target/cpufeatures/src/binding.o and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/build/binding.Makefile b/reverse_engineering/node_modules/cpu-features/build/binding.Makefile deleted file mode 100644 index b019785..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= ./build/. -.PHONY: all -all: - $(MAKE) config_deps build_deps cpufeatures diff --git a/reverse_engineering/node_modules/cpu-features/build/build_deps.target.mk b/reverse_engineering/node_modules/cpu-features/build/build_deps.target.mk deleted file mode 100644 index d0d477c..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/build_deps.target.mk +++ /dev/null @@ -1,38 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := build_deps -### Rules for action "build_deps": -quiet_cmd_binding_gyp_build_deps_target_build_deps = ACTION Building dependencies $@ -cmd_binding_gyp_build_deps_target_build_deps = LD_LIBRARY_PATH=$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; export LD_LIBRARY_PATH; cd $(srcdir)/.; mkdir -p /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build; cmake --build /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build --config Release - -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a: obj := $(abs_obj) -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a: builddir := $(abs_builddir) -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a: TOOLSET := $(TOOLSET) -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt FORCE_DO_CMD - $(call do_cmd,binding_gyp_build_deps_target_build_deps) - -all_deps += /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a -action_binding_gyp_build_deps_target_build_deps_outputs := /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a - - -### Rules for final target. -# Build our special outputs first. -$(obj).target/build_deps.stamp: | $(action_binding_gyp_build_deps_target_build_deps_outputs) - -# Preserve order dependency of special output on deps. -$(action_binding_gyp_build_deps_target_build_deps_outputs): | $(obj).target/config_deps.stamp - -$(obj).target/build_deps.stamp: TOOLSET := $(TOOLSET) -$(obj).target/build_deps.stamp: $(obj).target/config_deps.stamp FORCE_DO_CMD - $(call do_cmd,touch) - -all_deps += $(obj).target/build_deps.stamp -# Add target alias -.PHONY: build_deps -build_deps: $(obj).target/build_deps.stamp - -# Add target alias to "all" target. -.PHONY: all -all: build_deps - diff --git a/reverse_engineering/node_modules/cpu-features/build/config.gypi b/reverse_engineering/node_modules/cpu-features/build/config.gypi deleted file mode 100644 index 099a31c..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/config.gypi +++ /dev/null @@ -1,204 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "asan": 0, - "build_v8_with_gn": "false", - "coverage": "false", - "dcheck_always_on": 0, - "debug_nghttp2": "false", - "debug_node": "false", - "enable_lto": "false", - "enable_pgo_generate": "false", - "enable_pgo_use": "false", - "error_on_warn": "false", - "force_dynamic_crt": 0, - "gas_version": "2.30", - "host_arch": "x64", - "icu_data_in": "../../deps/icu-tmp/icudt69l.dat", - "icu_endianness": "l", - "icu_gyp_path": "tools/icu/icu-generic.gyp", - "icu_path": "deps/icu-small", - "icu_small": "false", - "icu_ver_major": "69", - "is_debug": 0, - "llvm_version": "0.0", - "napi_build_version": "8", - "node_byteorder": "little", - "node_debug_lib": "false", - "node_enable_d8": "false", - "node_install_npm": "true", - "node_module_version": 83, - "node_no_browser_globals": "false", - "node_prefix": "/", - "node_release_urlbase": "https://nodejs.org/download/release/", - "node_section_ordering_info": "", - "node_shared": "false", - "node_shared_brotli": "false", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_nghttp2": "false", - "node_shared_openssl": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_target_type": "executable", - "node_use_bundled_v8": "true", - "node_use_dtrace": "false", - "node_use_etw": "false", - "node_use_node_code_cache": "true", - "node_use_node_snapshot": "true", - "node_use_openssl": "true", - "node_use_v8_platform": "true", - "node_with_ltcg": "false", - "node_without_node_options": "false", - "openssl_fips": "", - "openssl_is_fips": "false", - "ossfuzz": "false", - "shlib_suffix": "so.83", - "target_arch": "x64", - "v8_enable_31bit_smis_on_64bit_arch": 0, - "v8_enable_gdbjit": 0, - "v8_enable_i18n_support": 1, - "v8_enable_inspector": 1, - "v8_enable_lite_mode": 0, - "v8_enable_object_print": 1, - "v8_enable_pointer_compression": 0, - "v8_no_strict_aliasing": 1, - "v8_optimized_debug": 1, - "v8_promise_internal_field_count": 1, - "v8_random_seed": 0, - "v8_trace_maps": 0, - "v8_use_siphash": 1, - "want_separate_host_toolset": 0, - "nodedir": "/home/vitalii/.cache/node-gyp/14.17.6", - "standalone_static_library": 1, - "cache_lock_stale": "60000", - "ham_it_up": "", - "legacy_bundling": "", - "sign_git_tag": "", - "user_agent": "npm/6.14.15 node/v14.17.6 linux x64", - "always_auth": "", - "bin_links": "true", - "key": "", - "allow_same_version": "", - "description": "true", - "fetch_retries": "2", - "heading": "npm", - "if_present": "", - "init_version": "1.0.0", - "user": "", - "prefer_online": "", - "force": "", - "only": "", - "read_only": "", - "cache_min": "10", - "init_license": "ISC", - "editor": "vi", - "rollback": "true", - "tag_version_prefix": "v", - "cache_max": "Infinity", - "timing": "", - "userconfig": "/home/vitalii/.npmrc", - "engine_strict": "", - "init_author_name": "", - "init_author_url": "", - "preid": "", - "tmp": "/tmp", - "depth": "Infinity", - "package_lock_only": "", - "save_dev": "", - "usage": "", - "metrics_registry": "https://registry.npmjs.org/", - "otp": "", - "package_lock": "true", - "progress": "true", - "https_proxy": "", - "save_prod": "", - "audit": "true", - "cidr": "", - "onload_script": "", - "sso_type": "oauth", - "rebuild_bundle": "true", - "save_bundle": "", - "shell": "/bin/bash", - "dry_run": "", - "format_package_lock": "true", - "prefix": "/usr", - "scope": "", - "browser": "", - "cache_lock_wait": "10000", - "ignore_prepublish": "", - "registry": "https://registry.npmjs.org/", - "save_optional": "", - "searchopts": "", - "versions": "", - "cache": "/home/vitalii/.npm", - "send_metrics": "", - "global_style": "", - "ignore_scripts": "", - "version": "", - "local_address": "", - "viewer": "man", - "node_gyp": "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js", - "audit_level": "low", - "prefer_offline": "", - "color": "true", - "sign_git_commit": "", - "fetch_retry_mintimeout": "10000", - "maxsockets": "50", - "offline": "", - "sso_poll_frequency": "500", - "umask": "0002", - "fund": "true", - "fetch_retry_maxtimeout": "60000", - "logs_max": "10", - "message": "%s", - "ca": "", - "cert": "", - "global": "", - "link": "", - "access": "", - "also": "", - "save": "true", - "unicode": "true", - "before": "", - "long": "", - "production": "", - "searchlimit": "20", - "unsafe_perm": "true", - "update_notifier": "true", - "auth_type": "legacy", - "node_version": "14.17.6", - "tag": "latest", - "git_tag_version": "true", - "commit_hooks": "true", - "script_shell": "", - "shrinkwrap": "true", - "fetch_retry_factor": "10", - "save_exact": "", - "strict_ssl": "true", - "dev": "", - "globalconfig": "/usr/etc/npmrc", - "init_module": "/home/vitalii/.npm-init.js", - "parseable": "", - "globalignorefile": "/usr/etc/npmignore", - "cache_lock_retries": "10", - "searchstaleness": "900", - "node_options": "", - "save_prefix": "^", - "scripts_prepend_node_path": "warn-only", - "group": "1000", - "init_author_email": "", - "searchexclude": "", - "git": "git", - "optional": "true", - "json": "" - } -} diff --git a/reverse_engineering/node_modules/cpu-features/build/config_deps.target.mk b/reverse_engineering/node_modules/cpu-features/build/config_deps.target.mk deleted file mode 100644 index 01cdc49..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/config_deps.target.mk +++ /dev/null @@ -1,38 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := config_deps -### Rules for action "config_deps": -quiet_cmd_binding_gyp_config_deps_target_config_deps = ACTION Configuring dependencies $@ -cmd_binding_gyp_config_deps_target_config_deps = LD_LIBRARY_PATH=$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; export LD_LIBRARY_PATH; cd $(srcdir)/.; mkdir -p /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build; cmake "-DCMAKE_BUILD_TYPE=Release" "-DBUILD_PIC=ON" -B/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build -H/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features - -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile: obj := $(abs_obj) -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile: builddir := $(abs_builddir) -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile: TOOLSET := $(TOOLSET) -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt FORCE_DO_CMD - $(call do_cmd,binding_gyp_config_deps_target_config_deps) - -all_deps += /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile -action_binding_gyp_config_deps_target_config_deps_outputs := /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile - - -### Rules for final target. -# Build our special outputs first. -$(obj).target/config_deps.stamp: | $(action_binding_gyp_config_deps_target_config_deps_outputs) - -# Preserve order dependency of special output on deps. -$(action_binding_gyp_config_deps_target_config_deps_outputs): | - -$(obj).target/config_deps.stamp: TOOLSET := $(TOOLSET) -$(obj).target/config_deps.stamp: FORCE_DO_CMD - $(call do_cmd,touch) - -all_deps += $(obj).target/config_deps.stamp -# Add target alias -.PHONY: config_deps -config_deps: $(obj).target/config_deps.stamp - -# Add target alias to "all" target. -.PHONY: all -all: config_deps - diff --git a/reverse_engineering/node_modules/cpu-features/build/cpufeatures.target.mk b/reverse_engineering/node_modules/cpu-features/build/cpufeatures.target.mk deleted file mode 100644 index d03cdb5..0000000 --- a/reverse_engineering/node_modules/cpu-features/build/cpufeatures.target.mk +++ /dev/null @@ -1,169 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := cpufeatures -DEFS_Debug := \ - '-DNODE_GYP_MODULE_NAME=cpufeatures' \ - '-DUSING_UV_SHARED=1' \ - '-DUSING_V8_SHARED=1' \ - '-DV8_DEPRECATION_WARNINGS=1' \ - '-DV8_DEPRECATION_WARNINGS' \ - '-DV8_IMMINENT_DEPRECATION_WARNINGS' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-D__STDC_FORMAT_MACROS' \ - '-DOPENSSL_NO_PINSHARED' \ - '-DOPENSSL_THREADS' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' \ - '-DV8_ENABLE_CHECKS' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -fPIC \ - -pthread \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -m64 \ - -O2 \ - -g \ - -O0 - -# Flags passed to only C files. -CFLAGS_C_Debug := - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti \ - -fno-exceptions \ - -std=gnu++1y - -INCS_Debug := \ - -I/home/vitalii/.cache/node-gyp/14.17.6/include/node \ - -I/home/vitalii/.cache/node-gyp/14.17.6/src \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/config \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/openssl/include \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/uv/include \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/zlib \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/v8/include \ - -I$(srcdir)/deps/cpu_features/include \ - -I$(srcdir)/src \ - -I$(srcdir)/../nan - -DEFS_Release := \ - '-DNODE_GYP_MODULE_NAME=cpufeatures' \ - '-DUSING_UV_SHARED=1' \ - '-DUSING_V8_SHARED=1' \ - '-DV8_DEPRECATION_WARNINGS=1' \ - '-DV8_DEPRECATION_WARNINGS' \ - '-DV8_IMMINENT_DEPRECATION_WARNINGS' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-D__STDC_FORMAT_MACROS' \ - '-DOPENSSL_NO_PINSHARED' \ - '-DOPENSSL_THREADS' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -fPIC \ - -pthread \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -m64 \ - -O2 \ - -O3 \ - -fno-omit-frame-pointer - -# Flags passed to only C files. -CFLAGS_C_Release := - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti \ - -fno-exceptions \ - -std=gnu++1y - -INCS_Release := \ - -I/home/vitalii/.cache/node-gyp/14.17.6/include/node \ - -I/home/vitalii/.cache/node-gyp/14.17.6/src \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/config \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/openssl/include \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/uv/include \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/zlib \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/v8/include \ - -I$(srcdir)/deps/cpu_features/include \ - -I$(srcdir)/src \ - -I$(srcdir)/../nan - -OBJS := \ - $(obj).target/$(TARGET)/src/binding.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# Make sure our dependencies are built before any of us. -$(OBJS): | $(obj).target/build_deps.stamp $(obj).target/config_deps.stamp - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -pthread \ - -rdynamic \ - -m64 - -LDFLAGS_Release := \ - -pthread \ - -rdynamic \ - -m64 - -LIBS := \ - /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a - -$(obj).target/cpufeatures.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(obj).target/cpufeatures.node: LIBS := $(LIBS) -$(obj).target/cpufeatures.node: TOOLSET := $(TOOLSET) -$(obj).target/cpufeatures.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(obj).target/cpufeatures.node -# Add target alias -.PHONY: cpufeatures -cpufeatures: $(builddir)/cpufeatures.node - -# Copy this to the executable output path. -$(builddir)/cpufeatures.node: TOOLSET := $(TOOLSET) -$(builddir)/cpufeatures.node: $(obj).target/cpufeatures.node FORCE_DO_CMD - $(call do_cmd,copy) - -all_deps += $(builddir)/cpufeatures.node -# Short alias for building this executable. -.PHONY: cpufeatures.node -cpufeatures.node: $(obj).target/cpufeatures.node $(builddir)/cpufeatures.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/cpufeatures.node - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.clang-format b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.clang-format deleted file mode 100644 index 06ea346..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.clang-format +++ /dev/null @@ -1,4 +0,0 @@ ---- -Language: Cpp -BasedOnStyle: Google -... diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile deleted file mode 100644 index 41dfc93..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -# Create a virtual environment with all tools installed -# ref: https://hub.docker.com/_/alpine -FROM alpine:edge -# Install system build dependencies -RUN apk add --no-cache git clang diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml deleted file mode 100644 index 510c104..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: clang-format Check - -on: [push, pull_request] - -jobs: - # Building using the github runner environement directly. - clang-format: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Fetch origin/master - run: git fetch origin master - - name: List of changed file(s) - run: git diff --name-only FETCH_HEAD - - - name: Build clang-format docker - run: cd .github/workflows && docker build --tag=linter . - - name: Check clang-format - run: docker run --rm --init -v $(pwd):/repo linter:latest clang-format --version - - name: clang-format help - run: docker run --rm --init -v $(pwd):/repo linter:latest clang-format --help - - - name: Check current commit - run: docker run --rm --init -v $(pwd):/repo -w /repo linter:latest sh -c "git diff --name-only FETCH_HEAD | grep '\.c$\|\.h$\|\.cc$' | xargs clang-format --style=file --dry-run --Werror " diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.npmignore b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.npmignore deleted file mode 100644 index 6285424..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -cmake_build/ -build/ - -*.swp diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.travis.yml b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.travis.yml deleted file mode 100644 index b5845be..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/.travis.yml +++ /dev/null @@ -1,121 +0,0 @@ -language: c - -sudo: false - -cache: - timeout: 1000 - directories: - - $HOME/cpu_features_archives - -addons: - apt_packages: - - ninja-build - -env: - global: - TOOLCHAIN=NATIVE - CMAKE_GENERATOR=Ninja - -matrix: - include: - - os: linux - compiler: gcc - env: - TARGET=x86_64-linux-gnu - - os: linux - compiler: clang - env: - TARGET=x86_64-linux-gnu - - os: osx - compiler: gcc - env: - TARGET=x86_64-osx - CMAKE_GENERATOR="Unix Makefiles" - - os: osx - compiler: clang - env: - TARGET=x86_64-osx - CMAKE_GENERATOR="Unix Makefiles" - - os: windows - env: - TARGET=x86_64-windows - CMAKE_GENERATOR="Visual Studio 15 2017 Win64" - - # see: https://docs.travis-ci.com/user/multi-cpu-architectures/ - - os: linux - arch: ppc64le - compiler: gcc - env: - TARGET=ppc64le-linux-gnu - - os: linux - arch: ppc64le - compiler: clang - env: - TARGET=ppc64le-linux-gnu - - # Toolchains for little-endian, 64-bit ARMv8 for GNU/Linux systems - - os: linux - env: - TOOLCHAIN=LINARO - TARGET=aarch64-linux-gnu - QEMU_ARCH=aarch64 - # Toolchains for little-endian, hard-float, 32-bit ARMv7 (and earlier) for GNU/Linux systems - - os: linux - env: - TOOLCHAIN=LINARO - TARGET=arm-linux-gnueabihf - QEMU_ARCH=arm - # Toolchains for little-endian, 32-bit ARMv8 for GNU/Linux systems - - os: linux - env: - TOOLCHAIN=LINARO - TARGET=armv8l-linux-gnueabihf - QEMU_ARCH=arm - # Toolchains for little-endian, soft-float, 32-bit ARMv7 (and earlier) for GNU/Linux systems - - os: linux - env: - TOOLCHAIN=LINARO - TARGET=arm-linux-gnueabi - QEMU_ARCH=arm - # Toolchains for big-endian, 64-bit ARMv8 for GNU/Linux systems - - os: linux - env: - TOOLCHAIN=LINARO - TARGET=aarch64_be-linux-gnu - QEMU_ARCH=DISABLED - # Toolchains for big-endian, hard-float, 32-bit ARMv7 (and earlier) for GNU/Linux systems - - os: linux - env: - TOOLCHAIN=LINARO - TARGET=armeb-linux-gnueabihf - QEMU_ARCH=DISABLED - # Toolchains for big-endian, soft-float, 32-bit ARMv7 (and earlier) for GNU/Linux systems - - os: linux - env: - TOOLCHAIN=LINARO - TARGET=armeb-linux-gnueabi - QEMU_ARCH=DISABLED - - os: linux - env: - TOOLCHAIN=CODESCAPE - TARGET=mips32 - QEMU_ARCH=mips - - os: linux - env: - TOOLCHAIN=CODESCAPE - TARGET=mips32el - QEMU_ARCH=mipsel - - os: linux - env: - TOOLCHAIN=CODESCAPE - TARGET=mips64 - QEMU_ARCH=mips64 - - os: linux - env: - TOOLCHAIN=CODESCAPE - TARGET=mips64el - QEMU_ARCH=mips64el - -script: - - cmake --version - - bash -e -x ./scripts/run_integration.sh diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt deleted file mode 100644 index 545f38f..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt +++ /dev/null @@ -1,256 +0,0 @@ -cmake_minimum_required(VERSION 3.0) - -# option() honors normal variables. -# see: https://cmake.org/cmake/help/git-stage/policy/CMP0077.html -if(POLICY CMP0077) - cmake_policy(SET CMP0077 NEW) -endif() - -project(CpuFeatures VERSION 0.5.0 LANGUAGES C) - -set(CMAKE_C_STANDARD 99) - -# Default Build Type to be Release -if(NOT CMAKE_BUILD_TYPE) - set(CMAKE_BUILD_TYPE "Release" CACHE STRING - "Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel." - FORCE) -endif(NOT CMAKE_BUILD_TYPE) - -# BUILD_TESTING is a standard CMake variable, but we declare it here to make it -# prominent in the GUI. -option(BUILD_TESTING "Enable test (depends on googletest)." OFF) -# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to make -# it prominent in the GUI. -# cpu_features uses bit-fields which are - to some extends - implementation-defined (see https://en.cppreference.com/w/c/language/bit_field). -# As a consequence it is discouraged to use cpu_features as a shared library because different compilers may interpret the code in different ways. -# Prefer static linking from source whenever possible. -option(BUILD_SHARED_LIBS "Build library as shared." OFF) -# PIC -option(BUILD_PIC "Build with Position Independant Code." OFF) # Default is off at least for GCC - -# Force PIC on unix when building shared libs -# see: https://en.wikipedia.org/wiki/Position-independent_code -if(BUILD_SHARED_LIBS AND UNIX) - set(BUILD_PIC ON) -endif() - -include(CheckIncludeFile) -include(CheckSymbolExists) -include(GNUInstallDirs) - -macro(setup_include_and_definitions TARGET_NAME) - target_include_directories(${TARGET_NAME} - PUBLIC $ - PRIVATE $ - ) - target_compile_definitions(${TARGET_NAME} - PUBLIC STACK_LINE_READER_BUFFER_SIZE=1024 - ) -endmacro() - -set(PROCESSOR_IS_MIPS FALSE) -set(PROCESSOR_IS_ARM FALSE) -set(PROCESSOR_IS_AARCH64 FALSE) -set(PROCESSOR_IS_X86 FALSE) -set(PROCESSOR_IS_POWER FALSE) - -if(CMAKE_SYSTEM_PROCESSOR MATCHES "^mips") - set(PROCESSOR_IS_MIPS TRUE) -elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^arm") - set(PROCESSOR_IS_ARM TRUE) -elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^aarch64") - set(PROCESSOR_IS_AARCH64 TRUE) -elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "(x86_64)|(AMD64|amd64)|(^i.86$)") - set(PROCESSOR_IS_X86 TRUE) -elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^(powerpc|ppc)") - set(PROCESSOR_IS_POWER TRUE) -endif() - -macro(add_cpu_features_headers_and_sources HDRS_LIST_NAME SRCS_LIST_NAME) - list(APPEND ${HDRS_LIST_NAME} ${PROJECT_SOURCE_DIR}/include/cpu_features_macros.h) - list(APPEND ${HDRS_LIST_NAME} ${PROJECT_SOURCE_DIR}/include/cpu_features_cache_info.h) - if(PROCESSOR_IS_MIPS) - list(APPEND ${HDRS_LIST_NAME} ${PROJECT_SOURCE_DIR}/include/cpuinfo_mips.h) - list(APPEND ${SRCS_LIST_NAME} ${PROJECT_SOURCE_DIR}/src/cpuinfo_mips.c) - elseif(PROCESSOR_IS_ARM) - list(APPEND ${HDRS_LIST_NAME} ${PROJECT_SOURCE_DIR}/include/cpuinfo_arm.h) - list(APPEND ${SRCS_LIST_NAME} ${PROJECT_SOURCE_DIR}/src/cpuinfo_arm.c) - elseif(PROCESSOR_IS_AARCH64) - list(APPEND ${HDRS_LIST_NAME} ${PROJECT_SOURCE_DIR}/include/cpuinfo_aarch64.h) - list(APPEND ${SRCS_LIST_NAME} ${PROJECT_SOURCE_DIR}/src/cpuinfo_aarch64.c) - elseif(PROCESSOR_IS_X86) - list(APPEND ${HDRS_LIST_NAME} ${PROJECT_SOURCE_DIR}/include/cpuinfo_x86.h) - list(APPEND ${SRCS_LIST_NAME} ${PROJECT_SOURCE_DIR}/include/internal/cpuid_x86.h) - list(APPEND ${SRCS_LIST_NAME} ${PROJECT_SOURCE_DIR}/src/cpuinfo_x86.c) - elseif(PROCESSOR_IS_POWER) - list(APPEND ${HDRS_LIST_NAME} ${PROJECT_SOURCE_DIR}/include/cpuinfo_ppc.h) - list(APPEND ${SRCS_LIST_NAME} ${PROJECT_SOURCE_DIR}/src/cpuinfo_ppc.c) - else() - message(FATAL_ERROR "Unsupported architectures ${CMAKE_SYSTEM_PROCESSOR}") - endif() -endmacro() - -# -# library : utils -# - -add_library(utils OBJECT - ${PROJECT_SOURCE_DIR}/include/internal/bit_utils.h - ${PROJECT_SOURCE_DIR}/include/internal/filesystem.h - ${PROJECT_SOURCE_DIR}/include/internal/stack_line_reader.h - ${PROJECT_SOURCE_DIR}/include/internal/string_view.h - ${PROJECT_SOURCE_DIR}/src/filesystem.c - ${PROJECT_SOURCE_DIR}/src/stack_line_reader.c - ${PROJECT_SOURCE_DIR}/src/string_view.c -) -set_property(TARGET utils PROPERTY POSITION_INDEPENDENT_CODE ${BUILD_PIC}) -setup_include_and_definitions(utils) - -# -# library : unix_based_hardware_detection -# - -if(UNIX) - add_library(unix_based_hardware_detection OBJECT - ${PROJECT_SOURCE_DIR}/include/internal/hwcaps.h - ${PROJECT_SOURCE_DIR}/include/internal/unix_features_aggregator.h - ${PROJECT_SOURCE_DIR}/src/hwcaps.c - ${PROJECT_SOURCE_DIR}/src/unix_features_aggregator.c - ) - setup_include_and_definitions(unix_based_hardware_detection) - check_include_file(dlfcn.h HAVE_DLFCN_H) - if(HAVE_DLFCN_H) - target_compile_definitions(unix_based_hardware_detection PRIVATE HAVE_DLFCN_H) - endif() - check_symbol_exists(getauxval "sys/auxv.h" HAVE_STRONG_GETAUXVAL) - if(HAVE_STRONG_GETAUXVAL) - target_compile_definitions(unix_based_hardware_detection PRIVATE HAVE_STRONG_GETAUXVAL) - endif() - set_property(TARGET unix_based_hardware_detection PROPERTY POSITION_INDEPENDENT_CODE ${BUILD_PIC}) -endif() - -# -# library : cpu_features -# -set (CPU_FEATURES_HDRS) -set (CPU_FEATURES_SRCS) -add_cpu_features_headers_and_sources(CPU_FEATURES_HDRS CPU_FEATURES_SRCS) -list(APPEND CPU_FEATURES_SRCS $) -if(NOT PROCESSOR_IS_X86 AND UNIX) - list(APPEND CPU_FEATURES_SRCS $) -endif() -add_library(cpu_features ${CPU_FEATURES_HDRS} ${CPU_FEATURES_SRCS}) -set_target_properties(cpu_features PROPERTIES PUBLIC_HEADER "${CPU_FEATURES_HDRS}") -setup_include_and_definitions(cpu_features) -target_link_libraries(cpu_features PUBLIC ${CMAKE_DL_LIBS}) -set_property(TARGET cpu_features PROPERTY POSITION_INDEPENDENT_CODE ${BUILD_PIC}) -target_include_directories(cpu_features - PUBLIC $ -) -add_library(CpuFeature::cpu_features ALIAS cpu_features) - -# -# program : list_cpu_features -# - -add_executable(list_cpu_features ${PROJECT_SOURCE_DIR}/src/utils/list_cpu_features.c) -target_link_libraries(list_cpu_features PRIVATE cpu_features) -add_executable(CpuFeature::list_cpu_features ALIAS list_cpu_features) - -# -# ndk_compat -# - -if(ANDROID) -add_subdirectory(ndk_compat) -endif() - -# -# tests -# - -include(CTest) -if(BUILD_TESTING) - # Automatically incorporate googletest into the CMake Project if target not - # found. - enable_language(CXX) - - set(CMAKE_CXX_STANDARD 11) - set(CMAKE_CXX_STANDARD_REQUIRED ON) - set(CMAKE_CXX_EXTENSIONS OFF) # prefer use of -std11 instead of -gnustd11 - - if(NOT TARGET gtest OR NOT TARGET gmock_main) - # Download and unpack googletest at configure time. - configure_file( - cmake/googletest.CMakeLists.txt.in - googletest-download/CMakeLists.txt - ) - - execute_process( - COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . - RESULT_VARIABLE result - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) - - if(result) - message(FATAL_ERROR "CMake step for googletest failed: ${result}") - endif() - - execute_process( - COMMAND ${CMAKE_COMMAND} --build . - RESULT_VARIABLE result - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) - - if(result) - message(FATAL_ERROR "Build step for googletest failed: ${result}") - endif() - - # Prevent overriding the parent project's compiler/linker settings on - # Windows. - set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) - - # Add googletest directly to our build. This defines the gtest and - # gtest_main targets. - add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src - ${CMAKE_BINARY_DIR}/googletest-build - EXCLUDE_FROM_ALL) - endif() - - add_subdirectory(test) -endif() - -# -# Install cpu_features and list_cpu_features -# - -include(GNUInstallDirs) -install(TARGETS cpu_features list_cpu_features - EXPORT CpuFeaturesTargets - PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/cpu_features - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} -) -install(EXPORT CpuFeaturesTargets - NAMESPACE CpuFeatures:: - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/CpuFeatures - COMPONENT Devel -) -include(CMakePackageConfigHelpers) -configure_package_config_file(cmake/CpuFeaturesConfig.cmake.in - "${PROJECT_BINARY_DIR}/CpuFeaturesConfig.cmake" - INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/CpuFeatures" - NO_SET_AND_CHECK_MACRO - NO_CHECK_REQUIRED_COMPONENTS_MACRO -) -write_basic_package_version_file( - "${PROJECT_BINARY_DIR}/CpuFeaturesConfigVersion.cmake" - COMPATIBILITY SameMajorVersion -) -install( - FILES - "${PROJECT_BINARY_DIR}/CpuFeaturesConfig.cmake" - "${PROJECT_BINARY_DIR}/CpuFeaturesConfigVersion.cmake" - DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/CpuFeatures" - COMPONENT Devel -) diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md deleted file mode 100644 index c980350..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md +++ /dev/null @@ -1,23 +0,0 @@ -# How to Contribute - -We'd love to accept your patches and contributions to this project. There are -just a few small guidelines you need to follow. - -## Contributor License Agreement - -Contributions to this project must be accompanied by a Contributor License -Agreement. You (or your employer) retain the copyright to your contribution; -this simply gives us permission to use and redistribute your contributions as -part of the project. Head over to to see -your current agreements on file or to sign a new one. - -You generally only need to submit a CLA once, so if you've already submitted one -(even if it was for a different project), you probably don't need to do it -again. - -## Code reviews - -All submissions, including submissions by project members, require review. We -use GitHub pull requests for this purpose. Consult -[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more -information on using pull requests. diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/LICENSE b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/LICENSE deleted file mode 100644 index a7043c6..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/LICENSE +++ /dev/null @@ -1,230 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - --------------------------------------------------------------------------------- -For files in the `ndk_compat` folder: --------------------------------------------------------------------------------- - -Copyright (C) 2010 The Android Open Source Project -All rights reserved. -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS -OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -SUCH DAMAGE. diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/README.md b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/README.md deleted file mode 100644 index 8a34168..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/README.md +++ /dev/null @@ -1,199 +0,0 @@ -# cpu_features [![Build Status](https://travis-ci.org/google/cpu_features.svg?branch=master)](https://travis-ci.org/google/cpu_features) [![Build status](https://ci.appveyor.com/api/projects/status/46d1owsj7n8dsylq/branch/master?svg=true)](https://ci.appveyor.com/project/gchatelet/cpu-features/branch/master) - -A cross-platform C library to retrieve CPU features (such as available -instructions) at runtime. - -## Table of Contents - -- [Design Rationale](#rationale) -- [Code samples](#codesample) -- [Running sample code](#usagesample) -- [What's supported](#support) -- [Android NDK's drop in replacement](#ndk) -- [License](#license) -- [Build with cmake](#cmake) - - -## Design Rationale - -- **Simple to use.** See the snippets below for examples. -- **Extensible.** Easy to add missing features or architectures. -- **Compatible with old compilers** and available on many architectures so it - can be used widely. To ensure that cpu_features works on as many platforms - as possible, we implemented it in a highly portable version of C: C99. -- **Sandbox-compatible.** The library uses a variety of strategies to cope - with sandboxed environments or when `cpuid` is unavailable. This is useful - when running integration tests in hermetic environments. -- **Thread safe, no memory allocation, and raises no exceptions.** - cpu_features is suitable for implementing fundamental libc functions like - `malloc`, `memcpy`, and `memcmp`. -- **Unit tested.** - - -## Code samples - -**Note:** For C++ code, the library functions are defined in the `CpuFeatures` namespace. - -### Checking features at runtime - -Here's a simple example that executes a codepath if the CPU supports both the -AES and the SSE4.2 instruction sets: - -```c -#include "cpuinfo_x86.h" - -// For C++, add `using namespace CpuFeatures;` -static const X86Features features = GetX86Info().features; - -void Compute(void) { - if (features.aes && features.sse4_2) { - // Run optimized code. - } else { - // Run standard code. - } -} -``` - -### Caching for faster evaluation of complex checks - -If you wish, you can read all the features at once into a global variable, and -then query for the specific features you care about. Below, we store all the ARM -features and then check whether AES and NEON are supported. - -```c -#include -#include "cpuinfo_arm.h" - -// For C++, add `using namespace CpuFeatures;` -static const ArmFeatures features = GetArmInfo().features; -static const bool has_aes_and_neon = features.aes && features.neon; - -// use has_aes_and_neon. -``` - -This is a good approach to take if you're checking for combinations of features -when using a compiler that is slow to extract individual bits from bit-packed -structures. - -### Checking compile time flags - -The following code determines whether the compiler was told to use the AVX -instruction set (e.g., `g++ -mavx`) and sets `has_avx` accordingly. - -```c -#include -#include "cpuinfo_x86.h" - -// For C++, add `using namespace CpuFeatures;` -static const X86Features features = GetX86Info().features; -static const bool has_avx = CPU_FEATURES_COMPILED_X86_AVX || features.avx; - -// use has_avx. -``` - -`CPU_FEATURES_COMPILED_X86_AVX` is set to 1 if the compiler was instructed to -use AVX and 0 otherwise, combining compile time and runtime knowledge. - -### Rejecting poor hardware implementations based on microarchitecture - -On x86, the first incarnation of a feature in a microarchitecture might not be -the most efficient (e.g. AVX on Sandy Bridge). We provide a function to retrieve -the underlying microarchitecture so you can decide whether to use it. - -Below, `has_fast_avx` is set to 1 if the CPU supports the AVX instruction -set—but only if it's not Sandy Bridge. - -```c -#include -#include "cpuinfo_x86.h" - -// For C++, add `using namespace CpuFeatures;` -static const X86Info info = GetX86Info(); -static const X86Microarchitecture uarch = GetX86Microarchitecture(&info); -static const bool has_fast_avx = info.features.avx && uarch != INTEL_SNB; - -// use has_fast_avx. -``` - -This feature is currently available only for x86 microarchitectures. - - -### Running sample code - -Building `cpu_features` (check [quickstart](#quickstart) below) brings a small executable to test the library. - -```shell - % ./build/list_cpu_features -arch : x86 -brand : Intel(R) Xeon(R) CPU E5-1650 0 @ 3.20GHz -family : 6 (0x06) -model : 45 (0x2D) -stepping : 7 (0x07) -uarch : INTEL_SNB -flags : aes,avx,cx16,smx,sse4_1,sse4_2,ssse3 -``` - -```shell -% ./build/list_cpu_features --json -{"arch":"x86","brand":" Intel(R) Xeon(R) CPU E5-1650 0 @ 3.20GHz","family":6,"model":45,"stepping":7,"uarch":"INTEL_SNB","flags":["aes","avx","cx16","smx","sse4_1","sse4_2","ssse3"]} -``` - - -## What's supported - -| | x86³ | ARM | AArch64 | MIPS⁴ | POWER | -|---------|:----:|:-------:|:-------:|:------:|:-------:| -| Android | yes² | yes¹ | yes¹ | yes¹ | N/A | -| iOS | N/A | not yet | not yet | N/A | N/A | -| Linux | yes² | yes¹ | yes¹ | yes¹ | yes¹ | -| MacOs | yes² | N/A | not yet | N/A | no | -| Windows | yes² | not yet | not yet | N/A | N/A | - -1. **Features revealed from Linux.** We gather data from several sources - depending on availability: - + from glibc's - [getauxval](https://www.gnu.org/software/libc/manual/html_node/Auxiliary-Vector.html) - + by parsing `/proc/self/auxv` - + by parsing `/proc/cpuinfo` -2. **Features revealed from CPU.** features are retrieved by using the `cpuid` - instruction. -3. **Microarchitecture detection.** On x86 some features are not always - implemented efficiently in hardware (e.g. AVX on Sandybridge). Exposing the - microarchitecture allows the client to reject particular microarchitectures. -4. All flavors of Mips are supported, little and big endian as well as 32/64 - bits. - - -## Android NDK's drop in replacement - -[cpu_features](https://github.com/google/cpu_features) is now officially -supporting Android and offers a drop in replacement of for the NDK's [cpu-features.h](https://android.googlesource.com/platform/ndk/+/master/sources/android/cpufeatures/cpu-features.h) -, see [ndk_compat](ndk_compat) folder for details. - - -## License - -The cpu_features library is licensed under the terms of the Apache license. -See [LICENSE](LICENSE) for more information. - - -## Build with CMake - -Please check the [CMake build instructions](cmake/README.md). - - -### Quickstart with `Ninja` - - - build `list_cpu_features` -``` - cmake -B/tmp/cpu_features -H. -GNinja -DCMAKE_BUILD_TYPE=Release - ninja -C/tmp/cpu_features - /tmp/cpu_features/list_cpu_features --json -``` - - - run tests -``` - cmake -B/tmp/cpu_features -H. -GNinja -DBUILD_TESTING=ON - ninja -C/tmp/cpu_features - ninja -C/tmp/cpu_features test -``` diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/WORKSPACE b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/WORKSPACE deleted file mode 100644 index 8ea8a8b..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/WORKSPACE +++ /dev/null @@ -1,7 +0,0 @@ -# ===== googletest ===== - -git_repository( - name = "com_google_googletest", - remote = "https://github.com/google/googletest.git", - commit = "c3f65335b79f47b05629e79a54685d899bc53b93", -) diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/appveyor.yml b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/appveyor.yml deleted file mode 100644 index f18635a..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/appveyor.yml +++ /dev/null @@ -1,24 +0,0 @@ -version: '{build}' -shallow_clone: true - -platform: x64 - -environment: - matrix: - - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - CMAKE_GENERATOR: "Visual Studio 15 2017 Win64" - - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 - CMAKE_GENERATOR: "Visual Studio 14 2015 Win64" - -matrix: - fast_finish: true - -before_build: - - cmake --version - - cmake -DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTING=ON -H. -Bcmake_build -G "%CMAKE_GENERATOR%" - -build_script: - - cmake --build cmake_build --config Debug --target ALL_BUILD - -test_script: - - cmake --build cmake_build --config Debug --target RUN_TESTS diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeCache.txt b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeCache.txt deleted file mode 100644 index af636ad..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeCache.txt +++ /dev/null @@ -1,385 +0,0 @@ -# This is the CMakeCache file. -# For build in directory: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build -# It was generated by CMake: /usr/bin/cmake -# You can edit this file to change values found and used by cmake. -# If you do not want to change any of the values, simply exit the editor. -# If you do want to change a value, simply edit, save, and exit the editor. -# The syntax for the file is as follows: -# KEY:TYPE=VALUE -# KEY is the name of a variable in the cache. -# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. -# VALUE is the current value for the KEY. - -######################## -# EXTERNAL cache entries -######################## - -//Build with Position Independant Code. -BUILD_PIC:BOOL=ON - -//Build library as shared. -BUILD_SHARED_LIBS:BOOL=OFF - -//Build the testing tree. -BUILD_TESTING:BOOL=OFF - -//Path to a program. -CMAKE_AR:FILEPATH=/usr/bin/ar - -//Choose the type of build, options are: None(CMAKE_CXX_FLAGS or -// CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel. -CMAKE_BUILD_TYPE:STRING=Release - -//Enable/Disable color output during build. -CMAKE_COLOR_MAKEFILE:BOOL=ON - -//C compiler -CMAKE_C_COMPILER:FILEPATH=/usr/bin/cc - -//A wrapper around 'ar' adding the appropriate '--plugin' option -// for the GCC compiler -CMAKE_C_COMPILER_AR:FILEPATH=/usr/bin/gcc-ar-7 - -//A wrapper around 'ranlib' adding the appropriate '--plugin' option -// for the GCC compiler -CMAKE_C_COMPILER_RANLIB:FILEPATH=/usr/bin/gcc-ranlib-7 - -//Flags used by the compiler during all build types. -CMAKE_C_FLAGS:STRING= - -//Flags used by the compiler during debug builds. -CMAKE_C_FLAGS_DEBUG:STRING=-g - -//Flags used by the compiler during release builds for minimum -// size. -CMAKE_C_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG - -//Flags used by the compiler during release builds. -CMAKE_C_FLAGS_RELEASE:STRING=-O3 -DNDEBUG - -//Flags used by the compiler during release builds with debug info. -CMAKE_C_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG - -//Flags used by the linker. -CMAKE_EXE_LINKER_FLAGS:STRING= - -//Flags used by the linker during debug builds. -CMAKE_EXE_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during release minsize builds. -CMAKE_EXE_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during release builds. -CMAKE_EXE_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during Release with Debug Info builds. -CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//Enable/Disable output of compile commands during generation. -CMAKE_EXPORT_COMPILE_COMMANDS:BOOL=OFF - -//User executables (bin) -CMAKE_INSTALL_BINDIR:PATH=bin - -//Read-only architecture-independent data (DATAROOTDIR) -CMAKE_INSTALL_DATADIR:PATH= - -//Read-only architecture-independent data root (share) -CMAKE_INSTALL_DATAROOTDIR:PATH=share - -//Documentation root (DATAROOTDIR/doc/PROJECT_NAME) -CMAKE_INSTALL_DOCDIR:PATH= - -//C header files (include) -CMAKE_INSTALL_INCLUDEDIR:PATH=include - -//Info documentation (DATAROOTDIR/info) -CMAKE_INSTALL_INFODIR:PATH= - -//Object code libraries (lib) -CMAKE_INSTALL_LIBDIR:PATH=lib - -//Program executables (libexec) -CMAKE_INSTALL_LIBEXECDIR:PATH=libexec - -//Locale-dependent data (DATAROOTDIR/locale) -CMAKE_INSTALL_LOCALEDIR:PATH= - -//Modifiable single-machine data (var) -CMAKE_INSTALL_LOCALSTATEDIR:PATH=var - -//Man documentation (DATAROOTDIR/man) -CMAKE_INSTALL_MANDIR:PATH= - -//C header files for non-gcc (/usr/include) -CMAKE_INSTALL_OLDINCLUDEDIR:PATH=/usr/include - -//Install path prefix, prepended onto install directories. -CMAKE_INSTALL_PREFIX:PATH=/usr/local - -//Run-time variable data (LOCALSTATEDIR/run) -CMAKE_INSTALL_RUNSTATEDIR:PATH= - -//System admin executables (sbin) -CMAKE_INSTALL_SBINDIR:PATH=sbin - -//Modifiable architecture-independent data (com) -CMAKE_INSTALL_SHAREDSTATEDIR:PATH=com - -//Read-only single-machine data (etc) -CMAKE_INSTALL_SYSCONFDIR:PATH=etc - -//Path to a program. -CMAKE_LINKER:FILEPATH=/usr/bin/ld - -//Path to a program. -CMAKE_MAKE_PROGRAM:FILEPATH=/usr/bin/make - -//Flags used by the linker during the creation of modules. -CMAKE_MODULE_LINKER_FLAGS:STRING= - -//Flags used by the linker during debug builds. -CMAKE_MODULE_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during release minsize builds. -CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during release builds. -CMAKE_MODULE_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during Release with Debug Info builds. -CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//Path to a program. -CMAKE_NM:FILEPATH=/usr/bin/nm - -//Path to a program. -CMAKE_OBJCOPY:FILEPATH=/usr/bin/objcopy - -//Path to a program. -CMAKE_OBJDUMP:FILEPATH=/usr/bin/objdump - -//Value Computed by CMake -CMAKE_PROJECT_NAME:STATIC=CpuFeatures - -//Path to a program. -CMAKE_RANLIB:FILEPATH=/usr/bin/ranlib - -//Flags used by the linker during the creation of dll's. -CMAKE_SHARED_LINKER_FLAGS:STRING= - -//Flags used by the linker during debug builds. -CMAKE_SHARED_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during release minsize builds. -CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during release builds. -CMAKE_SHARED_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during Release with Debug Info builds. -CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//If set, runtime paths are not added when installing shared libraries, -// but are added when building. -CMAKE_SKIP_INSTALL_RPATH:BOOL=NO - -//If set, runtime paths are not added when using shared libraries. -CMAKE_SKIP_RPATH:BOOL=NO - -//Flags used by the linker during the creation of static libraries. -CMAKE_STATIC_LINKER_FLAGS:STRING= - -//Flags used by the linker during debug builds. -CMAKE_STATIC_LINKER_FLAGS_DEBUG:STRING= - -//Flags used by the linker during release minsize builds. -CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL:STRING= - -//Flags used by the linker during release builds. -CMAKE_STATIC_LINKER_FLAGS_RELEASE:STRING= - -//Flags used by the linker during Release with Debug Info builds. -CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO:STRING= - -//Path to a program. -CMAKE_STRIP:FILEPATH=/usr/bin/strip - -//If this value is on, makefiles will be generated without the -// .SILENT directive, and all commands will be echoed to the console -// during the make. This is useful for debugging only. With Visual -// Studio IDE projects all commands are done without /nologo. -CMAKE_VERBOSE_MAKEFILE:BOOL=FALSE - -//Value Computed by CMake -CpuFeatures_BINARY_DIR:STATIC=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build - -//Value Computed by CMake -CpuFeatures_SOURCE_DIR:STATIC=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features - -//Dependencies for the target -cpu_features_LIB_DEPENDS:STATIC=general;dl; - - -######################## -# INTERNAL cache entries -######################## - -//ADVANCED property for variable: CMAKE_AR -CMAKE_AR-ADVANCED:INTERNAL=1 -//This is the directory where this CMakeCache.txt was created -CMAKE_CACHEFILE_DIR:INTERNAL=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build -//Major version of cmake used to create the current loaded cache -CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3 -//Minor version of cmake used to create the current loaded cache -CMAKE_CACHE_MINOR_VERSION:INTERNAL=10 -//Patch version of cmake used to create the current loaded cache -CMAKE_CACHE_PATCH_VERSION:INTERNAL=2 -//ADVANCED property for variable: CMAKE_COLOR_MAKEFILE -CMAKE_COLOR_MAKEFILE-ADVANCED:INTERNAL=1 -//Path to CMake executable. -CMAKE_COMMAND:INTERNAL=/usr/bin/cmake -//Path to cpack program executable. -CMAKE_CPACK_COMMAND:INTERNAL=/usr/bin/cpack -//Path to ctest program executable. -CMAKE_CTEST_COMMAND:INTERNAL=/usr/bin/ctest -//ADVANCED property for variable: CMAKE_C_COMPILER -CMAKE_C_COMPILER-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_COMPILER_AR -CMAKE_C_COMPILER_AR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_COMPILER_RANLIB -CMAKE_C_COMPILER_RANLIB-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS -CMAKE_C_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_DEBUG -CMAKE_C_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_MINSIZEREL -CMAKE_C_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_RELEASE -CMAKE_C_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_C_FLAGS_RELWITHDEBINFO -CMAKE_C_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//Executable file format -CMAKE_EXECUTABLE_FORMAT:INTERNAL=ELF -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS -CMAKE_EXE_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_DEBUG -CMAKE_EXE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_MINSIZEREL -CMAKE_EXE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELEASE -CMAKE_EXE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_EXPORT_COMPILE_COMMANDS -CMAKE_EXPORT_COMPILE_COMMANDS-ADVANCED:INTERNAL=1 -//Name of external makefile project generator. -CMAKE_EXTRA_GENERATOR:INTERNAL= -//Name of generator. -CMAKE_GENERATOR:INTERNAL=Unix Makefiles -//Name of generator platform. -CMAKE_GENERATOR_PLATFORM:INTERNAL= -//Name of generator toolset. -CMAKE_GENERATOR_TOOLSET:INTERNAL= -//Source directory with the top level CMakeLists.txt file for this -// project -CMAKE_HOME_DIRECTORY:INTERNAL=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features -//ADVANCED property for variable: CMAKE_INSTALL_BINDIR -CMAKE_INSTALL_BINDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_DATADIR -CMAKE_INSTALL_DATADIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_DATAROOTDIR -CMAKE_INSTALL_DATAROOTDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_DOCDIR -CMAKE_INSTALL_DOCDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_INCLUDEDIR -CMAKE_INSTALL_INCLUDEDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_INFODIR -CMAKE_INSTALL_INFODIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_LIBDIR -CMAKE_INSTALL_LIBDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_LIBEXECDIR -CMAKE_INSTALL_LIBEXECDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_LOCALEDIR -CMAKE_INSTALL_LOCALEDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_LOCALSTATEDIR -CMAKE_INSTALL_LOCALSTATEDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_MANDIR -CMAKE_INSTALL_MANDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_OLDINCLUDEDIR -CMAKE_INSTALL_OLDINCLUDEDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_RUNSTATEDIR -CMAKE_INSTALL_RUNSTATEDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_SBINDIR -CMAKE_INSTALL_SBINDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_SHAREDSTATEDIR -CMAKE_INSTALL_SHAREDSTATEDIR-ADVANCED:INTERNAL=1 -//Install .so files without execute permission. -CMAKE_INSTALL_SO_NO_EXE:INTERNAL=1 -//ADVANCED property for variable: CMAKE_INSTALL_SYSCONFDIR -CMAKE_INSTALL_SYSCONFDIR-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_LINKER -CMAKE_LINKER-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MAKE_PROGRAM -CMAKE_MAKE_PROGRAM-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS -CMAKE_MODULE_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_DEBUG -CMAKE_MODULE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL -CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELEASE -CMAKE_MODULE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_NM -CMAKE_NM-ADVANCED:INTERNAL=1 -//number of local generators -CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=1 -//ADVANCED property for variable: CMAKE_OBJCOPY -CMAKE_OBJCOPY-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_OBJDUMP -CMAKE_OBJDUMP-ADVANCED:INTERNAL=1 -//Platform information initialized -CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_RANLIB -CMAKE_RANLIB-ADVANCED:INTERNAL=1 -//Path to CMake installation. -CMAKE_ROOT:INTERNAL=/usr/share/cmake-3.10 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS -CMAKE_SHARED_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_DEBUG -CMAKE_SHARED_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL -CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELEASE -CMAKE_SHARED_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH -CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_SKIP_RPATH -CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS -CMAKE_STATIC_LINKER_FLAGS-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_DEBUG -CMAKE_STATIC_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL -CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELEASE -CMAKE_STATIC_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO -CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 -//ADVANCED property for variable: CMAKE_STRIP -CMAKE_STRIP-ADVANCED:INTERNAL=1 -//uname command -CMAKE_UNAME:INTERNAL=/bin/uname -//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE -CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1 -//Have include dlfcn.h -HAVE_DLFCN_H:INTERNAL=1 -//Have symbol getauxval -HAVE_STRONG_GETAUXVAL:INTERNAL=1 -//CMAKE_INSTALL_PREFIX during last run -_GNUInstallDirs_LAST_CMAKE_INSTALL_PREFIX:INTERNAL=/usr/local - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CMakeCCompiler.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CMakeCCompiler.cmake deleted file mode 100644 index 9e0e71d..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CMakeCCompiler.cmake +++ /dev/null @@ -1,73 +0,0 @@ -set(CMAKE_C_COMPILER "/usr/bin/cc") -set(CMAKE_C_COMPILER_ARG1 "") -set(CMAKE_C_COMPILER_ID "GNU") -set(CMAKE_C_COMPILER_VERSION "7.5.0") -set(CMAKE_C_COMPILER_VERSION_INTERNAL "") -set(CMAKE_C_COMPILER_WRAPPER "") -set(CMAKE_C_STANDARD_COMPUTED_DEFAULT "11") -set(CMAKE_C_COMPILE_FEATURES "c_std_90;c_function_prototypes;c_std_99;c_restrict;c_variadic_macros;c_std_11;c_static_assert") -set(CMAKE_C90_COMPILE_FEATURES "c_std_90;c_function_prototypes") -set(CMAKE_C99_COMPILE_FEATURES "c_std_99;c_restrict;c_variadic_macros") -set(CMAKE_C11_COMPILE_FEATURES "c_std_11;c_static_assert") - -set(CMAKE_C_PLATFORM_ID "Linux") -set(CMAKE_C_SIMULATE_ID "") -set(CMAKE_C_SIMULATE_VERSION "") - - - -set(CMAKE_AR "/usr/bin/ar") -set(CMAKE_C_COMPILER_AR "/usr/bin/gcc-ar-7") -set(CMAKE_RANLIB "/usr/bin/ranlib") -set(CMAKE_C_COMPILER_RANLIB "/usr/bin/gcc-ranlib-7") -set(CMAKE_LINKER "/usr/bin/ld") -set(CMAKE_COMPILER_IS_GNUCC 1) -set(CMAKE_C_COMPILER_LOADED 1) -set(CMAKE_C_COMPILER_WORKS TRUE) -set(CMAKE_C_ABI_COMPILED TRUE) -set(CMAKE_COMPILER_IS_MINGW ) -set(CMAKE_COMPILER_IS_CYGWIN ) -if(CMAKE_COMPILER_IS_CYGWIN) - set(CYGWIN 1) - set(UNIX 1) -endif() - -set(CMAKE_C_COMPILER_ENV_VAR "CC") - -if(CMAKE_COMPILER_IS_MINGW) - set(MINGW 1) -endif() -set(CMAKE_C_COMPILER_ID_RUN 1) -set(CMAKE_C_SOURCE_FILE_EXTENSIONS c;m) -set(CMAKE_C_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) -set(CMAKE_C_LINKER_PREFERENCE 10) - -# Save compiler ABI information. -set(CMAKE_C_SIZEOF_DATA_PTR "8") -set(CMAKE_C_COMPILER_ABI "ELF") -set(CMAKE_C_LIBRARY_ARCHITECTURE "x86_64-linux-gnu") - -if(CMAKE_C_SIZEOF_DATA_PTR) - set(CMAKE_SIZEOF_VOID_P "${CMAKE_C_SIZEOF_DATA_PTR}") -endif() - -if(CMAKE_C_COMPILER_ABI) - set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_C_COMPILER_ABI}") -endif() - -if(CMAKE_C_LIBRARY_ARCHITECTURE) - set(CMAKE_LIBRARY_ARCHITECTURE "x86_64-linux-gnu") -endif() - -set(CMAKE_C_CL_SHOWINCLUDES_PREFIX "") -if(CMAKE_C_CL_SHOWINCLUDES_PREFIX) - set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_C_CL_SHOWINCLUDES_PREFIX}") -endif() - - - - - -set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "gcc;gcc_s;c;gcc;gcc_s") -set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "/usr/lib/gcc/x86_64-linux-gnu/7;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib") -set(CMAKE_C_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "") diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CMakeDetermineCompilerABI_C.bin b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CMakeDetermineCompilerABI_C.bin deleted file mode 100644 index b1860a3..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CMakeDetermineCompilerABI_C.bin and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CMakeSystem.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CMakeSystem.cmake deleted file mode 100644 index 6ab2d72..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CMakeSystem.cmake +++ /dev/null @@ -1,15 +0,0 @@ -set(CMAKE_HOST_SYSTEM "Linux-5.4.0-89-generic") -set(CMAKE_HOST_SYSTEM_NAME "Linux") -set(CMAKE_HOST_SYSTEM_VERSION "5.4.0-89-generic") -set(CMAKE_HOST_SYSTEM_PROCESSOR "x86_64") - - - -set(CMAKE_SYSTEM "Linux-5.4.0-89-generic") -set(CMAKE_SYSTEM_NAME "Linux") -set(CMAKE_SYSTEM_VERSION "5.4.0-89-generic") -set(CMAKE_SYSTEM_PROCESSOR "x86_64") - -set(CMAKE_CROSSCOMPILING "FALSE") - -set(CMAKE_SYSTEM_LOADED 1) diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CompilerIdC/CMakeCCompilerId.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CompilerIdC/CMakeCCompilerId.c deleted file mode 100644 index 722faa8..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CompilerIdC/CMakeCCompilerId.c +++ /dev/null @@ -1,598 +0,0 @@ -#ifdef __cplusplus -# error "A C++ compiler has been selected for C." -#endif - -#if defined(__18CXX) -# define ID_VOID_MAIN -#endif -#if defined(__CLASSIC_C__) -/* cv-qualifiers did not exist in K&R C */ -# define const -# define volatile -#endif - - -/* Version number components: V=Version, R=Revision, P=Patch - Version date components: YYYY=Year, MM=Month, DD=Day */ - -#if defined(__INTEL_COMPILER) || defined(__ICC) -# define COMPILER_ID "Intel" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif - /* __INTEL_COMPILER = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100) -# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10) -# if defined(__INTEL_COMPILER_UPDATE) -# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE) -# else -# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER % 10) -# endif -# if defined(__INTEL_COMPILER_BUILD_DATE) - /* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */ -# define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE) -# endif -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif - -#elif defined(__PATHCC__) -# define COMPILER_ID "PathScale" -# define COMPILER_VERSION_MAJOR DEC(__PATHCC__) -# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__) -# if defined(__PATHCC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__) -# endif - -#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__) -# define COMPILER_ID "Embarcadero" -# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF) -# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) -# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) - -#elif defined(__BORLANDC__) -# define COMPILER_ID "Borland" - /* __BORLANDC__ = 0xVRR */ -# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) -# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) - -#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 -# define COMPILER_ID "Watcom" - /* __WATCOMC__ = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__WATCOMC__) -# define COMPILER_ID "OpenWatcom" - /* __WATCOMC__ = VVRP + 1100 */ -# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) -# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) -# if (__WATCOMC__ % 10) > 0 -# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) -# endif - -#elif defined(__SUNPRO_C) -# define COMPILER_ID "SunPro" -# if __SUNPRO_C >= 0x5100 - /* __SUNPRO_C = 0xVRRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) -# else - /* __SUNPRO_CC = 0xVRP */ -# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8) -# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF) -# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) -# endif - -#elif defined(__HP_cc) -# define COMPILER_ID "HP" - /* __HP_cc = VVRRPP */ -# define COMPILER_VERSION_MAJOR DEC(__HP_cc/10000) -# define COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100) -# define COMPILER_VERSION_PATCH DEC(__HP_cc % 100) - -#elif defined(__DECC) -# define COMPILER_ID "Compaq" - /* __DECC_VER = VVRRTPPPP */ -# define COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000) -# define COMPILER_VERSION_MINOR DEC(__DECC_VER/100000 % 100) -# define COMPILER_VERSION_PATCH DEC(__DECC_VER % 10000) - -#elif defined(__IBMC__) && defined(__COMPILER_VER__) -# define COMPILER_ID "zOS" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ >= 800 -# define COMPILER_ID "XL" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ < 800 -# define COMPILER_ID "VisualAge" - /* __IBMC__ = VRP */ -# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) -# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) -# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) - -#elif defined(__PGI) -# define COMPILER_ID "PGI" -# define COMPILER_VERSION_MAJOR DEC(__PGIC__) -# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) -# if defined(__PGIC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) -# endif - -#elif defined(_CRAYC) -# define COMPILER_ID "Cray" -# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) -# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) - -#elif defined(__TI_COMPILER_VERSION__) -# define COMPILER_ID "TI" - /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ -# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) -# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) -# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) - -#elif defined(__FUJITSU) || defined(__FCC_VERSION) || defined(__fcc_version) -# define COMPILER_ID "Fujitsu" - -#elif defined(__TINYC__) -# define COMPILER_ID "TinyCC" - -#elif defined(__BCC__) -# define COMPILER_ID "Bruce" - -#elif defined(__SCO_VERSION__) -# define COMPILER_ID "SCO" - -#elif defined(__clang__) && defined(__apple_build_version__) -# define COMPILER_ID "AppleClang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif -# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) - -#elif defined(__clang__) -# define COMPILER_ID "Clang" -# if defined(_MSC_VER) -# define SIMULATE_ID "MSVC" -# endif -# define COMPILER_VERSION_MAJOR DEC(__clang_major__) -# define COMPILER_VERSION_MINOR DEC(__clang_minor__) -# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) -# if defined(_MSC_VER) - /* _MSC_VER = VVRR */ -# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) -# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) -# endif - -#elif defined(__GNUC__) -# define COMPILER_ID "GNU" -# define COMPILER_VERSION_MAJOR DEC(__GNUC__) -# if defined(__GNUC_MINOR__) -# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) -# endif -# if defined(__GNUC_PATCHLEVEL__) -# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) -# endif - -#elif defined(_MSC_VER) -# define COMPILER_ID "MSVC" - /* _MSC_VER = VVRR */ -# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) -# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) -# if defined(_MSC_FULL_VER) -# if _MSC_VER >= 1400 - /* _MSC_FULL_VER = VVRRPPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) -# else - /* _MSC_FULL_VER = VVRRPPPP */ -# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) -# endif -# endif -# if defined(_MSC_BUILD) -# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) -# endif - -#elif defined(__VISUALDSPVERSION__) || defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__) -# define COMPILER_ID "ADSP" -#if defined(__VISUALDSPVERSION__) - /* __VISUALDSPVERSION__ = 0xVVRRPP00 */ -# define COMPILER_VERSION_MAJOR HEX(__VISUALDSPVERSION__>>24) -# define COMPILER_VERSION_MINOR HEX(__VISUALDSPVERSION__>>16 & 0xFF) -# define COMPILER_VERSION_PATCH HEX(__VISUALDSPVERSION__>>8 & 0xFF) -#endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# define COMPILER_ID "IAR" -# if defined(__VER__) -# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) -# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) -# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) -# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) -# endif - -#elif defined(__ARMCC_VERSION) -# define COMPILER_ID "ARMCC" -#if __ARMCC_VERSION >= 1000000 - /* __ARMCC_VERSION = VRRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#else - /* __ARMCC_VERSION = VRPPPP */ - # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) - # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) - # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) -#endif - - -#elif defined(__SDCC_VERSION_MAJOR) || defined(SDCC) -# define COMPILER_ID "SDCC" -# if defined(__SDCC_VERSION_MAJOR) -# define COMPILER_VERSION_MAJOR DEC(__SDCC_VERSION_MAJOR) -# define COMPILER_VERSION_MINOR DEC(__SDCC_VERSION_MINOR) -# define COMPILER_VERSION_PATCH DEC(__SDCC_VERSION_PATCH) -# else - /* SDCC = VRP */ -# define COMPILER_VERSION_MAJOR DEC(SDCC/100) -# define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10) -# define COMPILER_VERSION_PATCH DEC(SDCC % 10) -# endif - -#elif defined(_SGI_COMPILER_VERSION) || defined(_COMPILER_VERSION) -# define COMPILER_ID "MIPSpro" -# if defined(_SGI_COMPILER_VERSION) - /* _SGI_COMPILER_VERSION = VRP */ -# define COMPILER_VERSION_MAJOR DEC(_SGI_COMPILER_VERSION/100) -# define COMPILER_VERSION_MINOR DEC(_SGI_COMPILER_VERSION/10 % 10) -# define COMPILER_VERSION_PATCH DEC(_SGI_COMPILER_VERSION % 10) -# else - /* _COMPILER_VERSION = VRP */ -# define COMPILER_VERSION_MAJOR DEC(_COMPILER_VERSION/100) -# define COMPILER_VERSION_MINOR DEC(_COMPILER_VERSION/10 % 10) -# define COMPILER_VERSION_PATCH DEC(_COMPILER_VERSION % 10) -# endif - - -/* These compilers are either not known or too old to define an - identification macro. Try to identify the platform and guess that - it is the native compiler. */ -#elif defined(__sgi) -# define COMPILER_ID "MIPSpro" - -#elif defined(__hpux) || defined(__hpua) -# define COMPILER_ID "HP" - -#else /* unknown compiler */ -# define COMPILER_ID "" -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; -#ifdef SIMULATE_ID -char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; -#endif - -#ifdef __QNXNTO__ -char const* qnxnto = "INFO" ":" "qnxnto[]"; -#endif - -#if defined(__CRAYXE) || defined(__CRAYXC) -char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; -#endif - -#define STRINGIFY_HELPER(X) #X -#define STRINGIFY(X) STRINGIFY_HELPER(X) - -/* Identify known platforms by name. */ -#if defined(__linux) || defined(__linux__) || defined(linux) -# define PLATFORM_ID "Linux" - -#elif defined(__CYGWIN__) -# define PLATFORM_ID "Cygwin" - -#elif defined(__MINGW32__) -# define PLATFORM_ID "MinGW" - -#elif defined(__APPLE__) -# define PLATFORM_ID "Darwin" - -#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) -# define PLATFORM_ID "Windows" - -#elif defined(__FreeBSD__) || defined(__FreeBSD) -# define PLATFORM_ID "FreeBSD" - -#elif defined(__NetBSD__) || defined(__NetBSD) -# define PLATFORM_ID "NetBSD" - -#elif defined(__OpenBSD__) || defined(__OPENBSD) -# define PLATFORM_ID "OpenBSD" - -#elif defined(__sun) || defined(sun) -# define PLATFORM_ID "SunOS" - -#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) -# define PLATFORM_ID "AIX" - -#elif defined(__sgi) || defined(__sgi__) || defined(_SGI) -# define PLATFORM_ID "IRIX" - -#elif defined(__hpux) || defined(__hpux__) -# define PLATFORM_ID "HP-UX" - -#elif defined(__HAIKU__) -# define PLATFORM_ID "Haiku" - -#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) -# define PLATFORM_ID "BeOS" - -#elif defined(__QNX__) || defined(__QNXNTO__) -# define PLATFORM_ID "QNX" - -#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) -# define PLATFORM_ID "Tru64" - -#elif defined(__riscos) || defined(__riscos__) -# define PLATFORM_ID "RISCos" - -#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) -# define PLATFORM_ID "SINIX" - -#elif defined(__UNIX_SV__) -# define PLATFORM_ID "UNIX_SV" - -#elif defined(__bsdos__) -# define PLATFORM_ID "BSDOS" - -#elif defined(_MPRAS) || defined(MPRAS) -# define PLATFORM_ID "MP-RAS" - -#elif defined(__osf) || defined(__osf__) -# define PLATFORM_ID "OSF1" - -#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) -# define PLATFORM_ID "SCO_SV" - -#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) -# define PLATFORM_ID "ULTRIX" - -#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) -# define PLATFORM_ID "Xenix" - -#elif defined(__WATCOMC__) -# if defined(__LINUX__) -# define PLATFORM_ID "Linux" - -# elif defined(__DOS__) -# define PLATFORM_ID "DOS" - -# elif defined(__OS2__) -# define PLATFORM_ID "OS2" - -# elif defined(__WINDOWS__) -# define PLATFORM_ID "Windows3x" - -# else /* unknown platform */ -# define PLATFORM_ID -# endif - -#else /* unknown platform */ -# define PLATFORM_ID - -#endif - -/* For windows compilers MSVC and Intel we can determine - the architecture of the compiler being used. This is because - the compilers do not have flags that can change the architecture, - but rather depend on which compiler is being used -*/ -#if defined(_WIN32) && defined(_MSC_VER) -# if defined(_M_IA64) -# define ARCHITECTURE_ID "IA64" - -# elif defined(_M_X64) || defined(_M_AMD64) -# define ARCHITECTURE_ID "x64" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# elif defined(_M_ARM64) -# define ARCHITECTURE_ID "ARM64" - -# elif defined(_M_ARM) -# if _M_ARM == 4 -# define ARCHITECTURE_ID "ARMV4I" -# elif _M_ARM == 5 -# define ARCHITECTURE_ID "ARMV5I" -# else -# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) -# endif - -# elif defined(_M_MIPS) -# define ARCHITECTURE_ID "MIPS" - -# elif defined(_M_SH) -# define ARCHITECTURE_ID "SHx" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__WATCOMC__) -# if defined(_M_I86) -# define ARCHITECTURE_ID "I86" - -# elif defined(_M_IX86) -# define ARCHITECTURE_ID "X86" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif - -#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) -# if defined(__ICCARM__) -# define ARCHITECTURE_ID "ARM" - -# elif defined(__ICCAVR__) -# define ARCHITECTURE_ID "AVR" - -# else /* unknown architecture */ -# define ARCHITECTURE_ID "" -# endif -#else -# define ARCHITECTURE_ID -#endif - -/* Convert integer to decimal digit literals. */ -#define DEC(n) \ - ('0' + (((n) / 10000000)%10)), \ - ('0' + (((n) / 1000000)%10)), \ - ('0' + (((n) / 100000)%10)), \ - ('0' + (((n) / 10000)%10)), \ - ('0' + (((n) / 1000)%10)), \ - ('0' + (((n) / 100)%10)), \ - ('0' + (((n) / 10)%10)), \ - ('0' + ((n) % 10)) - -/* Convert integer to hex digit literals. */ -#define HEX(n) \ - ('0' + ((n)>>28 & 0xF)), \ - ('0' + ((n)>>24 & 0xF)), \ - ('0' + ((n)>>20 & 0xF)), \ - ('0' + ((n)>>16 & 0xF)), \ - ('0' + ((n)>>12 & 0xF)), \ - ('0' + ((n)>>8 & 0xF)), \ - ('0' + ((n)>>4 & 0xF)), \ - ('0' + ((n) & 0xF)) - -/* Construct a string literal encoding the version number components. */ -#ifdef COMPILER_VERSION_MAJOR -char const info_version[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', - COMPILER_VERSION_MAJOR, -# ifdef COMPILER_VERSION_MINOR - '.', COMPILER_VERSION_MINOR, -# ifdef COMPILER_VERSION_PATCH - '.', COMPILER_VERSION_PATCH, -# ifdef COMPILER_VERSION_TWEAK - '.', COMPILER_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct a string literal encoding the internal version number. */ -#ifdef COMPILER_VERSION_INTERNAL -char const info_version_internal[] = { - 'I', 'N', 'F', 'O', ':', - 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', - 'i','n','t','e','r','n','a','l','[', - COMPILER_VERSION_INTERNAL,']','\0'}; -#endif - -/* Construct a string literal encoding the version number components. */ -#ifdef SIMULATE_VERSION_MAJOR -char const info_simulate_version[] = { - 'I', 'N', 'F', 'O', ':', - 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', - SIMULATE_VERSION_MAJOR, -# ifdef SIMULATE_VERSION_MINOR - '.', SIMULATE_VERSION_MINOR, -# ifdef SIMULATE_VERSION_PATCH - '.', SIMULATE_VERSION_PATCH, -# ifdef SIMULATE_VERSION_TWEAK - '.', SIMULATE_VERSION_TWEAK, -# endif -# endif -# endif - ']','\0'}; -#endif - -/* Construct the string literal in pieces to prevent the source from - getting matched. Store it in a pointer rather than an array - because some compilers will just produce instructions to fill the - array rather than assigning a pointer to a static array. */ -char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; -char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; - - - - -#if !defined(__STDC__) -# if defined(_MSC_VER) && !defined(__clang__) -# define C_DIALECT "90" -# else -# define C_DIALECT -# endif -#elif __STDC_VERSION__ >= 201000L -# define C_DIALECT "11" -#elif __STDC_VERSION__ >= 199901L -# define C_DIALECT "99" -#else -# define C_DIALECT "90" -#endif -const char* info_language_dialect_default = - "INFO" ":" "dialect_default[" C_DIALECT "]"; - -/*--------------------------------------------------------------------------*/ - -#ifdef ID_VOID_MAIN -void main() {} -#else -# if defined(__CLASSIC_C__) -int main(argc, argv) int argc; char *argv[]; -# else -int main(int argc, char* argv[]) -# endif -{ - int require = 0; - require += info_compiler[argc]; - require += info_platform[argc]; - require += info_arch[argc]; -#ifdef COMPILER_VERSION_MAJOR - require += info_version[argc]; -#endif -#ifdef COMPILER_VERSION_INTERNAL - require += info_version_internal[argc]; -#endif -#ifdef SIMULATE_ID - require += info_simulate[argc]; -#endif -#ifdef SIMULATE_VERSION_MAJOR - require += info_simulate_version[argc]; -#endif -#if defined(__CRAYXE) || defined(__CRAYXC) - require += info_cray[argc]; -#endif - require += info_language_dialect_default[argc]; - (void)argv; - return require; -} -#endif diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CompilerIdC/a.out b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CompilerIdC/a.out deleted file mode 100644 index 11b7df4..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CompilerIdC/a.out and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeDirectoryInformation.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeDirectoryInformation.cmake deleted file mode 100644 index 6cbdc88..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeDirectoryInformation.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# Relative path conversion top directories. -set(CMAKE_RELATIVE_PATH_TOP_SOURCE "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features") -set(CMAKE_RELATIVE_PATH_TOP_BINARY "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build") - -# Force unix paths in dependencies. -set(CMAKE_FORCE_UNIX_PATHS 1) - - -# The C and CXX include file regular expressions for this directory. -set(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$") -set(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$") -set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN}) -set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN}) diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeOutput.log b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeOutput.log deleted file mode 100644 index cf6b48b..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeOutput.log +++ /dev/null @@ -1,260 +0,0 @@ -The system is: Linux - 5.4.0-89-generic - x86_64 -Compiling the C compiler identification source file "CMakeCCompilerId.c" succeeded. -Compiler: /usr/bin/cc -Build flags: -Id flags: - -The output was: -0 - - -Compilation of the C compiler identification source "CMakeCCompilerId.c" produced "a.out" - -The C compiler identification is GNU, found in "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/3.10.2/CompilerIdC/a.out" - -Determining if the C compiler works passed with the following output: -Change Dir: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp - -Run Build Command:"/usr/bin/make" "cmTC_b4896/fast" -make[1]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -/usr/bin/make -f CMakeFiles/cmTC_b4896.dir/build.make CMakeFiles/cmTC_b4896.dir/build -make[2]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -Building C object CMakeFiles/cmTC_b4896.dir/testCCompiler.c.o -/usr/bin/cc -o CMakeFiles/cmTC_b4896.dir/testCCompiler.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp/testCCompiler.c -Linking C executable cmTC_b4896 -/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_b4896.dir/link.txt --verbose=1 -/usr/bin/cc -rdynamic CMakeFiles/cmTC_b4896.dir/testCCompiler.c.o -o cmTC_b4896 -make[2]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -make[1]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' - - -Detecting C compiler ABI info compiled with the following output: -Change Dir: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp - -Run Build Command:"/usr/bin/make" "cmTC_185c3/fast" -make[1]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -/usr/bin/make -f CMakeFiles/cmTC_185c3.dir/build.make CMakeFiles/cmTC_185c3.dir/build -make[2]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -Building C object CMakeFiles/cmTC_185c3.dir/CMakeCCompilerABI.c.o -/usr/bin/cc -o CMakeFiles/cmTC_185c3.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake-3.10/Modules/CMakeCCompilerABI.c -Linking C executable cmTC_185c3 -/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_185c3.dir/link.txt --verbose=1 -/usr/bin/cc -v -rdynamic CMakeFiles/cmTC_185c3.dir/CMakeCCompilerABI.c.o -o cmTC_185c3 -Using built-in specs. -COLLECT_GCC=/usr/bin/cc -COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper -OFFLOAD_TARGET_NAMES=nvptx-none -OFFLOAD_TARGET_DEFAULT=1 -Target: x86_64-linux-gnu -Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.5.0-3ubuntu1~18.04' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu -Thread model: posix -gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04) -COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/ -LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../:/lib/:/usr/lib/ -COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_185c3' '-mtune=generic' '-march=x86-64' - /usr/lib/gcc/x86_64-linux-gnu/7/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/7/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper -plugin-opt=-fresolution=/tmp/cciMfx76.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -export-dynamic -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_185c3 /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/7 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/7/../../.. CMakeFiles/cmTC_185c3.dir/CMakeCCompilerABI.c.o -lgcc --push-state --as-needed -lgcc_s --pop-state -lc -lgcc --push-state --as-needed -lgcc_s --pop-state /usr/lib/gcc/x86_64-linux-gnu/7/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crtn.o -COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_185c3' '-mtune=generic' '-march=x86-64' -make[2]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -make[1]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' - - -Parsed C implicit link information from above output: - link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] - ignore line: [Change Dir: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp] - ignore line: [] - ignore line: [Run Build Command:"/usr/bin/make" "cmTC_185c3/fast"] - ignore line: [make[1]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp'] - ignore line: [/usr/bin/make -f CMakeFiles/cmTC_185c3.dir/build.make CMakeFiles/cmTC_185c3.dir/build] - ignore line: [make[2]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp'] - ignore line: [Building C object CMakeFiles/cmTC_185c3.dir/CMakeCCompilerABI.c.o] - ignore line: [/usr/bin/cc -o CMakeFiles/cmTC_185c3.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake-3.10/Modules/CMakeCCompilerABI.c] - ignore line: [Linking C executable cmTC_185c3] - ignore line: [/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_185c3.dir/link.txt --verbose=1] - ignore line: [/usr/bin/cc -v -rdynamic CMakeFiles/cmTC_185c3.dir/CMakeCCompilerABI.c.o -o cmTC_185c3 ] - ignore line: [Using built-in specs.] - ignore line: [COLLECT_GCC=/usr/bin/cc] - ignore line: [COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper] - ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none] - ignore line: [OFFLOAD_TARGET_DEFAULT=1] - ignore line: [Target: x86_64-linux-gnu] - ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.5.0-3ubuntu1~18.04' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu] - ignore line: [Thread model: posix] - ignore line: [gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04) ] - ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/] - ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../:/lib/:/usr/lib/] - ignore line: [COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_185c3' '-mtune=generic' '-march=x86-64'] - link line: [ /usr/lib/gcc/x86_64-linux-gnu/7/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/7/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper -plugin-opt=-fresolution=/tmp/cciMfx76.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -export-dynamic -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_185c3 /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/7 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/7/../../.. CMakeFiles/cmTC_185c3.dir/CMakeCCompilerABI.c.o -lgcc --push-state --as-needed -lgcc_s --pop-state -lc -lgcc --push-state --as-needed -lgcc_s --pop-state /usr/lib/gcc/x86_64-linux-gnu/7/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crtn.o] - arg [/usr/lib/gcc/x86_64-linux-gnu/7/collect2] ==> ignore - arg [-plugin] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/7/liblto_plugin.so] ==> ignore - arg [-plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper] ==> ignore - arg [-plugin-opt=-fresolution=/tmp/cciMfx76.res] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore - arg [-plugin-opt=-pass-through=-lc] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc] ==> ignore - arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore - arg [--build-id] ==> ignore - arg [--eh-frame-hdr] ==> ignore - arg [-m] ==> ignore - arg [elf_x86_64] ==> ignore - arg [--hash-style=gnu] ==> ignore - arg [--as-needed] ==> ignore - arg [-export-dynamic] ==> ignore - arg [-dynamic-linker] ==> ignore - arg [/lib64/ld-linux-x86-64.so.2] ==> ignore - arg [-pie] ==> ignore - arg [-znow] ==> ignore - arg [-zrelro] ==> ignore - arg [-o] ==> ignore - arg [cmTC_185c3] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crti.o] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/7/crtbeginS.o] ==> ignore - arg [-L/usr/lib/gcc/x86_64-linux-gnu/7] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/7] - arg [-L/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu] - arg [-L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib] - arg [-L/lib/x86_64-linux-gnu] ==> dir [/lib/x86_64-linux-gnu] - arg [-L/lib/../lib] ==> dir [/lib/../lib] - arg [-L/usr/lib/x86_64-linux-gnu] ==> dir [/usr/lib/x86_64-linux-gnu] - arg [-L/usr/lib/../lib] ==> dir [/usr/lib/../lib] - arg [-L/usr/lib/gcc/x86_64-linux-gnu/7/../../..] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/7/../../..] - arg [CMakeFiles/cmTC_185c3.dir/CMakeCCompilerABI.c.o] ==> ignore - arg [-lgcc] ==> lib [gcc] - arg [--push-state] ==> ignore - arg [--as-needed] ==> ignore - arg [-lgcc_s] ==> lib [gcc_s] - arg [--pop-state] ==> ignore - arg [-lc] ==> lib [c] - arg [-lgcc] ==> lib [gcc] - arg [--push-state] ==> ignore - arg [--as-needed] ==> ignore - arg [-lgcc_s] ==> lib [gcc_s] - arg [--pop-state] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/7/crtendS.o] ==> ignore - arg [/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crtn.o] ==> ignore - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/7] ==> [/usr/lib/gcc/x86_64-linux-gnu/7] - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib] ==> [/usr/lib] - collapse library dir [/lib/x86_64-linux-gnu] ==> [/lib/x86_64-linux-gnu] - collapse library dir [/lib/../lib] ==> [/lib] - collapse library dir [/usr/lib/x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] - collapse library dir [/usr/lib/../lib] ==> [/usr/lib] - collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/7/../../..] ==> [/usr/lib] - implicit libs: [gcc;gcc_s;c;gcc;gcc_s] - implicit dirs: [/usr/lib/gcc/x86_64-linux-gnu/7;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib] - implicit fwks: [] - - - - -Detecting C [-std=c11] compiler features compiled with the following output: -Change Dir: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp - -Run Build Command:"/usr/bin/make" "cmTC_48286/fast" -make[1]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -/usr/bin/make -f CMakeFiles/cmTC_48286.dir/build.make CMakeFiles/cmTC_48286.dir/build -make[2]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -Building C object CMakeFiles/cmTC_48286.dir/feature_tests.c.o -/usr/bin/cc -std=c11 -o CMakeFiles/cmTC_48286.dir/feature_tests.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/feature_tests.c -Linking C executable cmTC_48286 -/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_48286.dir/link.txt --verbose=1 -/usr/bin/cc -rdynamic CMakeFiles/cmTC_48286.dir/feature_tests.c.o -o cmTC_48286 -make[2]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -make[1]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' - - - Feature record: C_FEATURE:1c_function_prototypes - Feature record: C_FEATURE:1c_restrict - Feature record: C_FEATURE:1c_static_assert - Feature record: C_FEATURE:1c_variadic_macros - - -Detecting C [-std=c99] compiler features compiled with the following output: -Change Dir: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp - -Run Build Command:"/usr/bin/make" "cmTC_3e773/fast" -make[1]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -/usr/bin/make -f CMakeFiles/cmTC_3e773.dir/build.make CMakeFiles/cmTC_3e773.dir/build -make[2]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -Building C object CMakeFiles/cmTC_3e773.dir/feature_tests.c.o -/usr/bin/cc -std=c99 -o CMakeFiles/cmTC_3e773.dir/feature_tests.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/feature_tests.c -Linking C executable cmTC_3e773 -/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_3e773.dir/link.txt --verbose=1 -/usr/bin/cc -rdynamic CMakeFiles/cmTC_3e773.dir/feature_tests.c.o -o cmTC_3e773 -make[2]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -make[1]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' - - - Feature record: C_FEATURE:1c_function_prototypes - Feature record: C_FEATURE:1c_restrict - Feature record: C_FEATURE:0c_static_assert - Feature record: C_FEATURE:1c_variadic_macros - - -Detecting C [-std=c90] compiler features compiled with the following output: -Change Dir: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp - -Run Build Command:"/usr/bin/make" "cmTC_49468/fast" -make[1]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -/usr/bin/make -f CMakeFiles/cmTC_49468.dir/build.make CMakeFiles/cmTC_49468.dir/build -make[2]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -Building C object CMakeFiles/cmTC_49468.dir/feature_tests.c.o -/usr/bin/cc -std=c90 -o CMakeFiles/cmTC_49468.dir/feature_tests.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/feature_tests.c -Linking C executable cmTC_49468 -/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_49468.dir/link.txt --verbose=1 -/usr/bin/cc -rdynamic CMakeFiles/cmTC_49468.dir/feature_tests.c.o -o cmTC_49468 -make[2]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -make[1]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' - - - Feature record: C_FEATURE:1c_function_prototypes - Feature record: C_FEATURE:0c_restrict - Feature record: C_FEATURE:0c_static_assert - Feature record: C_FEATURE:0c_variadic_macros -Determining if the include file dlfcn.h exists passed with the following output: -Change Dir: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp - -Run Build Command:"/usr/bin/make" "cmTC_78ce6/fast" -make[1]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -/usr/bin/make -f CMakeFiles/cmTC_78ce6.dir/build.make CMakeFiles/cmTC_78ce6.dir/build -make[2]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -Building C object CMakeFiles/cmTC_78ce6.dir/CheckIncludeFile.c.o -/usr/bin/cc -o CMakeFiles/cmTC_78ce6.dir/CheckIncludeFile.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp/CheckIncludeFile.c -Linking C executable cmTC_78ce6 -/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_78ce6.dir/link.txt --verbose=1 -/usr/bin/cc -rdynamic CMakeFiles/cmTC_78ce6.dir/CheckIncludeFile.c.o -o cmTC_78ce6 -make[2]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -make[1]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' - - -Determining if the getauxval exist passed with the following output: -Change Dir: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp - -Run Build Command:"/usr/bin/make" "cmTC_7d1ae/fast" -make[1]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -/usr/bin/make -f CMakeFiles/cmTC_7d1ae.dir/build.make CMakeFiles/cmTC_7d1ae.dir/build -make[2]: Entering directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -Building C object CMakeFiles/cmTC_7d1ae.dir/CheckSymbolExists.c.o -/usr/bin/cc -o CMakeFiles/cmTC_7d1ae.dir/CheckSymbolExists.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp/CheckSymbolExists.c -Linking C executable cmTC_7d1ae -/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_7d1ae.dir/link.txt --verbose=1 -/usr/bin/cc -rdynamic CMakeFiles/cmTC_7d1ae.dir/CheckSymbolExists.c.o -o cmTC_7d1ae -make[2]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' -make[1]: Leaving directory '/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp' - -File /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/CMakeTmp/CheckSymbolExists.c: -/* */ -#include - -int main(int argc, char** argv) -{ - (void)argv; -#ifndef getauxval - return ((int*)(&getauxval))[argc]; -#else - (void)argc; - return 0; -#endif -} - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Export/lib/cmake/CpuFeatures/CpuFeaturesTargets-release.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Export/lib/cmake/CpuFeatures/CpuFeaturesTargets-release.cmake deleted file mode 100644 index b49552b..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Export/lib/cmake/CpuFeatures/CpuFeaturesTargets-release.cmake +++ /dev/null @@ -1,28 +0,0 @@ -#---------------------------------------------------------------- -# Generated CMake target import file for configuration "Release". -#---------------------------------------------------------------- - -# Commands may need to know the format version. -set(CMAKE_IMPORT_FILE_VERSION 1) - -# Import target "CpuFeatures::cpu_features" for configuration "Release" -set_property(TARGET CpuFeatures::cpu_features APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) -set_target_properties(CpuFeatures::cpu_features PROPERTIES - IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C" - IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/libcpu_features.a" - ) - -list(APPEND _IMPORT_CHECK_TARGETS CpuFeatures::cpu_features ) -list(APPEND _IMPORT_CHECK_FILES_FOR_CpuFeatures::cpu_features "${_IMPORT_PREFIX}/lib/libcpu_features.a" ) - -# Import target "CpuFeatures::list_cpu_features" for configuration "Release" -set_property(TARGET CpuFeatures::list_cpu_features APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) -set_target_properties(CpuFeatures::list_cpu_features PROPERTIES - IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/bin/list_cpu_features" - ) - -list(APPEND _IMPORT_CHECK_TARGETS CpuFeatures::list_cpu_features ) -list(APPEND _IMPORT_CHECK_FILES_FOR_CpuFeatures::list_cpu_features "${_IMPORT_PREFIX}/bin/list_cpu_features" ) - -# Commands beyond this point should not need to know the version. -set(CMAKE_IMPORT_FILE_VERSION) diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Export/lib/cmake/CpuFeatures/CpuFeaturesTargets.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Export/lib/cmake/CpuFeatures/CpuFeaturesTargets.cmake deleted file mode 100644 index dce3177..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Export/lib/cmake/CpuFeatures/CpuFeaturesTargets.cmake +++ /dev/null @@ -1,103 +0,0 @@ -# Generated by CMake - -if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.5) - message(FATAL_ERROR "CMake >= 2.6.0 required") -endif() -cmake_policy(PUSH) -cmake_policy(VERSION 2.6) -#---------------------------------------------------------------- -# Generated CMake target import file. -#---------------------------------------------------------------- - -# Commands may need to know the format version. -set(CMAKE_IMPORT_FILE_VERSION 1) - -# Protect against multiple inclusion, which would fail when already imported targets are added once more. -set(_targetsDefined) -set(_targetsNotDefined) -set(_expectedTargets) -foreach(_expectedTarget CpuFeatures::cpu_features CpuFeatures::list_cpu_features) - list(APPEND _expectedTargets ${_expectedTarget}) - if(NOT TARGET ${_expectedTarget}) - list(APPEND _targetsNotDefined ${_expectedTarget}) - endif() - if(TARGET ${_expectedTarget}) - list(APPEND _targetsDefined ${_expectedTarget}) - endif() -endforeach() -if("${_targetsDefined}" STREQUAL "${_expectedTargets}") - unset(_targetsDefined) - unset(_targetsNotDefined) - unset(_expectedTargets) - set(CMAKE_IMPORT_FILE_VERSION) - cmake_policy(POP) - return() -endif() -if(NOT "${_targetsDefined}" STREQUAL "") - message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_targetsDefined}\nTargets not yet defined: ${_targetsNotDefined}\n") -endif() -unset(_targetsDefined) -unset(_targetsNotDefined) -unset(_expectedTargets) - - -# Compute the installation prefix relative to this file. -get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH) -get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) -get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) -get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) -if(_IMPORT_PREFIX STREQUAL "/") - set(_IMPORT_PREFIX "") -endif() - -# Create imported target CpuFeatures::cpu_features -add_library(CpuFeatures::cpu_features STATIC IMPORTED) - -set_target_properties(CpuFeatures::cpu_features PROPERTIES - INTERFACE_COMPILE_DEFINITIONS "STACK_LINE_READER_BUFFER_SIZE=1024" - INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include/cpu_features" - INTERFACE_LINK_LIBRARIES "dl" -) - -# Create imported target CpuFeatures::list_cpu_features -add_executable(CpuFeatures::list_cpu_features IMPORTED) - -if(CMAKE_VERSION VERSION_LESS 2.8.12) - message(FATAL_ERROR "This file relies on consumers using CMake 2.8.12 or greater.") -endif() - -# Load information for each installed configuration. -get_filename_component(_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) -file(GLOB CONFIG_FILES "${_DIR}/CpuFeaturesTargets-*.cmake") -foreach(f ${CONFIG_FILES}) - include(${f}) -endforeach() - -# Cleanup temporary variables. -set(_IMPORT_PREFIX) - -# Loop over all imported files and verify that they actually exist -foreach(target ${_IMPORT_CHECK_TARGETS} ) - foreach(file ${_IMPORT_CHECK_FILES_FOR_${target}} ) - if(NOT EXISTS "${file}" ) - message(FATAL_ERROR "The imported target \"${target}\" references the file - \"${file}\" -but this file does not exist. Possible reasons include: -* The file was deleted, renamed, or moved to another location. -* An install or uninstall procedure did not complete successfully. -* The installation package was faulty and contained - \"${CMAKE_CURRENT_LIST_FILE}\" -but not all the files it references. -") - endif() - endforeach() - unset(_IMPORT_CHECK_FILES_FOR_${target}) -endforeach() -unset(_IMPORT_CHECK_TARGETS) - -# This file does not depend on other imported targets which have -# been exported from the same project but in a separate export set. - -# Commands beyond this point should not need to know the version. -set(CMAKE_IMPORT_FILE_VERSION) -cmake_policy(POP) diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Makefile.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Makefile.cmake deleted file mode 100644 index 502d6ab..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Makefile.cmake +++ /dev/null @@ -1,112 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# The generator used is: -set(CMAKE_DEPENDS_GENERATOR "Unix Makefiles") - -# The top level Makefile was generated from the following files: -set(CMAKE_MAKEFILE_DEPENDS - "CMakeCache.txt" - "../CMakeLists.txt" - "CMakeFiles/3.10.2/CMakeCCompiler.cmake" - "CMakeFiles/3.10.2/CMakeSystem.cmake" - "CMakeFiles/feature_tests.c" - "../cmake/CpuFeaturesConfig.cmake.in" - "/usr/share/cmake-3.10/Modules/BasicConfigVersion-SameMajorVersion.cmake.in" - "/usr/share/cmake-3.10/Modules/CMakeCCompiler.cmake.in" - "/usr/share/cmake-3.10/Modules/CMakeCCompilerABI.c" - "/usr/share/cmake-3.10/Modules/CMakeCInformation.cmake" - "/usr/share/cmake-3.10/Modules/CMakeCommonLanguageInclude.cmake" - "/usr/share/cmake-3.10/Modules/CMakeCompilerIdDetection.cmake" - "/usr/share/cmake-3.10/Modules/CMakeConfigurableFile.in" - "/usr/share/cmake-3.10/Modules/CMakeDetermineCCompiler.cmake" - "/usr/share/cmake-3.10/Modules/CMakeDetermineCompileFeatures.cmake" - "/usr/share/cmake-3.10/Modules/CMakeDetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/CMakeDetermineCompilerABI.cmake" - "/usr/share/cmake-3.10/Modules/CMakeDetermineCompilerId.cmake" - "/usr/share/cmake-3.10/Modules/CMakeDetermineSystem.cmake" - "/usr/share/cmake-3.10/Modules/CMakeFindBinUtils.cmake" - "/usr/share/cmake-3.10/Modules/CMakeGenericSystem.cmake" - "/usr/share/cmake-3.10/Modules/CMakeLanguageInformation.cmake" - "/usr/share/cmake-3.10/Modules/CMakePackageConfigHelpers.cmake" - "/usr/share/cmake-3.10/Modules/CMakeParseImplicitLinkInfo.cmake" - "/usr/share/cmake-3.10/Modules/CMakeSystem.cmake.in" - "/usr/share/cmake-3.10/Modules/CMakeSystemSpecificInformation.cmake" - "/usr/share/cmake-3.10/Modules/CMakeSystemSpecificInitialize.cmake" - "/usr/share/cmake-3.10/Modules/CMakeTestCCompiler.cmake" - "/usr/share/cmake-3.10/Modules/CMakeTestCompilerCommon.cmake" - "/usr/share/cmake-3.10/Modules/CMakeUnixFindMake.cmake" - "/usr/share/cmake-3.10/Modules/CTest.cmake" - "/usr/share/cmake-3.10/Modules/CTestUseLaunchers.cmake" - "/usr/share/cmake-3.10/Modules/CheckIncludeFile.c.in" - "/usr/share/cmake-3.10/Modules/CheckIncludeFile.cmake" - "/usr/share/cmake-3.10/Modules/CheckSymbolExists.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/ADSP-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/ARMCC-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/AppleClang-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/Borland-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/Bruce-C-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/CMakeCommonCompilerMacros.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/Clang-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/Clang-DetermineCompilerInternal.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/Compaq-C-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/Cray-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/Embarcadero-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/Fujitsu-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/GHS-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/GNU-C-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/GNU-C-FeatureTests.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/GNU-C.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/GNU-FindBinUtils.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/GNU.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/HP-C-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/IAR-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/IBMCPP-C-DetermineVersionInternal.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/Intel-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/MIPSpro-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/MSVC-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/NVIDIA-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/OpenWatcom-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/PGI-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/PathScale-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/SCO-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/SDCC-C-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/SunPro-C-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/TI-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/TinyCC-C-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/VisualAge-C-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/Watcom-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/XL-C-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/Compiler/zOS-C-DetermineCompiler.cmake" - "/usr/share/cmake-3.10/Modules/GNUInstallDirs.cmake" - "/usr/share/cmake-3.10/Modules/Internal/FeatureTesting.cmake" - "/usr/share/cmake-3.10/Modules/Platform/Linux-GNU-C.cmake" - "/usr/share/cmake-3.10/Modules/Platform/Linux-GNU.cmake" - "/usr/share/cmake-3.10/Modules/Platform/Linux.cmake" - "/usr/share/cmake-3.10/Modules/Platform/UnixPaths.cmake" - "/usr/share/cmake-3.10/Modules/WriteBasicConfigVersionFile.cmake" - ) - -# The corresponding makefile is: -set(CMAKE_MAKEFILE_OUTPUTS - "Makefile" - "CMakeFiles/cmake.check_cache" - ) - -# Byproducts of CMake generate step: -set(CMAKE_MAKEFILE_PRODUCTS - "CMakeFiles/3.10.2/CMakeSystem.cmake" - "CMakeFiles/3.10.2/CMakeCCompiler.cmake" - "CMakeFiles/3.10.2/CMakeCCompiler.cmake" - "CpuFeaturesConfig.cmake" - "CpuFeaturesConfigVersion.cmake" - "CMakeFiles/CMakeDirectoryInformation.cmake" - ) - -# Dependency information for all targets: -set(CMAKE_DEPEND_INFO_FILES - "CMakeFiles/unix_based_hardware_detection.dir/DependInfo.cmake" - "CMakeFiles/utils.dir/DependInfo.cmake" - "CMakeFiles/list_cpu_features.dir/DependInfo.cmake" - "CMakeFiles/cpu_features.dir/DependInfo.cmake" - ) diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Makefile2 b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Makefile2 deleted file mode 100644 index b3ccf31..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Makefile2 +++ /dev/null @@ -1,219 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# Default target executed when no arguments are given to make. -default_target: all - -.PHONY : default_target - -# The main recursive all target -all: - -.PHONY : all - -# The main recursive preinstall target -preinstall: - -.PHONY : preinstall - -#============================================================================= -# Special targets provided by cmake. - -# Disable implicit rules so canonical targets will work. -.SUFFIXES: - - -# Remove some rules from gmake that .SUFFIXES does not remove. -SUFFIXES = - -.SUFFIXES: .hpux_make_needs_suffix_list - - -# Suppress display of executed commands. -$(VERBOSE).SILENT: - - -# A target that is always out of date. -cmake_force: - -.PHONY : cmake_force - -#============================================================================= -# Set environment variables for the build. - -# The shell in which to execute make rules. -SHELL = /bin/sh - -# The CMake executable. -CMAKE_COMMAND = /usr/bin/cmake - -# The command to remove a file. -RM = /usr/bin/cmake -E remove -f - -# Escaping for special characters. -EQUALS = = - -# The top-level source directory on which CMake was run. -CMAKE_SOURCE_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features - -# The top-level build directory on which CMake was run. -CMAKE_BINARY_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build - -#============================================================================= -# Target rules for target CMakeFiles/unix_based_hardware_detection.dir - -# All Build rule for target. -CMakeFiles/unix_based_hardware_detection.dir/all: - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/depend - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/build - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=5,6 "Built target unix_based_hardware_detection" -.PHONY : CMakeFiles/unix_based_hardware_detection.dir/all - -# Include target in all. -all: CMakeFiles/unix_based_hardware_detection.dir/all - -.PHONY : all - -# Build rule for subdir invocation for target. -CMakeFiles/unix_based_hardware_detection.dir/rule: cmake_check_build_system - $(CMAKE_COMMAND) -E cmake_progress_start /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles 2 - $(MAKE) -f CMakeFiles/Makefile2 CMakeFiles/unix_based_hardware_detection.dir/all - $(CMAKE_COMMAND) -E cmake_progress_start /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles 0 -.PHONY : CMakeFiles/unix_based_hardware_detection.dir/rule - -# Convenience name for target. -unix_based_hardware_detection: CMakeFiles/unix_based_hardware_detection.dir/rule - -.PHONY : unix_based_hardware_detection - -# clean rule for target. -CMakeFiles/unix_based_hardware_detection.dir/clean: - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/clean -.PHONY : CMakeFiles/unix_based_hardware_detection.dir/clean - -# clean rule for target. -clean: CMakeFiles/unix_based_hardware_detection.dir/clean - -.PHONY : clean - -#============================================================================= -# Target rules for target CMakeFiles/utils.dir - -# All Build rule for target. -CMakeFiles/utils.dir/all: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/depend - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/build - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=7,8,9 "Built target utils" -.PHONY : CMakeFiles/utils.dir/all - -# Include target in all. -all: CMakeFiles/utils.dir/all - -.PHONY : all - -# Build rule for subdir invocation for target. -CMakeFiles/utils.dir/rule: cmake_check_build_system - $(CMAKE_COMMAND) -E cmake_progress_start /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles 3 - $(MAKE) -f CMakeFiles/Makefile2 CMakeFiles/utils.dir/all - $(CMAKE_COMMAND) -E cmake_progress_start /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles 0 -.PHONY : CMakeFiles/utils.dir/rule - -# Convenience name for target. -utils: CMakeFiles/utils.dir/rule - -.PHONY : utils - -# clean rule for target. -CMakeFiles/utils.dir/clean: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/clean -.PHONY : CMakeFiles/utils.dir/clean - -# clean rule for target. -clean: CMakeFiles/utils.dir/clean - -.PHONY : clean - -#============================================================================= -# Target rules for target CMakeFiles/list_cpu_features.dir - -# All Build rule for target. -CMakeFiles/list_cpu_features.dir/all: CMakeFiles/cpu_features.dir/all - $(MAKE) -f CMakeFiles/list_cpu_features.dir/build.make CMakeFiles/list_cpu_features.dir/depend - $(MAKE) -f CMakeFiles/list_cpu_features.dir/build.make CMakeFiles/list_cpu_features.dir/build - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=3,4 "Built target list_cpu_features" -.PHONY : CMakeFiles/list_cpu_features.dir/all - -# Include target in all. -all: CMakeFiles/list_cpu_features.dir/all - -.PHONY : all - -# Build rule for subdir invocation for target. -CMakeFiles/list_cpu_features.dir/rule: cmake_check_build_system - $(CMAKE_COMMAND) -E cmake_progress_start /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles 7 - $(MAKE) -f CMakeFiles/Makefile2 CMakeFiles/list_cpu_features.dir/all - $(CMAKE_COMMAND) -E cmake_progress_start /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles 0 -.PHONY : CMakeFiles/list_cpu_features.dir/rule - -# Convenience name for target. -list_cpu_features: CMakeFiles/list_cpu_features.dir/rule - -.PHONY : list_cpu_features - -# clean rule for target. -CMakeFiles/list_cpu_features.dir/clean: - $(MAKE) -f CMakeFiles/list_cpu_features.dir/build.make CMakeFiles/list_cpu_features.dir/clean -.PHONY : CMakeFiles/list_cpu_features.dir/clean - -# clean rule for target. -clean: CMakeFiles/list_cpu_features.dir/clean - -.PHONY : clean - -#============================================================================= -# Target rules for target CMakeFiles/cpu_features.dir - -# All Build rule for target. -CMakeFiles/cpu_features.dir/all: CMakeFiles/utils.dir/all - $(MAKE) -f CMakeFiles/cpu_features.dir/build.make CMakeFiles/cpu_features.dir/depend - $(MAKE) -f CMakeFiles/cpu_features.dir/build.make CMakeFiles/cpu_features.dir/build - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=1,2 "Built target cpu_features" -.PHONY : CMakeFiles/cpu_features.dir/all - -# Include target in all. -all: CMakeFiles/cpu_features.dir/all - -.PHONY : all - -# Build rule for subdir invocation for target. -CMakeFiles/cpu_features.dir/rule: cmake_check_build_system - $(CMAKE_COMMAND) -E cmake_progress_start /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles 5 - $(MAKE) -f CMakeFiles/Makefile2 CMakeFiles/cpu_features.dir/all - $(CMAKE_COMMAND) -E cmake_progress_start /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles 0 -.PHONY : CMakeFiles/cpu_features.dir/rule - -# Convenience name for target. -cpu_features: CMakeFiles/cpu_features.dir/rule - -.PHONY : cpu_features - -# clean rule for target. -CMakeFiles/cpu_features.dir/clean: - $(MAKE) -f CMakeFiles/cpu_features.dir/build.make CMakeFiles/cpu_features.dir/clean -.PHONY : CMakeFiles/cpu_features.dir/clean - -# clean rule for target. -clean: CMakeFiles/cpu_features.dir/clean - -.PHONY : clean - -#============================================================================= -# Special targets to cleanup operation of make. - -# Special rule to run CMake to check the build system integrity. -# No rule that depends on this can have commands that come from listfiles -# because they might be regenerated. -cmake_check_build_system: - $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 -.PHONY : cmake_check_build_system - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/TargetDirectories.txt b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/TargetDirectories.txt deleted file mode 100644 index 992fe07..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/TargetDirectories.txt +++ /dev/null @@ -1,10 +0,0 @@ -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/install/strip.dir -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/install/local.dir -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/install.dir -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_install_components.dir -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/rebuild_cache.dir -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/edit_cache.dir diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cmake.check_cache b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cmake.check_cache deleted file mode 100644 index 3dccd73..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cmake.check_cache +++ /dev/null @@ -1 +0,0 @@ -# This file is generated by cmake for dependency checking of the CMakeCache.txt file diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/C.includecache b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/C.includecache deleted file mode 100644 index 06eb68c..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/C.includecache +++ /dev/null @@ -1,54 +0,0 @@ -#IncludeRegexLine: ^[ ]*[#%][ ]*(include|import)[ ]*[<"]([^">]+)([">]) - -#IncludeRegexScan: ^.*$ - -#IncludeRegexComplain: ^$ - -#IncludeRegexTransform: - -../include/cpu_features_cache_info.h -cpu_features_macros.h -../include/cpu_features_macros.h - -../include/cpu_features_macros.h - -../include/cpuinfo_x86.h -cpu_features_cache_info.h -../include/cpu_features_cache_info.h -cpu_features_macros.h -../include/cpu_features_macros.h - -../include/internal/bit_utils.h -assert.h -- -stdbool.h -- -stdint.h -- -cpu_features_macros.h -../include/internal/cpu_features_macros.h - -../include/internal/cpuid_x86.h -stdint.h -- -cpu_features_macros.h -../include/internal/cpu_features_macros.h - -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_x86.c -cpuinfo_x86.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_x86.h -stdbool.h -- -string.h -- -internal/bit_utils.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/internal/bit_utils.h -internal/cpuid_x86.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/internal/cpuid_x86.h -cpuid.h -- -immintrin.h -- -intrin.h -- - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/DependInfo.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/DependInfo.cmake deleted file mode 100644 index a16543a..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/DependInfo.cmake +++ /dev/null @@ -1,27 +0,0 @@ -# The set of languages for which implicit dependencies are needed: -set(CMAKE_DEPENDS_LANGUAGES - "C" - ) -# The set of files for implicit dependencies of each language: -set(CMAKE_DEPENDS_CHECK_C - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_x86.c" "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o" - ) -set(CMAKE_C_COMPILER_ID "GNU") - -# Preprocessor definitions for this target. -set(CMAKE_TARGET_DEFINITIONS_C - "STACK_LINE_READER_BUFFER_SIZE=1024" - ) - -# The include file search paths: -set(CMAKE_C_TARGET_INCLUDE_PATH - "../include" - "../include/internal" - ) - -# Targets to which this target links. -set(CMAKE_TARGET_LINKED_INFO_FILES - ) - -# Fortran module output directory. -set(CMAKE_Fortran_TARGET_MODULE_DIR "") diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/build.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/build.make deleted file mode 100644 index 4c31093..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/build.make +++ /dev/null @@ -1,120 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# Delete rule output on recipe failure. -.DELETE_ON_ERROR: - - -#============================================================================= -# Special targets provided by cmake. - -# Disable implicit rules so canonical targets will work. -.SUFFIXES: - - -# Remove some rules from gmake that .SUFFIXES does not remove. -SUFFIXES = - -.SUFFIXES: .hpux_make_needs_suffix_list - - -# Suppress display of executed commands. -$(VERBOSE).SILENT: - - -# A target that is always out of date. -cmake_force: - -.PHONY : cmake_force - -#============================================================================= -# Set environment variables for the build. - -# The shell in which to execute make rules. -SHELL = /bin/sh - -# The CMake executable. -CMAKE_COMMAND = /usr/bin/cmake - -# The command to remove a file. -RM = /usr/bin/cmake -E remove -f - -# Escaping for special characters. -EQUALS = = - -# The top-level source directory on which CMake was run. -CMAKE_SOURCE_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features - -# The top-level build directory on which CMake was run. -CMAKE_BINARY_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build - -# Include any dependencies generated for this target. -include CMakeFiles/cpu_features.dir/depend.make - -# Include the progress variables for this target. -include CMakeFiles/cpu_features.dir/progress.make - -# Include the compile flags for this target's objects. -include CMakeFiles/cpu_features.dir/flags.make - -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o: CMakeFiles/cpu_features.dir/flags.make -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o: ../src/cpuinfo_x86.c - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_1) "Building C object CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -o CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_x86.c - -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.i: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing C source to CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.i" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -E /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_x86.c > CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.i - -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.s: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling C source to assembly CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.s" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -S /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_x86.c -o CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.s - -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o.requires: - -.PHONY : CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o.requires - -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o.provides: CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o.requires - $(MAKE) -f CMakeFiles/cpu_features.dir/build.make CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o.provides.build -.PHONY : CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o.provides - -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o.provides.build: CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o - - -# Object files for target cpu_features -cpu_features_OBJECTS = \ -"CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o" - -# External object files for target cpu_features -cpu_features_EXTERNAL_OBJECTS = \ -"/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/filesystem.c.o" \ -"/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/stack_line_reader.c.o" \ -"/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/string_view.c.o" - -libcpu_features.a: CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o -libcpu_features.a: CMakeFiles/utils.dir/src/filesystem.c.o -libcpu_features.a: CMakeFiles/utils.dir/src/stack_line_reader.c.o -libcpu_features.a: CMakeFiles/utils.dir/src/string_view.c.o -libcpu_features.a: CMakeFiles/cpu_features.dir/build.make -libcpu_features.a: CMakeFiles/cpu_features.dir/link.txt - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --bold --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_2) "Linking C static library libcpu_features.a" - $(CMAKE_COMMAND) -P CMakeFiles/cpu_features.dir/cmake_clean_target.cmake - $(CMAKE_COMMAND) -E cmake_link_script CMakeFiles/cpu_features.dir/link.txt --verbose=$(VERBOSE) - -# Rule to build all files generated by this target. -CMakeFiles/cpu_features.dir/build: libcpu_features.a - -.PHONY : CMakeFiles/cpu_features.dir/build - -CMakeFiles/cpu_features.dir/requires: CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o.requires - -.PHONY : CMakeFiles/cpu_features.dir/requires - -CMakeFiles/cpu_features.dir/clean: - $(CMAKE_COMMAND) -P CMakeFiles/cpu_features.dir/cmake_clean.cmake -.PHONY : CMakeFiles/cpu_features.dir/clean - -CMakeFiles/cpu_features.dir/depend: - cd /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build && $(CMAKE_COMMAND) -E cmake_depends "Unix Makefiles" /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/DependInfo.cmake --color=$(COLOR) -.PHONY : CMakeFiles/cpu_features.dir/depend - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/cmake_clean.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/cmake_clean.cmake deleted file mode 100644 index cc9cffc..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/cmake_clean.cmake +++ /dev/null @@ -1,10 +0,0 @@ -file(REMOVE_RECURSE - "CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o" - "libcpu_features.pdb" - "libcpu_features.a" -) - -# Per-language clean rules from dependency scanning. -foreach(lang C) - include(CMakeFiles/cpu_features.dir/cmake_clean_${lang}.cmake OPTIONAL) -endforeach() diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/cmake_clean_target.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/cmake_clean_target.cmake deleted file mode 100644 index 1116c85..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/cmake_clean_target.cmake +++ /dev/null @@ -1,3 +0,0 @@ -file(REMOVE_RECURSE - "libcpu_features.a" -) diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/depend.internal b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/depend.internal deleted file mode 100644 index 95edf29..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/depend.internal +++ /dev/null @@ -1,10 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o - ../include/cpu_features_cache_info.h - ../include/cpu_features_macros.h - ../include/cpuinfo_x86.h - ../include/internal/bit_utils.h - ../include/internal/cpuid_x86.h - /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_x86.c diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/depend.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/depend.make deleted file mode 100644 index 86cd1ca..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/depend.make +++ /dev/null @@ -1,10 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o: ../include/cpu_features_cache_info.h -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o: ../include/cpu_features_macros.h -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o: ../include/cpuinfo_x86.h -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o: ../include/internal/bit_utils.h -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o: ../include/internal/cpuid_x86.h -CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o: ../src/cpuinfo_x86.c - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/flags.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/flags.make deleted file mode 100644 index dca3026..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/flags.make +++ /dev/null @@ -1,10 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# compile C with /usr/bin/cc -C_FLAGS = -O3 -DNDEBUG -fPIC -std=gnu99 - -C_DEFINES = -DSTACK_LINE_READER_BUFFER_SIZE=1024 - -C_INCLUDES = -I/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include -I/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/link.txt b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/link.txt deleted file mode 100644 index ef08f1e..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/link.txt +++ /dev/null @@ -1,2 +0,0 @@ -/usr/bin/ar qc libcpu_features.a CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o CMakeFiles/utils.dir/src/filesystem.c.o CMakeFiles/utils.dir/src/stack_line_reader.c.o CMakeFiles/utils.dir/src/string_view.c.o -/usr/bin/ranlib libcpu_features.a diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/progress.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/progress.make deleted file mode 100644 index abadeb0..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/progress.make +++ /dev/null @@ -1,3 +0,0 @@ -CMAKE_PROGRESS_1 = 1 -CMAKE_PROGRESS_2 = 2 - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o deleted file mode 100644 index d38d480..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/feature_tests.bin b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/feature_tests.bin deleted file mode 100644 index 927e47d..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/feature_tests.bin and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/feature_tests.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/feature_tests.c deleted file mode 100644 index 83e86dd..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/feature_tests.c +++ /dev/null @@ -1,34 +0,0 @@ - - const char features[] = {"\n" -"C_FEATURE:" -#if (__GNUC__ * 100 + __GNUC_MINOR__) >= 304 -"1" -#else -"0" -#endif -"c_function_prototypes\n" -"C_FEATURE:" -#if (__GNUC__ * 100 + __GNUC_MINOR__) >= 304 && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L -"1" -#else -"0" -#endif -"c_restrict\n" -"C_FEATURE:" -#if (__GNUC__ * 100 + __GNUC_MINOR__) >= 406 && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201000L -"1" -#else -"0" -#endif -"c_static_assert\n" -"C_FEATURE:" -#if (__GNUC__ * 100 + __GNUC_MINOR__) >= 304 && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L -"1" -#else -"0" -#endif -"c_variadic_macros\n" - -}; - -int main(int argc, char** argv) { (void)argv; return features[argc]; } diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/C.includecache b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/C.includecache deleted file mode 100644 index 207158e..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/C.includecache +++ /dev/null @@ -1,82 +0,0 @@ -#IncludeRegexLine: ^[ ]*[#%][ ]*(include|import)[ ]*[<"]([^">]+)([">]) - -#IncludeRegexScan: ^.*$ - -#IncludeRegexComplain: ^$ - -#IncludeRegexTransform: - -../include/cpu_features_cache_info.h -cpu_features_macros.h -../include/cpu_features_macros.h - -../include/cpu_features_macros.h - -../include/cpuinfo_aarch64.h -cpu_features_cache_info.h -../include/cpu_features_cache_info.h -cpu_features_macros.h -../include/cpu_features_macros.h - -../include/cpuinfo_arm.h -stdint.h -- -cpu_features_cache_info.h -../include/cpu_features_cache_info.h -cpu_features_macros.h -../include/cpu_features_macros.h - -../include/cpuinfo_mips.h -cpu_features_cache_info.h -../include/cpu_features_cache_info.h -cpu_features_macros.h -../include/cpu_features_macros.h - -../include/cpuinfo_ppc.h -cpu_features_cache_info.h -../include/cpu_features_cache_info.h -cpu_features_macros.h -../include/cpu_features_macros.h -internal/hwcaps.h -../include/internal/hwcaps.h - -../include/cpuinfo_x86.h -cpu_features_cache_info.h -../include/cpu_features_cache_info.h -cpu_features_macros.h -../include/cpu_features_macros.h - -../include/internal/hwcaps.h -stdint.h -- -cpu_features_macros.h -../include/internal/cpu_features_macros.h - -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c -assert.h -- -stdarg.h -- -stdbool.h -- -stdint.h -- -stdio.h -- -stdlib.h -- -string.h -- -cpu_features_macros.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/cpu_features_macros.h -cpuinfo_x86.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/cpuinfo_x86.h -cpuinfo_arm.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/cpuinfo_arm.h -cpuinfo_aarch64.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/cpuinfo_aarch64.h -cpuinfo_mips.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/cpuinfo_mips.h -cpuinfo_ppc.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/cpuinfo_ppc.h - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/DependInfo.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/DependInfo.cmake deleted file mode 100644 index e3b56b1..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/DependInfo.cmake +++ /dev/null @@ -1,27 +0,0 @@ -# The set of languages for which implicit dependencies are needed: -set(CMAKE_DEPENDS_LANGUAGES - "C" - ) -# The set of files for implicit dependencies of each language: -set(CMAKE_DEPENDS_CHECK_C - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c" "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o" - ) -set(CMAKE_C_COMPILER_ID "GNU") - -# Preprocessor definitions for this target. -set(CMAKE_TARGET_DEFINITIONS_C - "STACK_LINE_READER_BUFFER_SIZE=1024" - ) - -# The include file search paths: -set(CMAKE_C_TARGET_INCLUDE_PATH - "../include" - ) - -# Targets to which this target links. -set(CMAKE_TARGET_LINKED_INFO_FILES - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/cpu_features.dir/DependInfo.cmake" - ) - -# Fortran module output directory. -set(CMAKE_Fortran_TARGET_MODULE_DIR "") diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/build.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/build.make deleted file mode 100644 index 4b6ec65..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/build.make +++ /dev/null @@ -1,114 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# Delete rule output on recipe failure. -.DELETE_ON_ERROR: - - -#============================================================================= -# Special targets provided by cmake. - -# Disable implicit rules so canonical targets will work. -.SUFFIXES: - - -# Remove some rules from gmake that .SUFFIXES does not remove. -SUFFIXES = - -.SUFFIXES: .hpux_make_needs_suffix_list - - -# Suppress display of executed commands. -$(VERBOSE).SILENT: - - -# A target that is always out of date. -cmake_force: - -.PHONY : cmake_force - -#============================================================================= -# Set environment variables for the build. - -# The shell in which to execute make rules. -SHELL = /bin/sh - -# The CMake executable. -CMAKE_COMMAND = /usr/bin/cmake - -# The command to remove a file. -RM = /usr/bin/cmake -E remove -f - -# Escaping for special characters. -EQUALS = = - -# The top-level source directory on which CMake was run. -CMAKE_SOURCE_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features - -# The top-level build directory on which CMake was run. -CMAKE_BINARY_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build - -# Include any dependencies generated for this target. -include CMakeFiles/list_cpu_features.dir/depend.make - -# Include the progress variables for this target. -include CMakeFiles/list_cpu_features.dir/progress.make - -# Include the compile flags for this target's objects. -include CMakeFiles/list_cpu_features.dir/flags.make - -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o: CMakeFiles/list_cpu_features.dir/flags.make -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o: ../src/utils/list_cpu_features.c - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_1) "Building C object CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -o CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c - -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.i: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing C source to CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.i" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -E /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c > CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.i - -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.s: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling C source to assembly CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.s" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -S /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c -o CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.s - -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o.requires: - -.PHONY : CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o.requires - -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o.provides: CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o.requires - $(MAKE) -f CMakeFiles/list_cpu_features.dir/build.make CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o.provides.build -.PHONY : CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o.provides - -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o.provides.build: CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o - - -# Object files for target list_cpu_features -list_cpu_features_OBJECTS = \ -"CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o" - -# External object files for target list_cpu_features -list_cpu_features_EXTERNAL_OBJECTS = - -list_cpu_features: CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o -list_cpu_features: CMakeFiles/list_cpu_features.dir/build.make -list_cpu_features: libcpu_features.a -list_cpu_features: CMakeFiles/list_cpu_features.dir/link.txt - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --bold --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_2) "Linking C executable list_cpu_features" - $(CMAKE_COMMAND) -E cmake_link_script CMakeFiles/list_cpu_features.dir/link.txt --verbose=$(VERBOSE) - -# Rule to build all files generated by this target. -CMakeFiles/list_cpu_features.dir/build: list_cpu_features - -.PHONY : CMakeFiles/list_cpu_features.dir/build - -CMakeFiles/list_cpu_features.dir/requires: CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o.requires - -.PHONY : CMakeFiles/list_cpu_features.dir/requires - -CMakeFiles/list_cpu_features.dir/clean: - $(CMAKE_COMMAND) -P CMakeFiles/list_cpu_features.dir/cmake_clean.cmake -.PHONY : CMakeFiles/list_cpu_features.dir/clean - -CMakeFiles/list_cpu_features.dir/depend: - cd /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build && $(CMAKE_COMMAND) -E cmake_depends "Unix Makefiles" /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/DependInfo.cmake --color=$(COLOR) -.PHONY : CMakeFiles/list_cpu_features.dir/depend - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/cmake_clean.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/cmake_clean.cmake deleted file mode 100644 index 2a77615..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/cmake_clean.cmake +++ /dev/null @@ -1,10 +0,0 @@ -file(REMOVE_RECURSE - "CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o" - "list_cpu_features.pdb" - "list_cpu_features" -) - -# Per-language clean rules from dependency scanning. -foreach(lang C) - include(CMakeFiles/list_cpu_features.dir/cmake_clean_${lang}.cmake OPTIONAL) -endforeach() diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/depend.internal b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/depend.internal deleted file mode 100644 index 40ec18b..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/depend.internal +++ /dev/null @@ -1,13 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o - ../include/cpu_features_cache_info.h - ../include/cpu_features_macros.h - ../include/cpuinfo_aarch64.h - ../include/cpuinfo_arm.h - ../include/cpuinfo_mips.h - ../include/cpuinfo_ppc.h - ../include/cpuinfo_x86.h - ../include/internal/hwcaps.h - /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/depend.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/depend.make deleted file mode 100644 index 6047430..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/depend.make +++ /dev/null @@ -1,13 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o: ../include/cpu_features_cache_info.h -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o: ../include/cpu_features_macros.h -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o: ../include/cpuinfo_aarch64.h -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o: ../include/cpuinfo_arm.h -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o: ../include/cpuinfo_mips.h -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o: ../include/cpuinfo_ppc.h -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o: ../include/cpuinfo_x86.h -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o: ../include/internal/hwcaps.h -CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o: ../src/utils/list_cpu_features.c - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/flags.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/flags.make deleted file mode 100644 index daaaeee..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/flags.make +++ /dev/null @@ -1,10 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# compile C with /usr/bin/cc -C_FLAGS = -O3 -DNDEBUG -std=gnu99 - -C_DEFINES = -DSTACK_LINE_READER_BUFFER_SIZE=1024 - -C_INCLUDES = -I/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/link.txt b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/link.txt deleted file mode 100644 index db897b0..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/link.txt +++ /dev/null @@ -1 +0,0 @@ -/usr/bin/cc -O3 -DNDEBUG -rdynamic CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o -o list_cpu_features libcpu_features.a -ldl diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/progress.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/progress.make deleted file mode 100644 index 8c8fb6f..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/progress.make +++ /dev/null @@ -1,3 +0,0 @@ -CMAKE_PROGRESS_1 = 3 -CMAKE_PROGRESS_2 = 4 - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o deleted file mode 100644 index 2d4a87a..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/progress.marks b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/progress.marks deleted file mode 100644 index ec63514..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/progress.marks +++ /dev/null @@ -1 +0,0 @@ -9 diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/C.includecache b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/C.includecache deleted file mode 100644 index 8407b8b..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/C.includecache +++ /dev/null @@ -1,72 +0,0 @@ -#IncludeRegexLine: ^[ ]*[#%][ ]*(include|import)[ ]*[<"]([^">]+)([">]) - -#IncludeRegexScan: ^.*$ - -#IncludeRegexComplain: ^$ - -#IncludeRegexTransform: - -../include/cpu_features_macros.h - -../include/internal/filesystem.h -stddef.h -- -stdint.h -- -cpu_features_macros.h -../include/internal/cpu_features_macros.h - -../include/internal/hwcaps.h -stdint.h -- -cpu_features_macros.h -../include/internal/cpu_features_macros.h - -../include/internal/string_view.h -stdbool.h -- -stddef.h -- -string.h -- -cpu_features_macros.h -../include/internal/cpu_features_macros.h - -../include/internal/unix_features_aggregator.h -ctype.h -- -stdint.h -- -cpu_features_macros.h -../include/internal/cpu_features_macros.h -internal/hwcaps.h -../include/internal/internal/hwcaps.h -internal/string_view.h -../include/internal/internal/string_view.h - -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c -internal/hwcaps.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/internal/hwcaps.h -stdlib.h -- -string.h -- -cpu_features_macros.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpu_features_macros.h -internal/filesystem.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/internal/filesystem.h -internal/string_view.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/internal/string_view.h -stdio.h -- -sys/auxv.h -- -dlfcn.h -- - -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/unix_features_aggregator.c -internal/unix_features_aggregator.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/internal/unix_features_aggregator.h -internal/string_view.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/internal/string_view.h - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/DependInfo.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/DependInfo.cmake deleted file mode 100644 index 311497b..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/DependInfo.cmake +++ /dev/null @@ -1,30 +0,0 @@ -# The set of languages for which implicit dependencies are needed: -set(CMAKE_DEPENDS_LANGUAGES - "C" - ) -# The set of files for implicit dependencies of each language: -set(CMAKE_DEPENDS_CHECK_C - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c" "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o" - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/unix_features_aggregator.c" "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o" - ) -set(CMAKE_C_COMPILER_ID "GNU") - -# Preprocessor definitions for this target. -set(CMAKE_TARGET_DEFINITIONS_C - "HAVE_DLFCN_H" - "HAVE_STRONG_GETAUXVAL" - "STACK_LINE_READER_BUFFER_SIZE=1024" - ) - -# The include file search paths: -set(CMAKE_C_TARGET_INCLUDE_PATH - "../include" - "../include/internal" - ) - -# Targets to which this target links. -set(CMAKE_TARGET_LINKED_INFO_FILES - ) - -# Fortran module output directory. -set(CMAKE_Fortran_TARGET_MODULE_DIR "") diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/build.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/build.make deleted file mode 100644 index 139bb24..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/build.make +++ /dev/null @@ -1,131 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# Delete rule output on recipe failure. -.DELETE_ON_ERROR: - - -#============================================================================= -# Special targets provided by cmake. - -# Disable implicit rules so canonical targets will work. -.SUFFIXES: - - -# Remove some rules from gmake that .SUFFIXES does not remove. -SUFFIXES = - -.SUFFIXES: .hpux_make_needs_suffix_list - - -# Suppress display of executed commands. -$(VERBOSE).SILENT: - - -# A target that is always out of date. -cmake_force: - -.PHONY : cmake_force - -#============================================================================= -# Set environment variables for the build. - -# The shell in which to execute make rules. -SHELL = /bin/sh - -# The CMake executable. -CMAKE_COMMAND = /usr/bin/cmake - -# The command to remove a file. -RM = /usr/bin/cmake -E remove -f - -# Escaping for special characters. -EQUALS = = - -# The top-level source directory on which CMake was run. -CMAKE_SOURCE_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features - -# The top-level build directory on which CMake was run. -CMAKE_BINARY_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build - -# Include any dependencies generated for this target. -include CMakeFiles/unix_based_hardware_detection.dir/depend.make - -# Include the progress variables for this target. -include CMakeFiles/unix_based_hardware_detection.dir/progress.make - -# Include the compile flags for this target's objects. -include CMakeFiles/unix_based_hardware_detection.dir/flags.make - -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o: CMakeFiles/unix_based_hardware_detection.dir/flags.make -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o: ../src/hwcaps.c - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_1) "Building C object CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -o CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c - -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.i: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing C source to CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.i" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -E /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c > CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.i - -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.s: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling C source to assembly CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.s" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -S /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c -o CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.s - -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o.requires: - -.PHONY : CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o.requires - -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o.provides: CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o.requires - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o.provides.build -.PHONY : CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o.provides - -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o.provides.build: CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o - - -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o: CMakeFiles/unix_based_hardware_detection.dir/flags.make -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o: ../src/unix_features_aggregator.c - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_2) "Building C object CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -o CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/unix_features_aggregator.c - -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.i: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing C source to CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.i" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -E /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/unix_features_aggregator.c > CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.i - -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.s: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling C source to assembly CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.s" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -S /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/unix_features_aggregator.c -o CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.s - -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o.requires: - -.PHONY : CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o.requires - -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o.provides: CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o.requires - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o.provides.build -.PHONY : CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o.provides - -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o.provides.build: CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o - - -unix_based_hardware_detection: CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o -unix_based_hardware_detection: CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o -unix_based_hardware_detection: CMakeFiles/unix_based_hardware_detection.dir/build.make - -.PHONY : unix_based_hardware_detection - -# Rule to build all files generated by this target. -CMakeFiles/unix_based_hardware_detection.dir/build: unix_based_hardware_detection - -.PHONY : CMakeFiles/unix_based_hardware_detection.dir/build - -CMakeFiles/unix_based_hardware_detection.dir/requires: CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o.requires -CMakeFiles/unix_based_hardware_detection.dir/requires: CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o.requires - -.PHONY : CMakeFiles/unix_based_hardware_detection.dir/requires - -CMakeFiles/unix_based_hardware_detection.dir/clean: - $(CMAKE_COMMAND) -P CMakeFiles/unix_based_hardware_detection.dir/cmake_clean.cmake -.PHONY : CMakeFiles/unix_based_hardware_detection.dir/clean - -CMakeFiles/unix_based_hardware_detection.dir/depend: - cd /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build && $(CMAKE_COMMAND) -E cmake_depends "Unix Makefiles" /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/DependInfo.cmake --color=$(COLOR) -.PHONY : CMakeFiles/unix_based_hardware_detection.dir/depend - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/cmake_clean.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/cmake_clean.cmake deleted file mode 100644 index ef5ea11..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/cmake_clean.cmake +++ /dev/null @@ -1,9 +0,0 @@ -file(REMOVE_RECURSE - "CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o" - "CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o" -) - -# Per-language clean rules from dependency scanning. -foreach(lang C) - include(CMakeFiles/unix_based_hardware_detection.dir/cmake_clean_${lang}.cmake OPTIONAL) -endforeach() diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/depend.internal b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/depend.internal deleted file mode 100644 index d8f78c0..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/depend.internal +++ /dev/null @@ -1,15 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o - ../include/cpu_features_macros.h - ../include/internal/filesystem.h - ../include/internal/hwcaps.h - ../include/internal/string_view.h - /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o - ../include/cpu_features_macros.h - ../include/internal/hwcaps.h - ../include/internal/string_view.h - ../include/internal/unix_features_aggregator.h - /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/unix_features_aggregator.c diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/depend.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/depend.make deleted file mode 100644 index 6a9140e..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/depend.make +++ /dev/null @@ -1,15 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o: ../include/cpu_features_macros.h -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o: ../include/internal/filesystem.h -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o: ../include/internal/hwcaps.h -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o: ../include/internal/string_view.h -CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o: ../src/hwcaps.c - -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o: ../include/cpu_features_macros.h -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o: ../include/internal/hwcaps.h -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o: ../include/internal/string_view.h -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o: ../include/internal/unix_features_aggregator.h -CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o: ../src/unix_features_aggregator.c - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/flags.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/flags.make deleted file mode 100644 index 8a9551a..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/flags.make +++ /dev/null @@ -1,10 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# compile C with /usr/bin/cc -C_FLAGS = -O3 -DNDEBUG -fPIC -std=gnu99 - -C_DEFINES = -DHAVE_DLFCN_H -DHAVE_STRONG_GETAUXVAL -DSTACK_LINE_READER_BUFFER_SIZE=1024 - -C_INCLUDES = -I/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include -I/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/progress.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/progress.make deleted file mode 100644 index 3a86673..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/progress.make +++ /dev/null @@ -1,3 +0,0 @@ -CMAKE_PROGRESS_1 = 5 -CMAKE_PROGRESS_2 = 6 - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o deleted file mode 100644 index 96d4635..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o deleted file mode 100644 index 029c3fe..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/C.includecache b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/C.includecache deleted file mode 100644 index c2f9dfa..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/C.includecache +++ /dev/null @@ -1,76 +0,0 @@ -#IncludeRegexLine: ^[ ]*[#%][ ]*(include|import)[ ]*[<"]([^">]+)([">]) - -#IncludeRegexScan: ^.*$ - -#IncludeRegexComplain: ^$ - -#IncludeRegexTransform: - -../include/cpu_features_macros.h - -../include/internal/filesystem.h -stddef.h -- -stdint.h -- -cpu_features_macros.h -../include/internal/cpu_features_macros.h - -../include/internal/stack_line_reader.h -stdbool.h -- -cpu_features_macros.h -../include/internal/cpu_features_macros.h -internal/string_view.h -../include/internal/internal/string_view.h - -../include/internal/string_view.h -stdbool.h -- -stddef.h -- -string.h -- -cpu_features_macros.h -../include/internal/cpu_features_macros.h - -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/filesystem.c -internal/filesystem.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/internal/filesystem.h -errno.h -- -fcntl.h -- -stdlib.h -- -sys/stat.h -- -sys/types.h -- -io.h -- -unistd.h -- - -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c -internal/stack_line_reader.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/internal/stack_line_reader.h -assert.h -- -errno.h -- -stdio.h -- -internal/filesystem.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/internal/filesystem.h - -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/string_view.c -internal/string_view.h -/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/internal/string_view.h -assert.h -- -ctype.h -- -string.h -- - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/DependInfo.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/DependInfo.cmake deleted file mode 100644 index 8aec4b0..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/DependInfo.cmake +++ /dev/null @@ -1,29 +0,0 @@ -# The set of languages for which implicit dependencies are needed: -set(CMAKE_DEPENDS_LANGUAGES - "C" - ) -# The set of files for implicit dependencies of each language: -set(CMAKE_DEPENDS_CHECK_C - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/filesystem.c" "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/filesystem.c.o" - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c" "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/stack_line_reader.c.o" - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/string_view.c" "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/string_view.c.o" - ) -set(CMAKE_C_COMPILER_ID "GNU") - -# Preprocessor definitions for this target. -set(CMAKE_TARGET_DEFINITIONS_C - "STACK_LINE_READER_BUFFER_SIZE=1024" - ) - -# The include file search paths: -set(CMAKE_C_TARGET_INCLUDE_PATH - "../include" - "../include/internal" - ) - -# Targets to which this target links. -set(CMAKE_TARGET_LINKED_INFO_FILES - ) - -# Fortran module output directory. -set(CMAKE_Fortran_TARGET_MODULE_DIR "") diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/build.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/build.make deleted file mode 100644 index 86e8acc..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/build.make +++ /dev/null @@ -1,157 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# Delete rule output on recipe failure. -.DELETE_ON_ERROR: - - -#============================================================================= -# Special targets provided by cmake. - -# Disable implicit rules so canonical targets will work. -.SUFFIXES: - - -# Remove some rules from gmake that .SUFFIXES does not remove. -SUFFIXES = - -.SUFFIXES: .hpux_make_needs_suffix_list - - -# Suppress display of executed commands. -$(VERBOSE).SILENT: - - -# A target that is always out of date. -cmake_force: - -.PHONY : cmake_force - -#============================================================================= -# Set environment variables for the build. - -# The shell in which to execute make rules. -SHELL = /bin/sh - -# The CMake executable. -CMAKE_COMMAND = /usr/bin/cmake - -# The command to remove a file. -RM = /usr/bin/cmake -E remove -f - -# Escaping for special characters. -EQUALS = = - -# The top-level source directory on which CMake was run. -CMAKE_SOURCE_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features - -# The top-level build directory on which CMake was run. -CMAKE_BINARY_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build - -# Include any dependencies generated for this target. -include CMakeFiles/utils.dir/depend.make - -# Include the progress variables for this target. -include CMakeFiles/utils.dir/progress.make - -# Include the compile flags for this target's objects. -include CMakeFiles/utils.dir/flags.make - -CMakeFiles/utils.dir/src/filesystem.c.o: CMakeFiles/utils.dir/flags.make -CMakeFiles/utils.dir/src/filesystem.c.o: ../src/filesystem.c - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_1) "Building C object CMakeFiles/utils.dir/src/filesystem.c.o" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -o CMakeFiles/utils.dir/src/filesystem.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/filesystem.c - -CMakeFiles/utils.dir/src/filesystem.c.i: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing C source to CMakeFiles/utils.dir/src/filesystem.c.i" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -E /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/filesystem.c > CMakeFiles/utils.dir/src/filesystem.c.i - -CMakeFiles/utils.dir/src/filesystem.c.s: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling C source to assembly CMakeFiles/utils.dir/src/filesystem.c.s" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -S /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/filesystem.c -o CMakeFiles/utils.dir/src/filesystem.c.s - -CMakeFiles/utils.dir/src/filesystem.c.o.requires: - -.PHONY : CMakeFiles/utils.dir/src/filesystem.c.o.requires - -CMakeFiles/utils.dir/src/filesystem.c.o.provides: CMakeFiles/utils.dir/src/filesystem.c.o.requires - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/filesystem.c.o.provides.build -.PHONY : CMakeFiles/utils.dir/src/filesystem.c.o.provides - -CMakeFiles/utils.dir/src/filesystem.c.o.provides.build: CMakeFiles/utils.dir/src/filesystem.c.o - - -CMakeFiles/utils.dir/src/stack_line_reader.c.o: CMakeFiles/utils.dir/flags.make -CMakeFiles/utils.dir/src/stack_line_reader.c.o: ../src/stack_line_reader.c - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_2) "Building C object CMakeFiles/utils.dir/src/stack_line_reader.c.o" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -o CMakeFiles/utils.dir/src/stack_line_reader.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c - -CMakeFiles/utils.dir/src/stack_line_reader.c.i: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing C source to CMakeFiles/utils.dir/src/stack_line_reader.c.i" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -E /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c > CMakeFiles/utils.dir/src/stack_line_reader.c.i - -CMakeFiles/utils.dir/src/stack_line_reader.c.s: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling C source to assembly CMakeFiles/utils.dir/src/stack_line_reader.c.s" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -S /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c -o CMakeFiles/utils.dir/src/stack_line_reader.c.s - -CMakeFiles/utils.dir/src/stack_line_reader.c.o.requires: - -.PHONY : CMakeFiles/utils.dir/src/stack_line_reader.c.o.requires - -CMakeFiles/utils.dir/src/stack_line_reader.c.o.provides: CMakeFiles/utils.dir/src/stack_line_reader.c.o.requires - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/stack_line_reader.c.o.provides.build -.PHONY : CMakeFiles/utils.dir/src/stack_line_reader.c.o.provides - -CMakeFiles/utils.dir/src/stack_line_reader.c.o.provides.build: CMakeFiles/utils.dir/src/stack_line_reader.c.o - - -CMakeFiles/utils.dir/src/string_view.c.o: CMakeFiles/utils.dir/flags.make -CMakeFiles/utils.dir/src/string_view.c.o: ../src/string_view.c - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_3) "Building C object CMakeFiles/utils.dir/src/string_view.c.o" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -o CMakeFiles/utils.dir/src/string_view.c.o -c /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/string_view.c - -CMakeFiles/utils.dir/src/string_view.c.i: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing C source to CMakeFiles/utils.dir/src/string_view.c.i" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -E /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/string_view.c > CMakeFiles/utils.dir/src/string_view.c.i - -CMakeFiles/utils.dir/src/string_view.c.s: cmake_force - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling C source to assembly CMakeFiles/utils.dir/src/string_view.c.s" - /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -S /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/string_view.c -o CMakeFiles/utils.dir/src/string_view.c.s - -CMakeFiles/utils.dir/src/string_view.c.o.requires: - -.PHONY : CMakeFiles/utils.dir/src/string_view.c.o.requires - -CMakeFiles/utils.dir/src/string_view.c.o.provides: CMakeFiles/utils.dir/src/string_view.c.o.requires - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/string_view.c.o.provides.build -.PHONY : CMakeFiles/utils.dir/src/string_view.c.o.provides - -CMakeFiles/utils.dir/src/string_view.c.o.provides.build: CMakeFiles/utils.dir/src/string_view.c.o - - -utils: CMakeFiles/utils.dir/src/filesystem.c.o -utils: CMakeFiles/utils.dir/src/stack_line_reader.c.o -utils: CMakeFiles/utils.dir/src/string_view.c.o -utils: CMakeFiles/utils.dir/build.make - -.PHONY : utils - -# Rule to build all files generated by this target. -CMakeFiles/utils.dir/build: utils - -.PHONY : CMakeFiles/utils.dir/build - -CMakeFiles/utils.dir/requires: CMakeFiles/utils.dir/src/filesystem.c.o.requires -CMakeFiles/utils.dir/requires: CMakeFiles/utils.dir/src/stack_line_reader.c.o.requires -CMakeFiles/utils.dir/requires: CMakeFiles/utils.dir/src/string_view.c.o.requires - -.PHONY : CMakeFiles/utils.dir/requires - -CMakeFiles/utils.dir/clean: - $(CMAKE_COMMAND) -P CMakeFiles/utils.dir/cmake_clean.cmake -.PHONY : CMakeFiles/utils.dir/clean - -CMakeFiles/utils.dir/depend: - cd /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build && $(CMAKE_COMMAND) -E cmake_depends "Unix Makefiles" /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/DependInfo.cmake --color=$(COLOR) -.PHONY : CMakeFiles/utils.dir/depend - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/cmake_clean.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/cmake_clean.cmake deleted file mode 100644 index de49fdf..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/cmake_clean.cmake +++ /dev/null @@ -1,10 +0,0 @@ -file(REMOVE_RECURSE - "CMakeFiles/utils.dir/src/filesystem.c.o" - "CMakeFiles/utils.dir/src/stack_line_reader.c.o" - "CMakeFiles/utils.dir/src/string_view.c.o" -) - -# Per-language clean rules from dependency scanning. -foreach(lang C) - include(CMakeFiles/utils.dir/cmake_clean_${lang}.cmake OPTIONAL) -endforeach() diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/depend.internal b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/depend.internal deleted file mode 100644 index 8bfa757..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/depend.internal +++ /dev/null @@ -1,17 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -CMakeFiles/utils.dir/src/filesystem.c.o - ../include/cpu_features_macros.h - ../include/internal/filesystem.h - /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/filesystem.c -CMakeFiles/utils.dir/src/stack_line_reader.c.o - ../include/cpu_features_macros.h - ../include/internal/filesystem.h - ../include/internal/stack_line_reader.h - ../include/internal/string_view.h - /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c -CMakeFiles/utils.dir/src/string_view.c.o - ../include/cpu_features_macros.h - ../include/internal/string_view.h - /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/string_view.c diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/depend.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/depend.make deleted file mode 100644 index 49618e4..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/depend.make +++ /dev/null @@ -1,17 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -CMakeFiles/utils.dir/src/filesystem.c.o: ../include/cpu_features_macros.h -CMakeFiles/utils.dir/src/filesystem.c.o: ../include/internal/filesystem.h -CMakeFiles/utils.dir/src/filesystem.c.o: ../src/filesystem.c - -CMakeFiles/utils.dir/src/stack_line_reader.c.o: ../include/cpu_features_macros.h -CMakeFiles/utils.dir/src/stack_line_reader.c.o: ../include/internal/filesystem.h -CMakeFiles/utils.dir/src/stack_line_reader.c.o: ../include/internal/stack_line_reader.h -CMakeFiles/utils.dir/src/stack_line_reader.c.o: ../include/internal/string_view.h -CMakeFiles/utils.dir/src/stack_line_reader.c.o: ../src/stack_line_reader.c - -CMakeFiles/utils.dir/src/string_view.c.o: ../include/cpu_features_macros.h -CMakeFiles/utils.dir/src/string_view.c.o: ../include/internal/string_view.h -CMakeFiles/utils.dir/src/string_view.c.o: ../src/string_view.c - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/flags.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/flags.make deleted file mode 100644 index dca3026..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/flags.make +++ /dev/null @@ -1,10 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# compile C with /usr/bin/cc -C_FLAGS = -O3 -DNDEBUG -fPIC -std=gnu99 - -C_DEFINES = -DSTACK_LINE_READER_BUFFER_SIZE=1024 - -C_INCLUDES = -I/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include -I/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/progress.make b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/progress.make deleted file mode 100644 index cd5d6f7..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/progress.make +++ /dev/null @@ -1,4 +0,0 @@ -CMAKE_PROGRESS_1 = 7 -CMAKE_PROGRESS_2 = 8 -CMAKE_PROGRESS_3 = 9 - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/filesystem.c.o b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/filesystem.c.o deleted file mode 100644 index 36b9cec..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/filesystem.c.o and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/stack_line_reader.c.o b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/stack_line_reader.c.o deleted file mode 100644 index 5f53a33..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/stack_line_reader.c.o and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/string_view.c.o b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/string_view.c.o deleted file mode 100644 index 31672b0..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/utils.dir/src/string_view.c.o and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CpuFeaturesConfig.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CpuFeaturesConfig.cmake deleted file mode 100644 index e0bf10e..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CpuFeaturesConfig.cmake +++ /dev/null @@ -1,3 +0,0 @@ -# CpuFeatures CMake configuration file - -include("${CMAKE_CURRENT_LIST_DIR}/CpuFeaturesTargets.cmake") diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CpuFeaturesConfigVersion.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CpuFeaturesConfigVersion.cmake deleted file mode 100644 index 9b9ee14..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CpuFeaturesConfigVersion.cmake +++ /dev/null @@ -1,46 +0,0 @@ -# This is a basic version file for the Config-mode of find_package(). -# It is used by write_basic_package_version_file() as input file for configure_file() -# to create a version-file which can be installed along a config.cmake file. -# -# The created file sets PACKAGE_VERSION_EXACT if the current version string and -# the requested version string are exactly the same and it sets -# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version, -# but only if the requested major version is the same as the current one. -# The variable CVF_VERSION must be set before calling configure_file(). - - -set(PACKAGE_VERSION "0.5.0") - -if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION) - set(PACKAGE_VERSION_COMPATIBLE FALSE) -else() - - if("0.5.0" MATCHES "^([0-9]+)\\.") - set(CVF_VERSION_MAJOR "${CMAKE_MATCH_1}") - else() - set(CVF_VERSION_MAJOR "0.5.0") - endif() - - if(PACKAGE_FIND_VERSION_MAJOR STREQUAL CVF_VERSION_MAJOR) - set(PACKAGE_VERSION_COMPATIBLE TRUE) - else() - set(PACKAGE_VERSION_COMPATIBLE FALSE) - endif() - - if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION) - set(PACKAGE_VERSION_EXACT TRUE) - endif() -endif() - - -# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it: -if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "8" STREQUAL "") - return() -endif() - -# check that the installed version has the same 32/64bit-ness as the one which is currently searching: -if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "8") - math(EXPR installedBits "8 * 8") - set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)") - set(PACKAGE_VERSION_UNSUITABLE TRUE) -endif() diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile deleted file mode 100644 index 633e3fe..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/Makefile +++ /dev/null @@ -1,450 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 3.10 - -# Default target executed when no arguments are given to make. -default_target: all - -.PHONY : default_target - -# Allow only one "make -f Makefile2" at a time, but pass parallelism. -.NOTPARALLEL: - - -#============================================================================= -# Special targets provided by cmake. - -# Disable implicit rules so canonical targets will work. -.SUFFIXES: - - -# Remove some rules from gmake that .SUFFIXES does not remove. -SUFFIXES = - -.SUFFIXES: .hpux_make_needs_suffix_list - - -# Suppress display of executed commands. -$(VERBOSE).SILENT: - - -# A target that is always out of date. -cmake_force: - -.PHONY : cmake_force - -#============================================================================= -# Set environment variables for the build. - -# The shell in which to execute make rules. -SHELL = /bin/sh - -# The CMake executable. -CMAKE_COMMAND = /usr/bin/cmake - -# The command to remove a file. -RM = /usr/bin/cmake -E remove -f - -# Escaping for special characters. -EQUALS = = - -# The top-level source directory on which CMake was run. -CMAKE_SOURCE_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features - -# The top-level build directory on which CMake was run. -CMAKE_BINARY_DIR = /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build - -#============================================================================= -# Targets provided globally by CMake. - -# Special rule for the target install/strip -install/strip: preinstall - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." - /usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake -.PHONY : install/strip - -# Special rule for the target install/strip -install/strip/fast: preinstall/fast - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." - /usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake -.PHONY : install/strip/fast - -# Special rule for the target install/local -install/local: preinstall - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." - /usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake -.PHONY : install/local - -# Special rule for the target install/local -install/local/fast: preinstall/fast - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." - /usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake -.PHONY : install/local/fast - -# Special rule for the target install -install: preinstall - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." - /usr/bin/cmake -P cmake_install.cmake -.PHONY : install - -# Special rule for the target install -install/fast: preinstall/fast - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." - /usr/bin/cmake -P cmake_install.cmake -.PHONY : install/fast - -# Special rule for the target list_install_components -list_install_components: - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Devel\" \"Unspecified\"" -.PHONY : list_install_components - -# Special rule for the target list_install_components -list_install_components/fast: list_install_components - -.PHONY : list_install_components/fast - -# Special rule for the target rebuild_cache -rebuild_cache: - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." - /usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) -.PHONY : rebuild_cache - -# Special rule for the target rebuild_cache -rebuild_cache/fast: rebuild_cache - -.PHONY : rebuild_cache/fast - -# Special rule for the target edit_cache -edit_cache: - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." - /usr/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. -.PHONY : edit_cache - -# Special rule for the target edit_cache -edit_cache/fast: edit_cache - -.PHONY : edit_cache/fast - -# The main all target -all: cmake_check_build_system - $(CMAKE_COMMAND) -E cmake_progress_start /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/progress.marks - $(MAKE) -f CMakeFiles/Makefile2 all - $(CMAKE_COMMAND) -E cmake_progress_start /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles 0 -.PHONY : all - -# The main clean target -clean: - $(MAKE) -f CMakeFiles/Makefile2 clean -.PHONY : clean - -# The main clean target -clean/fast: clean - -.PHONY : clean/fast - -# Prepare targets for installation. -preinstall: all - $(MAKE) -f CMakeFiles/Makefile2 preinstall -.PHONY : preinstall - -# Prepare targets for installation. -preinstall/fast: - $(MAKE) -f CMakeFiles/Makefile2 preinstall -.PHONY : preinstall/fast - -# clear depends -depend: - $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 -.PHONY : depend - -#============================================================================= -# Target rules for targets named unix_based_hardware_detection - -# Build rule for target. -unix_based_hardware_detection: cmake_check_build_system - $(MAKE) -f CMakeFiles/Makefile2 unix_based_hardware_detection -.PHONY : unix_based_hardware_detection - -# fast build rule for target. -unix_based_hardware_detection/fast: - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/build -.PHONY : unix_based_hardware_detection/fast - -#============================================================================= -# Target rules for targets named utils - -# Build rule for target. -utils: cmake_check_build_system - $(MAKE) -f CMakeFiles/Makefile2 utils -.PHONY : utils - -# fast build rule for target. -utils/fast: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/build -.PHONY : utils/fast - -#============================================================================= -# Target rules for targets named list_cpu_features - -# Build rule for target. -list_cpu_features: cmake_check_build_system - $(MAKE) -f CMakeFiles/Makefile2 list_cpu_features -.PHONY : list_cpu_features - -# fast build rule for target. -list_cpu_features/fast: - $(MAKE) -f CMakeFiles/list_cpu_features.dir/build.make CMakeFiles/list_cpu_features.dir/build -.PHONY : list_cpu_features/fast - -#============================================================================= -# Target rules for targets named cpu_features - -# Build rule for target. -cpu_features: cmake_check_build_system - $(MAKE) -f CMakeFiles/Makefile2 cpu_features -.PHONY : cpu_features - -# fast build rule for target. -cpu_features/fast: - $(MAKE) -f CMakeFiles/cpu_features.dir/build.make CMakeFiles/cpu_features.dir/build -.PHONY : cpu_features/fast - -src/cpuinfo_x86.o: src/cpuinfo_x86.c.o - -.PHONY : src/cpuinfo_x86.o - -# target to build an object file -src/cpuinfo_x86.c.o: - $(MAKE) -f CMakeFiles/cpu_features.dir/build.make CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.o -.PHONY : src/cpuinfo_x86.c.o - -src/cpuinfo_x86.i: src/cpuinfo_x86.c.i - -.PHONY : src/cpuinfo_x86.i - -# target to preprocess a source file -src/cpuinfo_x86.c.i: - $(MAKE) -f CMakeFiles/cpu_features.dir/build.make CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.i -.PHONY : src/cpuinfo_x86.c.i - -src/cpuinfo_x86.s: src/cpuinfo_x86.c.s - -.PHONY : src/cpuinfo_x86.s - -# target to generate assembly for a file -src/cpuinfo_x86.c.s: - $(MAKE) -f CMakeFiles/cpu_features.dir/build.make CMakeFiles/cpu_features.dir/src/cpuinfo_x86.c.s -.PHONY : src/cpuinfo_x86.c.s - -src/filesystem.o: src/filesystem.c.o - -.PHONY : src/filesystem.o - -# target to build an object file -src/filesystem.c.o: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/filesystem.c.o -.PHONY : src/filesystem.c.o - -src/filesystem.i: src/filesystem.c.i - -.PHONY : src/filesystem.i - -# target to preprocess a source file -src/filesystem.c.i: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/filesystem.c.i -.PHONY : src/filesystem.c.i - -src/filesystem.s: src/filesystem.c.s - -.PHONY : src/filesystem.s - -# target to generate assembly for a file -src/filesystem.c.s: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/filesystem.c.s -.PHONY : src/filesystem.c.s - -src/hwcaps.o: src/hwcaps.c.o - -.PHONY : src/hwcaps.o - -# target to build an object file -src/hwcaps.c.o: - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.o -.PHONY : src/hwcaps.c.o - -src/hwcaps.i: src/hwcaps.c.i - -.PHONY : src/hwcaps.i - -# target to preprocess a source file -src/hwcaps.c.i: - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.i -.PHONY : src/hwcaps.c.i - -src/hwcaps.s: src/hwcaps.c.s - -.PHONY : src/hwcaps.s - -# target to generate assembly for a file -src/hwcaps.c.s: - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/src/hwcaps.c.s -.PHONY : src/hwcaps.c.s - -src/stack_line_reader.o: src/stack_line_reader.c.o - -.PHONY : src/stack_line_reader.o - -# target to build an object file -src/stack_line_reader.c.o: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/stack_line_reader.c.o -.PHONY : src/stack_line_reader.c.o - -src/stack_line_reader.i: src/stack_line_reader.c.i - -.PHONY : src/stack_line_reader.i - -# target to preprocess a source file -src/stack_line_reader.c.i: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/stack_line_reader.c.i -.PHONY : src/stack_line_reader.c.i - -src/stack_line_reader.s: src/stack_line_reader.c.s - -.PHONY : src/stack_line_reader.s - -# target to generate assembly for a file -src/stack_line_reader.c.s: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/stack_line_reader.c.s -.PHONY : src/stack_line_reader.c.s - -src/string_view.o: src/string_view.c.o - -.PHONY : src/string_view.o - -# target to build an object file -src/string_view.c.o: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/string_view.c.o -.PHONY : src/string_view.c.o - -src/string_view.i: src/string_view.c.i - -.PHONY : src/string_view.i - -# target to preprocess a source file -src/string_view.c.i: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/string_view.c.i -.PHONY : src/string_view.c.i - -src/string_view.s: src/string_view.c.s - -.PHONY : src/string_view.s - -# target to generate assembly for a file -src/string_view.c.s: - $(MAKE) -f CMakeFiles/utils.dir/build.make CMakeFiles/utils.dir/src/string_view.c.s -.PHONY : src/string_view.c.s - -src/unix_features_aggregator.o: src/unix_features_aggregator.c.o - -.PHONY : src/unix_features_aggregator.o - -# target to build an object file -src/unix_features_aggregator.c.o: - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.o -.PHONY : src/unix_features_aggregator.c.o - -src/unix_features_aggregator.i: src/unix_features_aggregator.c.i - -.PHONY : src/unix_features_aggregator.i - -# target to preprocess a source file -src/unix_features_aggregator.c.i: - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.i -.PHONY : src/unix_features_aggregator.c.i - -src/unix_features_aggregator.s: src/unix_features_aggregator.c.s - -.PHONY : src/unix_features_aggregator.s - -# target to generate assembly for a file -src/unix_features_aggregator.c.s: - $(MAKE) -f CMakeFiles/unix_based_hardware_detection.dir/build.make CMakeFiles/unix_based_hardware_detection.dir/src/unix_features_aggregator.c.s -.PHONY : src/unix_features_aggregator.c.s - -src/utils/list_cpu_features.o: src/utils/list_cpu_features.c.o - -.PHONY : src/utils/list_cpu_features.o - -# target to build an object file -src/utils/list_cpu_features.c.o: - $(MAKE) -f CMakeFiles/list_cpu_features.dir/build.make CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.o -.PHONY : src/utils/list_cpu_features.c.o - -src/utils/list_cpu_features.i: src/utils/list_cpu_features.c.i - -.PHONY : src/utils/list_cpu_features.i - -# target to preprocess a source file -src/utils/list_cpu_features.c.i: - $(MAKE) -f CMakeFiles/list_cpu_features.dir/build.make CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.i -.PHONY : src/utils/list_cpu_features.c.i - -src/utils/list_cpu_features.s: src/utils/list_cpu_features.c.s - -.PHONY : src/utils/list_cpu_features.s - -# target to generate assembly for a file -src/utils/list_cpu_features.c.s: - $(MAKE) -f CMakeFiles/list_cpu_features.dir/build.make CMakeFiles/list_cpu_features.dir/src/utils/list_cpu_features.c.s -.PHONY : src/utils/list_cpu_features.c.s - -# Help Target -help: - @echo "The following are some of the valid targets for this Makefile:" - @echo "... all (the default if no target is provided)" - @echo "... clean" - @echo "... depend" - @echo "... install/strip" - @echo "... install/local" - @echo "... install" - @echo "... list_install_components" - @echo "... unix_based_hardware_detection" - @echo "... utils" - @echo "... rebuild_cache" - @echo "... list_cpu_features" - @echo "... cpu_features" - @echo "... edit_cache" - @echo "... src/cpuinfo_x86.o" - @echo "... src/cpuinfo_x86.i" - @echo "... src/cpuinfo_x86.s" - @echo "... src/filesystem.o" - @echo "... src/filesystem.i" - @echo "... src/filesystem.s" - @echo "... src/hwcaps.o" - @echo "... src/hwcaps.i" - @echo "... src/hwcaps.s" - @echo "... src/stack_line_reader.o" - @echo "... src/stack_line_reader.i" - @echo "... src/stack_line_reader.s" - @echo "... src/string_view.o" - @echo "... src/string_view.i" - @echo "... src/string_view.s" - @echo "... src/unix_features_aggregator.o" - @echo "... src/unix_features_aggregator.i" - @echo "... src/unix_features_aggregator.s" - @echo "... src/utils/list_cpu_features.o" - @echo "... src/utils/list_cpu_features.i" - @echo "... src/utils/list_cpu_features.s" -.PHONY : help - - - -#============================================================================= -# Special targets to cleanup operation of make. - -# Special rule to run CMake to check the build system integrity. -# No rule that depends on this can have commands that come from listfiles -# because they might be regenerated. -cmake_check_build_system: - $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 -.PHONY : cmake_check_build_system - diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/cmake_install.cmake b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/cmake_install.cmake deleted file mode 100644 index 6745051..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/cmake_install.cmake +++ /dev/null @@ -1,103 +0,0 @@ -# Install script for directory: /home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features - -# Set the install prefix -if(NOT DEFINED CMAKE_INSTALL_PREFIX) - set(CMAKE_INSTALL_PREFIX "/usr/local") -endif() -string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") - -# Set the install configuration name. -if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) - if(BUILD_TYPE) - string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" - CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") - else() - set(CMAKE_INSTALL_CONFIG_NAME "Release") - endif() - message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") -endif() - -# Set the component getting installed. -if(NOT CMAKE_INSTALL_COMPONENT) - if(COMPONENT) - message(STATUS "Install component: \"${COMPONENT}\"") - set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") - else() - set(CMAKE_INSTALL_COMPONENT) - endif() -endif() - -# Install shared libraries without execute permission? -if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) - set(CMAKE_INSTALL_SO_NO_EXE "1") -endif() - -# Is this installation the result of a crosscompile? -if(NOT DEFINED CMAKE_CROSSCOMPILING) - set(CMAKE_CROSSCOMPILING "FALSE") -endif() - -if("x${CMAKE_INSTALL_COMPONENT}x" STREQUAL "xUnspecifiedx" OR NOT CMAKE_INSTALL_COMPONENT) - file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE STATIC_LIBRARY FILES "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a") -endif() - -if("x${CMAKE_INSTALL_COMPONENT}x" STREQUAL "xUnspecifiedx" OR NOT CMAKE_INSTALL_COMPONENT) - file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/include/cpu_features" TYPE FILE FILES - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h" - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h" - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h" - ) -endif() - -if("x${CMAKE_INSTALL_COMPONENT}x" STREQUAL "xUnspecifiedx" OR NOT CMAKE_INSTALL_COMPONENT) - if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/bin/list_cpu_features" AND - NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/bin/list_cpu_features") - file(RPATH_CHECK - FILE "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/bin/list_cpu_features" - RPATH "") - endif() - file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/bin" TYPE EXECUTABLE FILES "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/list_cpu_features") - if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/bin/list_cpu_features" AND - NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/bin/list_cpu_features") - if(CMAKE_INSTALL_DO_STRIP) - execute_process(COMMAND "/usr/bin/strip" "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/bin/list_cpu_features") - endif() - endif() -endif() - -if("x${CMAKE_INSTALL_COMPONENT}x" STREQUAL "xDevelx" OR NOT CMAKE_INSTALL_COMPONENT) - if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/cmake/CpuFeatures/CpuFeaturesTargets.cmake") - file(DIFFERENT EXPORT_FILE_CHANGED FILES - "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/cmake/CpuFeatures/CpuFeaturesTargets.cmake" - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Export/lib/cmake/CpuFeatures/CpuFeaturesTargets.cmake") - if(EXPORT_FILE_CHANGED) - file(GLOB OLD_CONFIG_FILES "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/cmake/CpuFeatures/CpuFeaturesTargets-*.cmake") - if(OLD_CONFIG_FILES) - message(STATUS "Old export file \"$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/cmake/CpuFeatures/CpuFeaturesTargets.cmake\" will be replaced. Removing files [${OLD_CONFIG_FILES}].") - file(REMOVE ${OLD_CONFIG_FILES}) - endif() - endif() - endif() - file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/cmake/CpuFeatures" TYPE FILE FILES "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Export/lib/cmake/CpuFeatures/CpuFeaturesTargets.cmake") - if("${CMAKE_INSTALL_CONFIG_NAME}" MATCHES "^([Rr][Ee][Ll][Ee][Aa][Ss][Ee])$") - file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/cmake/CpuFeatures" TYPE FILE FILES "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CMakeFiles/Export/lib/cmake/CpuFeatures/CpuFeaturesTargets-release.cmake") - endif() -endif() - -if("x${CMAKE_INSTALL_COMPONENT}x" STREQUAL "xDevelx" OR NOT CMAKE_INSTALL_COMPONENT) - file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/cmake/CpuFeatures" TYPE FILE FILES - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CpuFeaturesConfig.cmake" - "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/CpuFeaturesConfigVersion.cmake" - ) -endif() - -if(CMAKE_INSTALL_COMPONENT) - set(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt") -else() - set(CMAKE_INSTALL_MANIFEST "install_manifest.txt") -endif() - -string(REPLACE ";" "\n" CMAKE_INSTALL_MANIFEST_CONTENT - "${CMAKE_INSTALL_MANIFEST_FILES}") -file(WRITE "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/${CMAKE_INSTALL_MANIFEST}" - "${CMAKE_INSTALL_MANIFEST_CONTENT}") diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a deleted file mode 100644 index 0a21a36..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/libcpu_features.a and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/list_cpu_features b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/list_cpu_features deleted file mode 100644 index 41425a6..0000000 Binary files a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/build/list_cpu_features and /dev/null differ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in deleted file mode 100644 index e0bf10e..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in +++ /dev/null @@ -1,3 +0,0 @@ -# CpuFeatures CMake configuration file - -include("${CMAKE_CURRENT_LIST_DIR}/CpuFeaturesTargets.cmake") diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in deleted file mode 100644 index 5a53ffd..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in +++ /dev/null @@ -1,3 +0,0 @@ -# CpuFeaturesNdkCompat CMake configuration file - -include("${CMAKE_CURRENT_LIST_DIR}/CpuFeaturesNdkCompatTargets.cmake") diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/README.md b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/README.md deleted file mode 100644 index b6baeaa..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# CMake build instructions - -## Recommended usage : Incorporating cpu_features into a CMake project - - For API / ABI compatibility reasons, it is recommended to build and use - cpu_features in a subdirectory of your project or as an embedded dependency. - - This is similar to the recommended usage of the googletest framework - ( https://github.com/google/googletest/blob/master/googletest/README.md ) - - Build and use step-by-step - - - 1- Download cpu_features and copy it in a sub-directory in your project. - or add cpu_features as a git-submodule in your project - - 2- You can then use the cmake command `add_subdirectory()` to include - cpu_features directly and use the `cpu_features` target in your project. - - 3- Add the `cpu_features` target to the `target_link_libraries()` section of - your executable or of your library. - -## Enabling tests - - CMake default options for cpu_features is Release built type with tests - disabled. To enable testing set cmake `BUILD_TESTING` variable to `ON`, - [.travis.yml](../.travis.yml) and [appveyor.yml](../appveyor.yml) have up to - date examples. diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in deleted file mode 100644 index d60a33e..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in +++ /dev/null @@ -1,15 +0,0 @@ -cmake_minimum_required(VERSION 2.8.2) - -project(googletest-download NONE) - -include(ExternalProject) -ExternalProject_Add(googletest - GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG master - SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src" - BINARY_DIR "${CMAKE_BINARY_DIR}/googletest-build" - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "" - TEST_COMMAND "" -) \ No newline at end of file diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h deleted file mode 100644 index b7cc046..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CPU_FEATURES_INCLUDE_CPUINFO_COMMON_H_ -#define CPU_FEATURES_INCLUDE_CPUINFO_COMMON_H_ - -#include "cpu_features_macros.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -typedef enum { - CPU_FEATURE_CACHE_NULL = 0, - CPU_FEATURE_CACHE_DATA = 1, - CPU_FEATURE_CACHE_INSTRUCTION = 2, - CPU_FEATURE_CACHE_UNIFIED = 3, - CPU_FEATURE_CACHE_TLB = 4, - CPU_FEATURE_CACHE_DTLB = 5, - CPU_FEATURE_CACHE_STLB = 6, - CPU_FEATURE_CACHE_PREFETCH = 7 -} CacheType; - -typedef struct { - int level; - CacheType cache_type; - int cache_size; // Cache size in bytes - int ways; // Associativity, 0 undefined, 0xFF fully associative - int line_size; // Cache line size in bytes - int tlb_entries; // number of entries for TLB - int partitioning; // number of lines per sector -} CacheLevelInfo; - -// Increase this value if more cache levels are needed. -#ifndef CPU_FEATURES_MAX_CACHE_LEVEL -#define CPU_FEATURES_MAX_CACHE_LEVEL 10 -#endif -typedef struct { - int size; - CacheLevelInfo levels[CPU_FEATURES_MAX_CACHE_LEVEL]; -} CacheInfo; - -CPU_FEATURES_END_CPP_NAMESPACE - -#endif // CPU_FEATURES_INCLUDE_CPUINFO_COMMON_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h deleted file mode 100644 index fae9f70..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CPU_FEATURES_INCLUDE_CPU_FEATURES_MACROS_H_ -#define CPU_FEATURES_INCLUDE_CPU_FEATURES_MACROS_H_ - -//////////////////////////////////////////////////////////////////////////////// -// Architectures -//////////////////////////////////////////////////////////////////////////////// - -#if defined(__pnacl__) || defined(__CLR_VER) -#define CPU_FEATURES_ARCH_VM -#endif - -#if (defined(_M_IX86) || defined(__i386__)) && !defined(CPU_FEATURES_ARCH_VM) -#define CPU_FEATURES_ARCH_X86_32 -#endif - -#if (defined(_M_X64) || defined(__x86_64__)) && !defined(CPU_FEATURES_ARCH_VM) -#define CPU_FEATURES_ARCH_X86_64 -#endif - -#if defined(CPU_FEATURES_ARCH_X86_32) || defined(CPU_FEATURES_ARCH_X86_64) -#define CPU_FEATURES_ARCH_X86 -#endif - -#if (defined(__arm__) || defined(_M_ARM)) -#define CPU_FEATURES_ARCH_ARM -#endif - -#if defined(__aarch64__) -#define CPU_FEATURES_ARCH_AARCH64 -#endif - -#if (defined(CPU_FEATURES_ARCH_AARCH64) || defined(CPU_FEATURES_ARCH_ARM)) -#define CPU_FEATURES_ARCH_ANY_ARM -#endif - -#if defined(__mips64) -#define CPU_FEATURES_ARCH_MIPS64 -#endif - -#if defined(__mips__) && !defined(__mips64) // mips64 also declares __mips__ -#define CPU_FEATURES_ARCH_MIPS32 -#endif - -#if defined(CPU_FEATURES_ARCH_MIPS32) || defined(CPU_FEATURES_ARCH_MIPS64) -#define CPU_FEATURES_ARCH_MIPS -#endif - -#if defined(__powerpc__) -#define CPU_FEATURES_ARCH_PPC -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Os -//////////////////////////////////////////////////////////////////////////////// - -#if defined(__linux__) -#define CPU_FEATURES_OS_LINUX_OR_ANDROID -#endif - -#if defined(__ANDROID__) -#define CPU_FEATURES_OS_ANDROID -#endif - -#if (defined(_WIN64) || defined(_WIN32)) -#define CPU_FEATURES_OS_WINDOWS -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Compilers -//////////////////////////////////////////////////////////////////////////////// - -#if defined(__clang__) -#define CPU_FEATURES_COMPILER_CLANG -#endif - -#if defined(__GNUC__) && !defined(__clang__) -#define CPU_FEATURES_COMPILER_GCC -#endif - -#if defined(_MSC_VER) -#define CPU_FEATURES_COMPILER_MSC -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Cpp -//////////////////////////////////////////////////////////////////////////////// - -#if defined(__cplusplus) -#define CPU_FEATURES_START_CPP_NAMESPACE \ - namespace cpu_features { \ - extern "C" { -#define CPU_FEATURES_END_CPP_NAMESPACE \ - } \ - } -#else -#define CPU_FEATURES_START_CPP_NAMESPACE -#define CPU_FEATURES_END_CPP_NAMESPACE -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Compiler flags -//////////////////////////////////////////////////////////////////////////////// - -// Use the following to check if a feature is known to be available at -// compile time. See README.md for an example. -#if defined(CPU_FEATURES_ARCH_X86) - -#if defined(__AES__) -#define CPU_FEATURES_COMPILED_X86_AES 1 -#else -#define CPU_FEATURES_COMPILED_X86_AES 0 -#endif // defined(__AES__) - -#if defined(__F16C__) -#define CPU_FEATURES_COMPILED_X86_F16C 1 -#else -#define CPU_FEATURES_COMPILED_X86_F16C 0 -#endif // defined(__F16C__) - -#if defined(__BMI__) -#define CPU_FEATURES_COMPILED_X86_BMI 1 -#else -#define CPU_FEATURES_COMPILED_X86_BMI 0 -#endif // defined(__BMI__) - -#if defined(__BMI2__) -#define CPU_FEATURES_COMPILED_X86_BMI2 1 -#else -#define CPU_FEATURES_COMPILED_X86_BMI2 0 -#endif // defined(__BMI2__) - -#if (defined(__SSE__) || (_M_IX86_FP >= 1)) -#define CPU_FEATURES_COMPILED_X86_SSE 1 -#else -#define CPU_FEATURES_COMPILED_X86_SSE 0 -#endif - -#if (defined(__SSE2__) || (_M_IX86_FP >= 2)) -#define CPU_FEATURES_COMPILED_X86_SSE2 1 -#else -#define CPU_FEATURES_COMPILED_X86_SSE2 0 -#endif - -#if defined(__SSE3__) -#define CPU_FEATURES_COMPILED_X86_SSE3 1 -#else -#define CPU_FEATURES_COMPILED_X86_SSE3 0 -#endif // defined(__SSE3__) - -#if defined(__SSSE3__) -#define CPU_FEATURES_COMPILED_X86_SSSE3 1 -#else -#define CPU_FEATURES_COMPILED_X86_SSSE3 0 -#endif // defined(__SSSE3__) - -#if defined(__SSE4_1__) -#define CPU_FEATURES_COMPILED_X86_SSE4_1 1 -#else -#define CPU_FEATURES_COMPILED_X86_SSE4_1 0 -#endif // defined(__SSE4_1__) - -#if defined(__SSE4_2__) -#define CPU_FEATURES_COMPILED_X86_SSE4_2 1 -#else -#define CPU_FEATURES_COMPILED_X86_SSE4_2 0 -#endif // defined(__SSE4_2__) - -#if defined(__AVX__) -#define CPU_FEATURES_COMPILED_X86_AVX 1 -#else -#define CPU_FEATURES_COMPILED_X86_AVX 0 -#endif // defined(__AVX__) - -#if defined(__AVX2__) -#define CPU_FEATURES_COMPILED_X86_AVX2 1 -#else -#define CPU_FEATURES_COMPILED_X86_AVX2 0 -#endif // defined(__AVX2__) - -#endif // defined(CPU_FEATURES_ARCH_X86) - -#if defined(CPU_FEATURES_ARCH_ANY_ARM) -#if defined(__ARM_NEON__) -#define CPU_FEATURES_COMPILED_ANY_ARM_NEON 1 -#else -#define CPU_FEATURES_COMPILED_ANY_ARM_NEON 0 -#endif // defined(__ARM_NEON__) -#endif // defined(CPU_FEATURES_ARCH_ANY_ARM) - -#if defined(CPU_FEATURES_ARCH_MIPS) -#if defined(__mips_msa) -#define CPU_FEATURES_COMPILED_MIPS_MSA 1 -#else -#define CPU_FEATURES_COMPILED_MIPS_MSA 0 -#endif // defined(__mips_msa) -#endif // defined(CPU_FEATURES_ARCH_MIPS) - -#endif // CPU_FEATURES_INCLUDE_CPU_FEATURES_MACROS_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h deleted file mode 100644 index bc2a5dc..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CPU_FEATURES_INCLUDE_CPUINFO_AARCH64_H_ -#define CPU_FEATURES_INCLUDE_CPUINFO_AARCH64_H_ - -#include "cpu_features_cache_info.h" -#include "cpu_features_macros.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -typedef struct { - int fp : 1; // Floating-point. - int asimd : 1; // Advanced SIMD. - int evtstrm : 1; // Generic timer generated events. - int aes : 1; // Hardware-accelerated Advanced Encryption Standard. - int pmull : 1; // Polynomial multiply long. - int sha1 : 1; // Hardware-accelerated SHA1. - int sha2 : 1; // Hardware-accelerated SHA2-256. - int crc32 : 1; // Hardware-accelerated CRC-32. - int atomics : 1; // Armv8.1 atomic instructions. - int fphp : 1; // Half-precision floating point support. - int asimdhp : 1; // Advanced SIMD half-precision support. - int cpuid : 1; // Access to certain ID registers. - int asimdrdm : 1; // Rounding Double Multiply Accumulate/Subtract. - int jscvt : 1; // Support for JavaScript conversion. - int fcma : 1; // Floating point complex numbers. - int lrcpc : 1; // Support for weaker release consistency. - int dcpop : 1; // Data persistence writeback. - int sha3 : 1; // Hardware-accelerated SHA3. - int sm3 : 1; // Hardware-accelerated SM3. - int sm4 : 1; // Hardware-accelerated SM4. - int asimddp : 1; // Dot product instruction. - int sha512 : 1; // Hardware-accelerated SHA512. - int sve : 1; // Scalable Vector Extension. - int asimdfhm : 1; // Additional half-precision instructions. - int dit : 1; // Data independent timing. - int uscat : 1; // Unaligned atomics support. - int ilrcpc : 1; // Additional support for weaker release consistency. - int flagm : 1; // Flag manipulation instructions. - int ssbs : 1; // Speculative Store Bypass Safe PSTATE bit. - int sb : 1; // Speculation barrier. - int paca : 1; // Address authentication. - int pacg : 1; // Generic authentication. - int dcpodp : 1; // Data cache clean to point of persistence. - int sve2 : 1; // Scalable Vector Extension (version 2). - int sveaes : 1; // SVE AES instructions. - int svepmull : 1; // SVE polynomial multiply long instructions. - int svebitperm : 1; // SVE bit permute instructions. - int svesha3 : 1; // SVE SHA3 instructions. - int svesm4 : 1; // SVE SM4 instructions. - int flagm2 : 1; // Additional flag manipulation instructions. - int frint : 1; // Floating point to integer rounding. - int svei8mm : 1; // SVE Int8 matrix multiplication instructions. - int svef32mm : 1; // SVE FP32 matrix multiplication instruction. - int svef64mm : 1; // SVE FP64 matrix multiplication instructions. - int svebf16 : 1; // SVE BFloat16 instructions. - int i8mm : 1; // Int8 matrix multiplication instructions. - int bf16 : 1; // BFloat16 instructions. - int dgh : 1; // Data Gathering Hint instruction. - int rng : 1; // True random number generator support. - int bti : 1; // Branch target identification. - - // Make sure to update Aarch64FeaturesEnum below if you add a field here. -} Aarch64Features; - -typedef struct { - Aarch64Features features; - int implementer; - int variant; - int part; - int revision; -} Aarch64Info; - -Aarch64Info GetAarch64Info(void); - -//////////////////////////////////////////////////////////////////////////////// -// Introspection functions - -typedef enum { - AARCH64_FP, - AARCH64_ASIMD, - AARCH64_EVTSTRM, - AARCH64_AES, - AARCH64_PMULL, - AARCH64_SHA1, - AARCH64_SHA2, - AARCH64_CRC32, - AARCH64_ATOMICS, - AARCH64_FPHP, - AARCH64_ASIMDHP, - AARCH64_CPUID, - AARCH64_ASIMDRDM, - AARCH64_JSCVT, - AARCH64_FCMA, - AARCH64_LRCPC, - AARCH64_DCPOP, - AARCH64_SHA3, - AARCH64_SM3, - AARCH64_SM4, - AARCH64_ASIMDDP, - AARCH64_SHA512, - AARCH64_SVE, - AARCH64_ASIMDFHM, - AARCH64_DIT, - AARCH64_USCAT, - AARCH64_ILRCPC, - AARCH64_FLAGM, - AARCH64_SSBS, - AARCH64_SB, - AARCH64_PACA, - AARCH64_PACG, - AARCH64_DCPODP, - AARCH64_SVE2, - AARCH64_SVEAES, - AARCH64_SVEPMULL, - AARCH64_SVEBITPERM, - AARCH64_SVESHA3, - AARCH64_SVESM4, - AARCH64_FLAGM2, - AARCH64_FRINT, - AARCH64_SVEI8MM, - AARCH64_SVEF32MM, - AARCH64_SVEF64MM, - AARCH64_SVEBF16, - AARCH64_I8MM, - AARCH64_BF16, - AARCH64_DGH, - AARCH64_RNG, - AARCH64_BTI, - AARCH64_LAST_, -} Aarch64FeaturesEnum; - -int GetAarch64FeaturesEnumValue(const Aarch64Features* features, - Aarch64FeaturesEnum value); - -const char* GetAarch64FeaturesEnumName(Aarch64FeaturesEnum); - -CPU_FEATURES_END_CPP_NAMESPACE - -#if !defined(CPU_FEATURES_ARCH_AARCH64) -#error "Including cpuinfo_aarch64.h from a non-aarch64 target." -#endif - -#endif // CPU_FEATURES_INCLUDE_CPUINFO_AARCH64_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h deleted file mode 100644 index 97a105c..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CPU_FEATURES_INCLUDE_CPUINFO_ARM_H_ -#define CPU_FEATURES_INCLUDE_CPUINFO_ARM_H_ - -#include // uint32_t - -#include "cpu_features_cache_info.h" -#include "cpu_features_macros.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -typedef struct { - int swp : 1; // SWP instruction (atomic read-modify-write) - int half : 1; // Half-word loads and stores - int thumb : 1; // Thumb (16-bit instruction set) - int _26bit : 1; // "26 Bit" Model (Processor status register folded into - // program counter) - int fastmult : 1; // 32x32->64-bit multiplication - int fpa : 1; // Floating point accelerator - int vfp : 1; // Vector Floating Point. - int edsp : 1; // DSP extensions (the 'e' variant of the ARM9 CPUs, and all - // others above) - int java : 1; // Jazelle (Java bytecode accelerator) - int iwmmxt : 1; // Intel Wireless MMX Technology. - int crunch : 1; // MaverickCrunch coprocessor - int thumbee : 1; // ThumbEE - int neon : 1; // Advanced SIMD. - int vfpv3 : 1; // VFP version 3 - int vfpv3d16 : 1; // VFP version 3 with 16 D-registers - int tls : 1; // TLS register - int vfpv4 : 1; // VFP version 4 with fast context switching - int idiva : 1; // SDIV and UDIV hardware division in ARM mode. - int idivt : 1; // SDIV and UDIV hardware division in Thumb mode. - int vfpd32 : 1; // VFP with 32 D-registers - int lpae : 1; // Large Physical Address Extension (>4GB physical memory on - // 32-bit architecture) - int evtstrm : 1; // kernel event stream using generic architected timer - int aes : 1; // Hardware-accelerated Advanced Encryption Standard. - int pmull : 1; // Polynomial multiply long. - int sha1 : 1; // Hardware-accelerated SHA1. - int sha2 : 1; // Hardware-accelerated SHA2-256. - int crc32 : 1; // Hardware-accelerated CRC-32. - - // Make sure to update ArmFeaturesEnum below if you add a field here. -} ArmFeatures; - -typedef struct { - ArmFeatures features; - int implementer; - int architecture; - int variant; - int part; - int revision; -} ArmInfo; - -// TODO(user): Add macros to know which features are present at compile -// time. - -ArmInfo GetArmInfo(void); - -// Compute CpuId from ArmInfo. -uint32_t GetArmCpuId(const ArmInfo* const info); - -//////////////////////////////////////////////////////////////////////////////// -// Introspection functions - -typedef enum { - ARM_SWP, - ARM_HALF, - ARM_THUMB, - ARM_26BIT, - ARM_FASTMULT, - ARM_FPA, - ARM_VFP, - ARM_EDSP, - ARM_JAVA, - ARM_IWMMXT, - ARM_CRUNCH, - ARM_THUMBEE, - ARM_NEON, - ARM_VFPV3, - ARM_VFPV3D16, - ARM_TLS, - ARM_VFPV4, - ARM_IDIVA, - ARM_IDIVT, - ARM_VFPD32, - ARM_LPAE, - ARM_EVTSTRM, - ARM_AES, - ARM_PMULL, - ARM_SHA1, - ARM_SHA2, - ARM_CRC32, - ARM_LAST_, -} ArmFeaturesEnum; - -int GetArmFeaturesEnumValue(const ArmFeatures* features, ArmFeaturesEnum value); - -const char* GetArmFeaturesEnumName(ArmFeaturesEnum); - -CPU_FEATURES_END_CPP_NAMESPACE - -#if !defined(CPU_FEATURES_ARCH_ARM) -#error "Including cpuinfo_arm.h from a non-arm target." -#endif - -#endif // CPU_FEATURES_INCLUDE_CPUINFO_ARM_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h deleted file mode 100644 index 642fd9e..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CPU_FEATURES_INCLUDE_CPUINFO_MIPS_H_ -#define CPU_FEATURES_INCLUDE_CPUINFO_MIPS_H_ - -#include "cpu_features_cache_info.h" -#include "cpu_features_macros.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -typedef struct { - int msa : 1; // MIPS SIMD Architecture - // https://www.mips.com/products/architectures/ase/simd/ - int eva : 1; // Enhanced Virtual Addressing - // https://www.mips.com/products/architectures/mips64/ - int r6 : 1; // True if is release 6 of the processor. - - // Make sure to update MipsFeaturesEnum below if you add a field here. -} MipsFeatures; - -typedef struct { - MipsFeatures features; -} MipsInfo; - -MipsInfo GetMipsInfo(void); - -//////////////////////////////////////////////////////////////////////////////// -// Introspection functions - -typedef enum { - MIPS_MSA, - MIPS_EVA, - MIPS_R6, - MIPS_LAST_, -} MipsFeaturesEnum; - -int GetMipsFeaturesEnumValue(const MipsFeatures* features, - MipsFeaturesEnum value); - -const char* GetMipsFeaturesEnumName(MipsFeaturesEnum); - -CPU_FEATURES_END_CPP_NAMESPACE - -#if !defined(CPU_FEATURES_ARCH_MIPS) -#error "Including cpuinfo_mips.h from a non-mips target." -#endif - -#endif // CPU_FEATURES_INCLUDE_CPUINFO_MIPS_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h deleted file mode 100644 index f691194..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2018 IBM -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CPU_FEATURES_INCLUDE_CPUINFO_PPC_H_ -#define CPU_FEATURES_INCLUDE_CPUINFO_PPC_H_ - -#include "cpu_features_cache_info.h" -#include "cpu_features_macros.h" -#include "internal/hwcaps.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -typedef struct { - int ppc32 : 1; - int ppc64 : 1; - int ppc601 : 1; - int altivec : 1; - int fpu : 1; - int mmu : 1; - int mac_4xx : 1; - int unifiedcache : 1; - int spe : 1; - int efpsingle : 1; - int efpdouble : 1; - int no_tb : 1; - int power4 : 1; - int power5 : 1; - int power5plus : 1; - int cell : 1; - int booke : 1; - int smt : 1; - int icachesnoop : 1; - int arch205 : 1; - int pa6t : 1; - int dfp : 1; - int power6ext : 1; - int arch206 : 1; - int vsx : 1; - int pseries_perfmon_compat : 1; - int truele : 1; - int ppcle : 1; - int arch207 : 1; - int htm : 1; - int dscr : 1; - int ebb : 1; - int isel : 1; - int tar : 1; - int vcrypto : 1; - int htm_nosc : 1; - int arch300 : 1; - int ieee128 : 1; - int darn : 1; - int scv : 1; - int htm_no_suspend : 1; - - // Make sure to update PPCFeaturesEnum below if you add a field here. -} PPCFeatures; - -typedef struct { - PPCFeatures features; -} PPCInfo; - -// This function is guaranteed to be malloc, memset and memcpy free. -PPCInfo GetPPCInfo(void); - -typedef struct { - char platform[64]; // 0 terminated string - char model[64]; // 0 terminated string - char machine[64]; // 0 terminated string - char cpu[64]; // 0 terminated string - PlatformType type; -} PPCPlatformStrings; - -PPCPlatformStrings GetPPCPlatformStrings(void); - -//////////////////////////////////////////////////////////////////////////////// -// Introspection functions - -typedef enum { - PPC_32, /* 32 bit mode execution */ - PPC_64, /* 64 bit mode execution */ - PPC_601_INSTR, /* Old POWER ISA */ - PPC_HAS_ALTIVEC, /* SIMD Unit*/ - PPC_HAS_FPU, /* Floating Point Unit */ - PPC_HAS_MMU, /* Memory management unit */ - PPC_HAS_4xxMAC, - PPC_UNIFIED_CACHE, /* Unified instruction and data cache */ - PPC_HAS_SPE, /* Signal processing extention unit */ - PPC_HAS_EFP_SINGLE, /* SPE single precision fpu */ - PPC_HAS_EFP_DOUBLE, /* SPE double precision fpu */ - PPC_NO_TB, /* No timebase */ - PPC_POWER4, - PPC_POWER5, - PPC_POWER5_PLUS, - PPC_CELL, /* Cell broadband engine */ - PPC_BOOKE, /* Embedded ISA */ - PPC_SMT, /* Simultaneous multi-threading */ - PPC_ICACHE_SNOOP, - PPC_ARCH_2_05, /* ISA 2.05 - POWER6 */ - PPC_PA6T, /* PA Semi 6T core ISA */ - PPC_HAS_DFP, /* Decimal floating point unit */ - PPC_POWER6_EXT, - PPC_ARCH_2_06, /* ISA 2.06 - POWER7 */ - PPC_HAS_VSX, /* Vector-scalar extension */ - PPC_PSERIES_PERFMON_COMPAT, /* Set of backwards compatibile performance - monitoring events */ - PPC_TRUE_LE, - PPC_PPC_LE, - PPC_ARCH_2_07, /* ISA 2.07 - POWER8 */ - PPC_HTM, /* Hardware Transactional Memory */ - PPC_DSCR, /* Data stream control register */ - PPC_EBB, /* Event base branching */ - PPC_ISEL, /* Integer select instructions */ - PPC_TAR, /* Target address register */ - PPC_VEC_CRYPTO, /* Vector cryptography instructions */ - PPC_HTM_NOSC, /* Transactions aborted when syscall made*/ - PPC_ARCH_3_00, /* ISA 3.00 - POWER9 */ - PPC_HAS_IEEE128, /* VSX IEEE Binary Float 128-bit */ - PPC_DARN, /* Deliver a random number instruction */ - PPC_SCV, /* scv syscall */ - PPC_HTM_NO_SUSPEND, /* TM w/out suspended state */ - PPC_LAST_, -} PPCFeaturesEnum; - -int GetPPCFeaturesEnumValue(const PPCFeatures* features, PPCFeaturesEnum value); - -const char* GetPPCFeaturesEnumName(PPCFeaturesEnum); - -CPU_FEATURES_END_CPP_NAMESPACE - -#if !defined(CPU_FEATURES_ARCH_PPC) -#error "Including cpuinfo_ppc.h from a non-ppc target." -#endif - -#endif // CPU_FEATURES_INCLUDE_CPUINFO_PPC_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h deleted file mode 100644 index c21a46a..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright 2017 Google Inc. -// Copyright 2020 Intel Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CPU_FEATURES_INCLUDE_CPUINFO_X86_H_ -#define CPU_FEATURES_INCLUDE_CPUINFO_X86_H_ - -#include "cpu_features_cache_info.h" -#include "cpu_features_macros.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -// See https://en.wikipedia.org/wiki/CPUID for a list of x86 cpu features. -// The field names are based on the short name provided in the wikipedia tables. -typedef struct { - int fpu : 1; - int tsc : 1; - int cx8 : 1; - int clfsh : 1; - int mmx : 1; - int aes : 1; - int erms : 1; - int f16c : 1; - int fma4 : 1; - int fma3 : 1; - int vaes : 1; - int vpclmulqdq : 1; - int bmi1 : 1; - int hle : 1; - int bmi2 : 1; - int rtm : 1; - int rdseed : 1; - int clflushopt : 1; - int clwb : 1; - - int sse : 1; - int sse2 : 1; - int sse3 : 1; - int ssse3 : 1; - int sse4_1 : 1; - int sse4_2 : 1; - int sse4a : 1; - - int avx : 1; - int avx2 : 1; - - int avx512f : 1; - int avx512cd : 1; - int avx512er : 1; - int avx512pf : 1; - int avx512bw : 1; - int avx512dq : 1; - int avx512vl : 1; - int avx512ifma : 1; - int avx512vbmi : 1; - int avx512vbmi2 : 1; - int avx512vnni : 1; - int avx512bitalg : 1; - int avx512vpopcntdq : 1; - int avx512_4vnniw : 1; - int avx512_4vbmi2 : 1; - int avx512_second_fma : 1; - int avx512_4fmaps : 1; - int avx512_bf16 : 1; - int avx512_vp2intersect : 1; - int amx_bf16 : 1; - int amx_tile : 1; - int amx_int8 : 1; - - int pclmulqdq : 1; - int smx : 1; - int sgx : 1; - int cx16 : 1; // aka. CMPXCHG16B - int sha : 1; - int popcnt : 1; - int movbe : 1; - int rdrnd : 1; - - int dca : 1; - int ss : 1; - // Make sure to update X86FeaturesEnum below if you add a field here. -} X86Features; - -typedef struct { - X86Features features; - int family; - int model; - int stepping; - char vendor[13]; // 0 terminated string -} X86Info; - -// Calls cpuid and returns an initialized X86info. -// This function is guaranteed to be malloc, memset and memcpy free. -X86Info GetX86Info(void); - -// Returns cache hierarchy informations. -// Can call cpuid multiple times. -// Only works on Intel CPU at the moment. -// This function is guaranteed to be malloc, memset and memcpy free. -CacheInfo GetX86CacheInfo(void); - -typedef enum { - X86_UNKNOWN, - INTEL_CORE, // CORE - INTEL_PNR, // PENRYN - INTEL_NHM, // NEHALEM - INTEL_ATOM_BNL, // BONNELL - INTEL_WSM, // WESTMERE - INTEL_SNB, // SANDYBRIDGE - INTEL_IVB, // IVYBRIDGE - INTEL_ATOM_SMT, // SILVERMONT - INTEL_HSW, // HASWELL - INTEL_BDW, // BROADWELL - INTEL_SKL, // SKYLAKE - INTEL_ATOM_GMT, // GOLDMONT - INTEL_KBL, // KABY LAKE - INTEL_CFL, // COFFEE LAKE - INTEL_WHL, // WHISKEY LAKE - INTEL_CNL, // CANNON LAKE - INTEL_ICL, // ICE LAKE - INTEL_TGL, // TIGER LAKE - INTEL_SPR, // SAPPHIRE RAPIDS - AMD_HAMMER, // K8 - AMD_K10, // K10 - AMD_BOBCAT, // K14 - AMD_BULLDOZER, // K15 - AMD_JAGUAR, // K16 - AMD_ZEN, // K17 -} X86Microarchitecture; - -// Returns the underlying microarchitecture by looking at X86Info's vendor, -// family and model. -X86Microarchitecture GetX86Microarchitecture(const X86Info* info); - -// Calls cpuid and fills the brand_string. -// - brand_string *must* be of size 49 (beware of array decaying). -// - brand_string will be zero terminated. -// - This function calls memcpy. -void FillX86BrandString(char brand_string[49]); - -//////////////////////////////////////////////////////////////////////////////// -// Introspection functions - -typedef enum { - X86_FPU, - X86_TSC, - X86_CX8, - X86_CLFSH, - X86_MMX, - X86_AES, - X86_ERMS, - X86_F16C, - X86_FMA4, - X86_FMA3, - X86_VAES, - X86_VPCLMULQDQ, - X86_BMI1, - X86_HLE, - X86_BMI2, - X86_RTM, - X86_RDSEED, - X86_CLFLUSHOPT, - X86_CLWB, - X86_SSE, - X86_SSE2, - X86_SSE3, - X86_SSSE3, - X86_SSE4_1, - X86_SSE4_2, - X86_SSE4A, - X86_AVX, - X86_AVX2, - X86_AVX512F, - X86_AVX512CD, - X86_AVX512ER, - X86_AVX512PF, - X86_AVX512BW, - X86_AVX512DQ, - X86_AVX512VL, - X86_AVX512IFMA, - X86_AVX512VBMI, - X86_AVX512VBMI2, - X86_AVX512VNNI, - X86_AVX512BITALG, - X86_AVX512VPOPCNTDQ, - X86_AVX512_4VNNIW, - X86_AVX512_4VBMI2, - X86_AVX512_SECOND_FMA, - X86_AVX512_4FMAPS, - X86_AVX512_BF16, - X86_AVX512_VP2INTERSECT, - X86_AMX_BF16, - X86_AMX_TILE, - X86_AMX_INT8, - X86_PCLMULQDQ, - X86_SMX, - X86_SGX, - X86_CX16, - X86_SHA, - X86_POPCNT, - X86_MOVBE, - X86_RDRND, - X86_DCA, - X86_SS, - X86_LAST_, -} X86FeaturesEnum; - -int GetX86FeaturesEnumValue(const X86Features* features, X86FeaturesEnum value); - -const char* GetX86FeaturesEnumName(X86FeaturesEnum); - -const char* GetX86MicroarchitectureName(X86Microarchitecture); - -CPU_FEATURES_END_CPP_NAMESPACE - -#if !defined(CPU_FEATURES_ARCH_X86) -#error "Including cpuinfo_x86.h from a non-x86 target." -#endif - -#endif // CPU_FEATURES_INCLUDE_CPUINFO_X86_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h deleted file mode 100644 index ae313b5..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CPU_FEATURES_INCLUDE_INTERNAL_BIT_UTILS_H_ -#define CPU_FEATURES_INCLUDE_INTERNAL_BIT_UTILS_H_ - -#include -#include -#include - -#include "cpu_features_macros.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -inline static bool IsBitSet(uint32_t reg, uint32_t bit) { - return (reg >> bit) & 0x1; -} - -inline static uint32_t ExtractBitRange(uint32_t reg, uint32_t msb, - uint32_t lsb) { - const uint64_t bits = msb - lsb + 1ULL; - const uint64_t mask = (1ULL << bits) - 1ULL; - assert(msb >= lsb); - return (reg >> lsb) & mask; -} - -CPU_FEATURES_END_CPP_NAMESPACE - -#endif // CPU_FEATURES_INCLUDE_INTERNAL_BIT_UTILS_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h deleted file mode 100644 index 754ca38..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CPU_FEATURES_INCLUDE_INTERNAL_CPUID_X86_H_ -#define CPU_FEATURES_INCLUDE_INTERNAL_CPUID_X86_H_ - -#include - -#include "cpu_features_macros.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -// A struct to hold the result of a call to cpuid. -typedef struct { - uint32_t eax, ebx, ecx, edx; -} Leaf; - -Leaf CpuIdEx(uint32_t leaf_id, int ecx); - -// Returns the eax value of the XCR0 register. -uint32_t GetXCR0Eax(void); - -CPU_FEATURES_END_CPP_NAMESPACE - -#endif // CPU_FEATURES_INCLUDE_INTERNAL_CPUID_X86_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h deleted file mode 100644 index d9cdafc..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// An interface for the filesystem that allows mocking the filesystem in -// unittests. -#ifndef CPU_FEATURES_INCLUDE_INTERNAL_FILESYSTEM_H_ -#define CPU_FEATURES_INCLUDE_INTERNAL_FILESYSTEM_H_ - -#include -#include - -#include "cpu_features_macros.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -// Same as linux "open(filename, O_RDONLY)", retries automatically on EINTR. -int CpuFeatures_OpenFile(const char* filename); - -// Same as linux "read(file_descriptor, buffer, buffer_size)", retries -// automatically on EINTR. -int CpuFeatures_ReadFile(int file_descriptor, void* buffer, size_t buffer_size); - -// Same as linux "close(file_descriptor)". -void CpuFeatures_CloseFile(int file_descriptor); - -CPU_FEATURES_END_CPP_NAMESPACE - -#endif // CPU_FEATURES_INCLUDE_INTERNAL_FILESYSTEM_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h deleted file mode 100644 index 8716eb8..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Interface to retrieve hardware capabilities. It relies on Linux's getauxval -// or `/proc/self/auxval` under the hood. -#ifndef CPU_FEATURES_INCLUDE_INTERNAL_HWCAPS_H_ -#define CPU_FEATURES_INCLUDE_INTERNAL_HWCAPS_H_ - -#include - -#include "cpu_features_macros.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -// To avoid depending on the linux kernel we reproduce the architecture specific -// constants here. - -// http://elixir.free-electrons.com/linux/latest/source/arch/arm64/include/uapi/asm/hwcap.h -#define AARCH64_HWCAP_FP (1UL << 0) -#define AARCH64_HWCAP_ASIMD (1UL << 1) -#define AARCH64_HWCAP_EVTSTRM (1UL << 2) -#define AARCH64_HWCAP_AES (1UL << 3) -#define AARCH64_HWCAP_PMULL (1UL << 4) -#define AARCH64_HWCAP_SHA1 (1UL << 5) -#define AARCH64_HWCAP_SHA2 (1UL << 6) -#define AARCH64_HWCAP_CRC32 (1UL << 7) -#define AARCH64_HWCAP_ATOMICS (1UL << 8) -#define AARCH64_HWCAP_FPHP (1UL << 9) -#define AARCH64_HWCAP_ASIMDHP (1UL << 10) -#define AARCH64_HWCAP_CPUID (1UL << 11) -#define AARCH64_HWCAP_ASIMDRDM (1UL << 12) -#define AARCH64_HWCAP_JSCVT (1UL << 13) -#define AARCH64_HWCAP_FCMA (1UL << 14) -#define AARCH64_HWCAP_LRCPC (1UL << 15) -#define AARCH64_HWCAP_DCPOP (1UL << 16) -#define AARCH64_HWCAP_SHA3 (1UL << 17) -#define AARCH64_HWCAP_SM3 (1UL << 18) -#define AARCH64_HWCAP_SM4 (1UL << 19) -#define AARCH64_HWCAP_ASIMDDP (1UL << 20) -#define AARCH64_HWCAP_SHA512 (1UL << 21) -#define AARCH64_HWCAP_SVE (1UL << 22) -#define AARCH64_HWCAP_ASIMDFHM (1UL << 23) -#define AARCH64_HWCAP_DIT (1UL << 24) -#define AARCH64_HWCAP_USCAT (1UL << 25) -#define AARCH64_HWCAP_ILRCPC (1UL << 26) -#define AARCH64_HWCAP_FLAGM (1UL << 27) -#define AARCH64_HWCAP_SSBS (1UL << 28) -#define AARCH64_HWCAP_SB (1UL << 29) -#define AARCH64_HWCAP_PACA (1UL << 30) -#define AARCH64_HWCAP_PACG (1UL << 31) - -#define AARCH64_HWCAP2_DCPODP (1UL << 0) -#define AARCH64_HWCAP2_SVE2 (1UL << 1) -#define AARCH64_HWCAP2_SVEAES (1UL << 2) -#define AARCH64_HWCAP2_SVEPMULL (1UL << 3) -#define AARCH64_HWCAP2_SVEBITPERM (1UL << 4) -#define AARCH64_HWCAP2_SVESHA3 (1UL << 5) -#define AARCH64_HWCAP2_SVESM4 (1UL << 6) -#define AARCH64_HWCAP2_FLAGM2 (1UL << 7) -#define AARCH64_HWCAP2_FRINT (1UL << 8) -#define AARCH64_HWCAP2_SVEI8MM (1UL << 9) -#define AARCH64_HWCAP2_SVEF32MM (1UL << 10) -#define AARCH64_HWCAP2_SVEF64MM (1UL << 11) -#define AARCH64_HWCAP2_SVEBF16 (1UL << 12) -#define AARCH64_HWCAP2_I8MM (1UL << 13) -#define AARCH64_HWCAP2_BF16 (1UL << 14) -#define AARCH64_HWCAP2_DGH (1UL << 15) -#define AARCH64_HWCAP2_RNG (1UL << 16) -#define AARCH64_HWCAP2_BTI (1UL << 17) - -// http://elixir.free-electrons.com/linux/latest/source/arch/arm/include/uapi/asm/hwcap.h -#define ARM_HWCAP_SWP (1UL << 0) -#define ARM_HWCAP_HALF (1UL << 1) -#define ARM_HWCAP_THUMB (1UL << 2) -#define ARM_HWCAP_26BIT (1UL << 3) -#define ARM_HWCAP_FAST_MULT (1UL << 4) -#define ARM_HWCAP_FPA (1UL << 5) -#define ARM_HWCAP_VFP (1UL << 6) -#define ARM_HWCAP_EDSP (1UL << 7) -#define ARM_HWCAP_JAVA (1UL << 8) -#define ARM_HWCAP_IWMMXT (1UL << 9) -#define ARM_HWCAP_CRUNCH (1UL << 10) -#define ARM_HWCAP_THUMBEE (1UL << 11) -#define ARM_HWCAP_NEON (1UL << 12) -#define ARM_HWCAP_VFPV3 (1UL << 13) -#define ARM_HWCAP_VFPV3D16 (1UL << 14) -#define ARM_HWCAP_TLS (1UL << 15) -#define ARM_HWCAP_VFPV4 (1UL << 16) -#define ARM_HWCAP_IDIVA (1UL << 17) -#define ARM_HWCAP_IDIVT (1UL << 18) -#define ARM_HWCAP_VFPD32 (1UL << 19) -#define ARM_HWCAP_LPAE (1UL << 20) -#define ARM_HWCAP_EVTSTRM (1UL << 21) -#define ARM_HWCAP2_AES (1UL << 0) -#define ARM_HWCAP2_PMULL (1UL << 1) -#define ARM_HWCAP2_SHA1 (1UL << 2) -#define ARM_HWCAP2_SHA2 (1UL << 3) -#define ARM_HWCAP2_CRC32 (1UL << 4) - -// http://elixir.free-electrons.com/linux/latest/source/arch/mips/include/uapi/asm/hwcap.h -#define MIPS_HWCAP_R6 (1UL << 0) -#define MIPS_HWCAP_MSA (1UL << 1) -#define MIPS_HWCAP_CRC32 (1UL << 2) - -// http://elixir.free-electrons.com/linux/latest/source/arch/powerpc/include/uapi/asm/cputable.h -#ifndef _UAPI__ASM_POWERPC_CPUTABLE_H -/* in AT_HWCAP */ -#define PPC_FEATURE_32 0x80000000 -#define PPC_FEATURE_64 0x40000000 -#define PPC_FEATURE_601_INSTR 0x20000000 -#define PPC_FEATURE_HAS_ALTIVEC 0x10000000 -#define PPC_FEATURE_HAS_FPU 0x08000000 -#define PPC_FEATURE_HAS_MMU 0x04000000 -#define PPC_FEATURE_HAS_4xxMAC 0x02000000 -#define PPC_FEATURE_UNIFIED_CACHE 0x01000000 -#define PPC_FEATURE_HAS_SPE 0x00800000 -#define PPC_FEATURE_HAS_EFP_SINGLE 0x00400000 -#define PPC_FEATURE_HAS_EFP_DOUBLE 0x00200000 -#define PPC_FEATURE_NO_TB 0x00100000 -#define PPC_FEATURE_POWER4 0x00080000 -#define PPC_FEATURE_POWER5 0x00040000 -#define PPC_FEATURE_POWER5_PLUS 0x00020000 -#define PPC_FEATURE_CELL 0x00010000 -#define PPC_FEATURE_BOOKE 0x00008000 -#define PPC_FEATURE_SMT 0x00004000 -#define PPC_FEATURE_ICACHE_SNOOP 0x00002000 -#define PPC_FEATURE_ARCH_2_05 0x00001000 -#define PPC_FEATURE_PA6T 0x00000800 -#define PPC_FEATURE_HAS_DFP 0x00000400 -#define PPC_FEATURE_POWER6_EXT 0x00000200 -#define PPC_FEATURE_ARCH_2_06 0x00000100 -#define PPC_FEATURE_HAS_VSX 0x00000080 - -#define PPC_FEATURE_PSERIES_PERFMON_COMPAT 0x00000040 - -/* Reserved - do not use 0x00000004 */ -#define PPC_FEATURE_TRUE_LE 0x00000002 -#define PPC_FEATURE_PPC_LE 0x00000001 - -/* in AT_HWCAP2 */ -#define PPC_FEATURE2_ARCH_2_07 0x80000000 -#define PPC_FEATURE2_HTM 0x40000000 -#define PPC_FEATURE2_DSCR 0x20000000 -#define PPC_FEATURE2_EBB 0x10000000 -#define PPC_FEATURE2_ISEL 0x08000000 -#define PPC_FEATURE2_TAR 0x04000000 -#define PPC_FEATURE2_VEC_CRYPTO 0x02000000 -#define PPC_FEATURE2_HTM_NOSC 0x01000000 -#define PPC_FEATURE2_ARCH_3_00 0x00800000 -#define PPC_FEATURE2_HAS_IEEE128 0x00400000 -#define PPC_FEATURE2_DARN 0x00200000 -#define PPC_FEATURE2_SCV 0x00100000 -#define PPC_FEATURE2_HTM_NO_SUSPEND 0x00080000 -#endif - -typedef struct { - unsigned long hwcaps; - unsigned long hwcaps2; -} HardwareCapabilities; - -HardwareCapabilities CpuFeatures_GetHardwareCapabilities(void); - -typedef struct { - char platform[64]; // 0 terminated string - char base_platform[64]; // 0 terminated string -} PlatformType; - -PlatformType CpuFeatures_GetPlatformType(void); - -CPU_FEATURES_END_CPP_NAMESPACE - -#endif // CPU_FEATURES_INCLUDE_INTERNAL_HWCAPS_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h deleted file mode 100644 index c540f6b..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Reads a file line by line and stores the data on the stack. This allows -// parsing files in one go without allocating. -#ifndef CPU_FEATURES_INCLUDE_INTERNAL_STACK_LINE_READER_H_ -#define CPU_FEATURES_INCLUDE_INTERNAL_STACK_LINE_READER_H_ - -#include - -#include "cpu_features_macros.h" -#include "internal/string_view.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -typedef struct { - char buffer[STACK_LINE_READER_BUFFER_SIZE]; - StringView view; - int fd; - bool skip_mode; -} StackLineReader; - -// Initializes a StackLineReader. -void StackLineReader_Initialize(StackLineReader* reader, int fd); - -typedef struct { - StringView line; // A view of the line. - bool eof; // Nothing more to read, we reached EOF. - bool full_line; // If false the line was truncated to - // STACK_LINE_READER_BUFFER_SIZE. -} LineResult; - -// Reads the file pointed to by fd and tries to read a full line. -LineResult StackLineReader_NextLine(StackLineReader* reader); - -CPU_FEATURES_END_CPP_NAMESPACE - -#endif // CPU_FEATURES_INCLUDE_INTERNAL_STACK_LINE_READER_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h deleted file mode 100644 index 5044dc8..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// A view over a piece of string. The view is not 0 terminated. -#ifndef CPU_FEATURES_INCLUDE_INTERNAL_STRING_VIEW_H_ -#define CPU_FEATURES_INCLUDE_INTERNAL_STRING_VIEW_H_ - -#include -#include -#include - -#include "cpu_features_macros.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -typedef struct { - const char* ptr; - size_t size; -} StringView; - -#ifdef __cplusplus -static const StringView kEmptyStringView = {NULL, 0}; -#else -static const StringView kEmptyStringView; -#endif - -// Returns a StringView from the provided string. -// Passing NULL is valid only if size is 0. -static inline StringView view(const char* str, const size_t size) { - StringView view; - view.ptr = str; - view.size = size; - return view; -} - -static inline StringView str(const char* str) { return view(str, strlen(str)); } - -// Returns the index of the first occurrence of c in view or -1 if not found. -int CpuFeatures_StringView_IndexOfChar(const StringView view, char c); - -// Returns the index of the first occurrence of sub_view in view or -1 if not -// found. -int CpuFeatures_StringView_IndexOf(const StringView view, - const StringView sub_view); - -// Returns whether a is equal to b (same content). -bool CpuFeatures_StringView_IsEquals(const StringView a, const StringView b); - -// Returns whether a starts with b. -bool CpuFeatures_StringView_StartsWith(const StringView a, const StringView b); - -// Removes count characters from the beginning of view or kEmptyStringView if -// count if greater than view.size. -StringView CpuFeatures_StringView_PopFront(const StringView str_view, - size_t count); - -// Removes count characters from the end of view or kEmptyStringView if count if -// greater than view.size. -StringView CpuFeatures_StringView_PopBack(const StringView str_view, - size_t count); - -// Keeps the count first characters of view or view if count if greater than -// view.size. -StringView CpuFeatures_StringView_KeepFront(const StringView str_view, - size_t count); - -// Retrieves the first character of view. If view is empty the behavior is -// undefined. -char CpuFeatures_StringView_Front(const StringView view); - -// Retrieves the last character of view. If view is empty the behavior is -// undefined. -char CpuFeatures_StringView_Back(const StringView view); - -// Removes leading and tailing space characters. -StringView CpuFeatures_StringView_TrimWhitespace(StringView view); - -// Convert StringView to positive integer. e.g. "42", "0x2a". -// Returns -1 on error. -int CpuFeatures_StringView_ParsePositiveNumber(const StringView view); - -// Copies src StringView to dst buffer. -void CpuFeatures_StringView_CopyString(const StringView src, char* dst, - size_t dst_size); - -// Checks if line contains the specified whitespace separated word. -bool CpuFeatures_StringView_HasWord(const StringView line, - const char* const word); - -// Get key/value from line. key and value are separated by ": ". -// key and value are cleaned up from leading and trailing whitespaces. -bool CpuFeatures_StringView_GetAttributeKeyValue(const StringView line, - StringView* key, - StringView* value); - -CPU_FEATURES_END_CPP_NAMESPACE - -#endif // CPU_FEATURES_INCLUDE_INTERNAL_STRING_VIEW_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/unix_features_aggregator.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/unix_features_aggregator.h deleted file mode 100644 index c20f154..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/include/internal/unix_features_aggregator.h +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// CapabilityConfig provides a way to map cpu features to hardware caps and -// /proc/cpuinfo flags. We then provide functions to update capabilities from -// either source. -#ifndef CPU_FEATURES_INCLUDE_INTERNAL_LINUX_FEATURES_AGGREGATOR_H_ -#define CPU_FEATURES_INCLUDE_INTERNAL_LINUX_FEATURES_AGGREGATOR_H_ - -#include -#include - -#include "cpu_features_macros.h" -#include "internal/hwcaps.h" -#include "internal/string_view.h" - -CPU_FEATURES_START_CPP_NAMESPACE - -// Use the following macro to declare setter functions to be used in -// CapabilityConfig. -#define DECLARE_SETTER(FeatureType, FeatureName) \ - static void set_##FeatureName(void* const features, bool value) { \ - ((FeatureType*)features)->FeatureName = value; \ - } - -// Use the following macro to declare getter functions to be used in -// CapabilityConfig. -#define DECLARE_GETTER(FeatureType, FeatureName) \ - static int get_##FeatureName(void* const features) { \ - return ((FeatureType*)features)->FeatureName; \ - } - -#define DECLARE_SETTER_AND_GETTER(FeatureType, FeatureName) \ - DECLARE_SETTER(FeatureType, FeatureName) \ - DECLARE_GETTER(FeatureType, FeatureName) - -// Describes the relationship between hardware caps and /proc/cpuinfo flags. -typedef struct { - const HardwareCapabilities hwcaps_mask; - const char* const proc_cpuinfo_flag; - void (*set_bit)(void* const, bool); // setter for the corresponding bit. - int (*get_bit)(void* const); // getter for the corresponding bit. -} CapabilityConfig; - -// For every config, looks into flags_line for the presence of the -// corresponding proc_cpuinfo_flag, calls `set_bit` accordingly. -// Note: features is a pointer to the underlying Feature struct. -void CpuFeatures_SetFromFlags(const size_t configs_size, - const CapabilityConfig* configs, - const StringView flags_line, - void* const features); - -// For every config, looks into hwcaps for the presence of the feature. Calls -// `set_bit` with true if the hardware capability is found. -// Note: features is a pointer to the underlying Feature struct. -void CpuFeatures_OverrideFromHwCaps(const size_t configs_size, - const CapabilityConfig* configs, - const HardwareCapabilities hwcaps, - void* const features); - -CPU_FEATURES_END_CPP_NAMESPACE -#endif // CPU_FEATURES_INCLUDE_INTERNAL_LINUX_FEATURES_AGGREGATOR_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt deleted file mode 100644 index 186708a..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt +++ /dev/null @@ -1,60 +0,0 @@ - -# -# library : NDK compat -# -find_package(Threads REQUIRED) -set (NDK_COMPAT_HDRS cpu-features.h) -set (NDK_COMPAT_SRCS - cpu-features.c - $ - $ -) -# Note that following `add_cpu_features_headers_and_sources` will use -# NDK_COMPAT_SRCS in lieu of NDK_COMPAT_HDRS because we don't want cpu_features -# headers to be installed alongside ndk_compat. -add_cpu_features_headers_and_sources(NDK_COMPAT_SRCS NDK_COMPAT_SRCS) -add_library(ndk_compat ${NDK_COMPAT_HDRS} ${NDK_COMPAT_SRCS}) -setup_include_and_definitions(ndk_compat) -target_include_directories(ndk_compat PUBLIC $) -target_link_libraries(ndk_compat PUBLIC ${CMAKE_DL_LIBS} ${CMAKE_THREAD_LIBS_INIT}) -set_target_properties(ndk_compat PROPERTIES PUBLIC_HEADER "${NDK_COMPAT_HDRS}") - -include(GNUInstallDirs) -install(TARGETS ndk_compat - EXPORT CpuFeaturesNdkCompatTargets - PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/ndk_compat - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} -) -install(EXPORT CpuFeaturesNdkCompatTargets - NAMESPACE CpuFeatures:: - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/CpuFeaturesNdkCompat - COMPONENT Devel -) -include(CMakePackageConfigHelpers) -configure_package_config_file(${PROJECT_SOURCE_DIR}/cmake/CpuFeaturesNdkCompatConfig.cmake.in - "${PROJECT_BINARY_DIR}/CpuFeaturesNdkCompatConfig.cmake" - INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/CpuFeaturesNdkCompat" - NO_SET_AND_CHECK_MACRO - NO_CHECK_REQUIRED_COMPONENTS_MACRO -) -write_basic_package_version_file( - "${PROJECT_BINARY_DIR}/CpuFeaturesNdkCompatConfigVersion.cmake" - COMPATIBILITY SameMajorVersion -) -install( - FILES - "${PROJECT_BINARY_DIR}/CpuFeaturesNdkCompatConfig.cmake" - "${PROJECT_BINARY_DIR}/CpuFeaturesNdkCompatConfigVersion.cmake" - DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/CpuFeaturesNdkCompat" - COMPONENT Devel -) - -# -# program : NDK compat test program -# -if(ENABLE_TESTING) - add_executable(ndk-compat-test ndk-compat-test.c) - target_link_libraries(ndk-compat-test PRIVATE ndk_compat) -endif() diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md deleted file mode 100644 index 38c8393..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md +++ /dev/null @@ -1,4 +0,0 @@ -Provides a header compatible with [android's NDK cpu-features.h](https://android.googlesource.com/platform/ndk/+/master/sources/android/cpufeatures/cpu-features.h). - -It is intended to be a drop in replacement for this header and help users -transition from the NDK to [Google's cpu_features library](https://github.com/google/cpu_features). diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c deleted file mode 100644 index 27ff7bb..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c +++ /dev/null @@ -1,205 +0,0 @@ -#include "cpu-features.h" - -#include - -#include "cpu_features_macros.h" -#include "internal/filesystem.h" -#include "internal/stack_line_reader.h" -#include "internal/string_view.h" - -#if defined(CPU_FEATURES_ARCH_ARM) -#include "cpuinfo_arm.h" -#elif defined(CPU_FEATURES_ARCH_X86) -#include "cpuinfo_x86.h" -#elif defined(CPU_FEATURES_ARCH_MIPS) -#include "cpuinfo_mips.h" -#elif defined(CPU_FEATURES_ARCH_AARCH64) -#include "cpuinfo_aarch64.h" -#endif - -static pthread_once_t g_once; -static int g_inited; -static uint64_t g_cpuFeatures; -static int g_cpuCount; - -#ifdef CPU_FEATURES_ARCH_ARM -static uint32_t g_cpuIdArm; -#endif - -static void set_cpu_mask_bit(uint32_t index, uint32_t* cpu_mask) { - *cpu_mask |= 1UL << index; -} - -// Examples of valid inputs: "31", "4-31" -static void parse_cpu_mask(const StringView text, uint32_t* cpu_mask) { - int separator_index = CpuFeatures_StringView_IndexOfChar(text, '-'); - if (separator_index < 0) { // A single cpu index - int cpu_index = CpuFeatures_StringView_ParsePositiveNumber(text); - if (cpu_index < 0) return; - set_cpu_mask_bit(cpu_index, cpu_mask); - } else { - int cpu_index_a = CpuFeatures_StringView_ParsePositiveNumber( - CpuFeatures_StringView_KeepFront(text, separator_index)); - int cpu_index_b = CpuFeatures_StringView_ParsePositiveNumber( - CpuFeatures_StringView_PopFront(text, separator_index + 1)); - int i; - if (cpu_index_a < 0 || cpu_index_b < 0) return; - for (i = cpu_index_a; i <= cpu_index_b; ++i) { - if (i < 32) { - set_cpu_mask_bit(i, cpu_mask); - } - } - } -} - -// Format specification from -// https://www.kernel.org/doc/Documentation/cputopology.txt -// Examples of valid inputs: "31", "2,4-31,32-63", "0-1,3" -static void parse_cpu_mask_line(const LineResult result, uint32_t* cpu_mask) { - if (!result.full_line || result.eof) return; - StringView line = result.line; - for (; line.size > 0;) { - int next_entry_index = CpuFeatures_StringView_IndexOfChar(line, ','); - if (next_entry_index < 0) { - parse_cpu_mask(line, cpu_mask); - break; - } - StringView entry = CpuFeatures_StringView_KeepFront(line, next_entry_index); - parse_cpu_mask(entry, cpu_mask); - line = CpuFeatures_StringView_PopFront(line, next_entry_index + 1); - } -} - -static void update_cpu_mask_from_file(const char* filename, - uint32_t* cpu_mask) { - const int fd = CpuFeatures_OpenFile(filename); - if (fd >= 0) { - StackLineReader reader; - StackLineReader_Initialize(&reader, fd); - parse_cpu_mask_line(StackLineReader_NextLine(&reader), cpu_mask); - CpuFeatures_CloseFile(fd); - } -} - -static int get_cpu_count(void) { - uint32_t cpu_mask = 0; - update_cpu_mask_from_file("/sys/devices/system/cpu/present", &cpu_mask); - update_cpu_mask_from_file("/sys/devices/system/cpu/possible", &cpu_mask); - return __builtin_popcount(cpu_mask); -} - -static void android_cpuInit(void) { - g_cpuFeatures = 0; - g_cpuCount = 1; - g_inited = 1; - - g_cpuCount = get_cpu_count(); - if (g_cpuCount == 0) { - g_cpuCount = 1; - } -#if defined(CPU_FEATURES_ARCH_ARM) - ArmInfo info = GetArmInfo(); - if (info.architecture == 7) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_ARMv7; - if (info.features.vfpv3) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFPv3; - if (info.features.neon) { - g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_NEON; - g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFP_D32; - } - if (info.features.vfpv3d16) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFP_FP16; - if (info.features.idiva) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_IDIV_ARM; - if (info.features.idivt) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_IDIV_THUMB2; - if (info.features.iwmmxt) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_iWMMXt; - if (info.features.aes) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_AES; - if (info.features.pmull) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_PMULL; - if (info.features.sha1) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_SHA1; - if (info.features.sha2) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_SHA2; - if (info.features.crc32) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_CRC32; - if (info.architecture >= 6) - g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_LDREX_STREX; - if (info.features.vfp) g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFPv2; - if (info.features.vfpv4) { - g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_VFP_FMA; - g_cpuFeatures |= ANDROID_CPU_ARM_FEATURE_NEON_FMA; - } - g_cpuIdArm = GetArmCpuId(&info); -#elif defined(CPU_FEATURES_ARCH_X86) - X86Info info = GetX86Info(); - if (info.features.ssse3) g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_SSSE3; - if (info.features.popcnt) g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_POPCNT; - if (info.features.movbe) g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_MOVBE; - if (info.features.sse4_1) g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_SSE4_1; - if (info.features.sse4_2) g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_SSE4_2; - if (info.features.aes) g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_AES_NI; - if (info.features.avx) g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_AVX; - if (info.features.rdrnd) g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_RDRAND; - if (info.features.avx2) g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_AVX2; - if (info.features.sha) g_cpuFeatures |= ANDROID_CPU_X86_FEATURE_SHA_NI; -#elif defined(CPU_FEATURES_ARCH_MIPS) - MipsInfo info = GetMipsInfo(); - if (info.features.r6) g_cpuFeatures |= ANDROID_CPU_MIPS_FEATURE_R6; - if (info.features.msa) g_cpuFeatures |= ANDROID_CPU_MIPS_FEATURE_MSA; -#elif defined(CPU_FEATURES_ARCH_AARCH64) - Aarch64Info info = GetAarch64Info(); - if (info.features.fp) g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_FP; - if (info.features.asimd) g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_ASIMD; - if (info.features.aes) g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_AES; - if (info.features.pmull) g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_PMULL; - if (info.features.sha1) g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_SHA1; - if (info.features.sha2) g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_SHA2; - if (info.features.crc32) g_cpuFeatures |= ANDROID_CPU_ARM64_FEATURE_CRC32; -#endif -} - -AndroidCpuFamily android_getCpuFamily(void) { -#if defined(CPU_FEATURES_ARCH_ARM) - return ANDROID_CPU_FAMILY_ARM; -#elif defined(CPU_FEATURES_ARCH_X86_32) - return ANDROID_CPU_FAMILY_X86; -#elif defined(CPU_FEATURES_ARCH_MIPS64) - return ANDROID_CPU_FAMILY_MIPS64; -#elif defined(CPU_FEATURES_ARCH_MIPS32) - return ANDROID_CPU_FAMILY_MIPS; -#elif defined(CPU_FEATURES_ARCH_AARCH64) - return ANDROID_CPU_FAMILY_ARM64; -#elif defined(CPU_FEATURES_ARCH_X86_64) - return ANDROID_CPU_FAMILY_X86_64; -#else - return ANDROID_CPU_FAMILY_UNKNOWN; -#endif -} - -uint64_t android_getCpuFeatures(void) { - pthread_once(&g_once, android_cpuInit); - return g_cpuFeatures; -} - -int android_getCpuCount(void) { - pthread_once(&g_once, android_cpuInit); - return g_cpuCount; -} - -static void android_cpuInitDummy(void) { g_inited = 1; } - -int android_setCpu(int cpu_count, uint64_t cpu_features) { - /* Fail if the library was already initialized. */ - if (g_inited) return 0; - g_cpuCount = (cpu_count <= 0 ? 1 : cpu_count); - g_cpuFeatures = cpu_features; - pthread_once(&g_once, android_cpuInitDummy); - return 1; -} - -#ifdef CPU_FEATURES_ARCH_ARM - -uint32_t android_getCpuIdArm(void) { - pthread_once(&g_once, android_cpuInit); - return g_cpuIdArm; -} - -int android_setCpuArm(int cpu_count, uint64_t cpu_features, uint32_t cpu_id) { - if (!android_setCpu(cpu_count, cpu_features)) return 0; - g_cpuIdArm = cpu_id; - return 1; -} - -#endif // CPU_FEATURES_ARCH_ARM diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h deleted file mode 100644 index 51bea53..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ -#ifndef GOOGLE_CPU_FEATURES_H -#define GOOGLE_CPU_FEATURES_H -#include -#include - -__BEGIN_DECLS - -/* A list of valid values returned by android_getCpuFamily(). - * They describe the CPU Architecture of the current process. - */ -typedef enum { - ANDROID_CPU_FAMILY_UNKNOWN = 0, - ANDROID_CPU_FAMILY_ARM, - ANDROID_CPU_FAMILY_X86, - ANDROID_CPU_FAMILY_MIPS, - ANDROID_CPU_FAMILY_ARM64, - ANDROID_CPU_FAMILY_X86_64, - ANDROID_CPU_FAMILY_MIPS64, - ANDROID_CPU_FAMILY_MAX /* do not remove */ -} AndroidCpuFamily; - -/* Return the CPU family of the current process. - * - * Note that this matches the bitness of the current process. I.e. when - * running a 32-bit binary on a 64-bit capable CPU, this will return the - * 32-bit CPU family value. - */ -extern AndroidCpuFamily android_getCpuFamily(void); - -/* Return a bitmap describing a set of optional CPU features that are - * supported by the current device's CPU. The exact bit-flags returned - * depend on the value returned by android_getCpuFamily(). See the - * documentation for the ANDROID_CPU_*_FEATURE_* flags below for details. - */ -extern uint64_t android_getCpuFeatures(void); - -/* The list of feature flags for ANDROID_CPU_FAMILY_ARM that can be - * recognized by the library (see note below for 64-bit ARM). Value details - * are: - * - * VFPv2: - * CPU supports the VFPv2 instruction set. Many, but not all, ARMv6 CPUs - * support these instructions. VFPv2 is a subset of VFPv3 so this will - * be set whenever VFPv3 is set too. - * - * ARMv7: - * CPU supports the ARMv7-A basic instruction set. - * This feature is mandated by the 'armeabi-v7a' ABI. - * - * VFPv3: - * CPU supports the VFPv3-D16 instruction set, providing hardware FPU - * support for single and double precision floating point registers. - * Note that only 16 FPU registers are available by default, unless - * the D32 bit is set too. This feature is also mandated by the - * 'armeabi-v7a' ABI. - * - * VFP_D32: - * CPU VFP optional extension that provides 32 FPU registers, - * instead of 16. Note that ARM mandates this feature is the 'NEON' - * feature is implemented by the CPU. - * - * NEON: - * CPU FPU supports "ARM Advanced SIMD" instructions, also known as - * NEON. Note that this mandates the VFP_D32 feature as well, per the - * ARM Architecture specification. - * - * VFP_FP16: - * Half-width floating precision VFP extension. If set, the CPU - * supports instructions to perform floating-point operations on - * 16-bit registers. This is part of the VFPv4 specification, but - * not mandated by any Android ABI. - * - * VFP_FMA: - * Fused multiply-accumulate VFP instructions extension. Also part of - * the VFPv4 specification, but not mandated by any Android ABI. - * - * NEON_FMA: - * Fused multiply-accumulate NEON instructions extension. Optional - * extension from the VFPv4 specification, but not mandated by any - * Android ABI. - * - * IDIV_ARM: - * Integer division available in ARM mode. Only available - * on recent CPUs (e.g. Cortex-A15). - * - * IDIV_THUMB2: - * Integer division available in Thumb-2 mode. Only available - * on recent CPUs (e.g. Cortex-A15). - * - * iWMMXt: - * Optional extension that adds MMX registers and operations to an - * ARM CPU. This is only available on a few XScale-based CPU designs - * sold by Marvell. Pretty rare in practice. - * - * AES: - * CPU supports AES instructions. These instructions are only - * available for 32-bit applications running on ARMv8 CPU. - * - * CRC32: - * CPU supports CRC32 instructions. These instructions are only - * available for 32-bit applications running on ARMv8 CPU. - * - * SHA2: - * CPU supports SHA2 instructions. These instructions are only - * available for 32-bit applications running on ARMv8 CPU. - * - * SHA1: - * CPU supports SHA1 instructions. These instructions are only - * available for 32-bit applications running on ARMv8 CPU. - * - * PMULL: - * CPU supports 64-bit PMULL and PMULL2 instructions. These - * instructions are only available for 32-bit applications - * running on ARMv8 CPU. - * - * If you want to tell the compiler to generate code that targets one of - * the feature set above, you should probably use one of the following - * flags (for more details, see technical note at the end of this file): - * - * -mfpu=vfp - * -mfpu=vfpv2 - * These are equivalent and tell GCC to use VFPv2 instructions for - * floating-point operations. Use this if you want your code to - * run on *some* ARMv6 devices, and any ARMv7-A device supported - * by Android. - * - * Generated code requires VFPv2 feature. - * - * -mfpu=vfpv3-d16 - * Tell GCC to use VFPv3 instructions (using only 16 FPU registers). - * This should be generic code that runs on any CPU that supports the - * 'armeabi-v7a' Android ABI. Note that no ARMv6 CPU supports this. - * - * Generated code requires VFPv3 feature. - * - * -mfpu=vfpv3 - * Tell GCC to use VFPv3 instructions with 32 FPU registers. - * Generated code requires VFPv3|VFP_D32 features. - * - * -mfpu=neon - * Tell GCC to use VFPv3 instructions with 32 FPU registers, and - * also support NEON intrinsics (see ). - * Generated code requires VFPv3|VFP_D32|NEON features. - * - * -mfpu=vfpv4-d16 - * Generated code requires VFPv3|VFP_FP16|VFP_FMA features. - * - * -mfpu=vfpv4 - * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32 features. - * - * -mfpu=neon-vfpv4 - * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32|NEON|NEON_FMA - * features. - * - * -mcpu=cortex-a7 - * -mcpu=cortex-a15 - * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32| - * NEON|NEON_FMA|IDIV_ARM|IDIV_THUMB2 - * This flag implies -mfpu=neon-vfpv4. - * - * -mcpu=iwmmxt - * Allows the use of iWMMXt instrinsics with GCC. - * - * IMPORTANT NOTE: These flags should only be tested when - * android_getCpuFamily() returns ANDROID_CPU_FAMILY_ARM, i.e. this is a - * 32-bit process. - * - * When running a 64-bit ARM process on an ARMv8 CPU, - * android_getCpuFeatures() will return a different set of bitflags - */ -enum { - ANDROID_CPU_ARM_FEATURE_ARMv7 = (1 << 0), - ANDROID_CPU_ARM_FEATURE_VFPv3 = (1 << 1), - ANDROID_CPU_ARM_FEATURE_NEON = (1 << 2), - ANDROID_CPU_ARM_FEATURE_LDREX_STREX = (1 << 3), - ANDROID_CPU_ARM_FEATURE_VFPv2 = (1 << 4), - ANDROID_CPU_ARM_FEATURE_VFP_D32 = (1 << 5), - ANDROID_CPU_ARM_FEATURE_VFP_FP16 = (1 << 6), - ANDROID_CPU_ARM_FEATURE_VFP_FMA = (1 << 7), - ANDROID_CPU_ARM_FEATURE_NEON_FMA = (1 << 8), - ANDROID_CPU_ARM_FEATURE_IDIV_ARM = (1 << 9), - ANDROID_CPU_ARM_FEATURE_IDIV_THUMB2 = (1 << 10), - ANDROID_CPU_ARM_FEATURE_iWMMXt = (1 << 11), - ANDROID_CPU_ARM_FEATURE_AES = (1 << 12), - ANDROID_CPU_ARM_FEATURE_PMULL = (1 << 13), - ANDROID_CPU_ARM_FEATURE_SHA1 = (1 << 14), - ANDROID_CPU_ARM_FEATURE_SHA2 = (1 << 15), - ANDROID_CPU_ARM_FEATURE_CRC32 = (1 << 16), -}; - -/* The bit flags corresponding to the output of android_getCpuFeatures() - * when android_getCpuFamily() returns ANDROID_CPU_FAMILY_ARM64. Value details - * are: - * - * FP: - * CPU has Floating-point unit. - * - * ASIMD: - * CPU has Advanced SIMD unit. - * - * AES: - * CPU supports AES instructions. - * - * CRC32: - * CPU supports CRC32 instructions. - * - * SHA2: - * CPU supports SHA2 instructions. - * - * SHA1: - * CPU supports SHA1 instructions. - * - * PMULL: - * CPU supports 64-bit PMULL and PMULL2 instructions. - */ -enum { - ANDROID_CPU_ARM64_FEATURE_FP = (1 << 0), - ANDROID_CPU_ARM64_FEATURE_ASIMD = (1 << 1), - ANDROID_CPU_ARM64_FEATURE_AES = (1 << 2), - ANDROID_CPU_ARM64_FEATURE_PMULL = (1 << 3), - ANDROID_CPU_ARM64_FEATURE_SHA1 = (1 << 4), - ANDROID_CPU_ARM64_FEATURE_SHA2 = (1 << 5), - ANDROID_CPU_ARM64_FEATURE_CRC32 = (1 << 6), -}; - -/* The bit flags corresponding to the output of android_getCpuFeatures() - * when android_getCpuFamily() returns ANDROID_CPU_FAMILY_X86 or - * ANDROID_CPU_FAMILY_X86_64. - */ -enum { - ANDROID_CPU_X86_FEATURE_SSSE3 = (1 << 0), - ANDROID_CPU_X86_FEATURE_POPCNT = (1 << 1), - ANDROID_CPU_X86_FEATURE_MOVBE = (1 << 2), - ANDROID_CPU_X86_FEATURE_SSE4_1 = (1 << 3), - ANDROID_CPU_X86_FEATURE_SSE4_2 = (1 << 4), - ANDROID_CPU_X86_FEATURE_AES_NI = (1 << 5), - ANDROID_CPU_X86_FEATURE_AVX = (1 << 6), - ANDROID_CPU_X86_FEATURE_RDRAND = (1 << 7), - ANDROID_CPU_X86_FEATURE_AVX2 = (1 << 8), - ANDROID_CPU_X86_FEATURE_SHA_NI = (1 << 9), -}; - -/* The bit flags corresponding to the output of android_getCpuFeatures() - * when android_getCpuFamily() returns ANDROID_CPU_FAMILY_MIPS - * or ANDROID_CPU_FAMILY_MIPS64. Values are: - * - * R6: - * CPU executes MIPS Release 6 instructions natively, and - * supports obsoleted R1..R5 instructions only via kernel traps. - * - * MSA: - * CPU supports Mips SIMD Architecture instructions. - */ -enum { - ANDROID_CPU_MIPS_FEATURE_R6 = (1 << 0), - ANDROID_CPU_MIPS_FEATURE_MSA = (1 << 1), -}; - -/* Return the number of CPU cores detected on this device. - * Please note the current implementation supports up to 32 cpus. - */ -extern int android_getCpuCount(void); - -/* The following is used to force the CPU count and features - * mask in sandboxed processes. Under 4.1 and higher, these processes - * cannot access /proc, which is the only way to get information from - * the kernel about the current hardware (at least on ARM). - * - * It _must_ be called only once, and before any android_getCpuXXX - * function, any other case will fail. - * - * This function return 1 on success, and 0 on failure. - */ -extern int android_setCpu(int cpu_count, uint64_t cpu_features); - -#ifdef __arm__ - -/* Retrieve the ARM 32-bit CPUID value from the kernel. - * Note that this cannot work on sandboxed processes under 4.1 and - * higher, unless you called android_setCpuArm() before. - */ -extern uint32_t android_getCpuIdArm(void); - -/* An ARM-specific variant of android_setCpu() that also allows you - * to set the ARM CPUID field. - */ -extern int android_setCpuArm(int cpu_count, uint64_t cpu_features, - uint32_t cpu_id); - -#endif - -__END_DECLS -#endif /* GOOGLE_CPU_FEATURES_H */ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c deleted file mode 100644 index e4005d4..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c +++ /dev/null @@ -1,12 +0,0 @@ -#include - -#include "cpu-features.h" - -int main() { - printf("android_getCpuFamily()=%d\n", android_getCpuFamily()); - printf("android_getCpuFeatures()=0x%08llx\n", android_getCpuFeatures()); - printf("android_getCpuCount()=%d\n", android_getCpuCount()); -#ifdef __arm__ - printf("android_getCpuIdArm()=0x%04x\n", android_getCpuIdArm()); -#endif //__arm__ -} diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh deleted file mode 100644 index fd88d60..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh +++ /dev/null @@ -1,209 +0,0 @@ -#!/usr/bin/env bash - -readonly SCRIPT_FOLDER=$(cd -P -- "$(dirname -- "$0")" && pwd -P) -readonly PROJECT_FOLDER="${SCRIPT_FOLDER}/.." -readonly ARCHIVE_FOLDER=~/cpu_features_archives -readonly QEMU_INSTALL=${ARCHIVE_FOLDER}/qemu -readonly DEFAULT_CMAKE_ARGS=" -DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTING=ON" - -function extract() { - case $1 in - *.tar.bz2) tar xjf "$1" ;; - *.tar.xz) tar xJf "$1" ;; - *.tar.gz) tar xzf "$1" ;; - *) - echo "don't know how to extract '$1'..." - exit 1 - esac -} - -function unpackifnotexists() { - mkdir -p "${ARCHIVE_FOLDER}" - cd "${ARCHIVE_FOLDER}" || exit - local URL=$1 - local RELATIVE_FOLDER=$2 - local DESTINATION="${ARCHIVE_FOLDER}/${RELATIVE_FOLDER}" - if [[ ! -d "${DESTINATION}" ]] ; then - local ARCHIVE_NAME=$(echo ${URL} | sed 's/.*\///') - test -f "${ARCHIVE_NAME}" || wget -q "${URL}" - extract "${ARCHIVE_NAME}" - rm -f "${ARCHIVE_NAME}" - fi -} - -function installqemuifneeded() { - local VERSION=${QEMU_VERSION:=2.11.1} - local ARCHES=${QEMU_ARCHES:=arm aarch64 i386 x86_64 mips mipsel mips64 mips64el} - local TARGETS=${QEMU_TARGETS:=$(echo "$ARCHES" | sed 's#$# #;s#\([^ ]*\) #\1-linux-user #g')} - - if echo "${VERSION} ${TARGETS}" | cmp --silent ${QEMU_INSTALL}/.build -; then - echo "qemu ${VERSION} up to date!" - return 0 - fi - - echo "VERSION: ${VERSION}" - echo "TARGETS: ${TARGETS}" - - rm -rf ${QEMU_INSTALL} - - # Checking for a tarball before downloading makes testing easier :-) - local QEMU_URL="http://wiki.qemu-project.org/download/qemu-${VERSION}.tar.xz" - local QEMU_FOLDER="qemu-${VERSION}" - unpackifnotexists ${QEMU_URL} ${QEMU_FOLDER} - cd ${QEMU_FOLDER} || exit - - ./configure \ - --prefix="${QEMU_INSTALL}" \ - --target-list="${TARGETS}" \ - --disable-docs \ - --disable-sdl \ - --disable-gtk \ - --disable-gnutls \ - --disable-gcrypt \ - --disable-nettle \ - --disable-curses \ - --static - - make -j4 - make install - - echo "$VERSION $TARGETS" > ${QEMU_INSTALL}/.build -} - -function assert_defined(){ - local VALUE=${1} - : "${VALUE?"${1} needs to be defined"}" -} - -function integrate() { - cd "${PROJECT_FOLDER}" - case "${OS}" in - "Windows_NT") CMAKE_BUILD_ARGS="--config Debug --target ALL_BUILD" - CMAKE_TEST_FILES="${BUILD_DIR}/test/Debug/*_test.exe" - DEMO=${BUILD_DIR}/Debug/list_cpu_features.exe - ;; - *) CMAKE_BUILD_ARGS="--target all" - CMAKE_TEST_FILES="${BUILD_DIR}/test/*_test" - DEMO=${BUILD_DIR}/list_cpu_features - ;; - esac - - # Generating CMake configuration - cmake -H. -B"${BUILD_DIR}" ${DEFAULT_CMAKE_ARGS} "${CMAKE_ADDITIONAL_ARGS[@]}" -G"${CMAKE_GENERATOR:-Unix Makefiles}" - - # Building - cmake --build "${BUILD_DIR}" ${CMAKE_BUILD_ARGS} - - # Running tests if needed - if [[ "${QEMU_ARCH}" == "DISABLED" ]]; then - return - fi - RUN_CMD="" - if [[ -n "${QEMU_ARCH}" ]]; then - installqemuifneeded - RUN_CMD="${QEMU_INSTALL}/bin/qemu-${QEMU_ARCH} ${QEMU_ARGS[@]}" - fi - for test_binary in ${CMAKE_TEST_FILES}; do - ${RUN_CMD} ${test_binary} - done - ${RUN_CMD} ${DEMO} -} - -function expand_linaro_config() { - assert_defined TARGET - local LINARO_ROOT_URL=https://releases.linaro.org/components/toolchain/binaries/7.2-2017.11 - - local GCC_URL=${LINARO_ROOT_URL}/${TARGET}/gcc-linaro-7.2.1-2017.11-x86_64_${TARGET}.tar.xz - local GCC_RELATIVE_FOLDER="gcc-linaro-7.2.1-2017.11-x86_64_${TARGET}" - unpackifnotexists "${GCC_URL}" "${GCC_RELATIVE_FOLDER}" - - local SYSROOT_URL=${LINARO_ROOT_URL}/${TARGET}/sysroot-glibc-linaro-2.25-2017.11-${TARGET}.tar.xz - local SYSROOT_RELATIVE_FOLDER=sysroot-glibc-linaro-2.25-2017.11-${TARGET} - unpackifnotexists "${SYSROOT_URL}" "${SYSROOT_RELATIVE_FOLDER}" - - local SYSROOT_FOLDER=${ARCHIVE_FOLDER}/${SYSROOT_RELATIVE_FOLDER} - local GCC_FOLDER=${ARCHIVE_FOLDER}/${GCC_RELATIVE_FOLDER} - - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_SYSTEM_NAME=Linux) - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_SYSTEM_PROCESSOR=${TARGET}) - - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_SYSROOT=${SYSROOT_FOLDER}) - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_C_COMPILER=${GCC_FOLDER}/bin/${TARGET}-gcc) - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_CXX_COMPILER=${GCC_FOLDER}/bin/${TARGET}-g++) - - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER) - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY) - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=ONLY) - - QEMU_ARGS+=(-L ${SYSROOT_FOLDER}) - QEMU_ARGS+=(-E LD_LIBRARY_PATH=/lib) -} - -function expand_codescape_config() { - assert_defined TARGET - local DATE=2017.10-08 - local CODESCAPE_URL=https://codescape.mips.com/components/toolchain/${DATE}/Codescape.GNU.Tools.Package.${DATE}.for.MIPS.MTI.Linux.CentOS-5.x86_64.tar.gz - local GCC_URL=${CODESCAPE_URL} - local GCC_RELATIVE_FOLDER="mips-mti-linux-gnu/${DATE}" - unpackifnotexists "${GCC_URL}" "${GCC_RELATIVE_FOLDER}" - - local GCC_FOLDER=${ARCHIVE_FOLDER}/${GCC_RELATIVE_FOLDER} - local MIPS_FLAGS="" - local LIBC_FOLDER_SUFFIX="" - local FLAVOUR="" - case "${TARGET}" in - "mips32") MIPS_FLAGS="-EB -mabi=32"; FLAVOUR="mips-r2-hard"; LIBC_FOLDER_SUFFIX="lib" ;; - "mips32el") MIPS_FLAGS="-EL -mabi=32"; FLAVOUR="mipsel-r2-hard"; LIBC_FOLDER_SUFFIX="lib" ;; - "mips64") MIPS_FLAGS="-EB -mabi=64"; FLAVOUR="mips-r2-hard"; LIBC_FOLDER_SUFFIX="lib64" ;; - "mips64el") MIPS_FLAGS="-EL -mabi=64"; FLAVOUR="mipsel-r2-hard"; LIBC_FOLDER_SUFFIX="lib64" ;; - *) echo 'unknown mips platform'; exit 1;; - esac - - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_FIND_ROOT_PATH=${GCC_FOLDER}) - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_SYSTEM_NAME=Linux) - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_SYSTEM_PROCESSOR=${TARGET}) - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_C_COMPILER=mips-mti-linux-gnu-gcc) - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_CXX_COMPILER=mips-mti-linux-gnu-g++) - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_C_COMPILER_ARG1="${MIPS_FLAGS}") - CMAKE_ADDITIONAL_ARGS+=(-DCMAKE_CXX_COMPILER_ARG1="${MIPS_FLAGS}") - - local SYSROOT_FOLDER=${GCC_FOLDER}/sysroot/${FLAVOUR} - - # Keeping only the sysroot of interest to save on travis cache. - if [[ "${CONTINUOUS_INTEGRATION}" = "true" ]]; then - for folder in ${GCC_FOLDER}/sysroot/*; do - if [[ "${folder}" != "${SYSROOT_FOLDER}" ]]; then - rm -rf ${folder} - fi - done - fi - - local LIBC_FOLDER=${GCC_FOLDER}/mips-mti-linux-gnu/lib/${FLAVOUR}/${LIBC_FOLDER_SUFFIX} - QEMU_ARGS+=(-L ${SYSROOT_FOLDER}) - QEMU_ARGS+=(-E LD_PRELOAD=${LIBC_FOLDER}/libstdc++.so.6:${LIBC_FOLDER}/libgcc_s.so.1) -} - -function expand_environment_and_integrate() { - assert_defined PROJECT_FOLDER - assert_defined TARGET - - BUILD_DIR="${PROJECT_FOLDER}/cmake_build/${TARGET}" - mkdir -p "${BUILD_DIR}" - - declare -a CONFIG_NAMES=() - declare -a QEMU_ARGS=() - declare -a CMAKE_ADDITIONAL_ARGS=() - - case ${TOOLCHAIN} in - LINARO) expand_linaro_config ;; - CODESCAPE) expand_codescape_config ;; - NATIVE) QEMU_ARCH="" ;; - *) echo "Unknown toolchain '${TOOLCHAIN}'..."; exit 1;; - esac - integrate -} - -if [ "${CONTINUOUS_INTEGRATION}" = "true" ]; then - QEMU_ARCHES=${QEMU_ARCH} - expand_environment_and_integrate -fi diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh deleted file mode 100644 index d1c61b0..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env bash - -source "$(dirname -- "$0")"/run_integration.sh - -# Toolchains for little-endian, 64-bit ARMv8 for GNU/Linux systems -function set_aarch64-linux-gnu() { - TOOLCHAIN=LINARO - TARGET=aarch64-linux-gnu - QEMU_ARCH=aarch64 -} - -# Toolchains for little-endian, hard-float, 32-bit ARMv7 (and earlier) for GNU/Linux systems -function set_arm-linux-gnueabihf() { - TOOLCHAIN=LINARO - TARGET=arm-linux-gnueabihf - QEMU_ARCH=arm -} - -# Toolchains for little-endian, 32-bit ARMv8 for GNU/Linux systems -function set_armv8l-linux-gnueabihf() { - TOOLCHAIN=LINARO - TARGET=armv8l-linux-gnueabihf - QEMU_ARCH=arm -} - -# Toolchains for little-endian, soft-float, 32-bit ARMv7 (and earlier) for GNU/Linux systems -function set_arm-linux-gnueabi() { - TOOLCHAIN=LINARO - TARGET=arm-linux-gnueabi - QEMU_ARCH=arm -} - -# Toolchains for big-endian, 64-bit ARMv8 for GNU/Linux systems -function set_aarch64_be-linux-gnu() { - TOOLCHAIN=LINARO - TARGET=aarch64_be-linux-gnu - QEMU_ARCH=DISABLED -} - -# Toolchains for big-endian, hard-float, 32-bit ARMv7 (and earlier) for GNU/Linux systems -function set_armeb-linux-gnueabihf() { - TOOLCHAIN=LINARO - TARGET=armeb-linux-gnueabihf - QEMU_ARCH=DISABLED -} - -# Toolchains for big-endian, soft-float, 32-bit ARMv7 (and earlier) for GNU/Linux systems -function set_armeb-linux-gnueabi() { - TOOLCHAIN=LINARO - TARGET=armeb-linux-gnueabi - QEMU_ARCH=DISABLED -} - -function set_mips32() { - TOOLCHAIN=CODESCAPE - TARGET=mips32 - QEMU_ARCH=mips -} - -function set_mips32el() { - TOOLCHAIN=CODESCAPE - TARGET=mips32el - QEMU_ARCH=mipsel -} - -function set_mips64() { - TOOLCHAIN=CODESCAPE - TARGET=mips64 - QEMU_ARCH=mips64 -} - -function set_mips64el() { - TOOLCHAIN=CODESCAPE - TARGET=mips64el - QEMU_ARCH=mips64el -} - -function set_native() { - TOOLCHAIN=NATIVE - TARGET=native - QEMU_ARCH="" -} - -ENVIRONMENTS=" - set_aarch64-linux-gnu - set_arm-linux-gnueabihf - set_armv8l-linux-gnueabihf - set_arm-linux-gnueabi - set_aarch64_be-linux-gnu - set_armeb-linux-gnueabihf - set_armeb-linux-gnueabi - set_mips32 - set_mips32el - set_mips64 - set_mips64el - set_native -" - -set -e - -CMAKE_GENERATOR="Ninja" - -for SET_ENVIRONMENT in ${ENVIRONMENTS}; do - ${SET_ENVIRONMENT} - expand_environment_and_integrate -done diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_aarch64.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_aarch64.c deleted file mode 100644 index 1e60652..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_aarch64.c +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "cpuinfo_aarch64.h" - -#include -#include - -#include "internal/filesystem.h" -#include "internal/hwcaps.h" -#include "internal/stack_line_reader.h" -#include "internal/string_view.h" -#include "internal/unix_features_aggregator.h" - -DECLARE_SETTER_AND_GETTER(Aarch64Features, fp) -DECLARE_SETTER_AND_GETTER(Aarch64Features, asimd) -DECLARE_SETTER_AND_GETTER(Aarch64Features, evtstrm) -DECLARE_SETTER_AND_GETTER(Aarch64Features, aes) -DECLARE_SETTER_AND_GETTER(Aarch64Features, pmull) -DECLARE_SETTER_AND_GETTER(Aarch64Features, sha1) -DECLARE_SETTER_AND_GETTER(Aarch64Features, sha2) -DECLARE_SETTER_AND_GETTER(Aarch64Features, crc32) -DECLARE_SETTER_AND_GETTER(Aarch64Features, atomics) -DECLARE_SETTER_AND_GETTER(Aarch64Features, fphp) -DECLARE_SETTER_AND_GETTER(Aarch64Features, asimdhp) -DECLARE_SETTER_AND_GETTER(Aarch64Features, cpuid) -DECLARE_SETTER_AND_GETTER(Aarch64Features, asimdrdm) -DECLARE_SETTER_AND_GETTER(Aarch64Features, jscvt) -DECLARE_SETTER_AND_GETTER(Aarch64Features, fcma) -DECLARE_SETTER_AND_GETTER(Aarch64Features, lrcpc) -DECLARE_SETTER_AND_GETTER(Aarch64Features, dcpop) -DECLARE_SETTER_AND_GETTER(Aarch64Features, sha3) -DECLARE_SETTER_AND_GETTER(Aarch64Features, sm3) -DECLARE_SETTER_AND_GETTER(Aarch64Features, sm4) -DECLARE_SETTER_AND_GETTER(Aarch64Features, asimddp) -DECLARE_SETTER_AND_GETTER(Aarch64Features, sha512) -DECLARE_SETTER_AND_GETTER(Aarch64Features, sve) -DECLARE_SETTER_AND_GETTER(Aarch64Features, asimdfhm) -DECLARE_SETTER_AND_GETTER(Aarch64Features, dit) -DECLARE_SETTER_AND_GETTER(Aarch64Features, uscat) -DECLARE_SETTER_AND_GETTER(Aarch64Features, ilrcpc) -DECLARE_SETTER_AND_GETTER(Aarch64Features, flagm) -DECLARE_SETTER_AND_GETTER(Aarch64Features, ssbs) -DECLARE_SETTER_AND_GETTER(Aarch64Features, sb) -DECLARE_SETTER_AND_GETTER(Aarch64Features, paca) -DECLARE_SETTER_AND_GETTER(Aarch64Features, pacg) -DECLARE_SETTER_AND_GETTER(Aarch64Features, dcpodp) -DECLARE_SETTER_AND_GETTER(Aarch64Features, sve2) -DECLARE_SETTER_AND_GETTER(Aarch64Features, sveaes) -DECLARE_SETTER_AND_GETTER(Aarch64Features, svepmull) -DECLARE_SETTER_AND_GETTER(Aarch64Features, svebitperm) -DECLARE_SETTER_AND_GETTER(Aarch64Features, svesha3) -DECLARE_SETTER_AND_GETTER(Aarch64Features, svesm4) -DECLARE_SETTER_AND_GETTER(Aarch64Features, flagm2) -DECLARE_SETTER_AND_GETTER(Aarch64Features, frint) -DECLARE_SETTER_AND_GETTER(Aarch64Features, svei8mm) -DECLARE_SETTER_AND_GETTER(Aarch64Features, svef32mm) -DECLARE_SETTER_AND_GETTER(Aarch64Features, svef64mm) -DECLARE_SETTER_AND_GETTER(Aarch64Features, svebf16) -DECLARE_SETTER_AND_GETTER(Aarch64Features, i8mm) -DECLARE_SETTER_AND_GETTER(Aarch64Features, bf16) -DECLARE_SETTER_AND_GETTER(Aarch64Features, dgh) -DECLARE_SETTER_AND_GETTER(Aarch64Features, rng) -DECLARE_SETTER_AND_GETTER(Aarch64Features, bti) - -static const CapabilityConfig kConfigs[] = { - // clang-format off - [AARCH64_FP] = {{AARCH64_HWCAP_FP, 0}, "fp", &set_fp, &get_fp}, - [AARCH64_ASIMD] = {{AARCH64_HWCAP_ASIMD, 0}, "asimd", &set_asimd, &get_asimd}, - [AARCH64_EVTSTRM] = {{AARCH64_HWCAP_EVTSTRM, 0}, "evtstrm", &set_evtstrm, &get_evtstrm}, - [AARCH64_AES] = {{AARCH64_HWCAP_AES, 0}, "aes", &set_aes, &get_aes}, - [AARCH64_PMULL] = {{AARCH64_HWCAP_PMULL, 0}, "pmull", &set_pmull, &get_pmull}, - [AARCH64_SHA1] = {{AARCH64_HWCAP_SHA1, 0}, "sha1", &set_sha1, &get_sha1}, - [AARCH64_SHA2] = {{AARCH64_HWCAP_SHA2, 0}, "sha2", &set_sha2, &get_sha2}, - [AARCH64_CRC32] = {{AARCH64_HWCAP_CRC32, 0}, "crc32", &set_crc32, &get_crc32}, - [AARCH64_ATOMICS] = {{AARCH64_HWCAP_ATOMICS, 0}, "atomics", &set_atomics, &get_atomics}, - [AARCH64_FPHP] = {{AARCH64_HWCAP_FPHP, 0}, "fphp", &set_fphp, &get_fphp}, - [AARCH64_ASIMDHP] = {{AARCH64_HWCAP_ASIMDHP, 0}, "asimdhp", &set_asimdhp, &get_asimdhp}, - [AARCH64_CPUID] = {{AARCH64_HWCAP_CPUID, 0}, "cpuid", &set_cpuid, &get_cpuid}, - [AARCH64_ASIMDRDM] = {{AARCH64_HWCAP_ASIMDRDM, 0}, "asimdrdm", &set_asimdrdm, &get_asimdrdm}, - [AARCH64_JSCVT] = {{AARCH64_HWCAP_JSCVT, 0}, "jscvt", &set_jscvt, &get_jscvt}, - [AARCH64_FCMA] = {{AARCH64_HWCAP_FCMA, 0}, "fcma", &set_fcma, &get_fcma}, - [AARCH64_LRCPC] = {{AARCH64_HWCAP_LRCPC, 0}, "lrcpc", &set_lrcpc, &get_lrcpc}, - [AARCH64_DCPOP] = {{AARCH64_HWCAP_DCPOP, 0}, "dcpop", &set_dcpop, &get_dcpop}, - [AARCH64_SHA3] = {{AARCH64_HWCAP_SHA3, 0}, "sha3", &set_sha3, &get_sha3}, - [AARCH64_SM3] = {{AARCH64_HWCAP_SM3, 0}, "sm3", &set_sm3, &get_sm3}, - [AARCH64_SM4] = {{AARCH64_HWCAP_SM4, 0}, "sm4", &set_sm4, &get_sm4}, - [AARCH64_ASIMDDP] = {{AARCH64_HWCAP_ASIMDDP, 0}, "asimddp", &set_asimddp, &get_asimddp}, - [AARCH64_SHA512] = {{AARCH64_HWCAP_SHA512, 0}, "sha512", &set_sha512, &get_sha512}, - [AARCH64_SVE] = {{AARCH64_HWCAP_SVE, 0}, "sve", &set_sve, &get_sve}, - [AARCH64_ASIMDFHM] = {{AARCH64_HWCAP_ASIMDFHM, 0}, "asimdfhm", &set_asimdfhm, &get_asimdfhm}, - [AARCH64_DIT] = {{AARCH64_HWCAP_DIT, 0}, "dit", &set_dit, &get_dit}, - [AARCH64_USCAT] = {{AARCH64_HWCAP_USCAT, 0}, "uscat", &set_uscat, &get_uscat}, - [AARCH64_ILRCPC] = {{AARCH64_HWCAP_ILRCPC, 0}, "ilrcpc", &set_ilrcpc, &get_ilrcpc}, - [AARCH64_FLAGM] = {{AARCH64_HWCAP_FLAGM, 0}, "flagm", &set_flagm, &get_flagm}, - [AARCH64_SSBS] = {{AARCH64_HWCAP_SSBS, 0}, "ssbs", &set_ssbs, &get_ssbs}, - [AARCH64_SB] = {{AARCH64_HWCAP_SB, 0}, "sb", &set_sb, &get_sb}, - [AARCH64_PACA] = {{AARCH64_HWCAP_PACA, 0}, "paca", &set_paca, &get_paca}, - [AARCH64_PACG] = {{AARCH64_HWCAP_PACG, 0}, "pacg", &set_pacg, &get_pacg}, - [AARCH64_DCPODP] = {{0, AARCH64_HWCAP2_DCPODP}, "dcpodp", &set_dcpodp, &get_dcpodp}, - [AARCH64_SVE2] = {{0, AARCH64_HWCAP2_SVE2}, "sve2", &set_sve2, &get_sve2}, - [AARCH64_SVEAES] = {{0, AARCH64_HWCAP2_SVEAES}, "sveaes", &set_sveaes, &get_sveaes}, - [AARCH64_SVEPMULL] = {{0, AARCH64_HWCAP2_SVEPMULL}, "svepmull", &set_svepmull, &get_svepmull}, - [AARCH64_SVEBITPERM] = {{0, AARCH64_HWCAP2_SVEBITPERM}, "svebitperm", &set_svebitperm, &get_svebitperm}, - [AARCH64_SVESHA3] = {{0, AARCH64_HWCAP2_SVESHA3}, "svesha3", &set_svesha3, &get_svesha3}, - [AARCH64_SVESM4] = {{0, AARCH64_HWCAP2_SVESM4}, "svesm4", &set_svesm4, &get_svesm4}, - [AARCH64_FLAGM2] = {{0, AARCH64_HWCAP2_FLAGM2}, "flagm2", &set_flagm2, &get_flagm2}, - [AARCH64_FRINT] = {{0, AARCH64_HWCAP2_FRINT}, "frint", &set_frint, &get_frint}, - [AARCH64_SVEI8MM] = {{0, AARCH64_HWCAP2_SVEI8MM}, "svei8mm", &set_svei8mm, &get_svei8mm}, - [AARCH64_SVEF32MM] = {{0, AARCH64_HWCAP2_SVEF32MM}, "svef32mm", &set_svef32mm, &get_svef32mm}, - [AARCH64_SVEF64MM] = {{0, AARCH64_HWCAP2_SVEF64MM}, "svef64mm", &set_svef64mm, &get_svef64mm}, - [AARCH64_SVEBF16] = {{0, AARCH64_HWCAP2_SVEBF16}, "svebf16", &set_svebf16, &get_svebf16}, - [AARCH64_I8MM] = {{0, AARCH64_HWCAP2_I8MM}, "i8mm", &set_i8mm, &get_i8mm}, - [AARCH64_BF16] = {{0, AARCH64_HWCAP2_BF16}, "bf16", &set_bf16, &get_bf16}, - [AARCH64_DGH] = {{0, AARCH64_HWCAP2_DGH}, "dgh", &set_dgh, &get_dgh}, - [AARCH64_RNG] = {{0, AARCH64_HWCAP2_RNG}, "rng", &set_rng, &get_rng}, - [AARCH64_BTI] = {{0, AARCH64_HWCAP2_BTI}, "bti", &set_bti, &get_bti}, - // clang-format on -}; - -static const size_t kConfigsSize = sizeof(kConfigs) / sizeof(CapabilityConfig); - -static bool HandleAarch64Line(const LineResult result, - Aarch64Info* const info) { - StringView line = result.line; - StringView key, value; - if (CpuFeatures_StringView_GetAttributeKeyValue(line, &key, &value)) { - if (CpuFeatures_StringView_IsEquals(key, str("Features"))) { - CpuFeatures_SetFromFlags(kConfigsSize, kConfigs, value, &info->features); - } else if (CpuFeatures_StringView_IsEquals(key, str("CPU implementer"))) { - info->implementer = CpuFeatures_StringView_ParsePositiveNumber(value); - } else if (CpuFeatures_StringView_IsEquals(key, str("CPU variant"))) { - info->variant = CpuFeatures_StringView_ParsePositiveNumber(value); - } else if (CpuFeatures_StringView_IsEquals(key, str("CPU part"))) { - info->part = CpuFeatures_StringView_ParsePositiveNumber(value); - } else if (CpuFeatures_StringView_IsEquals(key, str("CPU revision"))) { - info->revision = CpuFeatures_StringView_ParsePositiveNumber(value); - } - } - return !result.eof; -} - -static void FillProcCpuInfoData(Aarch64Info* const info) { - const int fd = CpuFeatures_OpenFile("/proc/cpuinfo"); - if (fd >= 0) { - StackLineReader reader; - StackLineReader_Initialize(&reader, fd); - for (;;) { - if (!HandleAarch64Line(StackLineReader_NextLine(&reader), info)) { - break; - } - } - CpuFeatures_CloseFile(fd); - } -} - -static const Aarch64Info kEmptyAarch64Info; - -Aarch64Info GetAarch64Info(void) { - assert(kConfigsSize == AARCH64_LAST_); - - // capabilities are fetched from both getauxval and /proc/cpuinfo so we can - // have some information if the executable is sandboxed (aka no access to - // /proc/cpuinfo). - Aarch64Info info = kEmptyAarch64Info; - - FillProcCpuInfoData(&info); - CpuFeatures_OverrideFromHwCaps(kConfigsSize, kConfigs, - CpuFeatures_GetHardwareCapabilities(), - &info.features); - - return info; -} - -//////////////////////////////////////////////////////////////////////////////// -// Introspection functions - -int GetAarch64FeaturesEnumValue(const Aarch64Features* features, - Aarch64FeaturesEnum value) { - if (value >= kConfigsSize) return false; - return kConfigs[value].get_bit((Aarch64Features*)features); -} - -const char* GetAarch64FeaturesEnumName(Aarch64FeaturesEnum value) { - if (value >= kConfigsSize) return "unknown feature"; - return kConfigs[value].proc_cpuinfo_flag; -} diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_arm.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_arm.c deleted file mode 100644 index ba27971..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_arm.c +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "cpuinfo_arm.h" - -#include -#include - -#include "internal/bit_utils.h" -#include "internal/filesystem.h" -#include "internal/hwcaps.h" -#include "internal/stack_line_reader.h" -#include "internal/string_view.h" -#include "internal/unix_features_aggregator.h" - -DECLARE_SETTER_AND_GETTER(ArmFeatures, swp) -DECLARE_SETTER_AND_GETTER(ArmFeatures, half) -DECLARE_SETTER_AND_GETTER(ArmFeatures, thumb) -DECLARE_SETTER_AND_GETTER(ArmFeatures, _26bit) -DECLARE_SETTER_AND_GETTER(ArmFeatures, fastmult) -DECLARE_SETTER_AND_GETTER(ArmFeatures, fpa) -DECLARE_SETTER_AND_GETTER(ArmFeatures, vfp) -DECLARE_SETTER_AND_GETTER(ArmFeatures, edsp) -DECLARE_SETTER_AND_GETTER(ArmFeatures, java) -DECLARE_SETTER_AND_GETTER(ArmFeatures, iwmmxt) -DECLARE_SETTER_AND_GETTER(ArmFeatures, crunch) -DECLARE_SETTER_AND_GETTER(ArmFeatures, thumbee) -DECLARE_SETTER_AND_GETTER(ArmFeatures, neon) -DECLARE_SETTER_AND_GETTER(ArmFeatures, vfpv3) -DECLARE_SETTER_AND_GETTER(ArmFeatures, vfpv3d16) -DECLARE_SETTER_AND_GETTER(ArmFeatures, tls) -DECLARE_SETTER_AND_GETTER(ArmFeatures, vfpv4) -DECLARE_SETTER_AND_GETTER(ArmFeatures, idiva) -DECLARE_SETTER_AND_GETTER(ArmFeatures, idivt) -DECLARE_SETTER_AND_GETTER(ArmFeatures, vfpd32) -DECLARE_SETTER_AND_GETTER(ArmFeatures, lpae) -DECLARE_SETTER_AND_GETTER(ArmFeatures, evtstrm) -DECLARE_SETTER_AND_GETTER(ArmFeatures, aes) -DECLARE_SETTER_AND_GETTER(ArmFeatures, pmull) -DECLARE_SETTER_AND_GETTER(ArmFeatures, sha1) -DECLARE_SETTER_AND_GETTER(ArmFeatures, sha2) -DECLARE_SETTER_AND_GETTER(ArmFeatures, crc32) - -static const CapabilityConfig kConfigs[] = { - // clang-format off - [ARM_SWP] = {{ARM_HWCAP_SWP, 0}, "swp", &set_swp, &get_swp}, - [ARM_HALF] = {{ARM_HWCAP_HALF, 0}, "half", &set_half, &get_half}, - [ARM_THUMB] = {{ARM_HWCAP_THUMB, 0}, "thumb", &set_thumb, &get_thumb}, - [ARM_26BIT] = {{ARM_HWCAP_26BIT, 0}, "26bit", &set__26bit, &get__26bit}, - [ARM_FASTMULT] = {{ARM_HWCAP_FAST_MULT, 0}, "fastmult", &set_fastmult, &get_fastmult}, - [ARM_FPA] = {{ARM_HWCAP_FPA, 0}, "fpa", &set_fpa, &get_fpa}, - [ARM_VFP] = {{ARM_HWCAP_VFP, 0}, "vfp", &set_vfp, &get_vfp}, - [ARM_EDSP] = {{ARM_HWCAP_EDSP, 0}, "edsp", &set_edsp, &get_edsp}, - [ARM_JAVA] = {{ARM_HWCAP_JAVA, 0}, "java", &set_java, &get_java}, - [ARM_IWMMXT] = {{ARM_HWCAP_IWMMXT, 0}, "iwmmxt", &set_iwmmxt, &get_iwmmxt}, - [ARM_CRUNCH] = {{ARM_HWCAP_CRUNCH, 0}, "crunch", &set_crunch, &get_crunch}, - [ARM_THUMBEE] = {{ARM_HWCAP_THUMBEE, 0}, "thumbee", &set_thumbee, &get_thumbee}, - [ARM_NEON] = {{ARM_HWCAP_NEON, 0}, "neon", &set_neon, &get_neon}, - [ARM_VFPV3] = {{ARM_HWCAP_VFPV3, 0}, "vfpv3", &set_vfpv3, &get_vfpv3}, - [ARM_VFPV3D16] = {{ARM_HWCAP_VFPV3D16, 0}, "vfpv3d16", &set_vfpv3d16, &get_vfpv3d16}, - [ARM_TLS] = {{ARM_HWCAP_TLS, 0}, "tls", &set_tls, &get_tls}, - [ARM_VFPV4] = {{ARM_HWCAP_VFPV4, 0}, "vfpv4", &set_vfpv4, &get_vfpv4}, - [ARM_IDIVA] = {{ARM_HWCAP_IDIVA, 0}, "idiva", &set_idiva, &get_idiva}, - [ARM_IDIVT] = {{ARM_HWCAP_IDIVT, 0}, "idivt", &set_idivt, &get_idivt}, - [ARM_VFPD32] = {{ARM_HWCAP_VFPD32, 0}, "vfpd32", &set_vfpd32, &get_vfpd32}, - [ARM_LPAE] = {{ARM_HWCAP_LPAE, 0}, "lpae", &set_lpae, &get_lpae}, - [ARM_EVTSTRM] = {{ARM_HWCAP_EVTSTRM, 0}, "evtstrm", &set_evtstrm, &get_evtstrm}, - [ARM_AES] = {{0, ARM_HWCAP2_AES}, "aes", &set_aes, &get_aes}, - [ARM_PMULL] = {{0, ARM_HWCAP2_PMULL}, "pmull", &set_pmull, &get_pmull}, - [ARM_SHA1] = {{0, ARM_HWCAP2_SHA1}, "sha1", &set_sha1, &get_sha1}, - [ARM_SHA2] = {{0, ARM_HWCAP2_SHA2}, "sha2", &set_sha2, &get_sha2}, - [ARM_CRC32] = {{0, ARM_HWCAP2_CRC32}, "crc32", &set_crc32, &get_crc32}, - // clang-format on -}; - -static const size_t kConfigsSize = sizeof(kConfigs) / sizeof(CapabilityConfig); - -typedef struct { - bool processor_reports_armv6; - bool hardware_reports_goldfish; -} ProcCpuInfoData; - -static int IndexOfNonDigit(StringView str) { - size_t index = 0; - while (str.size && isdigit(CpuFeatures_StringView_Front(str))) { - str = CpuFeatures_StringView_PopFront(str, 1); - ++index; - } - return index; -} - -static bool HandleArmLine(const LineResult result, ArmInfo* const info, - ProcCpuInfoData* const proc_info) { - StringView line = result.line; - StringView key, value; - if (CpuFeatures_StringView_GetAttributeKeyValue(line, &key, &value)) { - if (CpuFeatures_StringView_IsEquals(key, str("Features"))) { - CpuFeatures_SetFromFlags(kConfigsSize, kConfigs, value, &info->features); - } else if (CpuFeatures_StringView_IsEquals(key, str("CPU implementer"))) { - info->implementer = CpuFeatures_StringView_ParsePositiveNumber(value); - } else if (CpuFeatures_StringView_IsEquals(key, str("CPU variant"))) { - info->variant = CpuFeatures_StringView_ParsePositiveNumber(value); - } else if (CpuFeatures_StringView_IsEquals(key, str("CPU part"))) { - info->part = CpuFeatures_StringView_ParsePositiveNumber(value); - } else if (CpuFeatures_StringView_IsEquals(key, str("CPU revision"))) { - info->revision = CpuFeatures_StringView_ParsePositiveNumber(value); - } else if (CpuFeatures_StringView_IsEquals(key, str("CPU architecture"))) { - // CPU architecture is a number that may be followed by letters. e.g. - // "6TEJ", "7". - const StringView digits = - CpuFeatures_StringView_KeepFront(value, IndexOfNonDigit(value)); - info->architecture = CpuFeatures_StringView_ParsePositiveNumber(digits); - } else if (CpuFeatures_StringView_IsEquals(key, str("Processor")) || - CpuFeatures_StringView_IsEquals(key, str("model name"))) { - // Android reports this in a non-Linux standard "Processor" but sometimes - // also in "model name", Linux reports it only in "model name" - // see RaspberryPiZero (Linux) vs InvalidArmv7 (Android) test-cases - proc_info->processor_reports_armv6 = - CpuFeatures_StringView_IndexOf(value, str("(v6l)")) >= 0; - } else if (CpuFeatures_StringView_IsEquals(key, str("Hardware"))) { - proc_info->hardware_reports_goldfish = - CpuFeatures_StringView_IsEquals(value, str("Goldfish")); - } - } - return !result.eof; -} - -uint32_t GetArmCpuId(const ArmInfo* const info) { - return (ExtractBitRange(info->implementer, 7, 0) << 24) | - (ExtractBitRange(info->variant, 3, 0) << 20) | - (ExtractBitRange(info->part, 11, 0) << 4) | - (ExtractBitRange(info->revision, 3, 0) << 0); -} - -static void FixErrors(ArmInfo* const info, - ProcCpuInfoData* const proc_cpu_info_data) { - // Fixing Samsung kernel reporting invalid cpu architecture. - // http://code.google.com/p/android/issues/detail?id=10812 - if (proc_cpu_info_data->processor_reports_armv6 && info->architecture >= 7) { - info->architecture = 6; - } - - // Handle kernel configuration bugs that prevent the correct reporting of CPU - // features. - switch (GetArmCpuId(info)) { - case 0x4100C080: - // Special case: The emulator-specific Android 4.2 kernel fails to report - // support for the 32-bit ARM IDIV instruction. Technically, this is a - // feature of the virtual CPU implemented by the emulator. Note that it - // could also support Thumb IDIV in the future, and this will have to be - // slightly updated. - if (info->architecture >= 7 && - proc_cpu_info_data->hardware_reports_goldfish) { - info->features.idiva = true; - } - break; - case 0x511004D0: - // https://crbug.com/341598. - info->features.neon = false; - break; - case 0x510006F2: - case 0x510006F3: - // The Nexus 4 (Qualcomm Krait) kernel configuration forgets to report - // IDIV support. - info->features.idiva = true; - info->features.idivt = true; - break; - } - - // Propagate cpu features. - if (info->features.vfpv4) info->features.vfpv3 = true; - if (info->features.neon) info->features.vfpv3 = true; - if (info->features.vfpv3) info->features.vfp = true; -} - -static void FillProcCpuInfoData(ArmInfo* const info, - ProcCpuInfoData* proc_cpu_info_data) { - const int fd = CpuFeatures_OpenFile("/proc/cpuinfo"); - if (fd >= 0) { - StackLineReader reader; - StackLineReader_Initialize(&reader, fd); - for (;;) { - if (!HandleArmLine(StackLineReader_NextLine(&reader), info, - proc_cpu_info_data)) { - break; - } - } - CpuFeatures_CloseFile(fd); - } -} - -static const ArmInfo kEmptyArmInfo; - -static const ProcCpuInfoData kEmptyProcCpuInfoData; - -ArmInfo GetArmInfo(void) { - // capabilities are fetched from both getauxval and /proc/cpuinfo so we can - // have some information if the executable is sandboxed (aka no access to - // /proc/cpuinfo). - ArmInfo info = kEmptyArmInfo; - ProcCpuInfoData proc_cpu_info_data = kEmptyProcCpuInfoData; - - FillProcCpuInfoData(&info, &proc_cpu_info_data); - CpuFeatures_OverrideFromHwCaps(kConfigsSize, kConfigs, - CpuFeatures_GetHardwareCapabilities(), - &info.features); - - FixErrors(&info, &proc_cpu_info_data); - - return info; -} - -//////////////////////////////////////////////////////////////////////////////// -// Introspection functions - -int GetArmFeaturesEnumValue(const ArmFeatures* features, - ArmFeaturesEnum value) { - if (value >= kConfigsSize) return false; - return kConfigs[value].get_bit((ArmFeatures*)features); -} - -const char* GetArmFeaturesEnumName(ArmFeaturesEnum value) { - if (value >= kConfigsSize) return "unknown feature"; - return kConfigs[value].proc_cpuinfo_flag; -} diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_mips.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_mips.c deleted file mode 100644 index 1b2df9e..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_mips.c +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "cpuinfo_mips.h" - -#include - -#include "internal/filesystem.h" -#include "internal/stack_line_reader.h" -#include "internal/string_view.h" -#include "internal/unix_features_aggregator.h" - -DECLARE_SETTER_AND_GETTER(MipsFeatures, msa) -DECLARE_SETTER_AND_GETTER(MipsFeatures, eva) -DECLARE_SETTER_AND_GETTER(MipsFeatures, r6) - -static const CapabilityConfig kConfigs[] = { - [MIPS_MSA] = {{MIPS_HWCAP_MSA, 0}, "msa", &set_msa, &get_msa}, - [MIPS_EVA] = {{0, 0}, "eva", &set_eva, &get_eva}, - [MIPS_R6] = {{MIPS_HWCAP_R6, 0}, "r6", &set_r6, &get_r6}, -}; -static const size_t kConfigsSize = sizeof(kConfigs) / sizeof(CapabilityConfig); - -static bool HandleMipsLine(const LineResult result, - MipsFeatures* const features) { - StringView key, value; - // See tests for an example. - if (CpuFeatures_StringView_GetAttributeKeyValue(result.line, &key, &value)) { - if (CpuFeatures_StringView_IsEquals(key, str("ASEs implemented"))) { - CpuFeatures_SetFromFlags(kConfigsSize, kConfigs, value, features); - } - } - return !result.eof; -} - -static void FillProcCpuInfoData(MipsFeatures* const features) { - const int fd = CpuFeatures_OpenFile("/proc/cpuinfo"); - if (fd >= 0) { - StackLineReader reader; - StackLineReader_Initialize(&reader, fd); - for (;;) { - if (!HandleMipsLine(StackLineReader_NextLine(&reader), features)) { - break; - } - } - CpuFeatures_CloseFile(fd); - } -} - -static const MipsInfo kEmptyMipsInfo; - -MipsInfo GetMipsInfo(void) { - assert(kConfigsSize == MIPS_LAST_); - - // capabilities are fetched from both getauxval and /proc/cpuinfo so we can - // have some information if the executable is sandboxed (aka no access to - // /proc/cpuinfo). - MipsInfo info = kEmptyMipsInfo; - - FillProcCpuInfoData(&info.features); - CpuFeatures_OverrideFromHwCaps(kConfigsSize, kConfigs, - CpuFeatures_GetHardwareCapabilities(), - &info.features); - return info; -} - -//////////////////////////////////////////////////////////////////////////////// -// Introspection functions - -int GetMipsFeaturesEnumValue(const MipsFeatures* features, - MipsFeaturesEnum value) { - if (value >= kConfigsSize) return false; - return kConfigs[value].get_bit((MipsFeatures*)features); -} - -const char* GetMipsFeaturesEnumName(MipsFeaturesEnum value) { - if (value >= kConfigsSize) return "unknown feature"; - return kConfigs[value].proc_cpuinfo_flag; -} diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_ppc.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_ppc.c deleted file mode 100644 index 4353099..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_ppc.c +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2018 IBM. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "cpuinfo_ppc.h" - -#include -#include -#include - -#include "internal/bit_utils.h" -#include "internal/filesystem.h" -#include "internal/stack_line_reader.h" -#include "internal/string_view.h" -#include "internal/unix_features_aggregator.h" - -DECLARE_SETTER_AND_GETTER(PPCFeatures, ppc32) -DECLARE_SETTER_AND_GETTER(PPCFeatures, ppc64) -DECLARE_SETTER_AND_GETTER(PPCFeatures, ppc601) -DECLARE_SETTER_AND_GETTER(PPCFeatures, altivec) -DECLARE_SETTER_AND_GETTER(PPCFeatures, fpu) -DECLARE_SETTER_AND_GETTER(PPCFeatures, mmu) -DECLARE_SETTER_AND_GETTER(PPCFeatures, mac_4xx) -DECLARE_SETTER_AND_GETTER(PPCFeatures, unifiedcache) -DECLARE_SETTER_AND_GETTER(PPCFeatures, spe) -DECLARE_SETTER_AND_GETTER(PPCFeatures, efpsingle) -DECLARE_SETTER_AND_GETTER(PPCFeatures, efpdouble) -DECLARE_SETTER_AND_GETTER(PPCFeatures, no_tb) -DECLARE_SETTER_AND_GETTER(PPCFeatures, power4) -DECLARE_SETTER_AND_GETTER(PPCFeatures, power5) -DECLARE_SETTER_AND_GETTER(PPCFeatures, power5plus) -DECLARE_SETTER_AND_GETTER(PPCFeatures, cell) -DECLARE_SETTER_AND_GETTER(PPCFeatures, booke) -DECLARE_SETTER_AND_GETTER(PPCFeatures, smt) -DECLARE_SETTER_AND_GETTER(PPCFeatures, icachesnoop) -DECLARE_SETTER_AND_GETTER(PPCFeatures, arch205) -DECLARE_SETTER_AND_GETTER(PPCFeatures, pa6t) -DECLARE_SETTER_AND_GETTER(PPCFeatures, dfp) -DECLARE_SETTER_AND_GETTER(PPCFeatures, power6ext) -DECLARE_SETTER_AND_GETTER(PPCFeatures, arch206) -DECLARE_SETTER_AND_GETTER(PPCFeatures, vsx) -DECLARE_SETTER_AND_GETTER(PPCFeatures, pseries_perfmon_compat) -DECLARE_SETTER_AND_GETTER(PPCFeatures, truele) -DECLARE_SETTER_AND_GETTER(PPCFeatures, ppcle) -DECLARE_SETTER_AND_GETTER(PPCFeatures, arch207) -DECLARE_SETTER_AND_GETTER(PPCFeatures, htm) -DECLARE_SETTER_AND_GETTER(PPCFeatures, dscr) -DECLARE_SETTER_AND_GETTER(PPCFeatures, ebb) -DECLARE_SETTER_AND_GETTER(PPCFeatures, isel) -DECLARE_SETTER_AND_GETTER(PPCFeatures, tar) -DECLARE_SETTER_AND_GETTER(PPCFeatures, vcrypto) -DECLARE_SETTER_AND_GETTER(PPCFeatures, htm_nosc) -DECLARE_SETTER_AND_GETTER(PPCFeatures, arch300) -DECLARE_SETTER_AND_GETTER(PPCFeatures, ieee128) -DECLARE_SETTER_AND_GETTER(PPCFeatures, darn) -DECLARE_SETTER_AND_GETTER(PPCFeatures, scv) -DECLARE_SETTER_AND_GETTER(PPCFeatures, htm_no_suspend) - -static const CapabilityConfig kConfigs[] = { - // clang-format off - [PPC_32] = {{PPC_FEATURE_32, 0}, "ppc32", &set_ppc32, &get_ppc32}, - [PPC_64] = {{PPC_FEATURE_64, 0}, "ppc64", &set_ppc64, &get_ppc64}, - [PPC_601_INSTR] = {{PPC_FEATURE_601_INSTR, 0}, "ppc601", &set_ppc601, &get_ppc601}, - [PPC_HAS_ALTIVEC] = {{PPC_FEATURE_HAS_ALTIVEC, 0}, "altivec", &set_altivec, &get_altivec}, - [PPC_HAS_FPU] = {{PPC_FEATURE_HAS_FPU, 0}, "fpu", &set_fpu, &get_fpu}, - [PPC_HAS_MMU] = {{PPC_FEATURE_HAS_MMU, 0}, "mmu", &set_mmu, &get_mmu}, - [PPC_HAS_4xxMAC] = {{PPC_FEATURE_HAS_4xxMAC, 0}, "4xxmac", &set_mac_4xx, &get_mac_4xx}, - [PPC_UNIFIED_CACHE] = {{PPC_FEATURE_UNIFIED_CACHE, 0}, "ucache", &set_unifiedcache, &get_unifiedcache}, - [PPC_HAS_SPE] = {{PPC_FEATURE_HAS_SPE, 0}, "spe", &set_spe, &get_spe}, - [PPC_HAS_EFP_SINGLE] = {{PPC_FEATURE_HAS_EFP_SINGLE, 0}, "efpsingle", &set_efpsingle, &get_efpsingle}, - [PPC_HAS_EFP_DOUBLE] = {{PPC_FEATURE_HAS_EFP_DOUBLE, 0}, "efpdouble", &set_efpdouble, &get_efpdouble}, - [PPC_NO_TB] = {{PPC_FEATURE_NO_TB, 0}, "notb", &set_no_tb, &get_no_tb}, - [PPC_POWER4] = {{PPC_FEATURE_POWER4, 0}, "power4", &set_power4, &get_power4}, - [PPC_POWER5] = {{PPC_FEATURE_POWER5, 0}, "power5", &set_power5, &get_power5}, - [PPC_POWER5_PLUS] = {{PPC_FEATURE_POWER5_PLUS, 0}, "power5+", &set_power5plus, &get_power5plus}, - [PPC_CELL] = {{PPC_FEATURE_CELL, 0}, "cellbe", &set_cell, &get_cell}, - [PPC_BOOKE] = {{PPC_FEATURE_BOOKE, 0}, "booke", &set_booke, &get_booke}, - [PPC_SMT] = {{PPC_FEATURE_SMT, 0}, "smt", &set_smt, &get_smt}, - [PPC_ICACHE_SNOOP] = {{PPC_FEATURE_ICACHE_SNOOP, 0}, "ic_snoop", &set_icachesnoop, &get_icachesnoop}, - [PPC_ARCH_2_05] = {{PPC_FEATURE_ARCH_2_05, 0}, "arch_2_05", &set_arch205, &get_arch205}, - [PPC_PA6T] = {{PPC_FEATURE_PA6T, 0}, "pa6t", &set_pa6t, &get_pa6t}, - [PPC_HAS_DFP] = {{PPC_FEATURE_HAS_DFP, 0}, "dfp", &set_dfp, &get_dfp}, - [PPC_POWER6_EXT] = {{PPC_FEATURE_POWER6_EXT, 0}, "power6x", &set_power6ext, &get_power6ext}, - [PPC_ARCH_2_06] = {{PPC_FEATURE_ARCH_2_06, 0}, "arch_2_06", &set_arch206, &get_arch206}, - [PPC_HAS_VSX] = {{PPC_FEATURE_HAS_VSX, 0}, "vsx", &set_vsx, &get_vsx}, - [PPC_PSERIES_PERFMON_COMPAT] = {{PPC_FEATURE_PSERIES_PERFMON_COMPAT, 0}, "archpmu", &set_pseries_perfmon_compat, &get_pseries_perfmon_compat}, - [PPC_TRUE_LE] = {{PPC_FEATURE_TRUE_LE, 0}, "true_le", &set_truele, &get_truele}, - [PPC_PPC_LE] = {{PPC_FEATURE_PPC_LE, 0}, "ppcle", &set_ppcle, &get_ppcle}, - [PPC_ARCH_2_07] = {{0, PPC_FEATURE2_ARCH_2_07}, "arch_2_07", &set_arch207, &get_arch207}, - [PPC_HTM] = {{0, PPC_FEATURE2_HTM}, "htm", &set_htm, &get_htm}, - [PPC_DSCR] = {{0, PPC_FEATURE2_DSCR}, "dscr", &set_dscr, &get_dscr}, - [PPC_EBB] = {{0, PPC_FEATURE2_EBB}, "ebb", &set_ebb, &get_ebb}, - [PPC_ISEL] = {{0, PPC_FEATURE2_ISEL}, "isel", &set_isel, &get_isel}, - [PPC_TAR] = {{0, PPC_FEATURE2_TAR}, "tar", &set_tar, &get_tar}, - [PPC_VEC_CRYPTO] = {{0, PPC_FEATURE2_VEC_CRYPTO}, "vcrypto", &set_vcrypto, &get_vcrypto}, - [PPC_HTM_NOSC] = {{0, PPC_FEATURE2_HTM_NOSC}, "htm-nosc", &set_htm_nosc, &get_htm_nosc}, - [PPC_ARCH_3_00] = {{0, PPC_FEATURE2_ARCH_3_00}, "arch_3_00", &set_arch300, &get_arch300}, - [PPC_HAS_IEEE128] = {{0, PPC_FEATURE2_HAS_IEEE128}, "ieee128", &set_ieee128, &get_ieee128}, - [PPC_DARN] = {{0, PPC_FEATURE2_DARN}, "darn", &set_darn, &get_darn}, - [PPC_SCV] = {{0, PPC_FEATURE2_SCV}, "scv", &set_scv, &get_scv}, - [PPC_HTM_NO_SUSPEND] = {{0, PPC_FEATURE2_HTM_NO_SUSPEND}, "htm-no-suspend", &set_htm_no_suspend, &get_htm_no_suspend}, - // clang-format on -}; -static const size_t kConfigsSize = sizeof(kConfigs) / sizeof(CapabilityConfig); - -static bool HandlePPCLine(const LineResult result, - PPCPlatformStrings* const strings) { - StringView line = result.line; - StringView key, value; - if (CpuFeatures_StringView_GetAttributeKeyValue(line, &key, &value)) { - if (CpuFeatures_StringView_HasWord(key, "platform")) { - CpuFeatures_StringView_CopyString(value, strings->platform, - sizeof(strings->platform)); - } else if (CpuFeatures_StringView_IsEquals(key, str("model"))) { - CpuFeatures_StringView_CopyString(value, strings->model, - sizeof(strings->platform)); - } else if (CpuFeatures_StringView_IsEquals(key, str("machine"))) { - CpuFeatures_StringView_CopyString(value, strings->machine, - sizeof(strings->platform)); - } else if (CpuFeatures_StringView_IsEquals(key, str("cpu"))) { - CpuFeatures_StringView_CopyString(value, strings->cpu, - sizeof(strings->platform)); - } - } - return !result.eof; -} - -static void FillProcCpuInfoData(PPCPlatformStrings* const strings) { - const int fd = CpuFeatures_OpenFile("/proc/cpuinfo"); - if (fd >= 0) { - StackLineReader reader; - StackLineReader_Initialize(&reader, fd); - for (;;) { - if (!HandlePPCLine(StackLineReader_NextLine(&reader), strings)) { - break; - } - } - CpuFeatures_CloseFile(fd); - } -} - -static const PPCInfo kEmptyPPCInfo; - -PPCInfo GetPPCInfo(void) { - /* - * On Power feature flags aren't currently in cpuinfo so we only look at - * the auxilary vector. - */ - PPCInfo info = kEmptyPPCInfo; - - CpuFeatures_OverrideFromHwCaps(kConfigsSize, kConfigs, - CpuFeatures_GetHardwareCapabilities(), - &info.features); - return info; -} - -static const PPCPlatformStrings kEmptyPPCPlatformStrings; - -PPCPlatformStrings GetPPCPlatformStrings(void) { - PPCPlatformStrings strings = kEmptyPPCPlatformStrings; - - FillProcCpuInfoData(&strings); - strings.type = CpuFeatures_GetPlatformType(); - return strings; -} - -//////////////////////////////////////////////////////////////////////////////// -// Introspection functions - -int GetPPCFeaturesEnumValue(const PPCFeatures* features, - PPCFeaturesEnum value) { - if (value >= kConfigsSize) return false; - return kConfigs[value].get_bit((PPCFeatures*)features); -} - -const char* GetPPCFeaturesEnumName(PPCFeaturesEnum value) { - if (value >= kConfigsSize) return "unknown feature"; - return kConfigs[value].proc_cpuinfo_flag; -} diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_x86.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_x86.c deleted file mode 100644 index d5edd30..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/cpuinfo_x86.c +++ /dev/null @@ -1,1694 +0,0 @@ -// Copyright 2017 Google Inc. -// Copyright 2020 Intel Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "cpuinfo_x86.h" - -#include -#include - -#include "internal/bit_utils.h" -#include "internal/cpuid_x86.h" - -#if !defined(CPU_FEATURES_ARCH_X86) -#error "Cannot compile cpuinfo_x86 on a non x86 platform." -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Definitions for CpuId and GetXCR0Eax. -//////////////////////////////////////////////////////////////////////////////// - -#if defined(CPU_FEATURES_MOCK_CPUID_X86) -// Implementation will be provided by test/cpuinfo_x86_test.cc. -#elif defined(CPU_FEATURES_COMPILER_CLANG) || defined(CPU_FEATURES_COMPILER_GCC) - -#include - -Leaf CpuIdEx(uint32_t leaf_id, int ecx) { - Leaf leaf; - __cpuid_count(leaf_id, ecx, leaf.eax, leaf.ebx, leaf.ecx, leaf.edx); - return leaf; -} - -uint32_t GetXCR0Eax(void) { - uint32_t eax, edx; - /* named form of xgetbv not supported on OSX, so must use byte form, see: - https://github.com/asmjit/asmjit/issues/78 - */ - __asm(".byte 0x0F, 0x01, 0xd0" : "=a"(eax), "=d"(edx) : "c"(0)); - return eax; -} - -#elif defined(CPU_FEATURES_COMPILER_MSC) - -#include -#include // For __cpuidex() - -Leaf CpuIdEx(uint32_t leaf_id, int ecx) { - Leaf leaf; - int data[4]; - __cpuidex(data, leaf_id, ecx); - leaf.eax = data[0]; - leaf.ebx = data[1]; - leaf.ecx = data[2]; - leaf.edx = data[3]; - return leaf; -} - -uint32_t GetXCR0Eax(void) { return (uint32_t)_xgetbv(0); } - -#else -#error "Unsupported compiler, x86 cpuid requires either GCC, Clang or MSVC." -#endif - -static Leaf CpuId(uint32_t leaf_id) { return CpuIdEx(leaf_id, 0); } - -static const Leaf kEmptyLeaf; - -static Leaf SafeCpuIdEx(uint32_t max_cpuid_leaf, uint32_t leaf_id, int ecx) { - if (leaf_id <= max_cpuid_leaf) { - return CpuIdEx(leaf_id, ecx); - } else { - return kEmptyLeaf; - } -} - -static Leaf SafeCpuId(uint32_t max_cpuid_leaf, uint32_t leaf_id) { - return SafeCpuIdEx(max_cpuid_leaf, leaf_id, 0); -} - -#define MASK_XMM 0x2 -#define MASK_YMM 0x4 -#define MASK_MASKREG 0x20 -#define MASK_ZMM0_15 0x40 -#define MASK_ZMM16_31 0x80 -#define MASK_XTILECFG 0x20000 -#define MASK_XTILEDATA 0x40000 - -static bool HasMask(uint32_t value, uint32_t mask) { - return (value & mask) == mask; -} - -// Checks that operating system saves and restores xmm registers during context -// switches. -static bool HasXmmOsXSave(uint32_t xcr0_eax) { - return HasMask(xcr0_eax, MASK_XMM); -} - -// Checks that operating system saves and restores ymm registers during context -// switches. -static bool HasYmmOsXSave(uint32_t xcr0_eax) { - return HasMask(xcr0_eax, MASK_XMM | MASK_YMM); -} - -// Checks that operating system saves and restores zmm registers during context -// switches. -static bool HasZmmOsXSave(uint32_t xcr0_eax) { - return HasMask(xcr0_eax, MASK_XMM | MASK_YMM | MASK_MASKREG | MASK_ZMM0_15 | - MASK_ZMM16_31); -} - -// Checks that operating system saves and restores AMX/TMUL state during context -// switches. -static bool HasTmmOsXSave(uint32_t xcr0_eax) { - return HasMask(xcr0_eax, MASK_XMM | MASK_YMM | MASK_MASKREG | MASK_ZMM0_15 | - MASK_ZMM16_31 | MASK_XTILECFG | MASK_XTILEDATA); -} - -static bool HasSecondFMA(uint32_t model) { - // Skylake server - if (model == 0x55) { - char proc_name[49] = {0}; - FillX86BrandString(proc_name); - // detect Xeon - if (proc_name[9] == 'X') { - // detect Silver or Bronze - if (proc_name[17] == 'S' || proc_name[17] == 'B') return false; - // detect Gold 5_20 and below, except for Gold 53__ - if (proc_name[17] == 'G' && proc_name[22] == '5') - return ((proc_name[23] == '3') || - (proc_name[24] == '2' && proc_name[25] == '2')); - // detect Xeon W 210x - if (proc_name[17] == 'W' && proc_name[21] == '0') return false; - // detect Xeon D 2xxx - if (proc_name[17] == 'D' && proc_name[19] == '2' && proc_name[20] == '1') - return false; - } - return true; - } - // Cannon Lake client - if (model == 0x66) return false; - // Ice Lake client - if (model == 0x7d || model == 0x7e) return false; - // This is the right default... - return true; -} - -static void SetVendor(const Leaf leaf, char* const vendor) { - *(uint32_t*)(vendor) = leaf.ebx; - *(uint32_t*)(vendor + 4) = leaf.edx; - *(uint32_t*)(vendor + 8) = leaf.ecx; - vendor[12] = '\0'; -} - -static int IsVendor(const Leaf leaf, const char* const name) { - const uint32_t ebx = *(const uint32_t*)(name); - const uint32_t edx = *(const uint32_t*)(name + 4); - const uint32_t ecx = *(const uint32_t*)(name + 8); - return leaf.ebx == ebx && leaf.ecx == ecx && leaf.edx == edx; -} - -static const CacheLevelInfo kEmptyCacheLevelInfo; - -static CacheLevelInfo GetCacheLevelInfo(const uint32_t reg) { - const int UNDEF = -1; - const int KiB = 1024; - const int MiB = 1024 * KiB; - switch (reg) { - case 0x01: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 32, - .partitioning = 0}; - case 0x02: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * MiB, - .ways = 0xFF, - .line_size = UNDEF, - .tlb_entries = 2, - .partitioning = 0}; - case 0x03: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 64, - .partitioning = 0}; - case 0x04: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * MiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 8, - .partitioning = 0}; - case 0x05: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * MiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 32, - .partitioning = 0}; - case 0x06: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_INSTRUCTION, - .cache_size = 8 * KiB, - .ways = 4, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x08: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_INSTRUCTION, - .cache_size = 16 * KiB, - .ways = 4, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x09: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_INSTRUCTION, - .cache_size = 32 * KiB, - .ways = 4, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x0A: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 8 * KiB, - .ways = 2, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x0B: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * MiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 4, - .partitioning = 0}; - case 0x0C: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 16 * KiB, - .ways = 4, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x0D: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 16 * KiB, - .ways = 4, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x0E: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 24 * KiB, - .ways = 6, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x1D: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 128 * KiB, - .ways = 2, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x21: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 256 * KiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x22: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 512 * KiB, - .ways = 4, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 2}; - case 0x23: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 1 * MiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 2}; - case 0x24: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 1 * MiB, - .ways = 16, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x25: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 2 * MiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 2}; - case 0x29: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 4 * MiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 2}; - case 0x2C: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 32 * KiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x30: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_INSTRUCTION, - .cache_size = 32 * KiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x40: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = UNDEF, - .ways = UNDEF, - .line_size = UNDEF, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x41: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 128 * KiB, - .ways = 4, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x42: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 256 * KiB, - .ways = 4, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x43: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 512 * KiB, - .ways = 4, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x44: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 1 * MiB, - .ways = 4, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x45: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 2 * MiB, - .ways = 4, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x46: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 4 * MiB, - .ways = 4, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x47: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 8 * MiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x48: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 3 * MiB, - .ways = 12, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x49: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 4 * MiB, - .ways = 16, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case (0x49 | (1 << 8)): - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 4 * MiB, - .ways = 16, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x4A: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 6 * MiB, - .ways = 12, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x4B: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 8 * MiB, - .ways = 16, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x4C: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 12 * MiB, - .ways = 12, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x4D: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 16 * MiB, - .ways = 16, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x4E: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 6 * MiB, - .ways = 24, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x4F: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = UNDEF, - .line_size = UNDEF, - .tlb_entries = 32, - .partitioning = 0}; - case 0x50: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = UNDEF, - .line_size = UNDEF, - .tlb_entries = 64, - .partitioning = 0}; - case 0x51: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = UNDEF, - .line_size = UNDEF, - .tlb_entries = 128, - .partitioning = 0}; - case 0x52: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = UNDEF, - .line_size = UNDEF, - .tlb_entries = 256, - .partitioning = 0}; - case 0x55: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 2 * MiB, - .ways = 0xFF, - .line_size = UNDEF, - .tlb_entries = 7, - .partitioning = 0}; - case 0x56: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * MiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 16, - .partitioning = 0}; - case 0x57: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 16, - .partitioning = 0}; - case 0x59: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 0xFF, - .line_size = UNDEF, - .tlb_entries = 16, - .partitioning = 0}; - case 0x5A: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 2 * MiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 32, - .partitioning = 0}; - case 0x5B: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = UNDEF, - .line_size = UNDEF, - .tlb_entries = 64, - .partitioning = 0}; - case 0x5C: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = UNDEF, - .line_size = UNDEF, - .tlb_entries = 128, - .partitioning = 0}; - case 0x5D: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4, - .ways = UNDEF, - .line_size = UNDEF, - .tlb_entries = 256, - .partitioning = 0}; - case 0x60: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 16 * KiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x61: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 0xFF, - .line_size = UNDEF, - .tlb_entries = 48, - .partitioning = 0}; - case 0x63: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 2 * MiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 4, - .partitioning = 0}; - case 0x66: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 8 * KiB, - .ways = 4, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x67: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 16 * KiB, - .ways = 4, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x68: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 32 * KiB, - .ways = 4, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x70: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_INSTRUCTION, - .cache_size = 12 * KiB, - .ways = 8, - .line_size = UNDEF, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x71: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_INSTRUCTION, - .cache_size = 16 * KiB, - .ways = 8, - .line_size = UNDEF, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x72: - return (CacheLevelInfo){.level = 1, - .cache_type = CPU_FEATURE_CACHE_INSTRUCTION, - .cache_size = 32 * KiB, - .ways = 8, - .line_size = UNDEF, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x76: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 2 * MiB, - .ways = 0xFF, - .line_size = UNDEF, - .tlb_entries = 8, - .partitioning = 0}; - case 0x78: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 1 * MiB, - .ways = 4, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x79: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 128 * KiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 2}; - case 0x7A: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 256 * KiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 2}; - case 0x7B: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 512 * KiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 2}; - case 0x7C: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 1 * MiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 2}; - case 0x7D: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 2 * MiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x7F: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 512 * KiB, - .ways = 2, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x80: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 512 * KiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x82: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 256 * KiB, - .ways = 8, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x83: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 512 * KiB, - .ways = 8, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x84: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 1 * MiB, - .ways = 8, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x85: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 2 * MiB, - .ways = 8, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x86: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 512 * KiB, - .ways = 4, - .line_size = 32, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0x87: - return (CacheLevelInfo){.level = 2, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 1 * MiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xA0: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_DTLB, - .cache_size = 4 * KiB, - .ways = 0xFF, - .line_size = UNDEF, - .tlb_entries = 32, - .partitioning = 0}; - case 0xB0: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 128, - .partitioning = 0}; - case 0xB1: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 2 * MiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 8, - .partitioning = 0}; - case 0xB2: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 64, - .partitioning = 0}; - case 0xB3: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 128, - .partitioning = 0}; - case 0xB4: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 256, - .partitioning = 0}; - case 0xB5: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 8, - .line_size = UNDEF, - .tlb_entries = 64, - .partitioning = 0}; - case 0xB6: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 8, - .line_size = UNDEF, - .tlb_entries = 128, - .partitioning = 0}; - case 0xBA: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 64, - .partitioning = 0}; - case 0xC0: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_TLB, - .cache_size = 4 * KiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 8, - .partitioning = 0}; - case 0xC1: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_STLB, - .cache_size = 4 * KiB, - .ways = 8, - .line_size = UNDEF, - .tlb_entries = 1024, - .partitioning = 0}; - case 0xC2: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_DTLB, - .cache_size = 4 * KiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 16, - .partitioning = 0}; - case 0xC3: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_STLB, - .cache_size = 4 * KiB, - .ways = 6, - .line_size = UNDEF, - .tlb_entries = 1536, - .partitioning = 0}; - case 0xCA: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_STLB, - .cache_size = 4 * KiB, - .ways = 4, - .line_size = UNDEF, - .tlb_entries = 512, - .partitioning = 0}; - case 0xD0: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 512 * KiB, - .ways = 4, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xD1: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 1 * MiB, - .ways = 4, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xD2: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 2 * MiB, - .ways = 4, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xD6: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 1 * MiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xD7: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 2 * MiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xD8: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 4 * MiB, - .ways = 8, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xDC: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 1 * 1536 * KiB, - .ways = 12, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xDD: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 3 * MiB, - .ways = 12, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xDE: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 6 * MiB, - .ways = 12, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xE2: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 2 * MiB, - .ways = 16, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xE3: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 4 * MiB, - .ways = 16, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xE4: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 8 * MiB, - .ways = 16, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xEA: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 12 * MiB, - .ways = 24, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xEB: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 18 * MiB, - .ways = 24, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xEC: - return (CacheLevelInfo){.level = 3, - .cache_type = CPU_FEATURE_CACHE_DATA, - .cache_size = 24 * MiB, - .ways = 24, - .line_size = 64, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xF0: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_PREFETCH, - .cache_size = 64 * KiB, - .ways = UNDEF, - .line_size = UNDEF, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xF1: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_PREFETCH, - .cache_size = 128 * KiB, - .ways = UNDEF, - .line_size = UNDEF, - .tlb_entries = UNDEF, - .partitioning = 0}; - case 0xFF: - return (CacheLevelInfo){.level = UNDEF, - .cache_type = CPU_FEATURE_CACHE_NULL, - .cache_size = UNDEF, - .ways = UNDEF, - .line_size = UNDEF, - .tlb_entries = UNDEF, - .partitioning = 0}; - default: - return kEmptyCacheLevelInfo; - } -} - -static void GetByteArrayFromRegister(uint32_t result[4], const uint32_t reg) { - for (int i = 0; i < 4; ++i) { - result[i] = ExtractBitRange(reg, (i + 1) * 8, i * 8); - } -} - -static void ParseLeaf2(const int max_cpuid_leaf, CacheInfo* info) { - Leaf leaf = SafeCpuId(max_cpuid_leaf, 2); - uint32_t registers[] = {leaf.eax, leaf.ebx, leaf.ecx, leaf.edx}; - for (int i = 0; i < 4; ++i) { - if (registers[i] & (1U << 31)) { - continue; // register does not contains valid information - } - uint32_t bytes[4]; - GetByteArrayFromRegister(bytes, registers[i]); - for (int j = 0; j < 4; ++j) { - if (bytes[j] == 0xFF) - break; // leaf 4 should be used to fetch cache information - info->levels[info->size] = GetCacheLevelInfo(bytes[j]); - } - info->size++; - } -} - -static void ParseLeaf4(const int max_cpuid_leaf, CacheInfo* info) { - info->size = 0; - for (int cache_id = 0; cache_id < CPU_FEATURES_MAX_CACHE_LEVEL; cache_id++) { - const Leaf leaf = SafeCpuIdEx(max_cpuid_leaf, 4, cache_id); - CacheType cache_type = ExtractBitRange(leaf.eax, 4, 0); - if (cache_type == CPU_FEATURE_CACHE_NULL) { - info->levels[cache_id] = kEmptyCacheLevelInfo; - continue; - } - int level = ExtractBitRange(leaf.eax, 7, 5); - int line_size = ExtractBitRange(leaf.ebx, 11, 0) + 1; - int partitioning = ExtractBitRange(leaf.ebx, 21, 12) + 1; - int ways = ExtractBitRange(leaf.ebx, 31, 22) + 1; - int tlb_entries = leaf.ecx + 1; - int cache_size = (ways * partitioning * line_size * (tlb_entries)); - info->levels[cache_id] = (CacheLevelInfo){.level = level, - .cache_type = cache_type, - .cache_size = cache_size, - .ways = ways, - .line_size = line_size, - .tlb_entries = tlb_entries, - .partitioning = partitioning}; - info->size++; - } -} - -// Internal structure to hold the OS support for vector operations. -// Avoid to recompute them since each call to cpuid is ~100 cycles. -typedef struct { - bool have_sse; - bool have_avx; - bool have_avx512; - bool have_amx; -} OsSupport; - -// Reference https://en.wikipedia.org/wiki/CPUID. -static void ParseCpuId(const uint32_t max_cpuid_leaf, X86Info* info, - OsSupport* os_support) { - const Leaf leaf_1 = SafeCpuId(max_cpuid_leaf, 1); - const Leaf leaf_7 = SafeCpuId(max_cpuid_leaf, 7); - const Leaf leaf_7_1 = SafeCpuIdEx(max_cpuid_leaf, 7, 1); - - const bool have_xsave = IsBitSet(leaf_1.ecx, 26); - const bool have_osxsave = IsBitSet(leaf_1.ecx, 27); - const uint32_t xcr0_eax = (have_xsave && have_osxsave) ? GetXCR0Eax() : 0; - os_support->have_sse = HasXmmOsXSave(xcr0_eax); - os_support->have_avx = HasYmmOsXSave(xcr0_eax); - os_support->have_avx512 = HasZmmOsXSave(xcr0_eax); - os_support->have_amx = HasTmmOsXSave(xcr0_eax); - - const uint32_t family = ExtractBitRange(leaf_1.eax, 11, 8); - const uint32_t extended_family = ExtractBitRange(leaf_1.eax, 27, 20); - const uint32_t model = ExtractBitRange(leaf_1.eax, 7, 4); - const uint32_t extended_model = ExtractBitRange(leaf_1.eax, 19, 16); - - X86Features* const features = &info->features; - - info->family = extended_family + family; - info->model = (extended_model << 4) + model; - info->stepping = ExtractBitRange(leaf_1.eax, 3, 0); - - features->fpu = IsBitSet(leaf_1.edx, 0); - features->tsc = IsBitSet(leaf_1.edx, 4); - features->cx8 = IsBitSet(leaf_1.edx, 8); - features->clfsh = IsBitSet(leaf_1.edx, 19); - features->mmx = IsBitSet(leaf_1.edx, 23); - features->ss = IsBitSet(leaf_1.edx, 27); - features->pclmulqdq = IsBitSet(leaf_1.ecx, 1); - features->smx = IsBitSet(leaf_1.ecx, 6); - features->cx16 = IsBitSet(leaf_1.ecx, 13); - features->dca = IsBitSet(leaf_1.ecx, 18); - features->movbe = IsBitSet(leaf_1.ecx, 22); - features->popcnt = IsBitSet(leaf_1.ecx, 23); - features->aes = IsBitSet(leaf_1.ecx, 25); - features->f16c = IsBitSet(leaf_1.ecx, 29); - features->rdrnd = IsBitSet(leaf_1.ecx, 30); - features->sgx = IsBitSet(leaf_7.ebx, 2); - features->bmi1 = IsBitSet(leaf_7.ebx, 3); - features->hle = IsBitSet(leaf_7.ebx, 4); - features->bmi2 = IsBitSet(leaf_7.ebx, 8); - features->erms = IsBitSet(leaf_7.ebx, 9); - features->rtm = IsBitSet(leaf_7.ebx, 11); - features->rdseed = IsBitSet(leaf_7.ebx, 18); - features->clflushopt = IsBitSet(leaf_7.ebx, 23); - features->clwb = IsBitSet(leaf_7.ebx, 24); - features->sha = IsBitSet(leaf_7.ebx, 29); - features->vaes = IsBitSet(leaf_7.ecx, 9); - features->vpclmulqdq = IsBitSet(leaf_7.ecx, 10); - - if (os_support->have_sse) { - features->sse = IsBitSet(leaf_1.edx, 25); - features->sse2 = IsBitSet(leaf_1.edx, 26); - features->sse3 = IsBitSet(leaf_1.ecx, 0); - features->ssse3 = IsBitSet(leaf_1.ecx, 9); - features->sse4_1 = IsBitSet(leaf_1.ecx, 19); - features->sse4_2 = IsBitSet(leaf_1.ecx, 20); - } - - if (os_support->have_avx) { - features->fma3 = IsBitSet(leaf_1.ecx, 12); - features->avx = IsBitSet(leaf_1.ecx, 28); - features->avx2 = IsBitSet(leaf_7.ebx, 5); - } - - if (os_support->have_avx512) { - features->avx512f = IsBitSet(leaf_7.ebx, 16); - features->avx512cd = IsBitSet(leaf_7.ebx, 28); - features->avx512er = IsBitSet(leaf_7.ebx, 27); - features->avx512pf = IsBitSet(leaf_7.ebx, 26); - features->avx512bw = IsBitSet(leaf_7.ebx, 30); - features->avx512dq = IsBitSet(leaf_7.ebx, 17); - features->avx512vl = IsBitSet(leaf_7.ebx, 31); - features->avx512ifma = IsBitSet(leaf_7.ebx, 21); - features->avx512vbmi = IsBitSet(leaf_7.ecx, 1); - features->avx512vbmi2 = IsBitSet(leaf_7.ecx, 6); - features->avx512vnni = IsBitSet(leaf_7.ecx, 11); - features->avx512bitalg = IsBitSet(leaf_7.ecx, 12); - features->avx512vpopcntdq = IsBitSet(leaf_7.ecx, 14); - features->avx512_4vnniw = IsBitSet(leaf_7.edx, 2); - features->avx512_4vbmi2 = IsBitSet(leaf_7.edx, 3); - features->avx512_second_fma = HasSecondFMA(info->model); - features->avx512_4fmaps = IsBitSet(leaf_7.edx, 3); - features->avx512_bf16 = IsBitSet(leaf_7_1.eax, 5); - features->avx512_vp2intersect = IsBitSet(leaf_7.edx, 8); - } - - if (os_support->have_amx) { - features->amx_bf16 = IsBitSet(leaf_7.edx, 22); - features->amx_tile = IsBitSet(leaf_7.edx, 24); - features->amx_int8 = IsBitSet(leaf_7.edx, 25); - } -} - -// Reference -// https://en.wikipedia.org/wiki/CPUID#EAX=80000000h:_Get_Highest_Extended_Function_Implemented. -static void ParseExtraAMDCpuId(X86Info* info, OsSupport os_support) { - const Leaf leaf_80000000 = CpuId(0x80000000); - const uint32_t max_extended_cpuid_leaf = leaf_80000000.eax; - const Leaf leaf_80000001 = SafeCpuId(max_extended_cpuid_leaf, 0x80000001); - - X86Features* const features = &info->features; - - if (os_support.have_sse) { - features->sse4a = IsBitSet(leaf_80000001.ecx, 6); - } - - if (os_support.have_avx) { - features->fma4 = IsBitSet(leaf_80000001.ecx, 16); - } -} - -static const X86Info kEmptyX86Info; -static const OsSupport kEmptyOsSupport; -static const CacheInfo kEmptyCacheInfo; - -X86Info GetX86Info(void) { - X86Info info = kEmptyX86Info; - OsSupport os_support = kEmptyOsSupport; - const Leaf leaf_0 = CpuId(0); - const bool is_intel = IsVendor(leaf_0, "GenuineIntel"); - const bool is_amd = IsVendor(leaf_0, "AuthenticAMD"); - SetVendor(leaf_0, info.vendor); - if (is_intel || is_amd) { - const uint32_t max_cpuid_leaf = leaf_0.eax; - ParseCpuId(max_cpuid_leaf, &info, &os_support); - } - if (is_amd) { - ParseExtraAMDCpuId(&info, os_support); - } - return info; -} - -CacheInfo GetX86CacheInfo(void) { - CacheInfo info = kEmptyCacheInfo; - const Leaf leaf_0 = CpuId(0); - const uint32_t max_cpuid_leaf = leaf_0.eax; - if (IsVendor(leaf_0, "GenuineIntel")) { - ParseLeaf2(max_cpuid_leaf, &info); - ParseLeaf4(max_cpuid_leaf, &info); - } - return info; -} - -#define CPUID(FAMILY, MODEL) ((((FAMILY)&0xFF) << 8) | ((MODEL)&0xFF)) - -X86Microarchitecture GetX86Microarchitecture(const X86Info* info) { - if (memcmp(info->vendor, "GenuineIntel", sizeof(info->vendor)) == 0) { - switch (CPUID(info->family, info->model)) { - case CPUID(0x06, 0x35): - case CPUID(0x06, 0x36): - // https://en.wikipedia.org/wiki/Bonnell_(microarchitecture) - return INTEL_ATOM_BNL; - case CPUID(0x06, 0x37): - case CPUID(0x06, 0x4C): - // https://en.wikipedia.org/wiki/Silvermont - return INTEL_ATOM_SMT; - case CPUID(0x06, 0x5C): - // https://en.wikipedia.org/wiki/Goldmont - return INTEL_ATOM_GMT; - case CPUID(0x06, 0x0F): - case CPUID(0x06, 0x16): - // https://en.wikipedia.org/wiki/Intel_Core_(microarchitecture) - return INTEL_CORE; - case CPUID(0x06, 0x17): - case CPUID(0x06, 0x1D): - // https://en.wikipedia.org/wiki/Penryn_(microarchitecture) - return INTEL_PNR; - case CPUID(0x06, 0x1A): - case CPUID(0x06, 0x1E): - case CPUID(0x06, 0x1F): - case CPUID(0x06, 0x2E): - // https://en.wikipedia.org/wiki/Nehalem_(microarchitecture) - return INTEL_NHM; - case CPUID(0x06, 0x25): - case CPUID(0x06, 0x2C): - case CPUID(0x06, 0x2F): - // https://en.wikipedia.org/wiki/Westmere_(microarchitecture) - return INTEL_WSM; - case CPUID(0x06, 0x2A): - case CPUID(0x06, 0x2D): - // https://en.wikipedia.org/wiki/Sandy_Bridge#Models_and_steppings - return INTEL_SNB; - case CPUID(0x06, 0x3A): - case CPUID(0x06, 0x3E): - // https://en.wikipedia.org/wiki/Ivy_Bridge_(microarchitecture)#Models_and_steppings - return INTEL_IVB; - case CPUID(0x06, 0x3C): - case CPUID(0x06, 0x3F): - case CPUID(0x06, 0x45): - case CPUID(0x06, 0x46): - // https://en.wikipedia.org/wiki/Haswell_(microarchitecture) - return INTEL_HSW; - case CPUID(0x06, 0x3D): - case CPUID(0x06, 0x47): - case CPUID(0x06, 0x4F): - case CPUID(0x06, 0x56): - // https://en.wikipedia.org/wiki/Broadwell_(microarchitecture) - return INTEL_BDW; - case CPUID(0x06, 0x4E): - case CPUID(0x06, 0x55): - case CPUID(0x06, 0x5E): - // https://en.wikipedia.org/wiki/Skylake_(microarchitecture) - return INTEL_SKL; - case CPUID(0x06, 0x66): - // https://en.wikipedia.org/wiki/Cannon_Lake_(microarchitecture) - return INTEL_CNL; - case CPUID(0x06, 0x7D): // client - case CPUID(0x06, 0x7E): // client - case CPUID(0x06, 0x9D): // NNP-I - case CPUID(0x06, 0x6A): // server - case CPUID(0x06, 0x6C): // server - // https://en.wikipedia.org/wiki/Ice_Lake_(microprocessor) - return INTEL_ICL; - case CPUID(0x06, 0x8C): - case CPUID(0x06, 0x8D): - // https://en.wikipedia.org/wiki/Tiger_Lake_(microarchitecture) - return INTEL_TGL; - case CPUID(0x06, 0x8F): - // https://en.wikipedia.org/wiki/Sapphire_Rapids - return INTEL_SPR; - case CPUID(0x06, 0x8E): - switch (info->stepping) { - case 9: - return INTEL_KBL; // https://en.wikipedia.org/wiki/Kaby_Lake - case 10: - return INTEL_CFL; // https://en.wikipedia.org/wiki/Coffee_Lake - case 11: - return INTEL_WHL; // https://en.wikipedia.org/wiki/Whiskey_Lake_(microarchitecture) - default: - return X86_UNKNOWN; - } - case CPUID(0x06, 0x9E): - if (info->stepping > 9) { - // https://en.wikipedia.org/wiki/Coffee_Lake - return INTEL_CFL; - } else { - // https://en.wikipedia.org/wiki/Kaby_Lake - return INTEL_KBL; - } - default: - return X86_UNKNOWN; - } - } - if (memcmp(info->vendor, "AuthenticAMD", sizeof(info->vendor)) == 0) { - switch (info->family) { - // https://en.wikipedia.org/wiki/List_of_AMD_CPU_microarchitectures - case 0x0F: - return AMD_HAMMER; - case 0x10: - return AMD_K10; - case 0x14: - return AMD_BOBCAT; - case 0x15: - return AMD_BULLDOZER; - case 0x16: - return AMD_JAGUAR; - case 0x17: - return AMD_ZEN; - default: - return X86_UNKNOWN; - } - } - return X86_UNKNOWN; -} - -static void SetString(const uint32_t max_cpuid_ext_leaf, const uint32_t leaf_id, - char* buffer) { - const Leaf leaf = SafeCpuId(max_cpuid_ext_leaf, leaf_id); - // We allow calling memcpy from SetString which is only called when requesting - // X86BrandString. - memcpy(buffer, &leaf, sizeof(Leaf)); -} - -void FillX86BrandString(char brand_string[49]) { - const Leaf leaf_ext_0 = CpuId(0x80000000); - const uint32_t max_cpuid_leaf_ext = leaf_ext_0.eax; - SetString(max_cpuid_leaf_ext, 0x80000002, brand_string); - SetString(max_cpuid_leaf_ext, 0x80000003, brand_string + 16); - SetString(max_cpuid_leaf_ext, 0x80000004, brand_string + 32); - brand_string[48] = '\0'; -} - -//////////////////////////////////////////////////////////////////////////////// -// Introspection functions - -int GetX86FeaturesEnumValue(const X86Features* features, - X86FeaturesEnum value) { - switch (value) { - case X86_FPU: - return features->fpu; - case X86_TSC: - return features->tsc; - case X86_CX8: - return features->cx8; - case X86_CLFSH: - return features->clfsh; - case X86_MMX: - return features->mmx; - case X86_AES: - return features->aes; - case X86_ERMS: - return features->erms; - case X86_F16C: - return features->f16c; - case X86_FMA4: - return features->fma4; - case X86_FMA3: - return features->fma3; - case X86_VAES: - return features->vaes; - case X86_VPCLMULQDQ: - return features->vpclmulqdq; - case X86_BMI1: - return features->bmi1; - case X86_HLE: - return features->hle; - case X86_BMI2: - return features->bmi2; - case X86_RTM: - return features->rtm; - case X86_RDSEED: - return features->rdseed; - case X86_CLFLUSHOPT: - return features->clflushopt; - case X86_CLWB: - return features->clwb; - case X86_SSE: - return features->sse; - case X86_SSE2: - return features->sse2; - case X86_SSE3: - return features->sse3; - case X86_SSSE3: - return features->ssse3; - case X86_SSE4_1: - return features->sse4_1; - case X86_SSE4_2: - return features->sse4_2; - case X86_SSE4A: - return features->sse4a; - case X86_AVX: - return features->avx; - case X86_AVX2: - return features->avx2; - case X86_AVX512F: - return features->avx512f; - case X86_AVX512CD: - return features->avx512cd; - case X86_AVX512ER: - return features->avx512er; - case X86_AVX512PF: - return features->avx512pf; - case X86_AVX512BW: - return features->avx512bw; - case X86_AVX512DQ: - return features->avx512dq; - case X86_AVX512VL: - return features->avx512vl; - case X86_AVX512IFMA: - return features->avx512ifma; - case X86_AVX512VBMI: - return features->avx512vbmi; - case X86_AVX512VBMI2: - return features->avx512vbmi2; - case X86_AVX512VNNI: - return features->avx512vnni; - case X86_AVX512BITALG: - return features->avx512bitalg; - case X86_AVX512VPOPCNTDQ: - return features->avx512vpopcntdq; - case X86_AVX512_4VNNIW: - return features->avx512_4vnniw; - case X86_AVX512_4VBMI2: - return features->avx512_4vbmi2; - case X86_AVX512_SECOND_FMA: - return features->avx512_second_fma; - case X86_AVX512_4FMAPS: - return features->avx512_4fmaps; - case X86_AVX512_BF16: - return features->avx512_bf16; - case X86_AVX512_VP2INTERSECT: - return features->avx512_vp2intersect; - case X86_AMX_BF16: - return features->amx_bf16; - case X86_AMX_TILE: - return features->amx_tile; - case X86_AMX_INT8: - return features->amx_int8; - case X86_PCLMULQDQ: - return features->pclmulqdq; - case X86_SMX: - return features->smx; - case X86_SGX: - return features->sgx; - case X86_CX16: - return features->cx16; - case X86_SHA: - return features->sha; - case X86_POPCNT: - return features->popcnt; - case X86_MOVBE: - return features->movbe; - case X86_RDRND: - return features->rdrnd; - case X86_DCA: - return features->dca; - case X86_SS: - return features->ss; - case X86_LAST_: - break; - } - return false; -} - -const char* GetX86FeaturesEnumName(X86FeaturesEnum value) { - switch (value) { - case X86_FPU: - return "fpu"; - case X86_TSC: - return "tsc"; - case X86_CX8: - return "cx8"; - case X86_CLFSH: - return "clfsh"; - case X86_MMX: - return "mmx"; - case X86_AES: - return "aes"; - case X86_ERMS: - return "erms"; - case X86_F16C: - return "f16c"; - case X86_FMA4: - return "fma4"; - case X86_FMA3: - return "fma3"; - case X86_VAES: - return "vaes"; - case X86_VPCLMULQDQ: - return "vpclmulqdq"; - case X86_BMI1: - return "bmi1"; - case X86_HLE: - return "hle"; - case X86_BMI2: - return "bmi2"; - case X86_RTM: - return "rtm"; - case X86_RDSEED: - return "rdseed"; - case X86_CLFLUSHOPT: - return "clflushopt"; - case X86_CLWB: - return "clwb"; - case X86_SSE: - return "sse"; - case X86_SSE2: - return "sse2"; - case X86_SSE3: - return "sse3"; - case X86_SSSE3: - return "ssse3"; - case X86_SSE4_1: - return "sse4_1"; - case X86_SSE4_2: - return "sse4_2"; - case X86_SSE4A: - return "sse4a"; - case X86_AVX: - return "avx"; - case X86_AVX2: - return "avx2"; - case X86_AVX512F: - return "avx512f"; - case X86_AVX512CD: - return "avx512cd"; - case X86_AVX512ER: - return "avx512er"; - case X86_AVX512PF: - return "avx512pf"; - case X86_AVX512BW: - return "avx512bw"; - case X86_AVX512DQ: - return "avx512dq"; - case X86_AVX512VL: - return "avx512vl"; - case X86_AVX512IFMA: - return "avx512ifma"; - case X86_AVX512VBMI: - return "avx512vbmi"; - case X86_AVX512VBMI2: - return "avx512vbmi2"; - case X86_AVX512VNNI: - return "avx512vnni"; - case X86_AVX512BITALG: - return "avx512bitalg"; - case X86_AVX512VPOPCNTDQ: - return "avx512vpopcntdq"; - case X86_AVX512_4VNNIW: - return "avx512_4vnniw"; - case X86_AVX512_4VBMI2: - return "avx512_4vbmi2"; - case X86_AVX512_SECOND_FMA: - return "avx512_second_fma"; - case X86_AVX512_4FMAPS: - return "avx512_4fmaps"; - case X86_AVX512_BF16: - return "avx512_bf16"; - case X86_AVX512_VP2INTERSECT: - return "avx512_vp2intersect"; - case X86_AMX_BF16: - return "amx_bf16"; - case X86_AMX_TILE: - return "amx_tile"; - case X86_AMX_INT8: - return "amx_int8"; - case X86_PCLMULQDQ: - return "pclmulqdq"; - case X86_SMX: - return "smx"; - case X86_SGX: - return "sgx"; - case X86_CX16: - return "cx16"; - case X86_SHA: - return "sha"; - case X86_POPCNT: - return "popcnt"; - case X86_MOVBE: - return "movbe"; - case X86_RDRND: - return "rdrnd"; - case X86_DCA: - return "dca"; - case X86_SS: - return "ss"; - case X86_LAST_: - break; - } - return "unknown_feature"; -} - -const char* GetX86MicroarchitectureName(X86Microarchitecture uarch) { - switch (uarch) { - case X86_UNKNOWN: - return "X86_UNKNOWN"; - case INTEL_CORE: - return "INTEL_CORE"; - case INTEL_PNR: - return "INTEL_PNR"; - case INTEL_NHM: - return "INTEL_NHM"; - case INTEL_ATOM_BNL: - return "INTEL_ATOM_BNL"; - case INTEL_WSM: - return "INTEL_WSM"; - case INTEL_SNB: - return "INTEL_SNB"; - case INTEL_IVB: - return "INTEL_IVB"; - case INTEL_ATOM_SMT: - return "INTEL_ATOM_SMT"; - case INTEL_HSW: - return "INTEL_HSW"; - case INTEL_BDW: - return "INTEL_BDW"; - case INTEL_SKL: - return "INTEL_SKL"; - case INTEL_ATOM_GMT: - return "INTEL_ATOM_GMT"; - case INTEL_KBL: - return "INTEL_KBL"; - case INTEL_CFL: - return "INTEL_CFL"; - case INTEL_WHL: - return "INTEL_WHL"; - case INTEL_CNL: - return "INTEL_CNL"; - case INTEL_ICL: - return "INTEL_ICL"; - case INTEL_TGL: - return "INTEL_TGL"; - case INTEL_SPR: - return "INTEL_SPR"; - case AMD_HAMMER: - return "AMD_HAMMER"; - case AMD_K10: - return "AMD_K10"; - case AMD_BOBCAT: - return "AMD_BOBCAT"; - case AMD_BULLDOZER: - return "AMD_BULLDOZER"; - case AMD_JAGUAR: - return "AMD_JAGUAR"; - case AMD_ZEN: - return "AMD_ZEN"; - } - return "unknown microarchitecture"; -} diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/filesystem.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/filesystem.c deleted file mode 100644 index 2f7083b..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/filesystem.c +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "internal/filesystem.h" - -#include -#include -#include -#include -#include - -#if defined(CPU_FEATURES_MOCK_FILESYSTEM) -// Implementation will be provided by test/filesystem_for_testing.cc. -#elif defined(_MSC_VER) -#include -int CpuFeatures_OpenFile(const char* filename) { - int fd = -1; - _sopen_s(&fd, filename, _O_RDONLY, _SH_DENYWR, _S_IREAD); - return fd; -} - -void CpuFeatures_CloseFile(int file_descriptor) { _close(file_descriptor); } - -int CpuFeatures_ReadFile(int file_descriptor, void* buffer, - size_t buffer_size) { - return _read(file_descriptor, buffer, (unsigned int)buffer_size); -} - -#else -#include - -int CpuFeatures_OpenFile(const char* filename) { - int result; - do { - result = open(filename, O_RDONLY); - } while (result == -1L && errno == EINTR); - return result; -} - -void CpuFeatures_CloseFile(int file_descriptor) { close(file_descriptor); } - -int CpuFeatures_ReadFile(int file_descriptor, void* buffer, - size_t buffer_size) { - int result; - do { - result = read(file_descriptor, buffer, buffer_size); - } while (result == -1L && errno == EINTR); - return result; -} - -#endif diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c deleted file mode 100644 index 920e2f3..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "internal/hwcaps.h" - -#include -#include - -#include "cpu_features_macros.h" -#include "internal/filesystem.h" -#include "internal/string_view.h" - -#if defined(NDEBUG) -#define D(...) -#else -#include -#define D(...) \ - do { \ - printf(__VA_ARGS__); \ - fflush(stdout); \ - } while (0) -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Implementation of GetElfHwcapFromGetauxval -//////////////////////////////////////////////////////////////////////////////// - -#if defined(CPU_FEATURES_MOCK_GET_ELF_HWCAP_FROM_GETAUXVAL) -// Implementation will be provided by test/hwcaps_for_testing.cc. -#elif defined(HAVE_STRONG_GETAUXVAL) -#include -static unsigned long GetElfHwcapFromGetauxval(uint32_t hwcap_type) { - return getauxval(hwcap_type); -} -#elif defined(HAVE_DLFCN_H) -// On Android we probe the system's C library for a 'getauxval' function and -// call it if it exits, or return 0 for failure. This function is available -// since API level 20. -// -// This code does *NOT* check for '__ANDROID_API__ >= 20' to support the edge -// case where some NDK developers use headers for a platform that is newer than -// the one really targetted by their application. This is typically done to use -// newer native APIs only when running on more recent Android versions, and -// requires careful symbol management. -// -// Note that getauxval() can't really be re-implemented here, because its -// implementation does not parse /proc/self/auxv. Instead it depends on values -// that are passed by the kernel at process-init time to the C runtime -// initialization layer. - -#include -#define AT_HWCAP 16 -#define AT_HWCAP2 26 -#define AT_PLATFORM 15 -#define AT_BASE_PLATFORM 24 - -typedef unsigned long getauxval_func_t(unsigned long); - -static uint32_t GetElfHwcapFromGetauxval(uint32_t hwcap_type) { - uint32_t ret = 0; - void *libc_handle = NULL; - getauxval_func_t *func = NULL; - - dlerror(); // Cleaning error state before calling dlopen. - libc_handle = dlopen("libc.so", RTLD_NOW); - if (!libc_handle) { - D("Could not dlopen() C library: %s\n", dlerror()); - return 0; - } - func = (getauxval_func_t *)dlsym(libc_handle, "getauxval"); - if (!func) { - D("Could not find getauxval() in C library\n"); - } else { - // Note: getauxval() returns 0 on failure. Doesn't touch errno. - ret = (uint32_t)(*func)(hwcap_type); - } - dlclose(libc_handle); - return ret; -} -#else -#error "This platform does not provide hardware capabilities." -#endif - -// Implementation of GetHardwareCapabilities for OS that provide -// GetElfHwcapFromGetauxval(). - -// Fallback when getauxval is not available, retrieves hwcaps from -// "/proc/self/auxv". -static uint32_t GetElfHwcapFromProcSelfAuxv(uint32_t hwcap_type) { - struct { - uint32_t tag; - uint32_t value; - } entry; - uint32_t result = 0; - const char filepath[] = "/proc/self/auxv"; - const int fd = CpuFeatures_OpenFile(filepath); - if (fd < 0) { - D("Could not open %s\n", filepath); - return 0; - } - for (;;) { - const int ret = CpuFeatures_ReadFile(fd, (char *)&entry, sizeof entry); - if (ret < 0) { - D("Error while reading %s\n", filepath); - break; - } - // Detect end of list. - if (ret == 0 || (entry.tag == 0 && entry.value == 0)) { - break; - } - if (entry.tag == hwcap_type) { - result = entry.value; - break; - } - } - CpuFeatures_CloseFile(fd); - return result; -} - -// Retrieves hardware capabilities by first trying to call getauxval, if not -// available falls back to reading "/proc/self/auxv". -static unsigned long GetHardwareCapabilitiesFor(uint32_t type) { - unsigned long hwcaps = GetElfHwcapFromGetauxval(type); - if (!hwcaps) { - D("Parsing /proc/self/auxv to extract ELF hwcaps!\n"); - hwcaps = GetElfHwcapFromProcSelfAuxv(type); - } - return hwcaps; -} - -HardwareCapabilities CpuFeatures_GetHardwareCapabilities(void) { - HardwareCapabilities capabilities; - capabilities.hwcaps = GetHardwareCapabilitiesFor(AT_HWCAP); - capabilities.hwcaps2 = GetHardwareCapabilitiesFor(AT_HWCAP2); - return capabilities; -} - -PlatformType kEmptyPlatformType; - -PlatformType CpuFeatures_GetPlatformType(void) { - PlatformType type = kEmptyPlatformType; - char *platform = (char *)GetHardwareCapabilitiesFor(AT_PLATFORM); - char *base_platform = (char *)GetHardwareCapabilitiesFor(AT_BASE_PLATFORM); - - if (platform != NULL) - CpuFeatures_StringView_CopyString(str(platform), type.platform, - sizeof(type.platform)); - if (base_platform != NULL) - CpuFeatures_StringView_CopyString(str(base_platform), type.base_platform, - sizeof(type.base_platform)); - return type; -} diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c deleted file mode 100644 index dd29781..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "internal/stack_line_reader.h" - -#include -#include -#include - -#include "internal/filesystem.h" - -void StackLineReader_Initialize(StackLineReader* reader, int fd) { - reader->view.ptr = reader->buffer; - reader->view.size = 0; - reader->skip_mode = false; - reader->fd = fd; -} - -// Replaces the content of buffer with bytes from the file. -static int LoadFullBuffer(StackLineReader* reader) { - const int read = CpuFeatures_ReadFile(reader->fd, reader->buffer, - STACK_LINE_READER_BUFFER_SIZE); - assert(read >= 0); - reader->view.ptr = reader->buffer; - reader->view.size = read; - return read; -} - -// Appends with bytes from the file to buffer, filling the remaining space. -static int LoadMore(StackLineReader* reader) { - char* const ptr = reader->buffer + reader->view.size; - const size_t size_to_read = STACK_LINE_READER_BUFFER_SIZE - reader->view.size; - const int read = CpuFeatures_ReadFile(reader->fd, ptr, size_to_read); - assert(read >= 0); - assert(read <= (int)size_to_read); - reader->view.size += read; - return read; -} - -static int IndexOfEol(StackLineReader* reader) { - return CpuFeatures_StringView_IndexOfChar(reader->view, '\n'); -} - -// Relocate buffer's pending bytes at the beginning of the array and fills the -// remaining space with bytes from the file. -static int BringToFrontAndLoadMore(StackLineReader* reader) { - if (reader->view.size && reader->view.ptr != reader->buffer) { - memmove(reader->buffer, reader->view.ptr, reader->view.size); - } - reader->view.ptr = reader->buffer; - return LoadMore(reader); -} - -// Loads chunks of buffer size from disks until it contains a newline character -// or end of file. -static void SkipToNextLine(StackLineReader* reader) { - for (;;) { - const int read = LoadFullBuffer(reader); - if (read == 0) { - break; - } else { - const int eol_index = IndexOfEol(reader); - if (eol_index >= 0) { - reader->view = - CpuFeatures_StringView_PopFront(reader->view, eol_index + 1); - break; - } - } - } -} - -static LineResult CreateLineResult(bool eof, bool full_line, StringView view) { - LineResult result; - result.eof = eof; - result.full_line = full_line; - result.line = view; - return result; -} - -// Helper methods to provide clearer semantic in StackLineReader_NextLine. -static LineResult CreateEOFLineResult(StringView view) { - return CreateLineResult(true, true, view); -} - -static LineResult CreateTruncatedLineResult(StringView view) { - return CreateLineResult(false, false, view); -} - -static LineResult CreateValidLineResult(StringView view) { - return CreateLineResult(false, true, view); -} - -LineResult StackLineReader_NextLine(StackLineReader* reader) { - if (reader->skip_mode) { - SkipToNextLine(reader); - reader->skip_mode = false; - } - { - const bool can_load_more = - reader->view.size < STACK_LINE_READER_BUFFER_SIZE; - int eol_index = IndexOfEol(reader); - if (eol_index < 0 && can_load_more) { - const int read = BringToFrontAndLoadMore(reader); - if (read == 0) { - return CreateEOFLineResult(reader->view); - } - eol_index = IndexOfEol(reader); - } - if (eol_index < 0) { - reader->skip_mode = true; - return CreateTruncatedLineResult(reader->view); - } - { - StringView line = - CpuFeatures_StringView_KeepFront(reader->view, eol_index); - reader->view = - CpuFeatures_StringView_PopFront(reader->view, eol_index + 1); - return CreateValidLineResult(line); - } - } -} diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/string_view.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/string_view.c deleted file mode 100644 index 856731c..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/string_view.c +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "internal/string_view.h" - -#include -#include -#include - -int CpuFeatures_StringView_IndexOfChar(const StringView view, char c) { - if (view.ptr && view.size) { - const char* const found = (const char*)memchr(view.ptr, c, view.size); - if (found) { - return (int)(found - view.ptr); - } - } - return -1; -} - -int CpuFeatures_StringView_IndexOf(const StringView view, - const StringView sub_view) { - if (sub_view.size) { - StringView remainder = view; - while (remainder.size >= sub_view.size) { - const int found_index = - CpuFeatures_StringView_IndexOfChar(remainder, sub_view.ptr[0]); - if (found_index < 0) break; - remainder = CpuFeatures_StringView_PopFront(remainder, found_index); - if (CpuFeatures_StringView_StartsWith(remainder, sub_view)) { - return (int)(remainder.ptr - view.ptr); - } - remainder = CpuFeatures_StringView_PopFront(remainder, 1); - } - } - return -1; -} - -bool CpuFeatures_StringView_IsEquals(const StringView a, const StringView b) { - if (a.size == b.size) { - return a.ptr == b.ptr || memcmp(a.ptr, b.ptr, b.size) == 0; - } - return false; -} - -bool CpuFeatures_StringView_StartsWith(const StringView a, const StringView b) { - return a.ptr && b.ptr && b.size && a.size >= b.size - ? memcmp(a.ptr, b.ptr, b.size) == 0 - : false; -} - -StringView CpuFeatures_StringView_PopFront(const StringView str_view, - size_t count) { - if (count > str_view.size) { - return kEmptyStringView; - } - return view(str_view.ptr + count, str_view.size - count); -} - -StringView CpuFeatures_StringView_PopBack(const StringView str_view, - size_t count) { - if (count > str_view.size) { - return kEmptyStringView; - } - return view(str_view.ptr, str_view.size - count); -} - -StringView CpuFeatures_StringView_KeepFront(const StringView str_view, - size_t count) { - return count <= str_view.size ? view(str_view.ptr, count) : str_view; -} - -char CpuFeatures_StringView_Front(const StringView view) { - assert(view.size); - assert(view.ptr); - return view.ptr[0]; -} - -char CpuFeatures_StringView_Back(const StringView view) { - assert(view.size); - return view.ptr[view.size - 1]; -} - -StringView CpuFeatures_StringView_TrimWhitespace(StringView view) { - while (view.size && isspace(CpuFeatures_StringView_Front(view))) - view = CpuFeatures_StringView_PopFront(view, 1); - while (view.size && isspace(CpuFeatures_StringView_Back(view))) - view = CpuFeatures_StringView_PopBack(view, 1); - return view; -} - -static int HexValue(const char c) { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'a' && c <= 'f') return c - 'a' + 10; - if (c >= 'A' && c <= 'F') return c - 'A' + 10; - return -1; -} - -// Returns -1 if view contains non digits. -static int ParsePositiveNumberWithBase(const StringView view, int base) { - int result = 0; - StringView remainder = view; - for (; remainder.size; - remainder = CpuFeatures_StringView_PopFront(remainder, 1)) { - const int value = HexValue(CpuFeatures_StringView_Front(remainder)); - if (value < 0 || value >= base) return -1; - result = (result * base) + value; - } - return result; -} - -int CpuFeatures_StringView_ParsePositiveNumber(const StringView view) { - if (view.size) { - const StringView hex_prefix = str("0x"); - if (CpuFeatures_StringView_StartsWith(view, hex_prefix)) { - const StringView span_no_prefix = - CpuFeatures_StringView_PopFront(view, hex_prefix.size); - return ParsePositiveNumberWithBase(span_no_prefix, 16); - } - return ParsePositiveNumberWithBase(view, 10); - } - return -1; -} - -void CpuFeatures_StringView_CopyString(const StringView src, char* dst, - size_t dst_size) { - if (dst_size > 0) { - const size_t max_copy_size = dst_size - 1; - const size_t copy_size = - src.size > max_copy_size ? max_copy_size : src.size; - memcpy(dst, src.ptr, copy_size); - dst[copy_size] = '\0'; - } -} - -bool CpuFeatures_StringView_HasWord(const StringView line, - const char* const word_str) { - const StringView word = str(word_str); - StringView remainder = line; - for (;;) { - const int index_of_word = CpuFeatures_StringView_IndexOf(remainder, word); - if (index_of_word < 0) { - return false; - } else { - const StringView before = - CpuFeatures_StringView_KeepFront(line, index_of_word); - const StringView after = - CpuFeatures_StringView_PopFront(line, index_of_word + word.size); - const bool valid_before = - before.size == 0 || CpuFeatures_StringView_Back(before) == ' '; - const bool valid_after = - after.size == 0 || CpuFeatures_StringView_Front(after) == ' '; - if (valid_before && valid_after) return true; - remainder = - CpuFeatures_StringView_PopFront(remainder, index_of_word + word.size); - } - } - return false; -} - -bool CpuFeatures_StringView_GetAttributeKeyValue(const StringView line, - StringView* key, - StringView* value) { - const StringView sep = str(": "); - const int index_of_separator = CpuFeatures_StringView_IndexOf(line, sep); - if (index_of_separator < 0) return false; - *value = CpuFeatures_StringView_TrimWhitespace( - CpuFeatures_StringView_PopFront(line, index_of_separator + sep.size)); - *key = CpuFeatures_StringView_TrimWhitespace( - CpuFeatures_StringView_KeepFront(line, index_of_separator)); - return true; -} diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/unix_features_aggregator.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/unix_features_aggregator.c deleted file mode 100644 index 2f51ae4..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/unix_features_aggregator.c +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "internal/unix_features_aggregator.h" - -#include "internal/string_view.h" - -void CpuFeatures_SetFromFlags(const size_t configs_size, - const CapabilityConfig* configs, - const StringView flags_line, - void* const features) { - size_t i = 0; - for (; i < configs_size; ++i) { - const CapabilityConfig config = configs[i]; - config.set_bit(features, CpuFeatures_StringView_HasWord( - flags_line, config.proc_cpuinfo_flag)); - } -} - -static bool IsSet(const uint32_t mask, const uint32_t value) { - if (mask == 0) return false; - return (value & mask) == mask; -} - -static bool IsHwCapsSet(const HardwareCapabilities hwcaps_mask, - const HardwareCapabilities hwcaps) { - return IsSet(hwcaps_mask.hwcaps, hwcaps.hwcaps) || - IsSet(hwcaps_mask.hwcaps2, hwcaps.hwcaps2); -} - -void CpuFeatures_OverrideFromHwCaps(const size_t configs_size, - const CapabilityConfig* configs, - const HardwareCapabilities hwcaps, - void* const features) { - size_t i = 0; - for (; i < configs_size; ++i) { - const CapabilityConfig* config = &configs[i]; - if (IsHwCapsSet(config->hwcaps_mask, hwcaps)) { - config->set_bit(features, true); - } - } -} diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c deleted file mode 100644 index 0783648..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c +++ /dev/null @@ -1,438 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// This program dumps current host data to the standard output. -// Output can be text or json if the `--json` flag is passed. - -#include -#include -#include -#include -#include -#include -#include - -#include "cpu_features_macros.h" - -#if defined(CPU_FEATURES_ARCH_X86) -#include "cpuinfo_x86.h" -#elif defined(CPU_FEATURES_ARCH_ARM) -#include "cpuinfo_arm.h" -#elif defined(CPU_FEATURES_ARCH_AARCH64) -#include "cpuinfo_aarch64.h" -#elif defined(CPU_FEATURES_ARCH_MIPS) -#include "cpuinfo_mips.h" -#elif defined(CPU_FEATURES_ARCH_PPC) -#include "cpuinfo_ppc.h" -#endif - -// Design principles -// ----------------- -// We build a tree structure containing all the data to be displayed. -// Then depending on the output type (text or json) we walk the tree and display -// the data accordingly. - -// We use a bump allocator to allocate strings and nodes of the tree, -// Memory is not intented to be reclaimed. -typedef struct { - char* ptr; - size_t size; -} BumpAllocator; - -char gGlobalBuffer[64 * 1024]; -BumpAllocator gBumpAllocator = {.ptr = gGlobalBuffer, - .size = sizeof(gGlobalBuffer)}; - -static void internal_error() { - fputs("internal error\n", stderr); - exit(EXIT_FAILURE); -} - -#define ALIGN 8 - -static void assertAligned() { - if ((uintptr_t)(gBumpAllocator.ptr) % ALIGN) internal_error(); -} - -static void BA_Align() { - while (gBumpAllocator.size && (uintptr_t)(gBumpAllocator.ptr) % ALIGN) { - --gBumpAllocator.size; - ++gBumpAllocator.ptr; - } - assertAligned(); -} - -// Update the available memory left in the BumpAllocator. -static void* BA_Bump(size_t size) { - assertAligned(); - // Align size to next 8B boundary. - size = (size + ALIGN - 1) / ALIGN * ALIGN; - if (gBumpAllocator.size < size) internal_error(); - void* ptr = gBumpAllocator.ptr; - gBumpAllocator.size -= size; - gBumpAllocator.ptr += size; - return ptr; -} - -// The type of the nodes in the tree. -typedef enum { - NT_INVALID, - NT_INT, - NT_MAP, - NT_MAP_ENTRY, - NT_ARRAY, - NT_ARRAY_ELEMENT, - NT_STRING, -} NodeType; - -// The node in the tree. -typedef struct Node { - NodeType type; - unsigned integer; - const char* string; - struct Node* value; - struct Node* next; -} Node; - -// Creates an initialized Node. -static Node* BA_CreateNode(NodeType type) { - Node* tv = (Node*)BA_Bump(sizeof(Node)); - assert(tv); - *tv = (Node){.type = type}; - return tv; -} - -// Adds an integer node. -static Node* CreateInt(int value) { - Node* tv = BA_CreateNode(NT_INT); - tv->integer = value; - return tv; -} - -// Adds a string node. -// `value` must outlive the tree. -static Node* CreateConstantString(const char* value) { - Node* tv = BA_CreateNode(NT_STRING); - tv->string = value; - return tv; -} - -// Adds a map node. -static Node* CreateMap() { return BA_CreateNode(NT_MAP); } - -// Adds an array node. -static Node* CreateArray() { return BA_CreateNode(NT_ARRAY); } - -// Adds a formatted string node. -static Node* CreatePrintfString(const char* format, ...) { - va_list arglist; - va_start(arglist, format); - char* const ptr = gBumpAllocator.ptr; - const int written = vsnprintf(ptr, gBumpAllocator.size, format, arglist); - va_end(arglist); - if (written < 0 || written >= (int)gBumpAllocator.size) internal_error(); - return CreateConstantString((char*)BA_Bump(written)); -} - -// Adds a string node. -static Node* CreateString(const char* value) { - return CreatePrintfString("%s", value); -} - -// Adds a map entry node. -static void AddMapEntry(Node* map, const char* key, Node* value) { - assert(map && map->type == NT_MAP); - Node* current = map; - while (current->next) current = current->next; - current->next = (Node*)BA_Bump(sizeof(Node)); - *current->next = (Node){.type = NT_MAP_ENTRY, .string = key, .value = value}; -} - -// Adds an array element node. -static void AddArrayElement(Node* array, Node* value) { - assert(array && array->type == NT_ARRAY); - Node* current = array; - while (current->next) current = current->next; - current->next = (Node*)BA_Bump(sizeof(Node)); - *current->next = (Node){.type = NT_ARRAY_ELEMENT, .value = value}; -} - -static int cmp(const void* p1, const void* p2) { - return strcmp(*(const char* const*)p1, *(const char* const*)p2); -} - -#define DEFINE_ADD_FLAGS(HasFeature, FeatureName, FeatureType, LastEnum) \ - static void AddFlags(Node* map, const FeatureType* features) { \ - size_t i; \ - const char* ptrs[LastEnum] = {0}; \ - size_t count = 0; \ - for (i = 0; i < LastEnum; ++i) { \ - if (HasFeature(features, i)) { \ - ptrs[count] = FeatureName(i); \ - ++count; \ - } \ - } \ - qsort((void*)ptrs, count, sizeof(char*), cmp); \ - Node* const array = CreateArray(); \ - for (i = 0; i < count; ++i) \ - AddArrayElement(array, CreateConstantString(ptrs[i])); \ - AddMapEntry(map, "flags", array); \ - } - -#if defined(CPU_FEATURES_ARCH_X86) -DEFINE_ADD_FLAGS(GetX86FeaturesEnumValue, GetX86FeaturesEnumName, X86Features, - X86_LAST_) -#elif defined(CPU_FEATURES_ARCH_ARM) -DEFINE_ADD_FLAGS(GetArmFeaturesEnumValue, GetArmFeaturesEnumName, ArmFeatures, - ARM_LAST_) -#elif defined(CPU_FEATURES_ARCH_AARCH64) -DEFINE_ADD_FLAGS(GetAarch64FeaturesEnumValue, GetAarch64FeaturesEnumName, - Aarch64Features, AARCH64_LAST_) -#elif defined(CPU_FEATURES_ARCH_MIPS) -DEFINE_ADD_FLAGS(GetMipsFeaturesEnumValue, GetMipsFeaturesEnumName, - MipsFeatures, MIPS_LAST_) -#elif defined(CPU_FEATURES_ARCH_PPC) -DEFINE_ADD_FLAGS(GetPPCFeaturesEnumValue, GetPPCFeaturesEnumName, PPCFeatures, - PPC_LAST_) -#endif - -// Prints a json string with characters escaping. -static void printJsonString(const char* str) { - putchar('"'); - for (; str && *str; ++str) { - switch (*str) { - case '\"': - case '\\': - case '/': - case '\b': - case '\f': - case '\n': - case '\r': - case '\t': - putchar('\\'); - } - putchar(*str); - } - putchar('"'); -} - -// Walks a Node and print it as json. -static void printJson(const Node* current) { - assert(current); - switch (current->type) { - case NT_INVALID: - break; - case NT_INT: - printf("%d", current->integer); - break; - case NT_STRING: - printJsonString(current->string); - break; - case NT_ARRAY: - putchar('['); - if (current->next) printJson(current->next); - putchar(']'); - break; - case NT_MAP: - putchar('{'); - if (current->next) printJson(current->next); - putchar('}'); - break; - case NT_MAP_ENTRY: - printf("\"%s\":", current->string); - printJson(current->value); - if (current->next) { - putchar(','); - printJson(current->next); - } - break; - case NT_ARRAY_ELEMENT: - printJson(current->value); - if (current->next) { - putchar(','); - printJson(current->next); - } - break; - } -} - -// Walks a Node and print it as text. -static void printTextField(const Node* current) { - switch (current->type) { - case NT_INVALID: - break; - case NT_INT: - printf("%3d (0x%02X)", current->integer, current->integer); - break; - case NT_STRING: - fputs(current->string, stdout); - break; - case NT_ARRAY: - if (current->next) printTextField(current->next); - break; - case NT_MAP: - if (current->next) { - printf("{"); - printJson(current->next); - printf("}"); - } - break; - case NT_MAP_ENTRY: - printf("%-15s : ", current->string); - printTextField(current->value); - if (current->next) { - putchar('\n'); - printTextField(current->next); - } - break; - case NT_ARRAY_ELEMENT: - printTextField(current->value); - if (current->next) { - putchar(','); - printTextField(current->next); - } - break; - } -} - -static void printTextRoot(const Node* current) { - if (current->type == NT_MAP && current->next) printTextField(current->next); -} - -static void showUsage(const char* name) { - printf( - "\n" - "Usage: %s [options]\n" - " Options:\n" - " -h | --help Show help message.\n" - " -j | --json Format output as json instead of plain text.\n" - "\n", - name); -} - -static Node* GetCacheTypeString(CacheType cache_type) { - switch (cache_type) { - case CPU_FEATURE_CACHE_NULL: - return CreateConstantString("null"); - case CPU_FEATURE_CACHE_DATA: - return CreateConstantString("data"); - case CPU_FEATURE_CACHE_INSTRUCTION: - return CreateConstantString("instruction"); - case CPU_FEATURE_CACHE_UNIFIED: - return CreateConstantString("unified"); - case CPU_FEATURE_CACHE_TLB: - return CreateConstantString("tlb"); - case CPU_FEATURE_CACHE_DTLB: - return CreateConstantString("dtlb"); - case CPU_FEATURE_CACHE_STLB: - return CreateConstantString("stlb"); - case CPU_FEATURE_CACHE_PREFETCH: - return CreateConstantString("prefetch"); - } -} - -static void AddCacheInfo(Node* root, const CacheInfo* cache_info) { - Node* array = CreateArray(); - for (int i = 0; i < cache_info->size; ++i) { - CacheLevelInfo info = cache_info->levels[i]; - Node* map = CreateMap(); - AddMapEntry(map, "level", CreateInt(info.level)); - AddMapEntry(map, "cache_type", GetCacheTypeString(info.cache_type)); - AddMapEntry(map, "cache_size", CreateInt(info.cache_size)); - AddMapEntry(map, "ways", CreateInt(info.ways)); - AddMapEntry(map, "line_size", CreateInt(info.line_size)); - AddMapEntry(map, "tlb_entries", CreateInt(info.tlb_entries)); - AddMapEntry(map, "partitioning", CreateInt(info.partitioning)); - AddArrayElement(array, map); - } - AddMapEntry(root, "cache_info", array); -} - -static Node* CreateTree() { - Node* root = CreateMap(); -#if defined(CPU_FEATURES_ARCH_X86) - char brand_string[49]; - const X86Info info = GetX86Info(); - const CacheInfo cache_info = GetX86CacheInfo(); - FillX86BrandString(brand_string); - AddMapEntry(root, "arch", CreateString("x86")); - AddMapEntry(root, "brand", CreateString(brand_string)); - AddMapEntry(root, "family", CreateInt(info.family)); - AddMapEntry(root, "model", CreateInt(info.model)); - AddMapEntry(root, "stepping", CreateInt(info.stepping)); - AddMapEntry(root, "uarch", - CreateString( - GetX86MicroarchitectureName(GetX86Microarchitecture(&info)))); - AddFlags(root, &info.features); - AddCacheInfo(root, &cache_info); -#elif defined(CPU_FEATURES_ARCH_ARM) - const ArmInfo info = GetArmInfo(); - AddMapEntry(root, "arch", CreateString("ARM")); - AddMapEntry(root, "implementer", CreateInt(info.implementer)); - AddMapEntry(root, "architecture", CreateInt(info.architecture)); - AddMapEntry(root, "variant", CreateInt(info.variant)); - AddMapEntry(root, "part", CreateInt(info.part)); - AddMapEntry(root, "revision", CreateInt(info.revision)); - AddFlags(root, &info.features); -#elif defined(CPU_FEATURES_ARCH_AARCH64) - const Aarch64Info info = GetAarch64Info(); - AddMapEntry(root, "arch", CreateString("aarch64")); - AddMapEntry(root, "implementer", CreateInt(info.implementer)); - AddMapEntry(root, "variant", CreateInt(info.variant)); - AddMapEntry(root, "part", CreateInt(info.part)); - AddMapEntry(root, "revision", CreateInt(info.revision)); - AddFlags(root, &info.features); -#elif defined(CPU_FEATURES_ARCH_MIPS) - const MipsInfo info = GetMipsInfo(); - AddMapEntry(root, "arch", CreateString("mips")); - AddFlags(root, &info.features); -#elif defined(CPU_FEATURES_ARCH_PPC) - const PPCInfo info = GetPPCInfo(); - const PPCPlatformStrings strings = GetPPCPlatformStrings(); - AddMapEntry(root, "arch", CreateString("ppc")); - AddMapEntry(root, "platform", CreateString(strings.platform)); - AddMapEntry(root, "model", CreateString(strings.model)); - AddMapEntry(root, "machine", CreateString(strings.machine)); - AddMapEntry(root, "cpu", CreateString(strings.cpu)); - AddMapEntry(root, "instruction", CreateString(strings.type.platform)); - AddMapEntry(root, "microarchitecture", - CreateString(strings.type.base_platform)); - AddFlags(root, &info.features); -#endif - return root; -} - -int main(int argc, char** argv) { - BA_Align(); - const Node* const root = CreateTree(); - bool outputJson = false; - int i = 1; - for (; i < argc; ++i) { - const char* arg = argv[i]; - if (strcmp(arg, "-j") == 0 || strcmp(arg, "--json") == 0) { - outputJson = true; - } else { - showUsage(argv[0]); - if (strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0) - return EXIT_SUCCESS; - return EXIT_FAILURE; - } - } - if (outputJson) - printJson(root); - else - printTextRoot(root); - putchar('\n'); - return EXIT_SUCCESS; -} diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt deleted file mode 100644 index eb67ac0..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt +++ /dev/null @@ -1,88 +0,0 @@ -# -# libraries for tests -# - -include_directories(../include) -add_definitions(-DCPU_FEATURES_TEST) - -##------------------------------------------------------------------------------ -add_library(string_view ../src/string_view.c) -##------------------------------------------------------------------------------ -add_library(filesystem_for_testing filesystem_for_testing.cc) -target_compile_definitions(filesystem_for_testing PUBLIC CPU_FEATURES_MOCK_FILESYSTEM) -##------------------------------------------------------------------------------ -add_library(hwcaps_for_testing hwcaps_for_testing.cc) -target_compile_definitions(hwcaps_for_testing PUBLIC CPU_FEATURES_MOCK_GET_ELF_HWCAP_FROM_GETAUXVAL) -target_link_libraries(hwcaps_for_testing filesystem_for_testing) -##------------------------------------------------------------------------------ -add_library(stack_line_reader ../src/stack_line_reader.c) -target_compile_definitions(stack_line_reader PUBLIC STACK_LINE_READER_BUFFER_SIZE=1024) -target_link_libraries(stack_line_reader string_view) -##------------------------------------------------------------------------------ -add_library(stack_line_reader_for_test ../src/stack_line_reader.c) -target_compile_definitions(stack_line_reader_for_test PUBLIC STACK_LINE_READER_BUFFER_SIZE=16) -target_link_libraries(stack_line_reader_for_test string_view filesystem_for_testing) -##------------------------------------------------------------------------------ -add_library(all_libraries ../src/stack_line_reader.c ../src/unix_features_aggregator.c) -target_link_libraries(all_libraries hwcaps_for_testing stack_line_reader string_view) - -# -# tests -# -link_libraries(gtest gmock_main) - -## bit_utils_test -add_executable(bit_utils_test bit_utils_test.cc) -target_link_libraries(bit_utils_test) -add_test(NAME bit_utils_test COMMAND bit_utils_test) -##------------------------------------------------------------------------------ -## string_view_test -add_executable(string_view_test string_view_test.cc ../src/string_view.c) -target_link_libraries(string_view_test string_view) -add_test(NAME string_view_test COMMAND string_view_test) -##------------------------------------------------------------------------------ -## stack_line_reader_test -add_executable(stack_line_reader_test stack_line_reader_test.cc) -target_link_libraries(stack_line_reader_test stack_line_reader_for_test) -add_test(NAME stack_line_reader_test COMMAND stack_line_reader_test) -##------------------------------------------------------------------------------ -## unix_features_aggregator_test -add_executable(unix_features_aggregator_test unix_features_aggregator_test.cc) -target_link_libraries(unix_features_aggregator_test all_libraries) -add_test(NAME unix_features_aggregator_test COMMAND unix_features_aggregator_test) -##------------------------------------------------------------------------------ -## cpuinfo_x86_test -if(PROCESSOR_IS_X86) - add_executable(cpuinfo_x86_test cpuinfo_x86_test.cc ../src/cpuinfo_x86.c) - target_compile_definitions(cpuinfo_x86_test PUBLIC CPU_FEATURES_MOCK_CPUID_X86) - target_link_libraries(cpuinfo_x86_test all_libraries) - add_test(NAME cpuinfo_x86_test COMMAND cpuinfo_x86_test) -endif() -##------------------------------------------------------------------------------ -## cpuinfo_arm_test -if(PROCESSOR_IS_ARM) - add_executable(cpuinfo_arm_test cpuinfo_arm_test.cc ../src/cpuinfo_arm.c) - target_link_libraries(cpuinfo_arm_test all_libraries) - add_test(NAME cpuinfo_arm_test COMMAND cpuinfo_arm_test) -endif() -##------------------------------------------------------------------------------ -## cpuinfo_aarch64_test -if(PROCESSOR_IS_AARCH64) - add_executable(cpuinfo_aarch64_test cpuinfo_aarch64_test.cc ../src/cpuinfo_aarch64.c) - target_link_libraries(cpuinfo_aarch64_test all_libraries) - add_test(NAME cpuinfo_aarch64_test COMMAND cpuinfo_aarch64_test) -endif() -##------------------------------------------------------------------------------ -## cpuinfo_mips_test -if(PROCESSOR_IS_MIPS) - add_executable(cpuinfo_mips_test cpuinfo_mips_test.cc ../src/cpuinfo_mips.c) - target_link_libraries(cpuinfo_mips_test all_libraries) - add_test(NAME cpuinfo_mips_test COMMAND cpuinfo_mips_test) -endif() -##------------------------------------------------------------------------------ -## cpuinfo_ppc_test -if(PROCESSOR_IS_POWER) - add_executable(cpuinfo_ppc_test cpuinfo_ppc_test.cc ../src/cpuinfo_ppc.c) - target_link_libraries(cpuinfo_ppc_test all_libraries) - add_test(NAME cpuinfo_ppc_test COMMAND cpuinfo_ppc_test) -endif() diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc deleted file mode 100644 index 9c8c1bb..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "internal/bit_utils.h" - -#include "gtest/gtest.h" - -namespace cpu_features { -namespace { - -TEST(UtilsTest, IsBitSet) { - for (size_t bit_set = 0; bit_set < 32; ++bit_set) { - const uint32_t value = 1UL << bit_set; - for (uint32_t i = 0; i < 32; ++i) { - EXPECT_EQ(IsBitSet(value, i), i == bit_set); - } - } - - // testing 0, all bits should be 0. - for (uint32_t i = 0; i < 32; ++i) { - EXPECT_FALSE(IsBitSet(0, i)); - } - - // testing ~0, all bits should be 1. - for (uint32_t i = 0; i < 32; ++i) { - EXPECT_TRUE(IsBitSet(-1, i)); - } -} - -TEST(UtilsTest, ExtractBitRange) { - // Extracting all bits gives the same number. - EXPECT_EQ(ExtractBitRange(123, 31, 0), 123); - // Extracting 1 bit gives parity. - EXPECT_EQ(ExtractBitRange(123, 0, 0), 1); - EXPECT_EQ(ExtractBitRange(122, 0, 0), 0); - - EXPECT_EQ(ExtractBitRange(0xF0, 7, 4), 0xF); - EXPECT_EQ(ExtractBitRange(0x42 << 2, 10, 2), 0x42); -} - -} // namespace -} // namespace cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc deleted file mode 100644 index 10e037a..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "cpuinfo_aarch64.h" - -#include "filesystem_for_testing.h" -#include "gtest/gtest.h" -#include "hwcaps_for_testing.h" - -namespace cpu_features { -namespace { - -void DisableHardwareCapabilities() { SetHardwareCapabilities(0, 0); } - -TEST(CpuinfoAarch64Test, FromHardwareCap) { - SetHardwareCapabilities(AARCH64_HWCAP_FP | AARCH64_HWCAP_AES, 0); - GetEmptyFilesystem(); // disabling /proc/cpuinfo - const auto info = GetAarch64Info(); - EXPECT_TRUE(info.features.fp); - EXPECT_FALSE(info.features.asimd); - EXPECT_FALSE(info.features.evtstrm); - EXPECT_TRUE(info.features.aes); - EXPECT_FALSE(info.features.pmull); - EXPECT_FALSE(info.features.sha1); - EXPECT_FALSE(info.features.sha2); - EXPECT_FALSE(info.features.crc32); - EXPECT_FALSE(info.features.atomics); - EXPECT_FALSE(info.features.fphp); - EXPECT_FALSE(info.features.asimdhp); - EXPECT_FALSE(info.features.cpuid); - EXPECT_FALSE(info.features.asimdrdm); - EXPECT_FALSE(info.features.jscvt); - EXPECT_FALSE(info.features.fcma); - EXPECT_FALSE(info.features.lrcpc); - EXPECT_FALSE(info.features.dcpop); - EXPECT_FALSE(info.features.sha3); - EXPECT_FALSE(info.features.sm3); - EXPECT_FALSE(info.features.sm4); - EXPECT_FALSE(info.features.asimddp); - EXPECT_FALSE(info.features.sha512); - EXPECT_FALSE(info.features.sve); - EXPECT_FALSE(info.features.asimdfhm); - EXPECT_FALSE(info.features.dit); - EXPECT_FALSE(info.features.uscat); - EXPECT_FALSE(info.features.ilrcpc); - EXPECT_FALSE(info.features.flagm); - EXPECT_FALSE(info.features.ssbs); - EXPECT_FALSE(info.features.sb); - EXPECT_FALSE(info.features.paca); - EXPECT_FALSE(info.features.pacg); -} - -TEST(CpuinfoAarch64Test, FromHardwareCap2) { - SetHardwareCapabilities(AARCH64_HWCAP_FP, - AARCH64_HWCAP2_SVE2 | AARCH64_HWCAP2_BTI); - GetEmptyFilesystem(); // disabling /proc/cpuinfo - const auto info = GetAarch64Info(); - EXPECT_TRUE(info.features.fp); - - EXPECT_TRUE(info.features.sve2); - EXPECT_TRUE(info.features.bti); - - EXPECT_FALSE(info.features.dcpodp); - EXPECT_FALSE(info.features.sveaes); - EXPECT_FALSE(info.features.svepmull); - EXPECT_FALSE(info.features.svebitperm); - EXPECT_FALSE(info.features.svesha3); - EXPECT_FALSE(info.features.svesm4); - EXPECT_FALSE(info.features.flagm2); - EXPECT_FALSE(info.features.frint); - EXPECT_FALSE(info.features.svei8mm); - EXPECT_FALSE(info.features.svef32mm); - EXPECT_FALSE(info.features.svef64mm); - EXPECT_FALSE(info.features.svebf16); - EXPECT_FALSE(info.features.i8mm); - EXPECT_FALSE(info.features.bf16); - EXPECT_FALSE(info.features.dgh); - EXPECT_FALSE(info.features.rng); -} - -TEST(CpuinfoAarch64Test, ARMCortexA53) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", - R"(Processor : AArch64 Processor rev 3 (aarch64) -processor : 0 -processor : 1 -processor : 2 -processor : 3 -processor : 4 -processor : 5 -processor : 6 -processor : 7 -Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 -CPU implementer : 0x41 -CPU architecture: AArch64 -CPU variant : 0x0 -CPU part : 0xd03 -CPU revision : 3)"); - const auto info = GetAarch64Info(); - EXPECT_EQ(info.implementer, 0x41); - EXPECT_EQ(info.variant, 0x0); - EXPECT_EQ(info.part, 0xd03); - EXPECT_EQ(info.revision, 3); - - EXPECT_TRUE(info.features.fp); - EXPECT_TRUE(info.features.asimd); - EXPECT_TRUE(info.features.evtstrm); - EXPECT_TRUE(info.features.aes); - EXPECT_TRUE(info.features.pmull); - EXPECT_TRUE(info.features.sha1); - EXPECT_TRUE(info.features.sha2); - EXPECT_TRUE(info.features.crc32); - - EXPECT_FALSE(info.features.atomics); - EXPECT_FALSE(info.features.fphp); - EXPECT_FALSE(info.features.asimdhp); - EXPECT_FALSE(info.features.cpuid); - EXPECT_FALSE(info.features.asimdrdm); - EXPECT_FALSE(info.features.jscvt); - EXPECT_FALSE(info.features.fcma); - EXPECT_FALSE(info.features.lrcpc); - EXPECT_FALSE(info.features.dcpop); - EXPECT_FALSE(info.features.sha3); - EXPECT_FALSE(info.features.sm3); - EXPECT_FALSE(info.features.sm4); - EXPECT_FALSE(info.features.asimddp); - EXPECT_FALSE(info.features.sha512); - EXPECT_FALSE(info.features.sve); - EXPECT_FALSE(info.features.asimdfhm); - EXPECT_FALSE(info.features.dit); - EXPECT_FALSE(info.features.uscat); - EXPECT_FALSE(info.features.ilrcpc); - EXPECT_FALSE(info.features.flagm); - EXPECT_FALSE(info.features.ssbs); - EXPECT_FALSE(info.features.sb); - EXPECT_FALSE(info.features.paca); - EXPECT_FALSE(info.features.pacg); - EXPECT_FALSE(info.features.dcpodp); - EXPECT_FALSE(info.features.sve2); - EXPECT_FALSE(info.features.sveaes); - EXPECT_FALSE(info.features.svepmull); - EXPECT_FALSE(info.features.svebitperm); - EXPECT_FALSE(info.features.svesha3); - EXPECT_FALSE(info.features.svesm4); - EXPECT_FALSE(info.features.flagm2); - EXPECT_FALSE(info.features.frint); - EXPECT_FALSE(info.features.svei8mm); - EXPECT_FALSE(info.features.svef32mm); - EXPECT_FALSE(info.features.svef64mm); - EXPECT_FALSE(info.features.svebf16); - EXPECT_FALSE(info.features.i8mm); - EXPECT_FALSE(info.features.bf16); - EXPECT_FALSE(info.features.dgh); - EXPECT_FALSE(info.features.rng); - EXPECT_FALSE(info.features.bti); -} - -} // namespace -} // namespace cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc deleted file mode 100644 index 5dc73e4..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "cpuinfo_arm.h" - -#include "filesystem_for_testing.h" -#include "gtest/gtest.h" -#include "hwcaps_for_testing.h" - -namespace cpu_features { -namespace { - -void DisableHardwareCapabilities() { SetHardwareCapabilities(0, 0); } - -TEST(CpuinfoArmTest, FromHardwareCap) { - SetHardwareCapabilities(ARM_HWCAP_NEON, ARM_HWCAP2_AES | ARM_HWCAP2_CRC32); - GetEmptyFilesystem(); // disabling /proc/cpuinfo - const auto info = GetArmInfo(); - EXPECT_TRUE(info.features.vfp); // triggered by vfpv3 - EXPECT_TRUE(info.features.vfpv3); // triggered by neon - EXPECT_TRUE(info.features.neon); - EXPECT_TRUE(info.features.aes); - EXPECT_TRUE(info.features.crc32); - - EXPECT_FALSE(info.features.vfpv4); - EXPECT_FALSE(info.features.iwmmxt); - EXPECT_FALSE(info.features.crunch); - EXPECT_FALSE(info.features.thumbee); - EXPECT_FALSE(info.features.vfpv3d16); - EXPECT_FALSE(info.features.idiva); - EXPECT_FALSE(info.features.idivt); - EXPECT_FALSE(info.features.pmull); - EXPECT_FALSE(info.features.sha1); - EXPECT_FALSE(info.features.sha2); - - // check some random features with EnumValue(): - EXPECT_TRUE(GetArmFeaturesEnumValue(&info.features, ARM_VFP)); - EXPECT_FALSE(GetArmFeaturesEnumValue(&info.features, ARM_VFPV4)); - // out of bound EnumValue() check - EXPECT_FALSE(GetArmFeaturesEnumValue(&info.features, (ArmFeaturesEnum)~0x0)); -} - -TEST(CpuinfoArmTest, ODroidFromCpuInfo) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", R"(processor : 0 -model name : ARMv7 Processor rev 3 (v71) -BogoMIPS : 120.00 -Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae -CPU implementer : 0x41 -CPU architecture: 7 -CPU variant : 0x2 -CPU part : 0xc0f -CPU revision : 3)"); - const auto info = GetArmInfo(); - EXPECT_EQ(info.implementer, 0x41); - EXPECT_EQ(info.variant, 0x2); - EXPECT_EQ(info.part, 0xc0f); - EXPECT_EQ(info.revision, 3); - EXPECT_EQ(info.architecture, 7); - - EXPECT_FALSE(info.features.swp); - EXPECT_TRUE(info.features.half); - EXPECT_TRUE(info.features.thumb); - EXPECT_FALSE(info.features._26bit); - EXPECT_TRUE(info.features.fastmult); - EXPECT_FALSE(info.features.fpa); - EXPECT_TRUE(info.features.vfp); - EXPECT_TRUE(info.features.edsp); - EXPECT_FALSE(info.features.java); - EXPECT_FALSE(info.features.iwmmxt); - EXPECT_FALSE(info.features.crunch); - EXPECT_FALSE(info.features.thumbee); - EXPECT_TRUE(info.features.neon); - EXPECT_TRUE(info.features.vfpv3); - EXPECT_FALSE(info.features.vfpv3d16); - EXPECT_TRUE(info.features.tls); - EXPECT_TRUE(info.features.vfpv4); - EXPECT_TRUE(info.features.idiva); - EXPECT_TRUE(info.features.idivt); - EXPECT_TRUE(info.features.vfpd32); - EXPECT_TRUE(info.features.lpae); - EXPECT_FALSE(info.features.evtstrm); - EXPECT_FALSE(info.features.aes); - EXPECT_FALSE(info.features.pmull); - EXPECT_FALSE(info.features.sha1); - EXPECT_FALSE(info.features.sha2); - EXPECT_FALSE(info.features.crc32); -} - -// Linux test-case -TEST(CpuinfoArmTest, RaspberryPiZeroFromCpuInfo) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", R"(processor : 0 -model name : ARMv6-compatible processor rev 7 (v6l) -BogoMIPS : 697.95 -Features : half thumb fastmult vfp edsp java tls -CPU implementer : 0x41 -CPU architecture: 7 -CPU variant : 0x0 -CPU part : 0xb76 -CPU revision : 7 - -Hardware : BCM2835 -Revision : 9000c1 -Serial : 000000006cd946f3)"); - const auto info = GetArmInfo(); - EXPECT_EQ(info.implementer, 0x41); - EXPECT_EQ(info.variant, 0x0); - EXPECT_EQ(info.part, 0xb76); - EXPECT_EQ(info.revision, 7); - EXPECT_EQ(info.architecture, 6); - - EXPECT_FALSE(info.features.swp); - EXPECT_TRUE(info.features.half); - EXPECT_TRUE(info.features.thumb); - EXPECT_FALSE(info.features._26bit); - EXPECT_TRUE(info.features.fastmult); - EXPECT_FALSE(info.features.fpa); - EXPECT_TRUE(info.features.vfp); - EXPECT_TRUE(info.features.edsp); - EXPECT_TRUE(info.features.java); - EXPECT_FALSE(info.features.iwmmxt); - EXPECT_FALSE(info.features.crunch); - EXPECT_FALSE(info.features.thumbee); - EXPECT_FALSE(info.features.neon); - EXPECT_FALSE(info.features.vfpv3); - EXPECT_FALSE(info.features.vfpv3d16); - EXPECT_TRUE(info.features.tls); - EXPECT_FALSE(info.features.vfpv4); - EXPECT_FALSE(info.features.idiva); - EXPECT_FALSE(info.features.idivt); - EXPECT_FALSE(info.features.vfpd32); - EXPECT_FALSE(info.features.lpae); - EXPECT_FALSE(info.features.evtstrm); - EXPECT_FALSE(info.features.aes); - EXPECT_FALSE(info.features.pmull); - EXPECT_FALSE(info.features.sha1); - EXPECT_FALSE(info.features.sha2); - EXPECT_FALSE(info.features.crc32); -} - -TEST(CpuinfoArmTest, MarvellArmadaFromCpuInfo) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", R"(processor : 0 -model name : ARMv7 Processor rev 1 (v7l) -BogoMIPS : 50.00 -Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpd32 -CPU implementer : 0x41 -CPU architecture: 7 -CPU variant : 0x4 -CPU part : 0xc09 -CPU revision : 1 - -processor : 1 -model name : ARMv7 Processor rev 1 (v7l) -BogoMIPS : 50.00 -Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpd32 -CPU implementer : 0x41 -CPU architecture: 7 -CPU variant : 0x4 -CPU part : 0xc09 -CPU revision : 1 - -Hardware : Marvell Armada 380/385 (Device Tree) -Revision : 0000 -Serial : 0000000000000000)"); - const auto info = GetArmInfo(); - EXPECT_EQ(info.implementer, 0x41); - EXPECT_EQ(info.variant, 0x4); - EXPECT_EQ(info.part, 0xc09); - EXPECT_EQ(info.revision, 1); - EXPECT_EQ(info.architecture, 7); - - EXPECT_FALSE(info.features.swp); - EXPECT_TRUE(info.features.half); - EXPECT_TRUE(info.features.thumb); - EXPECT_FALSE(info.features._26bit); - EXPECT_TRUE(info.features.fastmult); - EXPECT_FALSE(info.features.fpa); - EXPECT_TRUE(info.features.vfp); - EXPECT_TRUE(info.features.edsp); - EXPECT_FALSE(info.features.java); - EXPECT_FALSE(info.features.iwmmxt); - EXPECT_FALSE(info.features.crunch); - EXPECT_FALSE(info.features.thumbee); - EXPECT_TRUE(info.features.neon); - EXPECT_TRUE(info.features.vfpv3); - EXPECT_FALSE(info.features.vfpv3d16); - EXPECT_TRUE(info.features.tls); - EXPECT_FALSE(info.features.vfpv4); - EXPECT_FALSE(info.features.idiva); - EXPECT_FALSE(info.features.idivt); - EXPECT_TRUE(info.features.vfpd32); - EXPECT_FALSE(info.features.lpae); - EXPECT_FALSE(info.features.evtstrm); - EXPECT_FALSE(info.features.aes); - EXPECT_FALSE(info.features.pmull); - EXPECT_FALSE(info.features.sha1); - EXPECT_FALSE(info.features.sha2); - EXPECT_FALSE(info.features.crc32); -} - -// Android test-case -// http://code.google.com/p/android/issues/detail?id=10812 -TEST(CpuinfoArmTest, InvalidArmv7) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", - R"(Processor : ARMv6-compatible processor rev 6 (v6l) -BogoMIPS : 199.47 -Features : swp half thumb fastmult vfp edsp java -CPU implementer : 0x41 -CPU architecture: 7 -CPU variant : 0x0 -CPU part : 0xb76 -CPU revision : 6 - -Hardware : SPICA -Revision : 0020 -Serial : 33323613546d00ec )"); - const auto info = GetArmInfo(); - EXPECT_EQ(info.architecture, 6); - - EXPECT_TRUE(info.features.swp); - EXPECT_TRUE(info.features.half); - EXPECT_TRUE(info.features.thumb); - EXPECT_FALSE(info.features._26bit); - EXPECT_TRUE(info.features.fastmult); - EXPECT_FALSE(info.features.fpa); - EXPECT_TRUE(info.features.vfp); - EXPECT_TRUE(info.features.edsp); - EXPECT_TRUE(info.features.java); - EXPECT_FALSE(info.features.iwmmxt); - EXPECT_FALSE(info.features.crunch); - EXPECT_FALSE(info.features.thumbee); - EXPECT_FALSE(info.features.neon); - EXPECT_FALSE(info.features.vfpv3); - EXPECT_FALSE(info.features.vfpv3d16); - EXPECT_FALSE(info.features.tls); - EXPECT_FALSE(info.features.vfpv4); - EXPECT_FALSE(info.features.idiva); - EXPECT_FALSE(info.features.idivt); - EXPECT_FALSE(info.features.vfpd32); - EXPECT_FALSE(info.features.lpae); - EXPECT_FALSE(info.features.evtstrm); - EXPECT_FALSE(info.features.aes); - EXPECT_FALSE(info.features.pmull); - EXPECT_FALSE(info.features.sha1); - EXPECT_FALSE(info.features.sha2); - EXPECT_FALSE(info.features.crc32); -} - -// Android test-case -// https://crbug.com/341598. -TEST(CpuinfoArmTest, InvalidNeon) { - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", - R"(Processor: ARMv7 Processory rev 0 (v71) -processor: 0 -BogoMIPS: 13.50 - -Processor: 1 -BogoMIPS: 13.50 - -Features: swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt -CPU implementer : 0x51 -CPU architecture: 7 -CPU variant: 0x1 -CPU part: 0x04d -CPU revision: 0 - -Hardware: SAMSUNG M2 -Revision: 0010 -Serial: 00001e030000354e)"); - const auto info = GetArmInfo(); - EXPECT_TRUE(info.features.swp); - EXPECT_FALSE(info.features.neon); -} - -// The Nexus 4 (Qualcomm Krait) kernel configuration forgets to report IDIV -// support. -TEST(CpuinfoArmTest, Nexus4_0x510006f2) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", - R"(CPU implementer : 0x51 -CPU architecture: 7 -CPU variant : 0x0 -CPU part : 0x6f -CPU revision : 2)"); - const auto info = GetArmInfo(); - EXPECT_TRUE(info.features.idiva); - EXPECT_TRUE(info.features.idivt); - - EXPECT_EQ(GetArmCpuId(&info), 0x510006f2); -} - -// The Nexus 4 (Qualcomm Krait) kernel configuration forgets to report IDIV -// support. -TEST(CpuinfoArmTest, Nexus4_0x510006f3) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", - R"(CPU implementer : 0x51 -CPU architecture: 7 -CPU variant : 0x0 -CPU part : 0x6f -CPU revision : 3)"); - const auto info = GetArmInfo(); - EXPECT_TRUE(info.features.idiva); - EXPECT_TRUE(info.features.idivt); - - EXPECT_EQ(GetArmCpuId(&info), 0x510006f3); -} - -// The emulator-specific Android 4.2 kernel fails to report support for the -// 32-bit ARM IDIV instruction. Technically, this is a feature of the virtual -// CPU implemented by the emulator. -TEST(CpuinfoArmTest, EmulatorSpecificIdiv) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", - R"(Processor : ARMv7 Processor rev 0 (v7l) -BogoMIPS : 629.14 -Features : swp half thumb fastmult vfp edsp neon vfpv3 -CPU implementer : 0x41 -CPU architecture: 7 -CPU variant : 0x0 -CPU part : 0xc08 -CPU revision : 0 - -Hardware : Goldfish -Revision : 0000 -Serial : 0000000000000000)"); - const auto info = GetArmInfo(); - EXPECT_TRUE(info.features.idiva); -} - -} // namespace -} // namespace cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc deleted file mode 100644 index fce9949..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "cpuinfo_mips.h" - -#include "filesystem_for_testing.h" -#include "gtest/gtest.h" -#include "hwcaps_for_testing.h" -#include "internal/stack_line_reader.h" -#include "internal/string_view.h" - -namespace cpu_features { - -namespace { - -void DisableHardwareCapabilities() { SetHardwareCapabilities(0, 0); } - -TEST(CpuinfoMipsTest, FromHardwareCapBoth) { - SetHardwareCapabilities(MIPS_HWCAP_MSA | MIPS_HWCAP_R6, 0); - GetEmptyFilesystem(); // disabling /proc/cpuinfo - const auto info = GetMipsInfo(); - EXPECT_TRUE(info.features.msa); - EXPECT_FALSE(info.features.eva); - EXPECT_TRUE(info.features.r6); -} - -TEST(CpuinfoMipsTest, FromHardwareCapOnlyOne) { - SetHardwareCapabilities(MIPS_HWCAP_MSA, 0); - GetEmptyFilesystem(); // disabling /proc/cpuinfo - const auto info = GetMipsInfo(); - EXPECT_TRUE(info.features.msa); - EXPECT_FALSE(info.features.eva); -} - -TEST(CpuinfoMipsTest, Ci40) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", R"(system type : IMG Pistachio SoC (B0) -machine : IMG Marduk – Ci40 with cc2520 -processor : 0 -cpu model : MIPS interAptiv (multi) V2.0 FPU V0.0 -BogoMIPS : 363.72 -wait instruction : yes -microsecond timers : yes -tlb_entries : 64 -extra interrupt vector : yes -hardware watchpoint : yes, count: 4, address/irw mask: [0x0ffc, 0x0ffc, 0x0ffb, 0x0ffb] -isa : mips1 mips2 mips32r1 mips32r2 -ASEs implemented : mips16 dsp mt eva -shadow register sets : 1 -kscratch registers : 0 -package : 0 -core : 0 -VCED exceptions : not available -VCEI exceptions : not available -VPE : 0 -)"); - const auto info = GetMipsInfo(); - EXPECT_FALSE(info.features.msa); - EXPECT_TRUE(info.features.eva); -} - -TEST(CpuinfoMipsTest, AR7161) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", - R"(system type : Atheros AR7161 rev 2 -machine : NETGEAR WNDR3700/WNDR3800/WNDRMAC -processor : 0 -cpu model : MIPS 24Kc V7.4 -BogoMIPS : 452.19 -wait instruction : yes -microsecond timers : yes -tlb_entries : 16 -extra interrupt vector : yes -hardware watchpoint : yes, count: 4, address/irw mask: [0x0000, 0x0f98, 0x0f78, 0x0df8] -ASEs implemented : mips16 -shadow register sets : 1 -kscratch registers : 0 -core : 0 -VCED exceptions : not available -VCEI exceptions : not available -)"); - const auto info = GetMipsInfo(); - EXPECT_FALSE(info.features.msa); - EXPECT_FALSE(info.features.eva); -} - -TEST(CpuinfoMipsTest, Goldfish) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", R"(system type : MIPS-Goldfish -Hardware : goldfish -Revison : 1 -processor : 0 -cpu model : MIPS 24Kc V0.0 FPU V0.0 -BogoMIPS : 1042.02 -wait instruction : yes -microsecond timers : yes -tlb_entries : 16 -extra interrupt vector : yes -hardware watchpoint : yes, count: 1, address/irw mask: [0x0ff8] -ASEs implemented : -shadow register sets : 1 -core : 0 -VCED exceptions : not available -VCEI exceptions : not available -)"); - const auto info = GetMipsInfo(); - EXPECT_FALSE(info.features.msa); - EXPECT_FALSE(info.features.eva); -} - -} // namespace -} // namespace cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc deleted file mode 100644 index 8f0cb65..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2018 IBM. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "cpuinfo_ppc.h" - -#include "filesystem_for_testing.h" -#include "gtest/gtest.h" -#include "hwcaps_for_testing.h" -#include "internal/string_view.h" - -namespace cpu_features { -namespace { - -void DisableHardwareCapabilities() { SetHardwareCapabilities(0, 0); } - -TEST(CpustringsPPCTest, FromHardwareCap) { - SetHardwareCapabilities(PPC_FEATURE_HAS_FPU | PPC_FEATURE_HAS_VSX, - PPC_FEATURE2_ARCH_3_00); - GetEmptyFilesystem(); // disabling /proc/cpuinfo - const auto info = GetPPCInfo(); - EXPECT_TRUE(info.features.fpu); - EXPECT_FALSE(info.features.mmu); - EXPECT_TRUE(info.features.vsx); - EXPECT_TRUE(info.features.arch300); - EXPECT_FALSE(info.features.power4); - EXPECT_FALSE(info.features.altivec); - EXPECT_FALSE(info.features.vcrypto); - EXPECT_FALSE(info.features.htm); -} - -TEST(CpustringsPPCTest, Blade) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", - R"(processor : 14 -cpu : POWER7 (architected), altivec supported -clock : 3000.000000MHz -revision : 2.1 (pvr 003f 0201) - -processor : 15 -cpu : POWER7 (architected), altivec supported -clock : 3000.000000MHz -revision : 2.1 (pvr 003f 0201) - -timebase : 512000000 -platform : pSeries -model : IBM,8406-70Y -machine : CHRP IBM,8406-70Y)"); - SetPlatformTypes("power7", "power8"); - const auto strings = GetPPCPlatformStrings(); - ASSERT_STREQ(strings.platform, "pSeries"); - ASSERT_STREQ(strings.model, "IBM,8406-70Y"); - ASSERT_STREQ(strings.machine, "CHRP IBM,8406-70Y"); - ASSERT_STREQ(strings.cpu, "POWER7 (architected), altivec supported"); - ASSERT_STREQ(strings.type.platform, "power7"); - ASSERT_STREQ(strings.type.base_platform, "power8"); -} - -TEST(CpustringsPPCTest, Firestone) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", - R"(processor : 126 -cpu : POWER8 (raw), altivec supported -clock : 2061.000000MHz -revision : 2.0 (pvr 004d 0200) - -processor : 127 -cpu : POWER8 (raw), altivec supported -clock : 2061.000000MHz -revision : 2.0 (pvr 004d 0200) - -timebase : 512000000 -platform : PowerNV -model : 8335-GTA -machine : PowerNV 8335-GTA -firmware : OPAL v3)"); - const auto strings = GetPPCPlatformStrings(); - ASSERT_STREQ(strings.platform, "PowerNV"); - ASSERT_STREQ(strings.model, "8335-GTA"); - ASSERT_STREQ(strings.machine, "PowerNV 8335-GTA"); - ASSERT_STREQ(strings.cpu, "POWER8 (raw), altivec supported"); -} - -TEST(CpustringsPPCTest, w8) { - DisableHardwareCapabilities(); - auto& fs = GetEmptyFilesystem(); - fs.CreateFile("/proc/cpuinfo", - R"(processor : 143 -cpu : POWER9, altivec supported -clock : 2300.000000MHz -revision : 2.2 (pvr 004e 1202) - -timebase : 512000000 -platform : PowerNV -model : 0000000000000000 -machine : PowerNV 0000000000000000 -firmware : OPAL -MMU : Radix)"); - const auto strings = GetPPCPlatformStrings(); - ASSERT_STREQ(strings.platform, "PowerNV"); - ASSERT_STREQ(strings.model, "0000000000000000"); - ASSERT_STREQ(strings.machine, "PowerNV 0000000000000000"); - ASSERT_STREQ(strings.cpu, "POWER9, altivec supported"); -} - -} // namespace -} // namespace cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc deleted file mode 100644 index e11a0ba..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc +++ /dev/null @@ -1,281 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "cpuinfo_x86.h" - -#include -#include -#include - -#include "gtest/gtest.h" -#include "internal/cpuid_x86.h" - -namespace cpu_features { - -class FakeCpu { - public: - Leaf CpuIdEx(uint32_t leaf_id, int ecx) const { - const auto itr = cpuid_leaves_.find(std::make_pair(leaf_id, ecx)); - if (itr != cpuid_leaves_.end()) { - return itr->second; - } - return {0, 0, 0, 0}; - } - - uint32_t GetXCR0Eax() const { return xcr0_eax_; } - - void SetLeaves(std::map, Leaf> configuration) { - cpuid_leaves_ = std::move(configuration); - } - - void SetOsBackupsExtendedRegisters(bool os_backups_extended_registers) { - xcr0_eax_ = os_backups_extended_registers ? -1 : 0; - } - - private: - std::map, Leaf> cpuid_leaves_; - uint32_t xcr0_eax_; -}; - -auto* g_fake_cpu = new FakeCpu(); - -extern "C" Leaf CpuIdEx(uint32_t leaf_id, int ecx) { - return g_fake_cpu->CpuIdEx(leaf_id, ecx); -} - -extern "C" uint32_t GetXCR0Eax(void) { return g_fake_cpu->GetXCR0Eax(); } - -namespace { - -TEST(CpuidX86Test, SandyBridge) { - g_fake_cpu->SetOsBackupsExtendedRegisters(true); - g_fake_cpu->SetLeaves({ - {{0x00000000, 0}, Leaf{0x0000000D, 0x756E6547, 0x6C65746E, 0x49656E69}}, - {{0x00000001, 0}, Leaf{0x000206A6, 0x00100800, 0x1F9AE3BF, 0xBFEBFBFF}}, - {{0x00000007, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, - }); - const auto info = GetX86Info(); - EXPECT_STREQ(info.vendor, "GenuineIntel"); - EXPECT_EQ(info.family, 0x06); - EXPECT_EQ(info.model, 0x02A); - EXPECT_EQ(info.stepping, 0x06); - // Leaf 7 is zeroed out so none of the Leaf 7 flags are set. - const auto features = info.features; - EXPECT_FALSE(features.erms); - EXPECT_FALSE(features.avx2); - EXPECT_FALSE(features.avx512f); - EXPECT_FALSE(features.avx512cd); - EXPECT_FALSE(features.avx512er); - EXPECT_FALSE(features.avx512pf); - EXPECT_FALSE(features.avx512bw); - EXPECT_FALSE(features.avx512dq); - EXPECT_FALSE(features.avx512vl); - EXPECT_FALSE(features.avx512ifma); - EXPECT_FALSE(features.avx512vbmi); - EXPECT_FALSE(features.avx512vbmi2); - EXPECT_FALSE(features.avx512vnni); - EXPECT_FALSE(features.avx512bitalg); - EXPECT_FALSE(features.avx512vpopcntdq); - EXPECT_FALSE(features.avx512_4vnniw); - EXPECT_FALSE(features.avx512_4fmaps); - // All old cpu features should be set. - EXPECT_TRUE(features.aes); - EXPECT_TRUE(features.ssse3); - EXPECT_TRUE(features.sse4_1); - EXPECT_TRUE(features.sse4_2); - EXPECT_TRUE(features.avx); - EXPECT_FALSE(features.sha); - EXPECT_TRUE(features.popcnt); - EXPECT_FALSE(features.movbe); - EXPECT_FALSE(features.rdrnd); -} - -const int KiB = 1024; -const int MiB = 1024 * KiB; - -TEST(CpuidX86Test, SandyBridgeTestOsSupport) { - g_fake_cpu->SetLeaves({ - {{0x00000000, 0}, Leaf{0x0000000D, 0x756E6547, 0x6C65746E, 0x49656E69}}, - {{0x00000001, 0}, Leaf{0x000206A6, 0x00100800, 0x1F9AE3BF, 0xBFEBFBFF}}, - {{0x00000007, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, - }); - // avx is disabled if os does not support backing up ymm registers. - g_fake_cpu->SetOsBackupsExtendedRegisters(false); - EXPECT_FALSE(GetX86Info().features.avx); - // avx is disabled if os does not support backing up ymm registers. - g_fake_cpu->SetOsBackupsExtendedRegisters(true); - EXPECT_TRUE(GetX86Info().features.avx); -} - -TEST(CpuidX86Test, SkyLake) { - g_fake_cpu->SetOsBackupsExtendedRegisters(true); - g_fake_cpu->SetLeaves({ - {{0x00000000, 0}, Leaf{0x00000016, 0x756E6547, 0x6C65746E, 0x49656E69}}, - {{0x00000001, 0}, Leaf{0x000406E3, 0x00100800, 0x7FFAFBBF, 0xBFEBFBFF}}, - {{0x00000007, 0}, Leaf{0x00000000, 0x029C67AF, 0x00000000, 0x00000000}}, - }); - const auto info = GetX86Info(); - EXPECT_STREQ(info.vendor, "GenuineIntel"); - EXPECT_EQ(info.family, 0x06); - EXPECT_EQ(info.model, 0x04E); - EXPECT_EQ(info.stepping, 0x03); - EXPECT_EQ(GetX86Microarchitecture(&info), X86Microarchitecture::INTEL_SKL); -} - -TEST(CpuidX86Test, Branding) { - g_fake_cpu->SetLeaves({ - {{0x00000000, 0}, Leaf{0x00000016, 0x756E6547, 0x6C65746E, 0x49656E69}}, - {{0x00000001, 0}, Leaf{0x000406E3, 0x00100800, 0x7FFAFBBF, 0xBFEBFBFF}}, - {{0x00000007, 0}, Leaf{0x00000000, 0x029C67AF, 0x00000000, 0x00000000}}, - {{0x80000000, 0}, Leaf{0x80000008, 0x00000000, 0x00000000, 0x00000000}}, - {{0x80000001, 0}, Leaf{0x00000000, 0x00000000, 0x00000121, 0x2C100000}}, - {{0x80000002, 0}, Leaf{0x65746E49, 0x2952286C, 0x726F4320, 0x4D542865}}, - {{0x80000003, 0}, Leaf{0x37692029, 0x3035362D, 0x43205530, 0x40205550}}, - {{0x80000004, 0}, Leaf{0x352E3220, 0x7A484730, 0x00000000, 0x00000000}}, - }); - char brand_string[49]; - FillX86BrandString(brand_string); - EXPECT_STREQ(brand_string, "Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz"); -} - -TEST(CpuidX86Test, KabyLakeCache) { - g_fake_cpu->SetLeaves({ - {{0x00000000, 0}, Leaf{0x00000016, 0x756E6547, 0x6C65746E, 0x49656E69}}, - {{0x00000001, 0}, Leaf{0x000406E3, 0x00100800, 0x7FFAFBBF, 0xBFEBFBFF}}, - {{0x00000004, 0}, Leaf{0x1C004121, 0x01C0003F, 0x0000003F, 0x00000000}}, - {{0x00000004, 1}, Leaf{0x1C004122, 0x01C0003F, 0x0000003F, 0x00000000}}, - {{0x00000004, 2}, Leaf{0x1C004143, 0x00C0003F, 0x000003FF, 0x00000000}}, - {{0x00000004, 3}, Leaf{0x1C03C163, 0x02C0003F, 0x00001FFF, 0x00000002}}, - {{0x00000007, 0}, Leaf{0x00000000, 0x029C67AF, 0x00000000, 0x00000000}}, - {{0x80000000, 0}, Leaf{0x80000008, 0x00000000, 0x00000000, 0x00000000}}, - {{0x80000001, 0}, Leaf{0x00000000, 0x00000000, 0x00000121, 0x2C100000}}, - {{0x80000002, 0}, Leaf{0x65746E49, 0x2952286C, 0x726F4320, 0x4D542865}}, - {{0x80000003, 0}, Leaf{0x37692029, 0x3035362D, 0x43205530, 0x40205550}}, - }); - const auto info = GetX86CacheInfo(); - EXPECT_EQ(info.size, 4); - EXPECT_EQ(info.levels[0].level, 1); - EXPECT_EQ(info.levels[0].cache_type, 1); - EXPECT_EQ(info.levels[0].cache_size, 32 * KiB); - EXPECT_EQ(info.levels[0].ways, 8); - EXPECT_EQ(info.levels[0].line_size, 64); - EXPECT_EQ(info.levels[0].tlb_entries, 64); - EXPECT_EQ(info.levels[0].partitioning, 1); - - EXPECT_EQ(info.levels[1].level, 1); - EXPECT_EQ(info.levels[1].cache_type, 2); - EXPECT_EQ(info.levels[1].cache_size, 32 * KiB); - EXPECT_EQ(info.levels[1].ways, 8); - EXPECT_EQ(info.levels[1].line_size, 64); - EXPECT_EQ(info.levels[1].tlb_entries, 64); - EXPECT_EQ(info.levels[1].partitioning, 1); - - EXPECT_EQ(info.levels[2].level, 2); - EXPECT_EQ(info.levels[2].cache_type, 3); - EXPECT_EQ(info.levels[2].cache_size, 256 * KiB); - EXPECT_EQ(info.levels[2].ways, 4); - EXPECT_EQ(info.levels[2].line_size, 64); - EXPECT_EQ(info.levels[2].tlb_entries, 1024); - EXPECT_EQ(info.levels[2].partitioning, 1); - - EXPECT_EQ(info.levels[3].level, 3); - EXPECT_EQ(info.levels[3].cache_type, 3); - EXPECT_EQ(info.levels[3].cache_size, 6 * MiB); - EXPECT_EQ(info.levels[3].ways, 12); - EXPECT_EQ(info.levels[3].line_size, 64); - EXPECT_EQ(info.levels[3].tlb_entries, 8192); - EXPECT_EQ(info.levels[3].partitioning, 1); -} - -TEST(CpuidX86Test, HSWCache) { - g_fake_cpu->SetLeaves({ - {{0x00000000, 0}, Leaf{0x00000016, 0x756E6547, 0x6C65746E, 0x49656E69}}, - {{0x00000001, 0}, Leaf{0x000406E3, 0x00100800, 0x7FFAFBBF, 0xBFEBFBFF}}, - {{0x00000004, 0}, Leaf{0x1C004121, 0x01C0003F, 0x0000003F, 0x00000000}}, - {{0x00000004, 1}, Leaf{0x1C004122, 0x01C0003F, 0x0000003F, 0x00000000}}, - {{0x00000004, 2}, Leaf{0x1C004143, 0x01C0003F, 0x000001FF, 0x00000000}}, - {{0x00000004, 3}, Leaf{0x1C03C163, 0x02C0003F, 0x00001FFF, 0x00000006}}, - {{0x00000007, 0}, Leaf{0x00000000, 0x029C67AF, 0x00000000, 0x00000000}}, - {{0x80000000, 0}, Leaf{0x80000008, 0x00000000, 0x00000000, 0x00000000}}, - {{0x80000001, 0}, Leaf{0x00000000, 0x00000000, 0x00000121, 0x2C100000}}, - {{0x80000002, 0}, Leaf{0x65746E49, 0x2952286C, 0x726F4320, 0x4D542865}}, - {{0x80000003, 0}, Leaf{0x37692029, 0x3035362D, 0x43205530, 0x40205550}}, - }); - const auto info = GetX86CacheInfo(); - EXPECT_EQ(info.size, 4); - EXPECT_EQ(info.levels[0].level, 1); - EXPECT_EQ(info.levels[0].cache_type, 1); - EXPECT_EQ(info.levels[0].cache_size, 32 * KiB); - EXPECT_EQ(info.levels[0].ways, 8); - EXPECT_EQ(info.levels[0].line_size, 64); - EXPECT_EQ(info.levels[0].tlb_entries, 64); - EXPECT_EQ(info.levels[0].partitioning, 1); - - EXPECT_EQ(info.levels[1].level, 1); - EXPECT_EQ(info.levels[1].cache_type, 2); - EXPECT_EQ(info.levels[1].cache_size, 32 * KiB); - EXPECT_EQ(info.levels[1].ways, 8); - EXPECT_EQ(info.levels[1].line_size, 64); - EXPECT_EQ(info.levels[1].tlb_entries, 64); - EXPECT_EQ(info.levels[1].partitioning, 1); - - EXPECT_EQ(info.levels[2].level, 2); - EXPECT_EQ(info.levels[2].cache_type, 3); - EXPECT_EQ(info.levels[2].cache_size, 256 * KiB); - EXPECT_EQ(info.levels[2].ways, 8); - EXPECT_EQ(info.levels[2].line_size, 64); - EXPECT_EQ(info.levels[2].tlb_entries, 512); - EXPECT_EQ(info.levels[2].partitioning, 1); - - EXPECT_EQ(info.levels[3].level, 3); - EXPECT_EQ(info.levels[3].cache_type, 3); - EXPECT_EQ(info.levels[3].cache_size, 6 * MiB); - EXPECT_EQ(info.levels[3].ways, 12); - EXPECT_EQ(info.levels[3].line_size, 64); - EXPECT_EQ(info.levels[3].tlb_entries, 8192); - EXPECT_EQ(info.levels[3].partitioning, 1); -} -// http://users.atw.hu/instlatx64/AuthenticAMD0630F81_K15_Godavari_CPUID.txt -TEST(CpuidX86Test, AMD_K15) { - g_fake_cpu->SetLeaves({ - {{0x00000000, 0}, Leaf{0x0000000D, 0x68747541, 0x444D4163, 0x69746E65}}, - {{0x00000001, 0}, Leaf{0x00630F81, 0x00040800, 0x3E98320B, 0x178BFBFF}}, - {{0x00000007, 0}, Leaf{0x00000000, 0x00000000, 0x00000000, 0x00000000}}, - {{0x80000000, 0}, Leaf{0x8000001E, 0x68747541, 0x444D4163, 0x69746E65}}, - {{0x80000001, 0}, Leaf{0x00630F81, 0x10000000, 0x0FEBBFFF, 0x2FD3FBFF}}, - {{0x80000002, 0}, Leaf{0x20444D41, 0x372D3841, 0x4B303736, 0x64615220}}, - {{0x80000003, 0}, Leaf{0x206E6F65, 0x202C3752, 0x43203031, 0x75706D6F}}, - {{0x80000004, 0}, Leaf{0x43206574, 0x7365726F, 0x2B433420, 0x00204736}}, - {{0x80000005, 0}, Leaf{0xFF40FF18, 0xFF40FF30, 0x10040140, 0x60030140}}, - }); - const auto info = GetX86Info(); - - EXPECT_STREQ(info.vendor, "AuthenticAMD"); - EXPECT_EQ(info.family, 0x15); - EXPECT_EQ(info.model, 0x38); - EXPECT_EQ(info.stepping, 0x01); - EXPECT_EQ(GetX86Microarchitecture(&info), - X86Microarchitecture::AMD_BULLDOZER); - - char brand_string[49]; - FillX86BrandString(brand_string); - EXPECT_STREQ(brand_string, "AMD A8-7670K Radeon R7, 10 Compute Cores 4C+6G "); -} - -// TODO(user): test what happens when xsave/osxsave are not present. -// TODO(user): test what happens when xmm/ymm/zmm os support are not -// present. - -} // namespace -} // namespace cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc deleted file mode 100644 index 0a11416..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "filesystem_for_testing.h" - -#include -#include -#include -#include -#include - -namespace cpu_features { - -FakeFile::FakeFile(int file_descriptor, const char* content) - : file_descriptor_(file_descriptor), content_(content) {} - -FakeFile::~FakeFile() { assert(!opened_); } - -void FakeFile::Open() { - assert(!opened_); - opened_ = true; -} - -void FakeFile::Close() { - assert(opened_); - opened_ = false; -} - -int FakeFile::Read(int fd, void* buf, size_t count) { - assert(count < INT_MAX); - assert(fd == file_descriptor_); - const size_t remainder = content_.size() - head_index_; - const size_t read = count > remainder ? remainder : count; - memcpy(buf, content_.data() + head_index_, read); - head_index_ += read; - assert(read < INT_MAX); - return (int)read; -} - -void FakeFilesystem::Reset() { files_.clear(); } - -FakeFile* FakeFilesystem::CreateFile(const std::string& filename, - const char* content) { - auto& file = files_[filename]; - file = - std::unique_ptr(new FakeFile(next_file_descriptor_++, content)); - return file.get(); -} - -FakeFile* FakeFilesystem::FindFileOrNull(const std::string& filename) const { - const auto itr = files_.find(filename); - return itr == files_.end() ? nullptr : itr->second.get(); -} - -FakeFile* FakeFilesystem::FindFileOrDie(const int file_descriptor) const { - for (const auto& filename_file_pair : files_) { - FakeFile* const file_ptr = filename_file_pair.second.get(); - if (file_ptr->GetFileDescriptor() == file_descriptor) { - return file_ptr; - } - } - assert(false); - return nullptr; -} - -static FakeFilesystem* kFilesystem = new FakeFilesystem(); - -FakeFilesystem& GetEmptyFilesystem() { - kFilesystem->Reset(); - return *kFilesystem; -} - -extern "C" int CpuFeatures_OpenFile(const char* filename) { - auto* const file = kFilesystem->FindFileOrNull(filename); - if (file) { - file->Open(); - return file->GetFileDescriptor(); - } - return -1; -} - -extern "C" void CpuFeatures_CloseFile(int file_descriptor) { - kFilesystem->FindFileOrDie(file_descriptor)->Close(); -} - -extern "C" int CpuFeatures_ReadFile(int file_descriptor, void* buffer, - size_t buffer_size) { - return kFilesystem->FindFileOrDie(file_descriptor) - ->Read(file_descriptor, buffer, buffer_size); -} - -} // namespace cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h deleted file mode 100644 index 7474b5f..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Implements a fake filesystem, useful for tests. -#ifndef CPU_FEATURES_TEST_FILESYSTEM_FOR_TESTING_H_ -#define CPU_FEATURES_TEST_FILESYSTEM_FOR_TESTING_H_ - -#include -#include -#include - -#include "internal/filesystem.h" - -namespace cpu_features { - -class FakeFile { - public: - explicit FakeFile(int file_descriptor, const char* content); - ~FakeFile(); - - void Open(); - void Close(); - int Read(int fd, void* buf, size_t count); - - int GetFileDescriptor() const { return file_descriptor_; } - - private: - const int file_descriptor_; - const std::string content_; - bool opened_ = false; - size_t head_index_ = 0; -}; - -class FakeFilesystem { - public: - void Reset(); - FakeFile* CreateFile(const std::string& filename, const char* content); - FakeFile* FindFileOrDie(const int file_descriptor) const; - FakeFile* FindFileOrNull(const std::string& filename) const; - - private: - int next_file_descriptor_ = 0; - std::unordered_map> files_; -}; - -FakeFilesystem& GetEmptyFilesystem(); - -} // namespace cpu_features - -#endif // CPU_FEATURES_TEST_FILESYSTEM_FOR_TESTING_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc deleted file mode 100644 index 39a8472..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "hwcaps_for_testing.h" - -#include - -#include "internal/string_view.h" - -namespace cpu_features { - -namespace { -static auto* const g_hardware_capabilities = new HardwareCapabilities(); -static auto* const g_platform_types = new PlatformType(); -} // namespace - -void SetHardwareCapabilities(uint32_t hwcaps, uint32_t hwcaps2) { - g_hardware_capabilities->hwcaps = hwcaps; - g_hardware_capabilities->hwcaps2 = hwcaps2; -} - -HardwareCapabilities CpuFeatures_GetHardwareCapabilities(void) { - return *g_hardware_capabilities; -} - -void SetPlatformTypes(const char* platform, const char* base_platform) { - CpuFeatures_StringView_CopyString(str(platform), g_platform_types->platform, - sizeof(g_platform_types->platform)); - CpuFeatures_StringView_CopyString(str(base_platform), - g_platform_types->base_platform, - sizeof(g_platform_types->base_platform)); -} - -PlatformType CpuFeatures_GetPlatformType(void) { return *g_platform_types; } -} // namespace cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h deleted file mode 100644 index 0d03777..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CPU_FEATURES_TEST_HWCAPS_FOR_TESTING_H_ -#define CPU_FEATURES_TEST_HWCAPS_FOR_TESTING_H_ - -#include "internal/hwcaps.h" - -namespace cpu_features { - -void SetHardwareCapabilities(uint32_t hwcaps, uint32_t hwcaps2); -void SetPlatformTypes(const char *platform, const char *base_platform); - -} // namespace cpu_features - -#endif // CPU_FEATURES_TEST_HWCAPS_FOR_TESTING_H_ diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc deleted file mode 100644 index 629122a..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "internal/stack_line_reader.h" - -#include "filesystem_for_testing.h" -#include "gtest/gtest.h" - -namespace cpu_features { - -bool operator==(const StringView& a, const StringView& b) { - return CpuFeatures_StringView_IsEquals(a, b); -} - -namespace { - -std::string ToString(StringView view) { return {view.ptr, view.size}; } - -TEST(StackLineReaderTest, Empty) { - auto& fs = GetEmptyFilesystem(); - auto* file = fs.CreateFile("/proc/cpuinfo", ""); - StackLineReader reader; - StackLineReader_Initialize(&reader, file->GetFileDescriptor()); - { - const auto result = StackLineReader_NextLine(&reader); - EXPECT_TRUE(result.eof); - EXPECT_TRUE(result.full_line); - EXPECT_EQ(result.line, str("")); - } -} - -TEST(StackLineReaderTest, ManySmallLines) { - auto& fs = GetEmptyFilesystem(); - auto* file = fs.CreateFile("/proc/cpuinfo", "a\nb\nc"); - - StackLineReader reader; - StackLineReader_Initialize(&reader, file->GetFileDescriptor()); - { - const auto result = StackLineReader_NextLine(&reader); - EXPECT_FALSE(result.eof); - EXPECT_TRUE(result.full_line); - EXPECT_EQ(result.line, str("a")); - } - { - const auto result = StackLineReader_NextLine(&reader); - EXPECT_FALSE(result.eof); - EXPECT_TRUE(result.full_line); - EXPECT_EQ(result.line, str("b")); - } - { - const auto result = StackLineReader_NextLine(&reader); - EXPECT_TRUE(result.eof); - EXPECT_TRUE(result.full_line); - EXPECT_EQ(result.line, str("c")); - } -} - -TEST(StackLineReaderTest, TruncatedLine) { - auto& fs = GetEmptyFilesystem(); - auto* file = fs.CreateFile("/proc/cpuinfo", R"(First -Second -More than 16 characters, this will be truncated. -last)"); - - StackLineReader reader; - StackLineReader_Initialize(&reader, file->GetFileDescriptor()); - { - const auto result = StackLineReader_NextLine(&reader); - EXPECT_FALSE(result.eof); - EXPECT_TRUE(result.full_line); - EXPECT_EQ(result.line, str("First")); - } - { - const auto result = StackLineReader_NextLine(&reader); - EXPECT_FALSE(result.eof); - EXPECT_TRUE(result.full_line); - EXPECT_EQ(result.line, str("Second")); - } - { - const auto result = StackLineReader_NextLine(&reader); - EXPECT_FALSE(result.eof); - EXPECT_FALSE(result.full_line); - EXPECT_EQ(result.line, str("More than 16 cha")); - } - { - const auto result = StackLineReader_NextLine(&reader); - EXPECT_TRUE(result.eof); - EXPECT_TRUE(result.full_line); - EXPECT_EQ(result.line, str("last")); - } -} - -TEST(StackLineReaderTest, TruncatedLines) { - auto& fs = GetEmptyFilesystem(); - auto* file = fs.CreateFile("/proc/cpuinfo", R"(More than 16 characters -Another line that is too long)"); - - StackLineReader reader; - StackLineReader_Initialize(&reader, file->GetFileDescriptor()); - { - const auto result = StackLineReader_NextLine(&reader); - EXPECT_FALSE(result.eof); - EXPECT_FALSE(result.full_line); - EXPECT_EQ(result.line, str("More than 16 cha")); - } - { - const auto result = StackLineReader_NextLine(&reader); - EXPECT_FALSE(result.eof); - EXPECT_FALSE(result.full_line); - EXPECT_EQ(result.line, str("Another line tha")); - } - { - const auto result = StackLineReader_NextLine(&reader); - EXPECT_TRUE(result.eof); - EXPECT_TRUE(result.full_line); - EXPECT_EQ(result.line, str("")); - } -} - -} // namespace -} // namespace cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc deleted file mode 100644 index 962f417..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "internal/string_view.h" - -#include "gtest/gtest.h" - -namespace cpu_features { - -bool operator==(const StringView& a, const StringView& b) { - return CpuFeatures_StringView_IsEquals(a, b); -} - -namespace { - -TEST(StringViewTest, Empty) { - EXPECT_EQ(kEmptyStringView.ptr, nullptr); - EXPECT_EQ(kEmptyStringView.size, 0); -} - -TEST(StringViewTest, Build) { - const auto view = str("test"); - EXPECT_EQ(view.ptr[0], 't'); - EXPECT_EQ(view.size, 4); -} - -TEST(StringViewTest, CpuFeatures_StringView_IndexOfChar) { - // Found. - EXPECT_EQ(CpuFeatures_StringView_IndexOfChar(str("test"), 'e'), 1); - EXPECT_EQ(CpuFeatures_StringView_IndexOfChar(str("test"), 't'), 0); - EXPECT_EQ(CpuFeatures_StringView_IndexOfChar(str("beef"), 'e'), 1); - // Not found. - EXPECT_EQ(CpuFeatures_StringView_IndexOfChar(str("test"), 'z'), -1); - // Empty. - EXPECT_EQ(CpuFeatures_StringView_IndexOfChar(kEmptyStringView, 'z'), -1); -} - -TEST(StringViewTest, CpuFeatures_StringView_IndexOf) { - // Found. - EXPECT_EQ(CpuFeatures_StringView_IndexOf(str("test"), str("es")), 1); - EXPECT_EQ(CpuFeatures_StringView_IndexOf(str("test"), str("test")), 0); - EXPECT_EQ(CpuFeatures_StringView_IndexOf(str("tesstest"), str("test")), 4); - // Not found. - EXPECT_EQ(CpuFeatures_StringView_IndexOf(str("test"), str("aa")), -1); - // Empty. - EXPECT_EQ(CpuFeatures_StringView_IndexOf(kEmptyStringView, str("aa")), -1); - EXPECT_EQ(CpuFeatures_StringView_IndexOf(str("aa"), kEmptyStringView), -1); -} - -TEST(StringViewTest, CpuFeatures_StringView_StartsWith) { - EXPECT_TRUE(CpuFeatures_StringView_StartsWith(str("test"), str("te"))); - EXPECT_TRUE(CpuFeatures_StringView_StartsWith(str("test"), str("test"))); - EXPECT_FALSE(CpuFeatures_StringView_StartsWith(str("test"), str("st"))); - EXPECT_FALSE(CpuFeatures_StringView_StartsWith(str("test"), str("est"))); - EXPECT_FALSE(CpuFeatures_StringView_StartsWith(str("test"), str(""))); - EXPECT_FALSE( - CpuFeatures_StringView_StartsWith(str("test"), kEmptyStringView)); - EXPECT_FALSE( - CpuFeatures_StringView_StartsWith(kEmptyStringView, str("test"))); -} - -TEST(StringViewTest, CpuFeatures_StringView_IsEquals) { - EXPECT_TRUE( - CpuFeatures_StringView_IsEquals(kEmptyStringView, kEmptyStringView)); - EXPECT_TRUE(CpuFeatures_StringView_IsEquals(kEmptyStringView, str(""))); - EXPECT_TRUE(CpuFeatures_StringView_IsEquals(str(""), kEmptyStringView)); - EXPECT_TRUE(CpuFeatures_StringView_IsEquals(str("test"), str("test"))); - EXPECT_TRUE(CpuFeatures_StringView_IsEquals(str("a"), str("a"))); - EXPECT_FALSE(CpuFeatures_StringView_IsEquals(str("a"), str("b"))); - EXPECT_FALSE(CpuFeatures_StringView_IsEquals(str("aa"), str("a"))); - EXPECT_FALSE(CpuFeatures_StringView_IsEquals(str("a"), str("aa"))); - EXPECT_FALSE(CpuFeatures_StringView_IsEquals(str("a"), kEmptyStringView)); - EXPECT_FALSE(CpuFeatures_StringView_IsEquals(kEmptyStringView, str("a"))); -} - -TEST(StringViewTest, CpuFeatures_StringView_PopFront) { - EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 2), str("st")); - EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 0), str("test")); - EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 4), str("")); - EXPECT_EQ(CpuFeatures_StringView_PopFront(str("test"), 100), str("")); -} - -TEST(StringViewTest, CpuFeatures_StringView_PopBack) { - EXPECT_EQ(CpuFeatures_StringView_PopBack(str("test"), 2), str("te")); - EXPECT_EQ(CpuFeatures_StringView_PopBack(str("test"), 0), str("test")); - EXPECT_EQ(CpuFeatures_StringView_PopBack(str("test"), 4), str("")); - EXPECT_EQ(CpuFeatures_StringView_PopBack(str("test"), 100), str("")); -} - -TEST(StringViewTest, CpuFeatures_StringView_KeepFront) { - EXPECT_EQ(CpuFeatures_StringView_KeepFront(str("test"), 2), str("te")); - EXPECT_EQ(CpuFeatures_StringView_KeepFront(str("test"), 0), str("")); - EXPECT_EQ(CpuFeatures_StringView_KeepFront(str("test"), 4), str("test")); - EXPECT_EQ(CpuFeatures_StringView_KeepFront(str("test"), 6), str("test")); -} - -TEST(StringViewTest, CpuFeatures_StringView_Front) { - EXPECT_EQ(CpuFeatures_StringView_Front(str("apple")), 'a'); - EXPECT_EQ(CpuFeatures_StringView_Front(str("a")), 'a'); -} - -TEST(StringViewTest, CpuFeatures_StringView_Back) { - EXPECT_EQ(CpuFeatures_StringView_Back(str("apple")), 'e'); - EXPECT_EQ(CpuFeatures_StringView_Back(str("a")), 'a'); -} - -TEST(StringViewTest, CpuFeatures_StringView_TrimWhitespace) { - EXPECT_EQ(CpuFeatures_StringView_TrimWhitespace(str(" first middle last ")), - str("first middle last")); - EXPECT_EQ(CpuFeatures_StringView_TrimWhitespace(str("first middle last ")), - str("first middle last")); - EXPECT_EQ(CpuFeatures_StringView_TrimWhitespace(str(" first middle last")), - str("first middle last")); - EXPECT_EQ(CpuFeatures_StringView_TrimWhitespace(str("first middle last")), - str("first middle last")); -} - -TEST(StringViewTest, CpuFeatures_StringView_ParsePositiveNumber) { - EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("42")), 42); - EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("0x2a")), 42); - EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("0x2A")), 42); - EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("0x2A2a")), 10794); - EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("0x2a2A")), 10794); - - EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("-10")), -1); - EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("-0x2A")), -1); - EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("abc")), -1); - EXPECT_EQ(CpuFeatures_StringView_ParsePositiveNumber(str("")), -1); -} - -TEST(StringViewTest, CpuFeatures_StringView_CopyString) { - char buf[4]; - buf[0] = 'X'; - - // Empty - CpuFeatures_StringView_CopyString(str(""), buf, sizeof(buf)); - EXPECT_STREQ(buf, ""); - - // Less - CpuFeatures_StringView_CopyString(str("a"), buf, sizeof(buf)); - EXPECT_STREQ(buf, "a"); - - // exact - CpuFeatures_StringView_CopyString(str("abc"), buf, sizeof(buf)); - EXPECT_STREQ(buf, "abc"); - - // More - CpuFeatures_StringView_CopyString(str("abcd"), buf, sizeof(buf)); - EXPECT_STREQ(buf, "abc"); -} - -TEST(StringViewTest, CpuFeatures_StringView_HasWord) { - // Find flags at beginning, middle and end. - EXPECT_TRUE( - CpuFeatures_StringView_HasWord(str("first middle last"), "first")); - EXPECT_TRUE( - CpuFeatures_StringView_HasWord(str("first middle last"), "middle")); - EXPECT_TRUE(CpuFeatures_StringView_HasWord(str("first middle last"), "last")); - // Do not match partial flags - EXPECT_FALSE( - CpuFeatures_StringView_HasWord(str("first middle last"), "irst")); - EXPECT_FALSE(CpuFeatures_StringView_HasWord(str("first middle last"), "mid")); - EXPECT_FALSE(CpuFeatures_StringView_HasWord(str("first middle last"), "las")); -} - -TEST(StringViewTest, CpuFeatures_StringView_GetAttributeKeyValue) { - const StringView line = str(" key : first middle last "); - StringView key, value; - EXPECT_TRUE(CpuFeatures_StringView_GetAttributeKeyValue(line, &key, &value)); - EXPECT_EQ(key, str("key")); - EXPECT_EQ(value, str("first middle last")); -} - -TEST(StringViewTest, FailingGetAttributeKeyValue) { - const StringView line = str("key first middle last"); - StringView key, value; - EXPECT_FALSE(CpuFeatures_StringView_GetAttributeKeyValue(line, &key, &value)); -} - -} // namespace -} // namespace cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/unix_features_aggregator_test.cc b/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/unix_features_aggregator_test.cc deleted file mode 100644 index 20d146c..0000000 --- a/reverse_engineering/node_modules/cpu-features/deps/cpu_features/test/unix_features_aggregator_test.cc +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2017 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "internal/unix_features_aggregator.h" - -#include - -#include "gtest/gtest.h" - -namespace cpu_features { - -namespace { - -struct Features { - bool a = false; - bool b = false; - bool c = false; -}; - -enum eFeatures { TEST_a, TEST_b, TEST_c }; - -DECLARE_SETTER_AND_GETTER(Features, a) -DECLARE_SETTER_AND_GETTER(Features, b) -DECLARE_SETTER_AND_GETTER(Features, c) - -class LinuxFeatureAggregatorTest : public testing::Test { - public: - const std::array kConfigs = { - {{{0b0001, 0b0000}, "a", &set_a, &get_a}, - {{0b0010, 0b0000}, "b", &set_b, &get_b}, - {{0b0000, 0b1100}, "c", &set_c, &get_c}}}; -}; - -TEST_F(LinuxFeatureAggregatorTest, FromFlagsEmpty) { - Features features; - CpuFeatures_SetFromFlags(kConfigs.size(), kConfigs.data(), str(""), - &features); - EXPECT_FALSE(features.a); - EXPECT_FALSE(features.b); - EXPECT_FALSE(features.c); - - EXPECT_FALSE(kConfigs[TEST_a].get_bit(&features)); -} - -TEST_F(LinuxFeatureAggregatorTest, FromFlagsAllSet) { - Features features; - CpuFeatures_SetFromFlags(kConfigs.size(), kConfigs.data(), str("a c b"), - &features); - EXPECT_TRUE(features.a); - EXPECT_TRUE(features.b); - EXPECT_TRUE(features.c); - - EXPECT_TRUE(kConfigs[TEST_a].get_bit(&features)); -} - -TEST_F(LinuxFeatureAggregatorTest, FromFlagsOnlyA) { - Features features; - CpuFeatures_SetFromFlags(kConfigs.size(), kConfigs.data(), str("a"), - &features); - EXPECT_TRUE(features.a); - EXPECT_FALSE(features.b); - EXPECT_FALSE(features.c); - - EXPECT_TRUE(kConfigs[TEST_a].get_bit(&features)); - EXPECT_FALSE(kConfigs[TEST_b].get_bit(&features)); - EXPECT_FALSE(kConfigs[TEST_c].get_bit(&features)); -} - -TEST_F(LinuxFeatureAggregatorTest, FromHwcapsNone) { - HardwareCapabilities capability; - capability.hwcaps = 0; // matches none - capability.hwcaps2 = 0; // matches none - Features features; - CpuFeatures_OverrideFromHwCaps(kConfigs.size(), kConfigs.data(), capability, - &features); - EXPECT_FALSE(features.a); - EXPECT_FALSE(features.b); - EXPECT_FALSE(features.c); -} - -TEST_F(LinuxFeatureAggregatorTest, FromHwcapsSet) { - HardwareCapabilities capability; - capability.hwcaps = 0b0010; // matches b but not a - capability.hwcaps2 = 0b1111; // matches c - Features features; - CpuFeatures_OverrideFromHwCaps(kConfigs.size(), kConfigs.data(), capability, - &features); - EXPECT_FALSE(features.a); - EXPECT_TRUE(features.b); - EXPECT_TRUE(features.c); -} - -} // namespace -} // namespace cpu_features diff --git a/reverse_engineering/node_modules/cpu-features/lib/index.js b/reverse_engineering/node_modules/cpu-features/lib/index.js deleted file mode 100644 index f1856cd..0000000 --- a/reverse_engineering/node_modules/cpu-features/lib/index.js +++ /dev/null @@ -1,3 +0,0 @@ -const binding = require('../build/Release/cpufeatures.node'); - -module.exports = binding.getCPUInfo; diff --git a/reverse_engineering/node_modules/cpu-features/package.json b/reverse_engineering/node_modules/cpu-features/package.json deleted file mode 100644 index a11e4ee..0000000 --- a/reverse_engineering/node_modules/cpu-features/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "_from": "cpu-features@0.0.2", - "_id": "cpu-features@0.0.2", - "_inBundle": false, - "_integrity": "sha512-/2yieBqvMcRj8McNzkycjW2v3OIUOibBfd2dLEJ0nWts8NobAxwiyw9phVNS6oDL8x8tz9F7uNVFEVpJncQpeA==", - "_location": "/cpu-features", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "cpu-features@0.0.2", - "name": "cpu-features", - "escapedName": "cpu-features", - "rawSpec": "0.0.2", - "saveSpec": null, - "fetchSpec": "0.0.2" - }, - "_requiredBy": [ - "/ssh2" - ], - "_resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.2.tgz", - "_shasum": "9f636156f1155fd04bdbaa028bb3c2fbef3cea7a", - "_spec": "cpu-features@0.0.2", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/ssh2", - "author": { - "name": "Brian White", - "email": "mscdex@mscdex.net" - }, - "bugs": { - "url": "https://github.com/mscdex/cpu-features/issues" - }, - "bundleDependencies": false, - "dependencies": { - "nan": "^2.14.1" - }, - "deprecated": false, - "description": "A simple binding to Google's cpu_features library for obtaining information about installed CPU(s)", - "engines": { - "node": ">=8.0.0" - }, - "gypfile": true, - "homepage": "https://github.com/mscdex/cpu-features#readme", - "keywords": [ - "cpu", - "detect", - "detection", - "features" - ], - "licenses": [ - { - "type": "MIT", - "url": "https://github.com/mscdex/cpu-features/raw/master/LICENSE" - } - ], - "main": "./lib/index", - "name": "cpu-features", - "repository": { - "type": "git", - "url": "git+https://github.com/mscdex/cpu-features.git" - }, - "scripts": { - "install": "node-gyp rebuild", - "test": "node test/test.js" - }, - "version": "0.0.2" -} diff --git a/reverse_engineering/node_modules/cpu-features/src/binding.cc b/reverse_engineering/node_modules/cpu-features/src/binding.cc deleted file mode 100644 index 8626714..0000000 --- a/reverse_engineering/node_modules/cpu-features/src/binding.cc +++ /dev/null @@ -1,153 +0,0 @@ -#include -#include -#include -#include // isspace - -#include "cpu_features_macros.h" - -#if defined(CPU_FEATURES_ARCH_X86) -# include "cpuinfo_x86.h" -# define GetFeatureName GetX86FeaturesEnumName -# define GetFeatureValue GetX86FeaturesEnumValue -# define FeatureType X86Features -# define FeatureEnumType X86FeaturesEnum -# define LastFeature X86_LAST_ -#elif defined(CPU_FEATURES_ARCH_ARM) -# include "cpuinfo_arm.h" -# define GetFeatureName GetArmFeaturesEnumName -# define GetFeatureValue GetArmFeaturesEnumValue -# define FeatureType ArmFeatures -# define FeatureEnumType ArmFeaturesEnum -# define LastFeature ARM_LAST_ -#elif defined(CPU_FEATURES_ARCH_AARCH64) -# include "cpuinfo_aarch64.h" -# define GetFeatureName GetAarch64FeaturesEnumName -# define GetFeatureValue GetAarch64FeaturesEnumValue -# define FeatureType Aarch64Features -# define FeatureEnumType Aarch64FeaturesEnum -# define LastFeature AARCH64_LAST_ -#elif defined(CPU_FEATURES_ARCH_MIPS) -# include "cpuinfo_mips.h" -# define GetFeatureName GetMipsFeaturesEnumName -# define GetFeatureValue GetMipsFeaturesEnumValue -# define FeatureType MipsFeatures -# define FeatureEnumType MipsFeaturesEnum -# define LastFeature MIPS_LAST_ -#elif defined(CPU_FEATURES_ARCH_PPC) -# include "cpuinfo_ppc.h" -# define GetFeatureName GetPPCFeaturesEnumName -# define GetFeatureValue GetPPCFeaturesEnumValue -# define FeatureType PPCFeatures -# define FeatureEnumType PPCFeaturesEnum -# define LastFeature PPC_LAST_ -#endif - -#define SET_FLAG(key) \ -Nan::Set(ret, Nan::New(key).ToLocalChecked(), Nan::New(true)) - -#define SET_STR(key, val) \ -Nan::Set(ret, \ - Nan::New(key).ToLocalChecked(), \ - Nan::New(trim(val)).ToLocalChecked()) - -#define SET_NUM(key, val) \ -Nan::Set(ret, Nan::New(key).ToLocalChecked(), Nan::New(val)) - -#define SET_VAL(key, val) \ -Nan::Set(ret, Nan::New(key).ToLocalChecked(), val) - -using namespace node; -using namespace v8; -using namespace cpu_features; -using namespace std; - -static inline void ltrim(string& s) { - s.erase(s.begin(), find_if(s.begin(), s.end(), [](int ch) { - return !isspace(ch); - })); -} - -static inline void rtrim(string& s) { - s.erase(find_if(s.rbegin(), s.rend(), [](int ch) { - return !isspace(ch); - }).base(), s.end()); -} - -static inline string trim(const char* str) { - string ret = str; - ltrim(ret); - rtrim(ret); - return ret; -} - -#if defined(LastFeature) -Local GenerateFlags(const FeatureType* features) { - const auto ret = Nan::New(); - for (size_t i = 0; i < LastFeature; ++i) { - const auto enum_val = static_cast(i); - if (GetFeatureValue(features, enum_val)) - SET_FLAG(GetFeatureName(enum_val)); - } - return ret; -} -#endif - -NAN_METHOD(GetCPUInfo) { - const auto ret = Nan::New(); -#if defined(CPU_FEATURES_ARCH_X86) - char brand_string[49]; - const X86Info details = GetX86Info(); - FillX86BrandString(brand_string); - SET_STR("arch", "x86"); - SET_STR("brand", brand_string); - SET_NUM("family", details.family); - SET_NUM("model", details.model); - SET_NUM("stepping", details.stepping); - SET_STR("uarch", - GetX86MicroarchitectureName(GetX86Microarchitecture(&details))); - SET_VAL("flags", GenerateFlags(&details.features)); -#elif defined(CPU_FEATURES_ARCH_ARM) - const ArmInfo details = GetArmInfo(); - SET_STR("arch", "arm"); - SET_NUM("implementer", details.implementer); - SET_NUM("architecture", details.architecture); - SET_NUM("variant", details.variant); - SET_NUM("part", details.part); - SET_NUM("revision", details.revision); - SET_VAL("flags", GenerateFlags(&details.features)); -#elif defined(CPU_FEATURES_ARCH_AARCH64) - const Aarch64Info details = GetAarch64Info(); - SET_STR("arch", "aarch64"); - SET_NUM("implementer", details.implementer); - SET_NUM("variant", details.variant); - SET_NUM("part", details.part); - SET_NUM("revision", details.revision); - SET_VAL("flags", GenerateFlags(&details.features)); -#elif defined(CPU_FEATURES_ARCH_MIPS) - const MipsInfo details = GetMipsInfo(); - SET_STR("arch", "mips"); - SET_VAL("flags", GenerateFlags(&details.features)); -#elif defined(CPU_FEATURES_ARCH_PPC) - const PPCInfo details = GetPPCInfo(); - const PPCPlatformStrings strings = GetPPCPlatformStrings(); - SET_STR("arch", "ppc"); - SET_STR("platform", strings.platform); - SET_STR("model", strings.model); - SET_STR("machine", strings.machine); - SET_STR("cpu", strings.cpu); - SET_STR("instruction set", strings.type.platform); - SET_STR("microarchitecture", strings.type.base_platform); - SET_VAL("flags", GenerateFlags(&details.features)); -#else - SET_STR("arch", "unknown"); - SET_VAL("flags", Nan::New()); -#endif - info.GetReturnValue().Set(ret); -} - -NAN_MODULE_INIT(init) { - Nan::Set(target, Nan::New("getCPUInfo").ToLocalChecked(), - Nan::GetFunction(Nan::New(GetCPUInfo)).ToLocalChecked()); -} - -NODE_MODULE(cpufeatures, init) diff --git a/reverse_engineering/node_modules/debug/.coveralls.yml b/reverse_engineering/node_modules/debug/.coveralls.yml deleted file mode 100644 index 20a7068..0000000 --- a/reverse_engineering/node_modules/debug/.coveralls.yml +++ /dev/null @@ -1 +0,0 @@ -repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/reverse_engineering/node_modules/debug/.eslintrc b/reverse_engineering/node_modules/debug/.eslintrc deleted file mode 100644 index 8a37ae2..0000000 --- a/reverse_engineering/node_modules/debug/.eslintrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "env": { - "browser": true, - "node": true - }, - "rules": { - "no-console": 0, - "no-empty": [1, { "allowEmptyCatch": true }] - }, - "extends": "eslint:recommended" -} diff --git a/reverse_engineering/node_modules/debug/.npmignore b/reverse_engineering/node_modules/debug/.npmignore deleted file mode 100644 index 5f60eec..0000000 --- a/reverse_engineering/node_modules/debug/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -support -test -examples -example -*.sock -dist -yarn.lock -coverage -bower.json diff --git a/reverse_engineering/node_modules/debug/.travis.yml b/reverse_engineering/node_modules/debug/.travis.yml deleted file mode 100644 index 6c6090c..0000000 --- a/reverse_engineering/node_modules/debug/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ - -language: node_js -node_js: - - "6" - - "5" - - "4" - -install: - - make node_modules - -script: - - make lint - - make test - - make coveralls diff --git a/reverse_engineering/node_modules/debug/CHANGELOG.md b/reverse_engineering/node_modules/debug/CHANGELOG.md deleted file mode 100644 index eadaa18..0000000 --- a/reverse_engineering/node_modules/debug/CHANGELOG.md +++ /dev/null @@ -1,362 +0,0 @@ - -2.6.9 / 2017-09-22 -================== - - * remove ReDoS regexp in %o formatter (#504) - -2.6.8 / 2017-05-18 -================== - - * Fix: Check for undefined on browser globals (#462, @marbemac) - -2.6.7 / 2017-05-16 -================== - - * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) - * Fix: Inline extend function in node implementation (#452, @dougwilson) - * Docs: Fix typo (#455, @msasad) - -2.6.5 / 2017-04-27 -================== - - * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) - * Misc: clean up browser reference checks (#447, @thebigredgeek) - * Misc: add npm-debug.log to .gitignore (@thebigredgeek) - - -2.6.4 / 2017-04-20 -================== - - * Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) - * Chore: ignore bower.json in npm installations. (#437, @joaovieira) - * Misc: update "ms" to v0.7.3 (@tootallnate) - -2.6.3 / 2017-03-13 -================== - - * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) - * Docs: Changelog fix (@thebigredgeek) - -2.6.2 / 2017-03-10 -================== - - * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) - * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) - * Docs: Add Slackin invite badge (@tootallnate) - -2.6.1 / 2017-02-10 -================== - - * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error - * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) - * Fix: IE8 "Expected identifier" error (#414, @vgoma) - * Fix: Namespaces would not disable once enabled (#409, @musikov) - -2.6.0 / 2016-12-28 -================== - - * Fix: added better null pointer checks for browser useColors (@thebigredgeek) - * Improvement: removed explicit `window.debug` export (#404, @tootallnate) - * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) - -2.5.2 / 2016-12-25 -================== - - * Fix: reference error on window within webworkers (#393, @KlausTrainer) - * Docs: fixed README typo (#391, @lurch) - * Docs: added notice about v3 api discussion (@thebigredgeek) - -2.5.1 / 2016-12-20 -================== - - * Fix: babel-core compatibility - -2.5.0 / 2016-12-20 -================== - - * Fix: wrong reference in bower file (@thebigredgeek) - * Fix: webworker compatibility (@thebigredgeek) - * Fix: output formatting issue (#388, @kribblo) - * Fix: babel-loader compatibility (#383, @escwald) - * Misc: removed built asset from repo and publications (@thebigredgeek) - * Misc: moved source files to /src (#378, @yamikuronue) - * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) - * Test: coveralls integration (#378, @yamikuronue) - * Docs: simplified language in the opening paragraph (#373, @yamikuronue) - -2.4.5 / 2016-12-17 -================== - - * Fix: `navigator` undefined in Rhino (#376, @jochenberger) - * Fix: custom log function (#379, @hsiliev) - * Improvement: bit of cleanup + linting fixes (@thebigredgeek) - * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) - * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) - -2.4.4 / 2016-12-14 -================== - - * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) - -2.4.3 / 2016-12-14 -================== - - * Fix: navigation.userAgent error for react native (#364, @escwald) - -2.4.2 / 2016-12-14 -================== - - * Fix: browser colors (#367, @tootallnate) - * Misc: travis ci integration (@thebigredgeek) - * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) - -2.4.1 / 2016-12-13 -================== - - * Fix: typo that broke the package (#356) - -2.4.0 / 2016-12-13 -================== - - * Fix: bower.json references unbuilt src entry point (#342, @justmatt) - * Fix: revert "handle regex special characters" (@tootallnate) - * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) - * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) - * Improvement: allow colors in workers (#335, @botverse) - * Improvement: use same color for same namespace. (#338, @lchenay) - -2.3.3 / 2016-11-09 -================== - - * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) - * Fix: Returning `localStorage` saved values (#331, Levi Thomason) - * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) - -2.3.2 / 2016-11-09 -================== - - * Fix: be super-safe in index.js as well (@TooTallNate) - * Fix: should check whether process exists (Tom Newby) - -2.3.1 / 2016-11-09 -================== - - * Fix: Added electron compatibility (#324, @paulcbetts) - * Improvement: Added performance optimizations (@tootallnate) - * Readme: Corrected PowerShell environment variable example (#252, @gimre) - * Misc: Removed yarn lock file from source control (#321, @fengmk2) - -2.3.0 / 2016-11-07 -================== - - * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) - * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) - * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) - * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) - * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) - * Package: Update "ms" to 0.7.2 (#315, @DevSide) - * Package: removed superfluous version property from bower.json (#207 @kkirsche) - * Readme: fix USE_COLORS to DEBUG_COLORS - * Readme: Doc fixes for format string sugar (#269, @mlucool) - * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) - * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) - * Readme: better docs for browser support (#224, @matthewmueller) - * Tooling: Added yarn integration for development (#317, @thebigredgeek) - * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) - * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) - * Misc: Updated contributors (@thebigredgeek) - -2.2.0 / 2015-05-09 -================== - - * package: update "ms" to v0.7.1 (#202, @dougwilson) - * README: add logging to file example (#193, @DanielOchoa) - * README: fixed a typo (#191, @amir-s) - * browser: expose `storage` (#190, @stephenmathieson) - * Makefile: add a `distclean` target (#189, @stephenmathieson) - -2.1.3 / 2015-03-13 -================== - - * Updated stdout/stderr example (#186) - * Updated example/stdout.js to match debug current behaviour - * Renamed example/stderr.js to stdout.js - * Update Readme.md (#184) - * replace high intensity foreground color for bold (#182, #183) - -2.1.2 / 2015-03-01 -================== - - * dist: recompile - * update "ms" to v0.7.0 - * package: update "browserify" to v9.0.3 - * component: fix "ms.js" repo location - * changed bower package name - * updated documentation about using debug in a browser - * fix: security error on safari (#167, #168, @yields) - -2.1.1 / 2014-12-29 -================== - - * browser: use `typeof` to check for `console` existence - * browser: check for `console.log` truthiness (fix IE 8/9) - * browser: add support for Chrome apps - * Readme: added Windows usage remarks - * Add `bower.json` to properly support bower install - -2.1.0 / 2014-10-15 -================== - - * node: implement `DEBUG_FD` env variable support - * package: update "browserify" to v6.1.0 - * package: add "license" field to package.json (#135, @panuhorsmalahti) - -2.0.0 / 2014-09-01 -================== - - * package: update "browserify" to v5.11.0 - * node: use stderr rather than stdout for logging (#29, @stephenmathieson) - -1.0.4 / 2014-07-15 -================== - - * dist: recompile - * example: remove `console.info()` log usage - * example: add "Content-Type" UTF-8 header to browser example - * browser: place %c marker after the space character - * browser: reset the "content" color via `color: inherit` - * browser: add colors support for Firefox >= v31 - * debug: prefer an instance `log()` function over the global one (#119) - * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) - -1.0.3 / 2014-07-09 -================== - - * Add support for multiple wildcards in namespaces (#122, @seegno) - * browser: fix lint - -1.0.2 / 2014-06-10 -================== - - * browser: update color palette (#113, @gscottolson) - * common: make console logging function configurable (#108, @timoxley) - * node: fix %o colors on old node <= 0.8.x - * Makefile: find node path using shell/which (#109, @timoxley) - -1.0.1 / 2014-06-06 -================== - - * browser: use `removeItem()` to clear localStorage - * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) - * package: add "contributors" section - * node: fix comment typo - * README: list authors - -1.0.0 / 2014-06-04 -================== - - * make ms diff be global, not be scope - * debug: ignore empty strings in enable() - * node: make DEBUG_COLORS able to disable coloring - * *: export the `colors` array - * npmignore: don't publish the `dist` dir - * Makefile: refactor to use browserify - * package: add "browserify" as a dev dependency - * Readme: add Web Inspector Colors section - * node: reset terminal color for the debug content - * node: map "%o" to `util.inspect()` - * browser: map "%j" to `JSON.stringify()` - * debug: add custom "formatters" - * debug: use "ms" module for humanizing the diff - * Readme: add "bash" syntax highlighting - * browser: add Firebug color support - * browser: add colors for WebKit browsers - * node: apply log to `console` - * rewrite: abstract common logic for Node & browsers - * add .jshintrc file - -0.8.1 / 2014-04-14 -================== - - * package: re-add the "component" section - -0.8.0 / 2014-03-30 -================== - - * add `enable()` method for nodejs. Closes #27 - * change from stderr to stdout - * remove unnecessary index.js file - -0.7.4 / 2013-11-13 -================== - - * remove "browserify" key from package.json (fixes something in browserify) - -0.7.3 / 2013-10-30 -================== - - * fix: catch localStorage security error when cookies are blocked (Chrome) - * add debug(err) support. Closes #46 - * add .browser prop to package.json. Closes #42 - -0.7.2 / 2013-02-06 -================== - - * fix package.json - * fix: Mobile Safari (private mode) is broken with debug - * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript - -0.7.1 / 2013-02-05 -================== - - * add repository URL to package.json - * add DEBUG_COLORED to force colored output - * add browserify support - * fix component. Closes #24 - -0.7.0 / 2012-05-04 -================== - - * Added .component to package.json - * Added debug.component.js build - -0.6.0 / 2012-03-16 -================== - - * Added support for "-" prefix in DEBUG [Vinay Pulim] - * Added `.enabled` flag to the node version [TooTallNate] - -0.5.0 / 2012-02-02 -================== - - * Added: humanize diffs. Closes #8 - * Added `debug.disable()` to the CS variant - * Removed padding. Closes #10 - * Fixed: persist client-side variant again. Closes #9 - -0.4.0 / 2012-02-01 -================== - - * Added browser variant support for older browsers [TooTallNate] - * Added `debug.enable('project:*')` to browser variant [TooTallNate] - * Added padding to diff (moved it to the right) - -0.3.0 / 2012-01-26 -================== - - * Added millisecond diff when isatty, otherwise UTC string - -0.2.0 / 2012-01-22 -================== - - * Added wildcard support - -0.1.0 / 2011-12-02 -================== - - * Added: remove colors unless stderr isatty [TooTallNate] - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/reverse_engineering/node_modules/debug/LICENSE b/reverse_engineering/node_modules/debug/LICENSE deleted file mode 100644 index 658c933..0000000 --- a/reverse_engineering/node_modules/debug/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software -and associated documentation files (the 'Software'), to deal in the Software without restriction, -including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial -portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT -LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/reverse_engineering/node_modules/debug/Makefile b/reverse_engineering/node_modules/debug/Makefile deleted file mode 100644 index 584da8b..0000000 --- a/reverse_engineering/node_modules/debug/Makefile +++ /dev/null @@ -1,50 +0,0 @@ -# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 -THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) -THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) - -# BIN directory -BIN := $(THIS_DIR)/node_modules/.bin - -# Path -PATH := node_modules/.bin:$(PATH) -SHELL := /bin/bash - -# applications -NODE ?= $(shell which node) -YARN ?= $(shell which yarn) -PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) -BROWSERIFY ?= $(NODE) $(BIN)/browserify - -.FORCE: - -install: node_modules - -node_modules: package.json - @NODE_ENV= $(PKG) install - @touch node_modules - -lint: .FORCE - eslint browser.js debug.js index.js node.js - -test-node: .FORCE - istanbul cover node_modules/mocha/bin/_mocha -- test/**.js - -test-browser: .FORCE - mkdir -p dist - - @$(BROWSERIFY) \ - --standalone debug \ - . > dist/debug.js - - karma start --single-run - rimraf dist - -test: .FORCE - concurrently \ - "make test-node" \ - "make test-browser" - -coveralls: - cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js - -.PHONY: all install clean distclean diff --git a/reverse_engineering/node_modules/debug/README.md b/reverse_engineering/node_modules/debug/README.md deleted file mode 100644 index f67be6b..0000000 --- a/reverse_engineering/node_modules/debug/README.md +++ /dev/null @@ -1,312 +0,0 @@ -# debug -[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) -[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) - - - -A tiny node.js debugging utility modelled after node core's debugging technique. - -**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** - -## Installation - -```bash -$ npm install debug -``` - -## Usage - -`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. - -Example _app.js_: - -```js -var debug = require('debug')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %s', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); -``` - -Example _worker.js_: - -```js -var debug = require('debug')('worker'); - -setInterval(function(){ - debug('doing some work'); -}, 1000); -``` - - The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: - - ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) - - ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) - -#### Windows note - - On Windows the environment variable is set using the `set` command. - - ```cmd - set DEBUG=*,-not_this - ``` - - Note that PowerShell uses different syntax to set environment variables. - - ```cmd - $env:DEBUG = "*,-not_this" - ``` - -Then, run the program to be debugged as usual. - -## Millisecond diff - - When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. - - ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) - - When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: - - ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) - -## Conventions - - If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". - -## Wildcards - - The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. - - You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". - -## Environment Variables - - When running through Node.js, you can set a few environment variables that will - change the behavior of the debug logging: - -| Name | Purpose | -|-----------|-------------------------------------------------| -| `DEBUG` | Enables/disables specific debugging namespaces. | -| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | -| `DEBUG_DEPTH` | Object inspection depth. | -| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | - - - __Note:__ The environment variables beginning with `DEBUG_` end up being - converted into an Options object that gets used with `%o`/`%O` formatters. - See the Node.js documentation for - [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) - for the complete list. - -## Formatters - - - Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: - -| Formatter | Representation | -|-----------|----------------| -| `%O` | Pretty-print an Object on multiple lines. | -| `%o` | Pretty-print an Object all on a single line. | -| `%s` | String. | -| `%d` | Number (both integer and float). | -| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | -| `%%` | Single percent sign ('%'). This does not consume an argument. | - -### Custom formatters - - You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: - -```js -const createDebug = require('debug') -createDebug.formatters.h = (v) => { - return v.toString('hex') -} - -// …elsewhere -const debug = createDebug('foo') -debug('this is hex: %h', new Buffer('hello world')) -// foo this is hex: 68656c6c6f20776f726c6421 +0ms -``` - -## Browser support - You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), - or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), - if you don't want to build it yourself. - - Debug's enable state is currently persisted by `localStorage`. - Consider the situation shown below where you have `worker:a` and `worker:b`, - and wish to debug both. You can enable this using `localStorage.debug`: - -```js -localStorage.debug = 'worker:*' -``` - -And then refresh the page. - -```js -a = debug('worker:a'); -b = debug('worker:b'); - -setInterval(function(){ - a('doing some work'); -}, 1000); - -setInterval(function(){ - b('doing some work'); -}, 1200); -``` - -#### Web Inspector Colors - - Colors are also enabled on "Web Inspectors" that understand the `%c` formatting - option. These are WebKit web inspectors, Firefox ([since version - 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) - and the Firebug plugin for Firefox (any version). - - Colored output looks something like: - - ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) - - -## Output streams - - By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: - -Example _stdout.js_: - -```js -var debug = require('debug'); -var error = debug('app:error'); - -// by default stderr is used -error('goes to stderr!'); - -var log = debug('app:log'); -// set this namespace to log via console.log -log.log = console.log.bind(console); // don't forget to bind to console! -log('goes to stdout'); -error('still goes to stderr!'); - -// set all output to go via console.info -// overrides all per-namespace log settings -debug.log = console.info.bind(console); -error('now goes to stdout via console.info'); -log('still goes to stdout, but via console.info now'); -``` - - -## Authors - - - TJ Holowaychuk - - Nathan Rajlich - - Andrew Rhyne - -## Backers - -Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## Sponsors - -Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -## License - -(The MIT License) - -Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/debug/component.json b/reverse_engineering/node_modules/debug/component.json deleted file mode 100644 index 9de2641..0000000 --- a/reverse_engineering/node_modules/debug/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "debug", - "repo": "visionmedia/debug", - "description": "small debugging utility", - "version": "2.6.9", - "keywords": [ - "debug", - "log", - "debugger" - ], - "main": "src/browser.js", - "scripts": [ - "src/browser.js", - "src/debug.js" - ], - "dependencies": { - "rauchg/ms.js": "0.7.1" - } -} diff --git a/reverse_engineering/node_modules/debug/karma.conf.js b/reverse_engineering/node_modules/debug/karma.conf.js deleted file mode 100644 index 103a82d..0000000 --- a/reverse_engineering/node_modules/debug/karma.conf.js +++ /dev/null @@ -1,70 +0,0 @@ -// Karma configuration -// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) - -module.exports = function(config) { - config.set({ - - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: '', - - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ['mocha', 'chai', 'sinon'], - - - // list of files / patterns to load in the browser - files: [ - 'dist/debug.js', - 'test/*spec.js' - ], - - - // list of files to exclude - exclude: [ - 'src/node.js' - ], - - - // preprocess matching files before serving them to the browser - // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - preprocessors: { - }, - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ['progress'], - - - // web server port - port: 9876, - - - // enable / disable colors in the output (reporters and logs) - colors: true, - - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: true, - - - // start these browsers - // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: ['PhantomJS'], - - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: false, - - // Concurrency level - // how many browser should be started simultaneous - concurrency: Infinity - }) -} diff --git a/reverse_engineering/node_modules/debug/node.js b/reverse_engineering/node_modules/debug/node.js deleted file mode 100644 index 7fc36fe..0000000 --- a/reverse_engineering/node_modules/debug/node.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./src/node'); diff --git a/reverse_engineering/node_modules/debug/package.json b/reverse_engineering/node_modules/debug/package.json deleted file mode 100644 index 52b92ec..0000000 --- a/reverse_engineering/node_modules/debug/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "_from": "debug@2.6.9", - "_id": "debug@2.6.9", - "_inBundle": false, - "_integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "_location": "/debug", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "debug@2.6.9", - "name": "debug", - "escapedName": "debug", - "rawSpec": "2.6.9", - "saveSpec": null, - "fetchSpec": "2.6.9" - }, - "_requiredBy": [ - "/tunnel-ssh" - ], - "_resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "_shasum": "5d128515df134ff327e90a4c93f4e077a536341f", - "_spec": "debug@2.6.9", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/tunnel-ssh", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "browser": "./src/browser.js", - "bugs": { - "url": "https://github.com/visionmedia/debug/issues" - }, - "bundleDependencies": false, - "component": { - "scripts": { - "debug/index.js": "browser.js", - "debug/debug.js": "debug.js" - } - }, - "contributors": [ - { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "http://n8.io" - }, - { - "name": "Andrew Rhyne", - "email": "rhyneandrew@gmail.com" - } - ], - "dependencies": { - "ms": "2.0.0" - }, - "deprecated": false, - "description": "small debugging utility", - "devDependencies": { - "browserify": "9.0.3", - "chai": "^3.5.0", - "concurrently": "^3.1.0", - "coveralls": "^2.11.15", - "eslint": "^3.12.1", - "istanbul": "^0.4.5", - "karma": "^1.3.0", - "karma-chai": "^0.1.0", - "karma-mocha": "^1.3.0", - "karma-phantomjs-launcher": "^1.0.2", - "karma-sinon": "^1.0.5", - "mocha": "^3.2.0", - "mocha-lcov-reporter": "^1.2.0", - "rimraf": "^2.5.4", - "sinon": "^1.17.6", - "sinon-chai": "^2.8.0" - }, - "homepage": "https://github.com/visionmedia/debug#readme", - "keywords": [ - "debug", - "log", - "debugger" - ], - "license": "MIT", - "main": "./src/index.js", - "name": "debug", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/debug.git" - }, - "version": "2.6.9" -} diff --git a/reverse_engineering/node_modules/debug/src/browser.js b/reverse_engineering/node_modules/debug/src/browser.js deleted file mode 100644 index 7106924..0000000 --- a/reverse_engineering/node_modules/debug/src/browser.js +++ /dev/null @@ -1,185 +0,0 @@ -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } - - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} diff --git a/reverse_engineering/node_modules/debug/src/debug.js b/reverse_engineering/node_modules/debug/src/debug.js deleted file mode 100644 index 6a5e3fc..0000000 --- a/reverse_engineering/node_modules/debug/src/debug.js +++ /dev/null @@ -1,202 +0,0 @@ - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; - -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - -exports.formatters = {}; - -/** - * Previous log timestamp. - */ - -var prevTime; - -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - -function selectColor(namespace) { - var hash = 0, i; - - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return exports.colors[Math.abs(hash) % exports.colors.length]; -} - -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - return debug; -} - -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } -} - -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} - -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} diff --git a/reverse_engineering/node_modules/debug/src/index.js b/reverse_engineering/node_modules/debug/src/index.js deleted file mode 100644 index e12cf4d..0000000 --- a/reverse_engineering/node_modules/debug/src/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ - -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = require('./browser.js'); -} else { - module.exports = require('./node.js'); -} diff --git a/reverse_engineering/node_modules/debug/src/inspector-log.js b/reverse_engineering/node_modules/debug/src/inspector-log.js deleted file mode 100644 index 60ea6c0..0000000 --- a/reverse_engineering/node_modules/debug/src/inspector-log.js +++ /dev/null @@ -1,15 +0,0 @@ -module.exports = inspectorLog; - -// black hole -const nullStream = new (require('stream').Writable)(); -nullStream._write = () => {}; - -/** - * Outputs a `console.log()` to the Node.js Inspector console *only*. - */ -function inspectorLog() { - const stdout = console._stdout; - console._stdout = nullStream; - console.log.apply(console, arguments); - console._stdout = stdout; -} diff --git a/reverse_engineering/node_modules/debug/src/node.js b/reverse_engineering/node_modules/debug/src/node.js deleted file mode 100644 index b15109c..0000000 --- a/reverse_engineering/node_modules/debug/src/node.js +++ /dev/null @@ -1,248 +0,0 @@ -/** - * Module dependencies. - */ - -var tty = require('tty'); -var util = require('util'); - -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); - - obj[prop] = val; - return obj; -}, {}); - -/** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log - */ - -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() -} - -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; - -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ - -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; - - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; - } -} - -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ - -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Copied from `node/src/node.js`. - * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. - */ - -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); - - // Note stream._type is used for test-module-load-list.js - - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; - - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - case 'FILE': - var fs = require('fs'); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; - - case 'PIPE': - case 'TCP': - var net = require('net'); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); - - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; - - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } - - // For supporting legacy API we put the FD here. - stream.fd = fd; - - stream._isStdio = true; - - return stream; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init (debug) { - debug.inspectOpts = {}; - - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ - -exports.enable(load()); diff --git a/reverse_engineering/node_modules/inherits/LICENSE b/reverse_engineering/node_modules/inherits/LICENSE deleted file mode 100644 index dea3013..0000000 --- a/reverse_engineering/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. - diff --git a/reverse_engineering/node_modules/inherits/README.md b/reverse_engineering/node_modules/inherits/README.md deleted file mode 100644 index b1c5665..0000000 --- a/reverse_engineering/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -Browser-friendly inheritance fully compatible with standard node.js -[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). - -This package exports standard `inherits` from node.js `util` module in -node environment, but also provides alternative browser-friendly -implementation through [browser -field](https://gist.github.com/shtylman/4339901). Alternative -implementation is a literal copy of standard one located in standalone -module to avoid requiring of `util`. It also has a shim for old -browsers with no `Object.create` support. - -While keeping you sure you are using standard `inherits` -implementation in node.js environment, it allows bundlers such as -[browserify](https://github.com/substack/node-browserify) to not -include full `util` package to your client code if all you need is -just `inherits` function. It worth, because browser shim for `util` -package is large and `inherits` is often the single function you need -from it. - -It's recommended to use this package instead of -`require('util').inherits` for any code that has chances to be used -not only in node.js but in browser too. - -## usage - -```js -var inherits = require('inherits'); -// then use exactly as the standard one -``` - -## note on version ~1.0 - -Version ~1.0 had completely different motivation and is not compatible -neither with 2.0 nor with standard node.js `inherits`. - -If you are using version ~1.0 and planning to switch to ~2.0, be -careful: - -* new version uses `super_` instead of `super` for referencing - superclass -* new version overwrites current prototype while old one preserves any - existing fields on it diff --git a/reverse_engineering/node_modules/inherits/inherits.js b/reverse_engineering/node_modules/inherits/inherits.js deleted file mode 100644 index f71f2d9..0000000 --- a/reverse_engineering/node_modules/inherits/inherits.js +++ /dev/null @@ -1,9 +0,0 @@ -try { - var util = require('util'); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = require('./inherits_browser.js'); -} diff --git a/reverse_engineering/node_modules/inherits/inherits_browser.js b/reverse_engineering/node_modules/inherits/inherits_browser.js deleted file mode 100644 index 86bbb3d..0000000 --- a/reverse_engineering/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,27 +0,0 @@ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} diff --git a/reverse_engineering/node_modules/inherits/package.json b/reverse_engineering/node_modules/inherits/package.json deleted file mode 100644 index e7d43f5..0000000 --- a/reverse_engineering/node_modules/inherits/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "_from": "inherits@^2.0.3", - "_id": "inherits@2.0.4", - "_inBundle": false, - "_integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "_location": "/inherits", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "inherits@^2.0.3", - "name": "inherits", - "escapedName": "inherits", - "rawSpec": "^2.0.3", - "saveSpec": null, - "fetchSpec": "^2.0.3" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "_shasum": "0fa2c64f932917c3433a0ded55363aae37416b7c", - "_spec": "inherits@^2.0.3", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/readable-stream", - "browser": "./inherits_browser.js", - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "devDependencies": { - "tap": "^14.2.4" - }, - "files": [ - "inherits.js", - "inherits_browser.js" - ], - "homepage": "https://github.com/isaacs/inherits#readme", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "license": "ISC", - "main": "./inherits.js", - "name": "inherits", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/inherits.git" - }, - "scripts": { - "test": "tap" - }, - "version": "2.0.4" -} diff --git a/reverse_engineering/node_modules/lodash.defaults/LICENSE b/reverse_engineering/node_modules/lodash.defaults/LICENSE deleted file mode 100644 index e0c69d5..0000000 --- a/reverse_engineering/node_modules/lodash.defaults/LICENSE +++ /dev/null @@ -1,47 +0,0 @@ -Copyright jQuery Foundation and other contributors - -Based on Underscore.js, copyright Jeremy Ashkenas, -DocumentCloud and Investigative Reporters & Editors - -This software consists of voluntary contributions made by many -individuals. For exact contribution history, see the revision history -available at https://github.com/lodash/lodash - -The following license applies to all parts of this software except as -documented below: - -==== - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -==== - -Copyright and related rights for sample code are waived via CC0. Sample -code is defined as all source code displayed within the prose of the -documentation. - -CC0: http://creativecommons.org/publicdomain/zero/1.0/ - -==== - -Files located in the node_modules and vendor directories are externally -maintained libraries used by this software which have their own -licenses; we recommend you read them, as their terms may differ from the -terms above. diff --git a/reverse_engineering/node_modules/lodash.defaults/README.md b/reverse_engineering/node_modules/lodash.defaults/README.md deleted file mode 100644 index a129849..0000000 --- a/reverse_engineering/node_modules/lodash.defaults/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# lodash.defaults v4.2.0 - -The [lodash](https://lodash.com/) method `_.defaults` exported as a [Node.js](https://nodejs.org/) module. - -## Installation - -Using npm: -```bash -$ {sudo -H} npm i -g npm -$ npm i --save lodash.defaults -``` - -In Node.js: -```js -var defaults = require('lodash.defaults'); -``` - -See the [documentation](https://lodash.com/docs#defaults) or [package source](https://github.com/lodash/lodash/blob/4.2.0-npm-packages/lodash.defaults) for more details. diff --git a/reverse_engineering/node_modules/lodash.defaults/index.js b/reverse_engineering/node_modules/lodash.defaults/index.js deleted file mode 100644 index 25eba9c..0000000 --- a/reverse_engineering/node_modules/lodash.defaults/index.js +++ /dev/null @@ -1,668 +0,0 @@ -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} - -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; - - var length = result.length, - skipIndexes = !!length; - - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; -} - -/** - * Used by `_.defaults` to customize its `_.assignIn` use. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ -function assignInDefaults(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; -} - -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } -} - -/** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; -} - -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; -} - -/** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ -function copyObject(source, props, object, customizer) { - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; -} - -/** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ -function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); -} - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); -} - -/** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ -function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; -} - -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; -} - -/** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; -} - -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} - -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} - -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} - -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); -}); - -/** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var defaults = baseRest(function(args) { - args.push(undefined, assignInDefaults); - return apply(assignInWith, undefined, args); -}); - -/** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ -function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); -} - -module.exports = defaults; diff --git a/reverse_engineering/node_modules/lodash.defaults/package.json b/reverse_engineering/node_modules/lodash.defaults/package.json deleted file mode 100644 index f2ba5c4..0000000 --- a/reverse_engineering/node_modules/lodash.defaults/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "lodash.defaults@^4.1.0", - "_id": "lodash.defaults@4.2.0", - "_inBundle": false, - "_integrity": "sha1-0JF4cW/+pN3p5ft7N/bwgCJ0WAw=", - "_location": "/lodash.defaults", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "lodash.defaults@^4.1.0", - "name": "lodash.defaults", - "escapedName": "lodash.defaults", - "rawSpec": "^4.1.0", - "saveSpec": null, - "fetchSpec": "^4.1.0" - }, - "_requiredBy": [ - "/tunnel-ssh" - ], - "_resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", - "_shasum": "d09178716ffea4dde9e5fb7b37f6f0802274580c", - "_spec": "lodash.defaults@^4.1.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/tunnel-ssh", - "author": { - "name": "John-David Dalton", - "email": "john.david.dalton@gmail.com", - "url": "http://allyoucanleet.com/" - }, - "bugs": { - "url": "https://github.com/lodash/lodash/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "John-David Dalton", - "email": "john.david.dalton@gmail.com", - "url": "http://allyoucanleet.com/" - }, - { - "name": "Blaine Bublitz", - "email": "blaine.bublitz@gmail.com", - "url": "https://github.com/phated" - }, - { - "name": "Mathias Bynens", - "email": "mathias@qiwi.be", - "url": "https://mathiasbynens.be/" - } - ], - "deprecated": false, - "description": "The lodash method `_.defaults` exported as a module.", - "homepage": "https://lodash.com/", - "icon": "https://lodash.com/icon.svg", - "keywords": [ - "lodash-modularized", - "defaults" - ], - "license": "MIT", - "name": "lodash.defaults", - "repository": { - "type": "git", - "url": "git+https://github.com/lodash/lodash.git" - }, - "scripts": { - "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" - }, - "version": "4.2.0" -} diff --git a/reverse_engineering/node_modules/ms/index.js b/reverse_engineering/node_modules/ms/index.js deleted file mode 100644 index 6a522b1..0000000 --- a/reverse_engineering/node_modules/ms/index.js +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} diff --git a/reverse_engineering/node_modules/ms/license.md b/reverse_engineering/node_modules/ms/license.md deleted file mode 100644 index 69b6125..0000000 --- a/reverse_engineering/node_modules/ms/license.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Zeit, Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/reverse_engineering/node_modules/ms/package.json b/reverse_engineering/node_modules/ms/package.json deleted file mode 100644 index ac7e030..0000000 --- a/reverse_engineering/node_modules/ms/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "ms@2.0.0", - "_id": "ms@2.0.0", - "_inBundle": false, - "_integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "_location": "/ms", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "ms@2.0.0", - "name": "ms", - "escapedName": "ms", - "rawSpec": "2.0.0", - "saveSpec": null, - "fetchSpec": "2.0.0" - }, - "_requiredBy": [ - "/debug" - ], - "_resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "_shasum": "5608aeadfc00be6c2901df5f9861788de0d597c8", - "_spec": "ms@2.0.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/debug", - "bugs": { - "url": "https://github.com/zeit/ms/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Tiny milisecond conversion utility", - "devDependencies": { - "eslint": "3.19.0", - "expect.js": "0.3.1", - "husky": "0.13.3", - "lint-staged": "3.4.1", - "mocha": "3.4.1" - }, - "eslintConfig": { - "extends": "eslint:recommended", - "env": { - "node": true, - "es6": true - } - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/zeit/ms#readme", - "license": "MIT", - "lint-staged": { - "*.js": [ - "npm run lint", - "prettier --single-quote --write", - "git add" - ] - }, - "main": "./index", - "name": "ms", - "repository": { - "type": "git", - "url": "git+https://github.com/zeit/ms.git" - }, - "scripts": { - "lint": "eslint lib/* bin/*", - "precommit": "lint-staged", - "test": "mocha tests.js" - }, - "version": "2.0.0" -} diff --git a/reverse_engineering/node_modules/ms/readme.md b/reverse_engineering/node_modules/ms/readme.md deleted file mode 100644 index 84a9974..0000000 --- a/reverse_engineering/node_modules/ms/readme.md +++ /dev/null @@ -1,51 +0,0 @@ -# ms - -[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) -[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) - -Use this package to easily convert various time formats to milliseconds. - -## Examples - -```js -ms('2 days') // 172800000 -ms('1d') // 86400000 -ms('10h') // 36000000 -ms('2.5 hrs') // 9000000 -ms('2h') // 7200000 -ms('1m') // 60000 -ms('5s') // 5000 -ms('1y') // 31557600000 -ms('100') // 100 -``` - -### Convert from milliseconds - -```js -ms(60000) // "1m" -ms(2 * 60000) // "2m" -ms(ms('10 hours')) // "10h" -``` - -### Time format written-out - -```js -ms(60000, { long: true }) // "1 minute" -ms(2 * 60000, { long: true }) // "2 minutes" -ms(ms('10 hours'), { long: true }) // "10 hours" -``` - -## Features - -- Works both in [node](https://nodejs.org) and in the browser. -- If a number is supplied to `ms`, a string with a unit is returned. -- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). -- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. - -## Caught a bug? - -1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device -2. Link the package to the global module directory: `npm link` -3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! - -As always, you can run the tests using: `npm test` diff --git a/reverse_engineering/node_modules/nan/CHANGELOG.md b/reverse_engineering/node_modules/nan/CHANGELOG.md deleted file mode 100644 index 2838f1a..0000000 --- a/reverse_engineering/node_modules/nan/CHANGELOG.md +++ /dev/null @@ -1,541 +0,0 @@ -# NAN ChangeLog - -**Version 2.15.0: current Node 16.6.1, Node 0.12: 0.12.18, Node 0.10: 0.10.48, iojs: 3.3.1** - -### 2.15.0 Aug 4 2021 - - - Feature: add ScriptOrigin (#918) d09debf9eeedcb7ca4073e84ffe5fbb455ecb709 - -### 2.14.2 Oct 13 2020 - - - Bugfix: fix gcc 8 function cast warning (#899) 35f0fab205574b2cbda04e6347c8b2db755e124f - -### 2.14.1 Apr 21 2020 - - - Bugfix: use GetBackingStore() instead of GetContents() (#888) 2c023bd447661a61071da318b0ff4003c3858d39 - -### 2.14.0 May 16 2019 - - - Feature: Add missing methods to Nan::Maybe (#852) 4e962489fb84a184035b9fa74f245f650249aca6 - -### 2.13.2 Mar 24 2019 - - - Bugfix: remove usage of deprecated `IsNearDeath` (#842) fbaf42252af279c3d867c6b193571f9711c39847 - -### 2.13.1 Mar 14 2019 - - - Bugfix: check V8 version directly instead of inferring from NMV (#840) 12f9df9f393285de8fb4a8cd01478dc4fe3b089d - -### 2.13.0 Mar 13 2019 - - - Feature: add support for node master (#831) 113c0282072e7ff4f9dfc98b432fd894b798c2c - -### 2.12.1 Dec 18 2018 - - - Bugfix: Fix build breakage with Node.js 10.0.0-10.9.0. (#833) 625e90e8fef8d39ffa7247250a76a100b2487474 - -### 2.12.0 Dec 16 2018 - - - Bugfix: Add scope.Escape() to Call() (#817) 2e5ed4fc3a8ac80a6ef1f2a55099ab3ac8800dc6 - - Bugfix: Fix Node.js v10.12.0 deprecation warnings. 509859cc23b1770376b56550a027840a2ce0f73d - - Feature: Allow SetWeak() for non-object persistent handles. (#824) e6ef6a48e7e671fe3e4b7dddaa8912a3f8262ecd - -### 2.11.1 Sep 29 2018 - - - Fix: adapt to V8 7.0 24a22c3b25eeeec2016c6ec239bdd6169e985447 - -### 2.11.0 Aug 25 2018 - - - Removal: remove `FunctionCallbackInfo::Callee` for nodejs `>= 10` 1a56c0a6efd4fac944cb46c30912a8e023bda7d4 - - Bugfix: Fix `AsyncProgressWorkerBase::WorkProgress` sends invalid data b0c764d1dab11e9f8b37ffb81e2560a4498aad5e - - Feature: Introduce `GetCurrentEventLoop` b4911b0bb1f6d47d860e10ec014d941c51efac5e - - Feature: Add `NAN_MODULE_WORKER_ENABLED` macro as a replacement for `NAN_MODULE` b058fb047d18a58250e66ae831444441c1f2ac7a - -### 2.10.0 Mar 16 2018 - - - Deprecation: Deprecate `MakeCallback` 5e92b19a59e194241d6a658bd6ff7bfbda372950 - - Feature: add `Nan::Call` overload 4482e1242fe124d166fc1a5b2be3c1cc849fe452 - - Feature: add more `Nan::Call` overloads 8584e63e6d04c7d2eb8c4a664e4ef57d70bf672b - - Feature: Fix deprecation warnings for Node 10 1caf258243b0602ed56922bde74f1c91b0cbcb6a - -### 2.9.2 Feb 22 2018 - - - Bugfix: Bandaid for async hooks 212bd2f849be14ef1b02fc85010b053daa24252b - -### 2.9.1 Feb 22 2018 - - - Bugfix: Avoid deprecation warnings in deprecated `Nan::Callback::operator()` 372b14d91289df4604b0f81780709708c45a9aa4 - - Bugfix: Avoid deprecation warnings in `Nan::JSON` 3bc294bce0b7d0a3ee4559926303e5ed4866fda2 - -### 2.9.0 Feb 22 2018 - - - Deprecation: Deprecate legacy `Callback::Call` 6dd5fa690af61ca3523004b433304c581b3ea309 - - Feature: introduce `AsyncResource` class 90c0a179c0d8cb5fd26f1a7d2b1d6231eb402d48o - - Feature: Add context aware `Nan::Callback::Call` functions 7169e09fb088418b6e388222e88b4c13f07ebaee - - Feature: Make `AsyncWorker` context aware 066ba21a6fb9e2b5230c9ed3a6fc51f1211736a4 - - Feature: add `Callback` overload to `Nan::Call` 5328daf66e202658c1dc0d916c3aaba99b3cc606 - - Bugfix: fix warning: suggest parentheses around `&&` within `||` b2bb63d68b8ae623a526b542764e1ac82319cb2c - - Bugfix: Fix compilation on io.js 3 d06114dba0a522fb436f0c5f47b994210968cd7b - -### 2.8.0 Nov 15 2017 - - - Deprecation: Deprecate `Nan::ForceSet` in favor of `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 - - Feature: Add `Nan::AsyncProgressQueueWorker` a976636ecc2ef617d1b061ce4a6edf39923691cb - - Feature: Add `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 - - Bugfix: Fix compiling on io.js 1 & 2 82705a64503ce60c62e98df5bd02972bba090900 - - Bugfix: Use DefineOwnProperty instead of ForceSet 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 - -### 2.7.0 Aug 30 2017 - - - Feature: Add `Nan::To()` overload. b93280670c9f6da42ed4cf6cbf085ffdd87bd65b - - Bugfix: Fix ternary in `Nan::MaybeLocal::FromMaybe()`. 79a26f7d362e756a9524e672a82c3d603b542867 - -### 2.6.2 Apr 12 2017 - - - Bugfix: Fix v8::JSON::Parse() deprecation warning. 87f6a3c65815fa062296a994cc863e2fa124867d - -### 2.6.1 Apr 6 2017 - - - Bugfix: nan_json.h: fix build breakage in Node 6 ac8d47dc3c10bfbf3f15a6b951633120c0ee6d51 - -### 2.6.0 Apr 6 2017 - - - Feature: nan: add support for JSON::Parse & Stringify b533226c629cce70e1932a873bb6f849044a56c5 - -### 2.5.1 Jan 23 2017 - - - Bugfix: Fix disappearing handle for private value 6a80995694f162ef63dbc9948fbefd45d4485aa0 - - Bugfix: Add missing scopes a93b8bae6bc7d32a170db6e89228b7f60ee57112 - - Bugfix: Use string::data instead of string::front in NewOneByteString d5f920371e67e1f3b268295daee6e83af86b6e50 - -### 2.5.0 Dec 21 2016 - - - Feature: Support Private accessors a86255cb357e8ad8ccbf1f6a4a901c921e39a178 - - Bugfix: Abort in delete operators that shouldn't be called 0fe38215ff8581703967dfd26c12793feb960018 - -### 2.4.0 Jul 10 2016 - - - Feature: Rewrite Callback to add Callback::Reset c4cf44d61f8275cd5f7b0c911d7a806d4004f649 - - Feature: AsyncProgressWorker: add template types for .send 1242c9a11a7ed481c8f08ec06316385cacc513d0 - - Bugfix: Add constness to old Persistent comparison operators bd43cb9982c7639605d60fd073efe8cae165d9b2 - -### 2.3.5 May 31 2016 - - - Bugfix: Replace NAN_INLINE with 'inline' keyword. 71819d8725f822990f439479c9aba3b240804909 - -### 2.3.4 May 31 2016 - - - Bugfix: Remove V8 deprecation warnings 0592fb0a47f3a1c7763087ebea8e1138829f24f9 - - Bugfix: Fix new versions not to use WeakCallbackInfo::IsFirstPass 615c19d9e03d4be2049c10db0151edbc3b229246 - - Bugfix: Make ObjectWrap::handle() const d19af99595587fe7a26bd850af6595c2a7145afc - - Bugfix: Fix compilation errors related to 0592fb0a47f3a1c7763087ebea8e1138829f24f9 e9191c525b94f652718325e28610a1adcf90fed8 - -### 2.3.3 May 4 2016 - - - Bugfix: Refactor SetMethod() to deal with v8::Templates (#566) b9083cf6d5de6ebe6bcb49c7502fbb7c0d9ddda8 - -### 2.3.2 Apr 27 2016 - - - Bugfix: Fix compilation on outdated versions due to Handle removal f8b7c875d04d425a41dfd4f3f8345bc3a11e6c52 - -### 2.3.1 Apr 27 2016 - - - Bugfix: Don't use deprecated v8::Template::Set() in SetMethod a90951e9ea70fa1b3836af4b925322919159100e - -### 2.3.0 Apr 27 2016 - - - Feature: added Signal() for invoking async callbacks without sending data from AsyncProgressWorker d8adba45f20e077d00561b20199133620c990b38 - - Bugfix: Don't use deprecated v8::Template::Set() 00dacf0a4b86027415867fa7f1059acc499dcece - -### 2.2.1 Mar 29 2016 - - - Bugfix: Use NewFromUnsigned in ReturnValue::Set(uint32_t i) for pre_12 3a18f9bdce29826e0e4c217854bc476918241a58 - - Performance: Remove unneeeded nullptr checks b715ef44887931c94f0d1605b3b1a4156eebece9 - -### 2.2.0 Jan 9 2016 - - - Feature: Add Function::Call wrapper 4c157474dacf284d125c324177b45aa5dabc08c6 - - Feature: Rename GC*logueCallback to GCCallback for > 4.0 3603435109f981606d300eb88004ca101283acec - - Bugfix: Fix Global::Pass for old versions 367e82a60fbaa52716232cc89db1cc3f685d77d9 - - Bugfix: Remove weird MaybeLocal wrapping of what already is a MaybeLocal 23b4590db10c2ba66aee2338aebe9751c4cb190b - -### 2.1.0 Oct 8 2015 - - - Deprecation: Deprecate NanErrnoException in favor of ErrnoException 0af1ca4cf8b3f0f65ed31bc63a663ab3319da55c - - Feature: added helper class for accessing contents of typedarrays 17b51294c801e534479d5463697a73462d0ca555 - - Feature: [Maybe types] Add MakeMaybe(...) 48d7b53d9702b0c7a060e69ea10fea8fb48d814d - - Feature: new: allow utf16 string with length 66ac6e65c8ab9394ef588adfc59131b3b9d8347b - - Feature: Introduce SetCallHandler and SetCallAsFunctionHandler 7764a9a115d60ba10dc24d86feb0fbc9b4f75537 - - Bugfix: Enable creating Locals from Globals under Node 0.10. 9bf9b8b190821af889790fdc18ace57257e4f9ff - - Bugfix: Fix issue #462 where PropertyCallbackInfo data is not stored safely. 55f50adedd543098526c7b9f4fffd607d3f9861f - -### 2.0.9 Sep 8 2015 - - - Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7 - -### 2.0.8 Aug 28 2015 - - - Work around duplicate linking bug in clang 11902da - -### 2.0.7 Aug 26 2015 - - - Build: Repackage - -### 2.0.6 Aug 26 2015 - - - Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1 - - Bugfix: Remove unused static std::map instances 525bddc - - Bugfix: Make better use of maybe versions of APIs bfba85b - - Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d - -### 2.0.5 Aug 10 2015 - - - Bugfix: Reimplement weak callback in ObjectWrap 98d38c1 - - Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d - -### 2.0.4 Aug 6 2015 - - - Build: Repackage - -### 2.0.3 Aug 6 2015 - - - Bugfix: Don't use clang++ / g++ syntax extension. 231450e - -### 2.0.2 Aug 6 2015 - - - Build: Repackage - -### 2.0.1 Aug 6 2015 - - - Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687 - - Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601 - - Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f - - Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed - -### 2.0.0 Jul 31 2015 - - - Change: Renamed identifiers with leading underscores b5932b4 - - Change: Replaced NanObjectWrapHandle with class NanObjectWrap 464f1e1 - - Change: Replace NanScope and NanEscpableScope macros with classes 47751c4 - - Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99 - - Change: Rename NanBufferUse to NanNewBuffer 3e8b0a5 - - Change: Rename NanNewBuffer to NanCopyBuffer d6af78d - - Change: Remove Nan prefix from all names 72d1f67 - - Change: Update Buffer API for new upstream changes d5d3291 - - Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope 21a7a6a - - Change: Get rid of Handles e6c0daf - - Feature: Support io.js 3 with V8 4.4 - - Feature: Introduce NanPersistent 7fed696 - - Feature: Introduce NanGlobal 4408da1 - - Feature: Added NanTryCatch 10f1ca4 - - Feature: Update for V8 v4.3 4b6404a - - Feature: Introduce NanNewOneByteString c543d32 - - Feature: Introduce namespace Nan 67ed1b1 - - Removal: Remove NanLocker and NanUnlocker dd6e401 - - Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9 - - Removal: Remove NanReturn* macros d90a25c - - Removal: Remove HasInstance e8f84fe - - -### 1.9.0 Jul 31 2015 - - - Feature: Added `NanFatalException` 81d4a2c - - Feature: Added more error types 4265f06 - - Feature: Added dereference and function call operators to NanCallback c4b2ed0 - - Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c - - Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6 - - Feature: Added NanErrnoException dd87d9e - - Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130 - - Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c - - Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b - -### 1.8.4 Apr 26 2015 - - - Build: Repackage - -### 1.8.3 Apr 26 2015 - - - Bugfix: Include missing header 1af8648 - -### 1.8.2 Apr 23 2015 - - - Build: Repackage - -### 1.8.1 Apr 23 2015 - - - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3 - -### 1.8.0 Apr 23 2015 - - - Feature: Allow primitives with NanReturnValue 2e4475e - - Feature: Added comparison operators to NanCallback 55b075e - - Feature: Backport thread local storage 15bb7fa - - Removal: Remove support for signatures with arguments 8a2069d - - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59 - -### 1.7.0 Feb 28 2015 - - - Feature: Made NanCallback::Call accept optional target 8d54da7 - - Feature: Support atom-shell 0.21 0b7f1bb - -### 1.6.2 Feb 6 2015 - - - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 - -### 1.6.1 Jan 23 2015 - - - Build: version bump - -### 1.5.3 Jan 23 2015 - - - Build: repackage - -### 1.6.0 Jan 23 2015 - - - Deprecated `NanNewContextHandle` in favor of `NanNew` 49259af - - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 - - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 - -### 1.5.2 Jan 23 2015 - - - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 - - Bugfix: Readded missing String constructors 18d828f - - Bugfix: Add overload handling NanNew(..) 5ef813b - - Bugfix: Fix uv_work_cb versioning 997e4ae - - Bugfix: Add function factory and test 4eca89c - - Bugfix: Add object template factory and test cdcb951 - - Correctness: Lifted an io.js related typedef c9490be - - Correctness: Make explicit downcasts of String lengths 00074e6 - - Windows: Limit the scope of disabled warning C4530 83d7deb - -### 1.5.1 Jan 15 2015 - - - Build: version bump - -### 1.4.3 Jan 15 2015 - - - Build: version bump - -### 1.4.2 Jan 15 2015 - - - Feature: Support io.js 0dbc5e8 - -### 1.5.0 Jan 14 2015 - - - Feature: Support io.js b003843 - - Correctness: Improved NanNew internals 9cd4f6a - - Feature: Implement progress to NanAsyncWorker 8d6a160 - -### 1.4.1 Nov 8 2014 - - - Bugfix: Handle DEBUG definition correctly - - Bugfix: Accept int as Boolean - -### 1.4.0 Nov 1 2014 - - - Feature: Added NAN_GC_CALLBACK 6a5c245 - - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 - - Correctness: Added constness to references in NanHasInstance 02c61cd - - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 - - Windoze: Shut Visual Studio up when compiling 8d558c1 - - License: Switch to plain MIT from custom hacked MIT license 11de983 - - Build: Added test target to Makefile e232e46 - - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 - - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 - - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 - -### 1.3.0 Aug 2 2014 - - - Added NanNew(std::string) - - Added NanNew(std::string&) - - Added NanAsciiString helper class - - Added NanUtf8String helper class - - Added NanUcs2String helper class - - Deprecated NanRawString() - - Deprecated NanCString() - - Added NanGetIsolateData(v8::Isolate *isolate) - - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) - - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) - - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - -### 1.2.0 Jun 5 2014 - - - Add NanSetPrototypeTemplate - - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, - introduced _NanWeakCallbackDispatcher - - Removed -Wno-unused-local-typedefs from test builds - - Made test builds Windows compatible ('Sleep()') - -### 1.1.2 May 28 2014 - - - Release to fix more stuff-ups in 1.1.1 - -### 1.1.1 May 28 2014 - - - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 - -### 1.1.0 May 25 2014 - - - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead - - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), - (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, - v8::String::ExternalAsciiStringResource* - - Deprecate NanSymbol() - - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker - -### 1.0.0 May 4 2014 - - - Heavy API changes for V8 3.25 / Node 0.11.13 - - Use cpplint.py - - Removed NanInitPersistent - - Removed NanPersistentToLocal - - Removed NanFromV8String - - Removed NanMakeWeak - - Removed NanNewLocal - - Removed NAN_WEAK_CALLBACK_OBJECT - - Removed NAN_WEAK_CALLBACK_DATA - - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions - - Introduce NanUndefined, NanNull, NanTrue and NanFalse - - Introduce NanEscapableScope and NanEscapeScope - - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) - - Introduce NanMakeCallback for node::MakeCallback - - Introduce NanSetTemplate - - Introduce NanGetCurrentContext - - Introduce NanCompileScript and NanRunScript - - Introduce NanAdjustExternalMemory - - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback - - Introduce NanGetHeapStatistics - - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() - -### 0.8.0 Jan 9 2014 - - - NanDispose -> NanDisposePersistent, deprecate NanDispose - - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() - -### 0.7.1 Jan 9 2014 - - - Fixes to work against debug builds of Node - - Safer NanPersistentToLocal (avoid reinterpret_cast) - - Speed up common NanRawString case by only extracting flattened string when necessary - -### 0.7.0 Dec 17 2013 - - - New no-arg form of NanCallback() constructor. - - NanCallback#Call takes Handle rather than Local - - Removed deprecated NanCallback#Run method, use NanCallback#Call instead - - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS - - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() - - Introduce NanRawString() for char* (or appropriate void*) from v8::String - (replacement for NanFromV8String) - - Introduce NanCString() for null-terminated char* from v8::String - -### 0.6.0 Nov 21 2013 - - - Introduce NanNewLocal(v8::Handle value) for use in place of - v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 - -### 0.5.2 Nov 16 2013 - - - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public - -### 0.5.1 Nov 12 2013 - - - Use node::MakeCallback() instead of direct v8::Function::Call() - -### 0.5.0 Nov 11 2013 - - - Added @TooTallNate as collaborator - - New, much simpler, "include_dirs" for binding.gyp - - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros - -### 0.4.4 Nov 2 2013 - - - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ - -### 0.4.3 Nov 2 2013 - - - Include node_object_wrap.h, removed from node.h for Node 0.11.8. - -### 0.4.2 Nov 2 2013 - - - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for - Node 0.11.8 release. - -### 0.4.1 Sep 16 2013 - - - Added explicit `#include ` as it was removed from node.h for v0.11.8 - -### 0.4.0 Sep 2 2013 - - - Added NAN_INLINE and NAN_DEPRECATED and made use of them - - Added NanError, NanTypeError and NanRangeError - - Cleaned up code - -### 0.3.2 Aug 30 2013 - - - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent - in NanAsyncWorker - -### 0.3.1 Aug 20 2013 - - - fix "not all control paths return a value" compile warning on some platforms - -### 0.3.0 Aug 19 2013 - - - Made NAN work with NPM - - Lots of fixes to NanFromV8String, pulling in features from new Node core - - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API - - Added optional error number argument for NanThrowError() - - Added NanInitPersistent() - - Added NanReturnNull() and NanReturnEmptyString() - - Added NanLocker and NanUnlocker - - Added missing scopes - - Made sure to clear disposed Persistent handles - - Changed NanAsyncWorker to allocate error messages on the heap - - Changed NanThrowError(Local) to NanThrowError(Handle) - - Fixed leak in NanAsyncWorker when errmsg is used - -### 0.2.2 Aug 5 2013 - - - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() - -### 0.2.1 Aug 5 2013 - - - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for - NanFromV8String() - -### 0.2.0 Aug 5 2013 - - - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, - NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY - - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, - _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, - _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, - _NAN_PROPERTY_QUERY_ARGS - - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer - - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, - NAN_WEAK_CALLBACK_DATA, NanMakeWeak - - Renamed THROW_ERROR to _NAN_THROW_ERROR - - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) - - Added NanBufferUse(char*, uint32_t) - - Added NanNewContextHandle(v8::ExtensionConfiguration*, - v8::Handle, v8::Handle) - - Fixed broken NanCallback#GetFunction() - - Added optional encoding and size arguments to NanFromV8String() - - Added NanGetPointerSafe() and NanSetPointerSafe() - - Added initial test suite (to be expanded) - - Allow NanUInt32OptionValue to convert any Number object - -### 0.1.0 Jul 21 2013 - - - Added `NAN_GETTER`, `NAN_SETTER` - - Added `NanThrowError` with single Local argument - - Added `NanNewBufferHandle` with single uint32_t argument - - Added `NanHasInstance(Persistent&, Handle)` - - Added `Local NanCallback#GetFunction()` - - Added `NanCallback#Call(int, Local[])` - - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/reverse_engineering/node_modules/nan/LICENSE.md b/reverse_engineering/node_modules/nan/LICENSE.md deleted file mode 100644 index dddd13d..0000000 --- a/reverse_engineering/node_modules/nan/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -The MIT License (MIT) -===================== - -Copyright (c) 2018 NAN contributors ------------------------------------ - -*NAN contributors listed at * - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/nan/README.md b/reverse_engineering/node_modules/nan/README.md deleted file mode 100644 index 8988a09..0000000 --- a/reverse_engineering/node_modules/nan/README.md +++ /dev/null @@ -1,456 +0,0 @@ -Native Abstractions for Node.js -=============================== - -**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10, 0.12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 and 16.** - -***Current version: 2.15.0*** - -*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* - -[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/) - -[![Build Status](https://api.travis-ci.com/nodejs/nan.svg?branch=master)](https://travis-ci.com/nodejs/nan) -[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) - -Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. - -This project also contains some helper utilities that make addon development a bit more pleasant. - - * **[News & Updates](#news)** - * **[Usage](#usage)** - * **[Example](#example)** - * **[API](#api)** - * **[Tests](#tests)** - * **[Known issues](#issues)** - * **[Governance & Contributing](#governance)** - - - -## News & Updates - - - -## Usage - -Simply add **NAN** as a dependency in the *package.json* of your Node addon: - -``` bash -$ npm install --save nan -``` - -Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include ` in your *.cpp* files: - -``` python -"include_dirs" : [ - "` when compiling your addon. - - - -## Example - -Just getting started with Nan? Take a look at the **[Node Add-on Examples](https://github.com/nodejs/node-addon-examples)**. - -Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality. - -For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. - -Yet another example is **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. - -Also take a look at our comprehensive **[C++ test suite](https://github.com/nodejs/nan/tree/master/test/cpp)** which has a plethora of code snippets for your pasting pleasure. - - - -## API - -Additional to the NAN documentation below, please consult: - -* [The V8 Getting Started * Guide](https://v8.dev/docs/embed) -* [V8 API Documentation](https://v8docs.nodesource.com/) -* [Node Add-on Documentation](https://nodejs.org/api/addons.html) - - - -### JavaScript-accessible methods - -A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information. - -In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. - -* **Method argument types** - - Nan::FunctionCallbackInfo - - Nan::PropertyCallbackInfo - - Nan::ReturnValue -* **Method declarations** - - Method declaration - - Getter declaration - - Setter declaration - - Property getter declaration - - Property setter declaration - - Property enumerator declaration - - Property deleter declaration - - Property query declaration - - Index getter declaration - - Index setter declaration - - Index enumerator declaration - - Index deleter declaration - - Index query declaration -* Method and template helpers - - Nan::SetMethod() - - Nan::SetPrototypeMethod() - - Nan::SetAccessor() - - Nan::SetNamedPropertyHandler() - - Nan::SetIndexedPropertyHandler() - - Nan::SetTemplate() - - Nan::SetPrototypeTemplate() - - Nan::SetInstanceTemplate() - - Nan::SetCallHandler() - - Nan::SetCallAsFunctionHandler() - -### Scopes - -A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. - -A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. - -The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. - - - Nan::HandleScope - - Nan::EscapableHandleScope - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection). - -### Persistent references - -An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. - -Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. - - - Nan::PersistentBase & v8::PersistentBase - - Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits - - Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits - - Nan::Persistent - - Nan::Global - - Nan::WeakCallbackInfo - - Nan::WeakCallbackType - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). - -### New - -NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. - - - Nan::New() - - Nan::Undefined() - - Nan::Null() - - Nan::True() - - Nan::False() - - Nan::EmptyString() - - -### Converters - -NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. - - - Nan::To() - -### Maybe Types - -The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. - -* **Maybe Types** - - Nan::MaybeLocal - - Nan::Maybe - - Nan::Nothing - - Nan::Just -* **Maybe Helpers** - - Nan::Call() - - Nan::ToDetailString() - - Nan::ToArrayIndex() - - Nan::Equals() - - Nan::NewInstance() - - Nan::GetFunction() - - Nan::Set() - - Nan::DefineOwnProperty() - - Nan::ForceSet() - - Nan::Get() - - Nan::GetPropertyAttributes() - - Nan::Has() - - Nan::Delete() - - Nan::GetPropertyNames() - - Nan::GetOwnPropertyNames() - - Nan::SetPrototype() - - Nan::ObjectProtoToString() - - Nan::HasOwnProperty() - - Nan::HasRealNamedProperty() - - Nan::HasRealIndexedProperty() - - Nan::HasRealNamedCallbackProperty() - - Nan::GetRealNamedPropertyInPrototypeChain() - - Nan::GetRealNamedProperty() - - Nan::CallAsFunction() - - Nan::CallAsConstructor() - - Nan::GetSourceLine() - - Nan::GetLineNumber() - - Nan::GetStartColumn() - - Nan::GetEndColumn() - - Nan::CloneElementAt() - - Nan::HasPrivate() - - Nan::GetPrivate() - - Nan::SetPrivate() - - Nan::DeletePrivate() - - Nan::MakeMaybe() - -### Script - -NAN provides `v8::Script` helpers as the API has changed over the supported versions of V8. - - - Nan::CompileScript() - - Nan::RunScript() - - Nan::ScriptOrigin - - -### JSON - -The _JSON_ object provides the C++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object. - - - Nan::JSON.Parse - - Nan::JSON.Stringify - -Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments. - -### Errors - -NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. - -Note that an Error object is simply a specialized form of `v8::Value`. - -Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. - - - Nan::Error() - - Nan::RangeError() - - Nan::ReferenceError() - - Nan::SyntaxError() - - Nan::TypeError() - - Nan::ThrowError() - - Nan::ThrowRangeError() - - Nan::ThrowReferenceError() - - Nan::ThrowSyntaxError() - - Nan::ThrowTypeError() - - Nan::FatalException() - - Nan::ErrnoException() - - Nan::TryCatch - - -### Buffers - -NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. - - - Nan::NewBuffer() - - Nan::CopyBuffer() - - Nan::FreeCallback() - -### Nan::Callback - -`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. - - - Nan::Callback - -### Asynchronous work helpers - -`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier. - - - Nan::AsyncWorker - - Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker - - Nan::AsyncProgressQueueWorker - - Nan::AsyncQueueWorker - -### Strings & Bytes - -Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. - - - Nan::Encoding - - Nan::Encode() - - Nan::DecodeBytes() - - Nan::DecodeWrite() - - -### Object Wrappers - -The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects. - - - Nan::ObjectWrap - - -### V8 internals - -The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. - - - NAN_GC_CALLBACK() - - Nan::AddGCEpilogueCallback() - - Nan::RemoveGCEpilogueCallback() - - Nan::AddGCPrologueCallback() - - Nan::RemoveGCPrologueCallback() - - Nan::GetHeapStatistics() - - Nan::SetCounterFunction() - - Nan::SetCreateHistogramFunction() - - Nan::SetAddHistogramSampleFunction() - - Nan::IdleNotification() - - Nan::LowMemoryNotification() - - Nan::ContextDisposedNotification() - - Nan::GetInternalFieldPointer() - - Nan::SetInternalFieldPointer() - - Nan::AdjustExternalMemory() - - -### Miscellaneous V8 Helpers - - - Nan::Utf8String - - Nan::GetCurrentContext() - - Nan::SetIsolateData() - - Nan::GetIsolateData() - - Nan::TypedArrayContents - - -### Miscellaneous Node Helpers - - - Nan::AsyncResource - - Nan::MakeCallback() - - NAN_MODULE_INIT() - - Nan::Export() - - - - - - -### Tests - -To run the NAN tests do: - -``` sh -npm install -npm run-script rebuild-tests -npm test -``` - -Or just: - -``` sh -npm install -make test -``` - - - -## Known issues - -### Compiling against Node.js 0.12 on OSX - -With new enough compilers available on OSX, the versions of V8 headers corresponding to Node.js 0.12 -do not compile anymore. The error looks something like: - -``` -❯ CXX(target) Release/obj.target/accessors/cpp/accessors.o -In file included from ../cpp/accessors.cpp:9: -In file included from ../../nan.h:51: -In file included from /Users/ofrobots/.node-gyp/0.12.18/include/node/node.h:61: -/Users/ofrobots/.node-gyp/0.12.18/include/node/v8.h:5800:54: error: 'CreateHandle' is a protected member of 'v8::HandleScope' - return Handle(reinterpret_cast(HandleScope::CreateHandle( - ~~~~~~~~~~~~~^~~~~~~~~~~~ -``` - -This can be worked around by patching your local versions of v8.h corresponding to Node 0.12 to make -`v8::Handle` a friend of `v8::HandleScope`. Since neither Node.js not V8 support this release line anymore -this patch cannot be released by either project in an official release. - -For this reason, we do not test against Node.js 0.12 on OSX in this project's CI. If you need to support -that configuration, you will need to either get an older compiler, or apply a source patch to the version -of V8 headers as a workaround. - - - -## Governance & Contributing - -NAN is governed by the [Node.js Addon API Working Group](https://github.com/nodejs/CTC/blob/master/WORKING_GROUPS.md#addon-api) - -### Addon API Working Group (WG) - -The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. - -Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other Node.js projects. - -The WG has final authority over this project including: - -* Technical direction -* Project governance and process (including this policy) -* Contribution policy -* GitHub repository hosting -* Maintaining the list of additional Collaborators - -For the current list of WG members, see the project [README.md](./README.md#collaborators). - -Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. - -_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. - -For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). - -### Consensus Seeking Process - -The WG follows a [Consensus Seeking](https://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. - -Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. - -If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. - - - -## Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -* (a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -* (b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -* (c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -* (d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. - - - -### WG Members / Collaborators - - - - - - - - - - -
Rod VaggGitHub/rvaggTwitter/@rvagg
Benjamin ByholmGitHub/kkoopa-
Trevor NorrisGitHub/trevnorrisTwitter/@trevnorris
Nathan RajlichGitHub/TooTallNateTwitter/@TooTallNate
Brett LawsonGitHub/brett19Twitter/@brett19x
Ben NoordhuisGitHub/bnoordhuisTwitter/@bnoordhuis
David SiegelGitHub/agnatTwitter/@agnat
Michael Ira KrufkyGitHub/mkrufkyTwitter/@mkrufky
- -## Licence & copyright - -Copyright (c) 2018 NAN WG Members / Collaborators (listed above). - -Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/reverse_engineering/node_modules/nan/doc/asyncworker.md b/reverse_engineering/node_modules/nan/doc/asyncworker.md deleted file mode 100644 index 04231f8..0000000 --- a/reverse_engineering/node_modules/nan/doc/asyncworker.md +++ /dev/null @@ -1,146 +0,0 @@ -## Asynchronous work helpers - -`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier. - - - Nan::AsyncWorker - - Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker - - Nan::AsyncProgressQueueWorker - - Nan::AsyncQueueWorker - - -### Nan::AsyncWorker - -`Nan::AsyncWorker` is an _abstract_ class that you can subclass to have much of the annoying asynchronous queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the asynchronous work is in progress. - -This class internally handles the details of creating an [`AsyncResource`][AsyncResource], and running the callback in the -correct async context. To be able to identify the async resources created by this class in async-hooks, provide a -`resource_name` to the constructor. It is recommended that the module name be used as a prefix to the `resource_name` to avoid -collisions in the names. For more details see [`AsyncResource`][AsyncResource] documentation. The `resource_name` needs to stay valid for the lifetime of the worker instance. - -Definition: - -```c++ -class AsyncWorker { - public: - explicit AsyncWorker(Callback *callback_, const char* resource_name = "nan:AsyncWorker"); - - virtual ~AsyncWorker(); - - virtual void WorkComplete(); - - void SaveToPersistent(const char *key, const v8::Local &value); - - void SaveToPersistent(const v8::Local &key, - const v8::Local &value); - - void SaveToPersistent(uint32_t index, - const v8::Local &value); - - v8::Local GetFromPersistent(const char *key) const; - - v8::Local GetFromPersistent(const v8::Local &key) const; - - v8::Local GetFromPersistent(uint32_t index) const; - - virtual void Execute() = 0; - - uv_work_t request; - - virtual void Destroy(); - - protected: - Persistent persistentHandle; - - Callback *callback; - - virtual void HandleOKCallback(); - - virtual void HandleErrorCallback(); - - void SetErrorMessage(const char *msg); - - const char* ErrorMessage(); -}; -``` - - -### Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker - -`Nan::AsyncProgressWorkerBase` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript. - -Previously the definition of `Nan::AsyncProgressWorker` only allowed sending `const char` data. Now extending `Nan::AsyncProgressWorker` will yield an instance of the implicit `Nan::AsyncProgressWorkerBase` template with type `` for compatibility. - -`Nan::AsyncProgressWorkerBase` & `Nan::AsyncProgressWorker` is intended for best-effort delivery of nonessential progress messages, e.g. a progress bar. The last event sent before the main thread is woken will be delivered. - -Definition: - -```c++ -template -class AsyncProgressWorkerBase : public AsyncWorker { - public: - explicit AsyncProgressWorkerBase(Callback *callback_, const char* resource_name = ...); - - virtual ~AsyncProgressWorkerBase(); - - void WorkProgress(); - - class ExecutionProgress { - public: - void Signal() const; - void Send(const T* data, size_t count) const; - }; - - virtual void Execute(const ExecutionProgress& progress) = 0; - - virtual void HandleProgressCallback(const T *data, size_t count) = 0; - - virtual void Destroy(); -}; - -typedef AsyncProgressWorkerBase AsyncProgressWorker; -``` - - -### Nan::AsyncProgressQueueWorker - -`Nan::AsyncProgressQueueWorker` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript. - -`Nan::AsyncProgressQueueWorker` behaves exactly the same as `Nan::AsyncProgressWorker`, except all events are queued and delivered to the main thread. - -Definition: - -```c++ -template -class AsyncProgressQueueWorker : public AsyncWorker { - public: - explicit AsyncProgressQueueWorker(Callback *callback_, const char* resource_name = "nan:AsyncProgressQueueWorker"); - - virtual ~AsyncProgressQueueWorker(); - - void WorkProgress(); - - class ExecutionProgress { - public: - void Send(const T* data, size_t count) const; - }; - - virtual void Execute(const ExecutionProgress& progress) = 0; - - virtual void HandleProgressCallback(const T *data, size_t count) = 0; - - virtual void Destroy(); -}; -``` - - -### Nan::AsyncQueueWorker - -`Nan::AsyncQueueWorker` will run a `Nan::AsyncWorker` asynchronously via libuv. Both the `execute` and `after_work` steps are taken care of for you. Most of the logic for this is embedded in `Nan::AsyncWorker`. - -Definition: - -```c++ -void AsyncQueueWorker(AsyncWorker *); -``` - -[AsyncResource]: node_misc.md#api_nan_asyncresource diff --git a/reverse_engineering/node_modules/nan/doc/buffers.md b/reverse_engineering/node_modules/nan/doc/buffers.md deleted file mode 100644 index 8d8d25c..0000000 --- a/reverse_engineering/node_modules/nan/doc/buffers.md +++ /dev/null @@ -1,54 +0,0 @@ -## Buffers - -NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. - - - Nan::NewBuffer() - - Nan::CopyBuffer() - - Nan::FreeCallback() - - -### Nan::NewBuffer() - -Allocate a new `node::Buffer` object with the specified size and optional data. Calls `node::Buffer::New()`. - -Note that when creating a `Buffer` using `Nan::NewBuffer()` and an existing `char*`, it is assumed that the ownership of the pointer is being transferred to the new `Buffer` for management. -When a `node::Buffer` instance is garbage collected and a `FreeCallback` has not been specified, `data` will be disposed of via a call to `free()`. -You _must not_ free the memory space manually once you have created a `Buffer` in this way. - -Signature: - -```c++ -Nan::MaybeLocal Nan::NewBuffer(uint32_t size) -Nan::MaybeLocal Nan::NewBuffer(char* data, uint32_t size) -Nan::MaybeLocal Nan::NewBuffer(char *data, - size_t length, - Nan::FreeCallback callback, - void *hint) -``` - - - -### Nan::CopyBuffer() - -Similar to [`Nan::NewBuffer()`](#api_nan_new_buffer) except that an implicit memcpy will occur within Node. Calls `node::Buffer::Copy()`. - -Management of the `char*` is left to the user, you should manually free the memory space if necessary as the new `Buffer` will have its own copy. - -Signature: - -```c++ -Nan::MaybeLocal Nan::CopyBuffer(const char *data, uint32_t size) -``` - - - -### Nan::FreeCallback() - -A free callback that can be provided to [`Nan::NewBuffer()`](#api_nan_new_buffer). -The supplied callback will be invoked when the `Buffer` undergoes garbage collection. - -Signature: - -```c++ -typedef void (*FreeCallback)(char *data, void *hint); -``` diff --git a/reverse_engineering/node_modules/nan/doc/callback.md b/reverse_engineering/node_modules/nan/doc/callback.md deleted file mode 100644 index f7af0bf..0000000 --- a/reverse_engineering/node_modules/nan/doc/callback.md +++ /dev/null @@ -1,76 +0,0 @@ -## Nan::Callback - -`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. - - - Nan::Callback - - -### Nan::Callback - -```c++ -class Callback { - public: - Callback(); - - explicit Callback(const v8::Local &fn); - - ~Callback(); - - bool operator==(const Callback &other) const; - - bool operator!=(const Callback &other) const; - - v8::Local operator*() const; - - MaybeLocal operator()(AsyncResource* async_resource, - v8::Local target, - int argc = 0, - v8::Local argv[] = 0) const; - - MaybeLocal operator()(AsyncResource* async_resource, - int argc = 0, - v8::Local argv[] = 0) const; - - void SetFunction(const v8::Local &fn); - - v8::Local GetFunction() const; - - bool IsEmpty() const; - - void Reset(const v8::Local &fn); - - void Reset(); - - MaybeLocal Call(v8::Local target, - int argc, - v8::Local argv[], - AsyncResource* async_resource) const; - MaybeLocal Call(int argc, - v8::Local argv[], - AsyncResource* async_resource) const; - - // Deprecated versions. Use the versions that accept an async_resource instead - // as they run the callback in the correct async context as specified by the - // resource. If you want to call a synchronous JS function (i.e. on a - // non-empty JS stack), you can use Nan::Call instead. - v8::Local operator()(v8::Local target, - int argc = 0, - v8::Local argv[] = 0) const; - - v8::Local operator()(int argc = 0, - v8::Local argv[] = 0) const; - v8::Local Call(v8::Local target, - int argc, - v8::Local argv[]) const; - - v8::Local Call(int argc, v8::Local argv[]) const; -}; -``` - -Example usage: - -```c++ -v8::Local function; -Nan::Callback callback(function); -callback.Call(0, 0); -``` diff --git a/reverse_engineering/node_modules/nan/doc/converters.md b/reverse_engineering/node_modules/nan/doc/converters.md deleted file mode 100644 index d20861b..0000000 --- a/reverse_engineering/node_modules/nan/doc/converters.md +++ /dev/null @@ -1,41 +0,0 @@ -## Converters - -NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. - - - Nan::To() - - -### Nan::To() - -Converts a `v8::Local` to a different subtype of `v8::Value` or to a native data type. Returns a `Nan::MaybeLocal<>` or a `Nan::Maybe<>` accordingly. - -See [maybe_types.md](./maybe_types.md) for more information on `Nan::Maybe` types. - -Signatures: - -```c++ -// V8 types -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); - -// Native types -Nan::Maybe Nan::To(v8::Local val); -Nan::Maybe Nan::To(v8::Local val); -Nan::Maybe Nan::To(v8::Local val); -Nan::Maybe Nan::To(v8::Local val); -Nan::Maybe Nan::To(v8::Local val); -``` - -### Example - -```c++ -v8::Local val; -Nan::MaybeLocal str = Nan::To(val); -Nan::Maybe d = Nan::To(val); -``` - diff --git a/reverse_engineering/node_modules/nan/doc/errors.md b/reverse_engineering/node_modules/nan/doc/errors.md deleted file mode 100644 index 843435b..0000000 --- a/reverse_engineering/node_modules/nan/doc/errors.md +++ /dev/null @@ -1,226 +0,0 @@ -## Errors - -NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. - -Note that an Error object is simply a specialized form of `v8::Value`. - -Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. - - - Nan::Error() - - Nan::RangeError() - - Nan::ReferenceError() - - Nan::SyntaxError() - - Nan::TypeError() - - Nan::ThrowError() - - Nan::ThrowRangeError() - - Nan::ThrowReferenceError() - - Nan::ThrowSyntaxError() - - Nan::ThrowTypeError() - - Nan::FatalException() - - Nan::ErrnoException() - - Nan::TryCatch - - - -### Nan::Error() - -Create a new Error object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. - -Note that an Error object is simply a specialized form of `v8::Value`. - -Signature: - -```c++ -v8::Local Nan::Error(const char *msg); -v8::Local Nan::Error(v8::Local msg); -``` - - - -### Nan::RangeError() - -Create a new RangeError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. - -Note that an RangeError object is simply a specialized form of `v8::Value`. - -Signature: - -```c++ -v8::Local Nan::RangeError(const char *msg); -v8::Local Nan::RangeError(v8::Local msg); -``` - - - -### Nan::ReferenceError() - -Create a new ReferenceError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. - -Note that an ReferenceError object is simply a specialized form of `v8::Value`. - -Signature: - -```c++ -v8::Local Nan::ReferenceError(const char *msg); -v8::Local Nan::ReferenceError(v8::Local msg); -``` - - - -### Nan::SyntaxError() - -Create a new SyntaxError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. - -Note that an SyntaxError object is simply a specialized form of `v8::Value`. - -Signature: - -```c++ -v8::Local Nan::SyntaxError(const char *msg); -v8::Local Nan::SyntaxError(v8::Local msg); -``` - - - -### Nan::TypeError() - -Create a new TypeError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. - -Note that an TypeError object is simply a specialized form of `v8::Value`. - -Signature: - -```c++ -v8::Local Nan::TypeError(const char *msg); -v8::Local Nan::TypeError(v8::Local msg); -``` - - - -### Nan::ThrowError() - -Throw an Error object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new Error object will be created. - -Signature: - -```c++ -void Nan::ThrowError(const char *msg); -void Nan::ThrowError(v8::Local msg); -void Nan::ThrowError(v8::Local error); -``` - - - -### Nan::ThrowRangeError() - -Throw an RangeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new RangeError object will be created. - -Signature: - -```c++ -void Nan::ThrowRangeError(const char *msg); -void Nan::ThrowRangeError(v8::Local msg); -void Nan::ThrowRangeError(v8::Local error); -``` - - - -### Nan::ThrowReferenceError() - -Throw an ReferenceError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new ReferenceError object will be created. - -Signature: - -```c++ -void Nan::ThrowReferenceError(const char *msg); -void Nan::ThrowReferenceError(v8::Local msg); -void Nan::ThrowReferenceError(v8::Local error); -``` - - - -### Nan::ThrowSyntaxError() - -Throw an SyntaxError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new SyntaxError object will be created. - -Signature: - -```c++ -void Nan::ThrowSyntaxError(const char *msg); -void Nan::ThrowSyntaxError(v8::Local msg); -void Nan::ThrowSyntaxError(v8::Local error); -``` - - - -### Nan::ThrowTypeError() - -Throw an TypeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new TypeError object will be created. - -Signature: - -```c++ -void Nan::ThrowTypeError(const char *msg); -void Nan::ThrowTypeError(v8::Local msg); -void Nan::ThrowTypeError(v8::Local error); -``` - - -### Nan::FatalException() - -Replaces `node::FatalException()` which has a different API across supported versions of Node. For use with [`Nan::TryCatch`](#api_nan_try_catch). - -Signature: - -```c++ -void Nan::FatalException(const Nan::TryCatch& try_catch); -``` - - -### Nan::ErrnoException() - -Replaces `node::ErrnoException()` which has a different API across supported versions of Node. - -Signature: - -```c++ -v8::Local Nan::ErrnoException(int errorno, - const char* syscall = NULL, - const char* message = NULL, - const char* path = NULL); -``` - - - -### Nan::TryCatch - -A simple wrapper around [`v8::TryCatch`](https://v8docs.nodesource.com/node-8.16/d4/dc6/classv8_1_1_try_catch.html) compatible with all supported versions of V8. Can be used as a direct replacement in most cases. See also [`Nan::FatalException()`](#api_nan_fatal_exception) for an internal use compatible with `node::FatalException`. - -Signature: - -```c++ -class Nan::TryCatch { - public: - Nan::TryCatch(); - - bool HasCaught() const; - - bool CanContinue() const; - - v8::Local ReThrow(); - - v8::Local Exception() const; - - // Nan::MaybeLocal for older versions of V8 - v8::MaybeLocal StackTrace() const; - - v8::Local Message() const; - - void Reset(); - - void SetVerbose(bool value); - - void SetCaptureMessage(bool value); -}; -``` - diff --git a/reverse_engineering/node_modules/nan/doc/json.md b/reverse_engineering/node_modules/nan/doc/json.md deleted file mode 100644 index 55beb26..0000000 --- a/reverse_engineering/node_modules/nan/doc/json.md +++ /dev/null @@ -1,62 +0,0 @@ -## JSON - -The _JSON_ object provides the C++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object. - - - Nan::JSON.Parse - - Nan::JSON.Stringify - -Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments. - - - -### Nan::JSON.Parse - -A simple wrapper around [`v8::JSON::Parse`](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html#a936310d2540fb630ed37d3ee3ffe4504). - -Definition: - -```c++ -Nan::MaybeLocal Nan::JSON::Parse(v8::Local json_string); -``` - -Use `JSON.Parse(json_string)` to parse a string into a `v8::Value`. - -Example: - -```c++ -v8::Local json_string = Nan::New("{ \"JSON\": \"object\" }").ToLocalChecked(); - -Nan::JSON NanJSON; -Nan::MaybeLocal result = NanJSON.Parse(json_string); -if (!result.IsEmpty()) { - v8::Local val = result.ToLocalChecked(); -} -``` - - - -### Nan::JSON.Stringify - -A simple wrapper around [`v8::JSON::Stringify`](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html#a44b255c3531489ce43f6110209138860). - -Definition: - -```c++ -Nan::MaybeLocal Nan::JSON::Stringify(v8::Local json_object, v8::Local gap = v8::Local()); -``` - -Use `JSON.Stringify(value)` to stringify a `v8::Object`. - -Example: - -```c++ -// using `v8::Local val` from the `JSON::Parse` example -v8::Local obj = Nan::To(val).ToLocalChecked(); - -Nan::JSON NanJSON; -Nan::MaybeLocal result = NanJSON.Stringify(obj); -if (!result.IsEmpty()) { - v8::Local stringified = result.ToLocalChecked(); -} -``` - diff --git a/reverse_engineering/node_modules/nan/doc/maybe_types.md b/reverse_engineering/node_modules/nan/doc/maybe_types.md deleted file mode 100644 index 142851a..0000000 --- a/reverse_engineering/node_modules/nan/doc/maybe_types.md +++ /dev/null @@ -1,583 +0,0 @@ -## Maybe Types - -The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. - -* **Maybe Types** - - Nan::MaybeLocal - - Nan::Maybe - - Nan::Nothing - - Nan::Just -* **Maybe Helpers** - - Nan::Call() - - Nan::ToDetailString() - - Nan::ToArrayIndex() - - Nan::Equals() - - Nan::NewInstance() - - Nan::GetFunction() - - Nan::Set() - - Nan::DefineOwnProperty() - - Nan::ForceSet() - - Nan::Get() - - Nan::GetPropertyAttributes() - - Nan::Has() - - Nan::Delete() - - Nan::GetPropertyNames() - - Nan::GetOwnPropertyNames() - - Nan::SetPrototype() - - Nan::ObjectProtoToString() - - Nan::HasOwnProperty() - - Nan::HasRealNamedProperty() - - Nan::HasRealIndexedProperty() - - Nan::HasRealNamedCallbackProperty() - - Nan::GetRealNamedPropertyInPrototypeChain() - - Nan::GetRealNamedProperty() - - Nan::CallAsFunction() - - Nan::CallAsConstructor() - - Nan::GetSourceLine() - - Nan::GetLineNumber() - - Nan::GetStartColumn() - - Nan::GetEndColumn() - - Nan::CloneElementAt() - - Nan::HasPrivate() - - Nan::GetPrivate() - - Nan::SetPrivate() - - Nan::DeletePrivate() - - Nan::MakeMaybe() - - -### Nan::MaybeLocal - -A `Nan::MaybeLocal` is a wrapper around [`v8::Local`](https://v8docs.nodesource.com/node-8.16/de/deb/classv8_1_1_local.html) that enforces a check that determines whether the `v8::Local` is empty before it can be used. - -If an API method returns a `Nan::MaybeLocal`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, an empty `Nan::MaybeLocal` is returned. - -Definition: - -```c++ -template class Nan::MaybeLocal { - public: - MaybeLocal(); - - template MaybeLocal(v8::Local that); - - bool IsEmpty() const; - - template bool ToLocal(v8::Local *out); - - // Will crash if the MaybeLocal<> is empty. - v8::Local ToLocalChecked(); - - template v8::Local FromMaybe(v8::Local default_value) const; -}; -``` - -See the documentation for [`v8::MaybeLocal`](https://v8docs.nodesource.com/node-8.16/d8/d7d/classv8_1_1_maybe_local.html) for further details. - - -### Nan::Maybe - -A simple `Nan::Maybe` type, representing an object which may or may not have a value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html. - -If an API method returns a `Nan::Maybe<>`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, a "Nothing" value is returned. - -Definition: - -```c++ -template class Nan::Maybe { - public: - bool IsNothing() const; - bool IsJust() const; - - // Will crash if the Maybe<> is nothing. - T FromJust(); - - T FromMaybe(const T& default_value); - - bool operator==(const Maybe &other); - - bool operator!=(const Maybe &other); -}; -``` - -See the documentation for [`v8::Maybe`](https://v8docs.nodesource.com/node-8.16/d9/d4b/classv8_1_1_maybe.html) for further details. - - -### Nan::Nothing - -Construct an empty `Nan::Maybe` type representing _nothing_. - -```c++ -template Nan::Maybe Nan::Nothing(); -``` - - -### Nan::Just - -Construct a `Nan::Maybe` type representing _just_ a value. - -```c++ -template Nan::Maybe Nan::Just(const T &t); -``` - - -### Nan::Call() - -A helper method for calling a synchronous [`v8::Function#Call()`](https://v8docs.nodesource.com/node-8.16/d5/d54/classv8_1_1_function.html#a9c3d0e4e13ddd7721fce238aa5b94a11) in a way compatible across supported versions of V8. - -For asynchronous callbacks, use Nan::Callback::Call along with an AsyncResource. - -Signature: - -```c++ -Nan::MaybeLocal Nan::Call(v8::Local fun, v8::Local recv, int argc, v8::Local argv[]); -Nan::MaybeLocal Nan::Call(const Nan::Callback& callback, v8::Local recv, - int argc, v8::Local argv[]); -Nan::MaybeLocal Nan::Call(const Nan::Callback& callback, int argc, v8::Local argv[]); -``` - - - -### Nan::ToDetailString() - -A helper method for calling [`v8::Value#ToDetailString()`](https://v8docs.nodesource.com/node-8.16/dc/d0a/classv8_1_1_value.html#a2f9770296dc2c8d274bc8cc0dca243e5) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::ToDetailString(v8::Local val); -``` - - - -### Nan::ToArrayIndex() - -A helper method for calling [`v8::Value#ToArrayIndex()`](https://v8docs.nodesource.com/node-8.16/dc/d0a/classv8_1_1_value.html#acc5bbef3c805ec458470c0fcd6f13493) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::ToArrayIndex(v8::Local val); -``` - - - -### Nan::Equals() - -A helper method for calling [`v8::Value#Equals()`](https://v8docs.nodesource.com/node-8.16/dc/d0a/classv8_1_1_value.html#a08fba1d776a59bbf6864b25f9152c64b) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::Equals(v8::Local a, v8::Local(b)); -``` - - - -### Nan::NewInstance() - -A helper method for calling [`v8::Function#NewInstance()`](https://v8docs.nodesource.com/node-8.16/d5/d54/classv8_1_1_function.html#ae477558b10c14b76ed00e8dbab44ce5b) and [`v8::ObjectTemplate#NewInstance()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#ad605a7543cfbc5dab54cdb0883d14ae4) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::NewInstance(v8::Local h); -Nan::MaybeLocal Nan::NewInstance(v8::Local h, int argc, v8::Local argv[]); -Nan::MaybeLocal Nan::NewInstance(v8::Local h); -``` - - - -### Nan::GetFunction() - -A helper method for calling [`v8::FunctionTemplate#GetFunction()`](https://v8docs.nodesource.com/node-8.16/d8/d83/classv8_1_1_function_template.html#a56d904662a86eca78da37d9bb0ed3705) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetFunction(v8::Local t); -``` - - - -### Nan::Set() - -A helper method for calling [`v8::Object#Set()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a67604ea3734f170c66026064ea808f20) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::Set(v8::Local obj, - v8::Local key, - v8::Local value) -Nan::Maybe Nan::Set(v8::Local obj, - uint32_t index, - v8::Local value); -``` - - - -### Nan::DefineOwnProperty() - -A helper method for calling [`v8::Object#DefineOwnProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a6f76b2ed605cb8f9185b92de0033a820) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::DefineOwnProperty(v8::Local obj, - v8::Local key, - v8::Local value, - v8::PropertyAttribute attribs = v8::None); -``` - - - -### Nan::ForceSet() - -Deprecated, use Nan::DefineOwnProperty(). - -A helper method for calling [`v8::Object#ForceSet()`](https://v8docs.nodesource.com/node-0.12/db/d85/classv8_1_1_object.html#acfbdfd7427b516ebdb5c47c4df5ed96c) in a way compatible across supported versions of V8. - -Signature: - -```c++ -NAN_DEPRECATED Nan::Maybe Nan::ForceSet(v8::Local obj, - v8::Local key, - v8::Local value, - v8::PropertyAttribute attribs = v8::None); -``` - - - -### Nan::Get() - -A helper method for calling [`v8::Object#Get()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a2565f03e736694f6b1e1cf22a0b4eac2) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::Get(v8::Local obj, - v8::Local key); -Nan::MaybeLocal Nan::Get(v8::Local obj, uint32_t index); -``` - - - -### Nan::GetPropertyAttributes() - -A helper method for calling [`v8::Object#GetPropertyAttributes()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a9b898894da3d1db2714fd9325a54fe57) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::GetPropertyAttributes( - v8::Local obj, - v8::Local key); -``` - - - -### Nan::Has() - -A helper method for calling [`v8::Object#Has()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab3c3d89ea7c2f9afd08965bd7299a41d) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::Has(v8::Local obj, v8::Local key); -Nan::Maybe Nan::Has(v8::Local obj, uint32_t index); -``` - - - -### Nan::Delete() - -A helper method for calling [`v8::Object#Delete()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a48e4a19b2cedff867eecc73ddb7d377f) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::Delete(v8::Local obj, - v8::Local key); -Nan::Maybe Nan::Delete(v8::Local obj, uint32_t index); -``` - - - -### Nan::GetPropertyNames() - -A helper method for calling [`v8::Object#GetPropertyNames()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#aced885270cfd2c956367b5eedc7fbfe8) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetPropertyNames(v8::Local obj); -``` - - - -### Nan::GetOwnPropertyNames() - -A helper method for calling [`v8::Object#GetOwnPropertyNames()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a79a6e4d66049b9aa648ed4dfdb23e6eb) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetOwnPropertyNames(v8::Local obj); -``` - - - -### Nan::SetPrototype() - -A helper method for calling [`v8::Object#SetPrototype()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a442706b22fceda6e6d1f632122a9a9f4) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::SetPrototype(v8::Local obj, - v8::Local prototype); -``` - - - -### Nan::ObjectProtoToString() - -A helper method for calling [`v8::Object#ObjectProtoToString()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab7a92b4dcf822bef72f6c0ac6fea1f0b) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::ObjectProtoToString(v8::Local obj); -``` - - - -### Nan::HasOwnProperty() - -A helper method for calling [`v8::Object#HasOwnProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab7b7245442ca6de1e1c145ea3fd653ff) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::HasOwnProperty(v8::Local obj, - v8::Local key); -``` - - - -### Nan::HasRealNamedProperty() - -A helper method for calling [`v8::Object#HasRealNamedProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ad8b80a59c9eb3c1e6c3cd6c84571f767) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::HasRealNamedProperty(v8::Local obj, - v8::Local key); -``` - - - -### Nan::HasRealIndexedProperty() - -A helper method for calling [`v8::Object#HasRealIndexedProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#af94fc1135a5e74a2193fb72c3a1b9855) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::HasRealIndexedProperty(v8::Local obj, - uint32_t index); -``` - - - -### Nan::HasRealNamedCallbackProperty() - -A helper method for calling [`v8::Object#HasRealNamedCallbackProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#af743b7ea132b89f84d34d164d0668811) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::HasRealNamedCallbackProperty( - v8::Local obj, - v8::Local key); -``` - - - -### Nan::GetRealNamedPropertyInPrototypeChain() - -A helper method for calling [`v8::Object#GetRealNamedPropertyInPrototypeChain()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a8700b1862e6b4783716964ba4d5e6172) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetRealNamedPropertyInPrototypeChain( - v8::Local obj, - v8::Local key); -``` - - - -### Nan::GetRealNamedProperty() - -A helper method for calling [`v8::Object#GetRealNamedProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a84471a824576a5994fdd0ffcbf99ccc0) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetRealNamedProperty(v8::Local obj, - v8::Local key); -``` - - - -### Nan::CallAsFunction() - -A helper method for calling [`v8::Object#CallAsFunction()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ad3ffc36f3dfc3592ce2a96bc047ee2cd) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::CallAsFunction(v8::Local obj, - v8::Local recv, - int argc, - v8::Local argv[]); -``` - - - -### Nan::CallAsConstructor() - -A helper method for calling [`v8::Object#CallAsConstructor()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a50d571de50d0b0dfb28795619d07a01b) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::CallAsConstructor(v8::Local obj, - int argc, - v8::Local argv[]); -``` - - - -### Nan::GetSourceLine() - -A helper method for calling [`v8::Message#GetSourceLine()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#a849f7a6c41549d83d8159825efccd23a) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetSourceLine(v8::Local msg); -``` - - - -### Nan::GetLineNumber() - -A helper method for calling [`v8::Message#GetLineNumber()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#adbe46c10a88a6565f2732a2d2adf99b9) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::GetLineNumber(v8::Local msg); -``` - - - -### Nan::GetStartColumn() - -A helper method for calling [`v8::Message#GetStartColumn()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#a60ede616ba3822d712e44c7a74487ba6) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::GetStartColumn(v8::Local msg); -``` - - - -### Nan::GetEndColumn() - -A helper method for calling [`v8::Message#GetEndColumn()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#aaa004cf19e529da980bc19fcb76d93be) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::GetEndColumn(v8::Local msg); -``` - - - -### Nan::CloneElementAt() - -A helper method for calling [`v8::Array#CloneElementAt()`](https://v8docs.nodesource.com/node-4.8/d3/d32/classv8_1_1_array.html#a1d3a878d4c1c7cae974dd50a1639245e) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::CloneElementAt(v8::Local array, uint32_t index); -``` - - -### Nan::HasPrivate() - -A helper method for calling [`v8::Object#HasPrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#af68a0b98066cfdeb8f943e98a40ba08d) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::HasPrivate(v8::Local object, v8::Local key); -``` - - -### Nan::GetPrivate() - -A helper method for calling [`v8::Object#GetPrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a169f2da506acbec34deadd9149a1925a) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetPrivate(v8::Local object, v8::Local key); -``` - - -### Nan::SetPrivate() - -A helper method for calling [`v8::Object#SetPrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ace1769b0f3b86bfe9fda1010916360ee) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::SetPrivate(v8::Local object, v8::Local key, v8::Local value); -``` - - -### Nan::DeletePrivate() - -A helper method for calling [`v8::Object#DeletePrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a138bb32a304f3982be02ad499693b8fd) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::DeletePrivate(v8::Local object, v8::Local key); -``` - - -### Nan::MakeMaybe() - -Wraps a `v8::Local<>` in a `Nan::MaybeLocal<>`. When called with a `Nan::MaybeLocal<>` it just returns its argument. This is useful in generic template code that builds on NAN. - -Synopsis: - -```c++ - MaybeLocal someNumber = MakeMaybe(New(3.141592654)); - MaybeLocal someString = MakeMaybe(New("probably")); -``` - -Signature: - -```c++ -template class MaybeMaybe> -Nan::MaybeLocal Nan::MakeMaybe(MaybeMaybe v); -``` diff --git a/reverse_engineering/node_modules/nan/doc/methods.md b/reverse_engineering/node_modules/nan/doc/methods.md deleted file mode 100644 index 9642d02..0000000 --- a/reverse_engineering/node_modules/nan/doc/methods.md +++ /dev/null @@ -1,664 +0,0 @@ -## JavaScript-accessible methods - -A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information. - -In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. - -* **Method argument types** - - Nan::FunctionCallbackInfo - - Nan::PropertyCallbackInfo - - Nan::ReturnValue -* **Method declarations** - - Method declaration - - Getter declaration - - Setter declaration - - Property getter declaration - - Property setter declaration - - Property enumerator declaration - - Property deleter declaration - - Property query declaration - - Index getter declaration - - Index setter declaration - - Index enumerator declaration - - Index deleter declaration - - Index query declaration -* Method and template helpers - - Nan::SetMethod() - - Nan::SetPrototypeMethod() - - Nan::SetAccessor() - - Nan::SetNamedPropertyHandler() - - Nan::SetIndexedPropertyHandler() - - Nan::SetTemplate() - - Nan::SetPrototypeTemplate() - - Nan::SetInstanceTemplate() - - Nan::SetCallHandler() - - Nan::SetCallAsFunctionHandler() - - -### Nan::FunctionCallbackInfo - -`Nan::FunctionCallbackInfo` should be used in place of [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.16/dd/d0d/classv8_1_1_function_callback_info.html), even with older versions of Node where `v8::FunctionCallbackInfo` does not exist. - -Definition: - -```c++ -template class FunctionCallbackInfo { - public: - ReturnValue GetReturnValue() const; - v8::Local Callee(); // NOTE: Not available in NodeJS >= 10.0.0 - v8::Local Data(); - v8::Local Holder(); - bool IsConstructCall(); - int Length() const; - v8::Local operator[](int i) const; - v8::Local This() const; - v8::Isolate *GetIsolate() const; -}; -``` - -See the [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.16/dd/d0d/classv8_1_1_function_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from methods. - -**Note:** `FunctionCallbackInfo::Callee` is removed in Node.js after `10.0.0` because it is was deprecated in V8. Consider using `info.Data()` to pass any information you need. - - -### Nan::PropertyCallbackInfo - -`Nan::PropertyCallbackInfo` should be used in place of [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.16/d7/dc5/classv8_1_1_property_callback_info.html), even with older versions of Node where `v8::PropertyCallbackInfo` does not exist. - -Definition: - -```c++ -template class PropertyCallbackInfo : public PropertyCallbackInfoBase { - public: - ReturnValue GetReturnValue() const; - v8::Isolate* GetIsolate() const; - v8::Local Data() const; - v8::Local This() const; - v8::Local Holder() const; -}; -``` - -See the [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.16/d7/dc5/classv8_1_1_property_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from property accessor methods. - - -### Nan::ReturnValue - -`Nan::ReturnValue` is used in place of [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.16/da/da7/classv8_1_1_return_value.html) on both [`Nan::FunctionCallbackInfo`](#api_nan_function_callback_info) and [`Nan::PropertyCallbackInfo`](#api_nan_property_callback_info) as the return type of `GetReturnValue()`. - -Example usage: - -```c++ -void EmptyArray(const Nan::FunctionCallbackInfo& info) { - info.GetReturnValue().Set(Nan::New()); -} -``` - -Definition: - -```c++ -template class ReturnValue { - public: - // Handle setters - template void Set(const v8::Local &handle); - template void Set(const Nan::Global &handle); - - // Fast primitive setters - void Set(bool value); - void Set(double i); - void Set(int32_t i); - void Set(uint32_t i); - - // Fast JS primitive setters - void SetNull(); - void SetUndefined(); - void SetEmptyString(); - - // Convenience getter for isolate - v8::Isolate *GetIsolate() const; -}; -``` - -See the documentation on [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.16/da/da7/classv8_1_1_return_value.html) for further information on this. - - -### Method declaration - -JavaScript-accessible methods should be declared with the following signature to form a `Nan::FunctionCallback`: - -```c++ -typedef void(*FunctionCallback)(const FunctionCallbackInfo&); -``` - -Example: - -```c++ -void MethodName(const Nan::FunctionCallbackInfo& info) { - ... -} -``` - -You do not need to declare a new `HandleScope` within a method as one is implicitly created for you. - -**Example usage** - -```c++ -// .h: -class Foo : public Nan::ObjectWrap { - ... - - static void Bar(const Nan::FunctionCallbackInfo& info); - static void Baz(const Nan::FunctionCallbackInfo& info); -} - - -// .cc: -void Foo::Bar(const Nan::FunctionCallbackInfo& info) { - ... -} - -void Foo::Baz(const Nan::FunctionCallbackInfo& info) { - ... -} -``` - -A helper macro `NAN_METHOD(methodname)` exists, compatible with NAN v1 method declarations. - -**Example usage with `NAN_METHOD(methodname)`** - -```c++ -// .h: -class Foo : public Nan::ObjectWrap { - ... - - static NAN_METHOD(Bar); - static NAN_METHOD(Baz); -} - - -// .cc: -NAN_METHOD(Foo::Bar) { - ... -} - -NAN_METHOD(Foo::Baz) { - ... -} -``` - -Use [`Nan::SetPrototypeMethod`](#api_nan_set_prototype_method) to attach a method to a JavaScript function prototype or [`Nan::SetMethod`](#api_nan_set_method) to attach a method directly on a JavaScript object. - - -### Getter declaration - -JavaScript-accessible getters should be declared with the following signature to form a `Nan::GetterCallback`: - -```c++ -typedef void(*GetterCallback)(v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void GetterName(v8::Local property, - const Nan::PropertyCallbackInfo& info) { - ... -} -``` - -You do not need to declare a new `HandleScope` within a getter as one is implicitly created for you. - -A helper macro `NAN_GETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors). - - -### Setter declaration - -JavaScript-accessible setters should be declared with the following signature to form a Nan::SetterCallback: - -```c++ -typedef void(*SetterCallback)(v8::Local, - v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void SetterName(v8::Local property, - v8::Local value, - const Nan::PropertyCallbackInfo& info) { - ... -} -``` - -You do not need to declare a new `HandleScope` within a setter as one is implicitly created for you. - -A helper macro `NAN_SETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors). - - -### Property getter declaration - -JavaScript-accessible property getters should be declared with the following signature to form a Nan::PropertyGetterCallback: - -```c++ -typedef void(*PropertyGetterCallback)(v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void PropertyGetterName(v8::Local property, - const Nan::PropertyCallbackInfo& info) { - ... -} -``` - -You do not need to declare a new `HandleScope` within a property getter as one is implicitly created for you. - -A helper macro `NAN_PROPERTY_GETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Property setter declaration - -JavaScript-accessible property setters should be declared with the following signature to form a Nan::PropertySetterCallback: - -```c++ -typedef void(*PropertySetterCallback)(v8::Local, - v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void PropertySetterName(v8::Local property, - v8::Local value, - const Nan::PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a property setter as one is implicitly created for you. - -A helper macro `NAN_PROPERTY_SETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Property enumerator declaration - -JavaScript-accessible property enumerators should be declared with the following signature to form a Nan::PropertyEnumeratorCallback: - -```c++ -typedef void(*PropertyEnumeratorCallback)(const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void PropertyEnumeratorName(const Nan::PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a property enumerator as one is implicitly created for you. - -A helper macro `NAN_PROPERTY_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Property deleter declaration - -JavaScript-accessible property deleters should be declared with the following signature to form a Nan::PropertyDeleterCallback: - -```c++ -typedef void(*PropertyDeleterCallback)(v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void PropertyDeleterName(v8::Local property, - const Nan::PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a property deleter as one is implicitly created for you. - -A helper macro `NAN_PROPERTY_DELETER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Property query declaration - -JavaScript-accessible property query methods should be declared with the following signature to form a Nan::PropertyQueryCallback: - -```c++ -typedef void(*PropertyQueryCallback)(v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void PropertyQueryName(v8::Local property, - const Nan::PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a property query method as one is implicitly created for you. - -A helper macro `NAN_PROPERTY_QUERY(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Index getter declaration - -JavaScript-accessible index getter methods should be declared with the following signature to form a Nan::IndexGetterCallback: - -```c++ -typedef void(*IndexGetterCallback)(uint32_t, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void IndexGetterName(uint32_t index, const PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a index getter as one is implicitly created for you. - -A helper macro `NAN_INDEX_GETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Index setter declaration - -JavaScript-accessible index setter methods should be declared with the following signature to form a Nan::IndexSetterCallback: - -```c++ -typedef void(*IndexSetterCallback)(uint32_t, - v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void IndexSetterName(uint32_t index, - v8::Local value, - const PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a index setter as one is implicitly created for you. - -A helper macro `NAN_INDEX_SETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Index enumerator declaration - -JavaScript-accessible index enumerator methods should be declared with the following signature to form a Nan::IndexEnumeratorCallback: - -```c++ -typedef void(*IndexEnumeratorCallback)(const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void IndexEnumeratorName(const PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a index enumerator as one is implicitly created for you. - -A helper macro `NAN_INDEX_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Index deleter declaration - -JavaScript-accessible index deleter methods should be declared with the following signature to form a Nan::IndexDeleterCallback: - -```c++ -typedef void(*IndexDeleterCallback)(uint32_t, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void IndexDeleterName(uint32_t index, const PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a index deleter as one is implicitly created for you. - -A helper macro `NAN_INDEX_DELETER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Index query declaration - -JavaScript-accessible index query methods should be declared with the following signature to form a Nan::IndexQueryCallback: - -```c++ -typedef void(*IndexQueryCallback)(uint32_t, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void IndexQueryName(uint32_t index, const PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a index query method as one is implicitly created for you. - -A helper macro `NAN_INDEX_QUERY(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Nan::SetMethod() - -Sets a method with a given name directly on a JavaScript object where the method has the `Nan::FunctionCallback` signature (see Method declaration). - -Signature: - -```c++ -void Nan::SetMethod(v8::Local recv, - const char *name, - Nan::FunctionCallback callback, - v8::Local data = v8::Local()) -void Nan::SetMethod(v8::Local templ, - const char *name, - Nan::FunctionCallback callback, - v8::Local data = v8::Local()) -``` - - -### Nan::SetPrototypeMethod() - -Sets a method with a given name on a `FunctionTemplate`'s prototype where the method has the `Nan::FunctionCallback` signature (see Method declaration). - -Signature: - -```c++ -void Nan::SetPrototypeMethod(v8::Local recv, - const char* name, - Nan::FunctionCallback callback, - v8::Local data = v8::Local()) -``` - - -### Nan::SetAccessor() - -Sets getters and setters for a property with a given name on an `ObjectTemplate` or a plain `Object`. Accepts getters with the `Nan::GetterCallback` signature (see Getter declaration) and setters with the `Nan::SetterCallback` signature (see Setter declaration). - -Signature: - -```c++ -void SetAccessor(v8::Local tpl, - v8::Local name, - Nan::GetterCallback getter, - Nan::SetterCallback setter = 0, - v8::Local data = v8::Local(), - v8::AccessControl settings = v8::DEFAULT, - v8::PropertyAttribute attribute = v8::None, - imp::Sig signature = imp::Sig()); -bool SetAccessor(v8::Local obj, - v8::Local name, - Nan::GetterCallback getter, - Nan::SetterCallback setter = 0, - v8::Local data = v8::Local(), - v8::AccessControl settings = v8::DEFAULT, - v8::PropertyAttribute attribute = v8::None) -``` - -See the V8 [`ObjectTemplate#SetAccessor()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#aca0ed196f8a9adb1f68b1aadb6c9cd77) and [`Object#SetAccessor()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ae91b3b56b357f285288c89fbddc46d1b) for further information about how to use `Nan::SetAccessor()`. - - -### Nan::SetNamedPropertyHandler() - -Sets named property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts: - -* Property getters with the `Nan::PropertyGetterCallback` signature (see Property getter declaration) -* Property setters with the `Nan::PropertySetterCallback` signature (see Property setter declaration) -* Property query methods with the `Nan::PropertyQueryCallback` signature (see Property query declaration) -* Property deleters with the `Nan::PropertyDeleterCallback` signature (see Property deleter declaration) -* Property enumerators with the `Nan::PropertyEnumeratorCallback` signature (see Property enumerator declaration) - -Signature: - -```c++ -void SetNamedPropertyHandler(v8::Local tpl, - Nan::PropertyGetterCallback getter, - Nan::PropertySetterCallback setter = 0, - Nan::PropertyQueryCallback query = 0, - Nan::PropertyDeleterCallback deleter = 0, - Nan::PropertyEnumeratorCallback enumerator = 0, - v8::Local data = v8::Local()) -``` - -See the V8 [`ObjectTemplate#SetNamedPropertyHandler()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#a33b3ebd7de641f6cc6414b7de01fc1c7) for further information about how to use `Nan::SetNamedPropertyHandler()`. - - -### Nan::SetIndexedPropertyHandler() - -Sets indexed property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts: - -* Indexed property getters with the `Nan::IndexGetterCallback` signature (see Index getter declaration) -* Indexed property setters with the `Nan::IndexSetterCallback` signature (see Index setter declaration) -* Indexed property query methods with the `Nan::IndexQueryCallback` signature (see Index query declaration) -* Indexed property deleters with the `Nan::IndexDeleterCallback` signature (see Index deleter declaration) -* Indexed property enumerators with the `Nan::IndexEnumeratorCallback` signature (see Index enumerator declaration) - -Signature: - -```c++ -void SetIndexedPropertyHandler(v8::Local tpl, - Nan::IndexGetterCallback getter, - Nan::IndexSetterCallback setter = 0, - Nan::IndexQueryCallback query = 0, - Nan::IndexDeleterCallback deleter = 0, - Nan::IndexEnumeratorCallback enumerator = 0, - v8::Local data = v8::Local()) -``` - -See the V8 [`ObjectTemplate#SetIndexedPropertyHandler()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#ac89f06d634add0e890452033f7d17ff1) for further information about how to use `Nan::SetIndexedPropertyHandler()`. - - -### Nan::SetTemplate() - -Adds properties on an `Object`'s or `Function`'s template. - -Signature: - -```c++ -void Nan::SetTemplate(v8::Local templ, - const char *name, - v8::Local value); -void Nan::SetTemplate(v8::Local templ, - v8::Local name, - v8::Local value, - v8::PropertyAttribute attributes) -``` - -Calls the `Template`'s [`Set()`](https://v8docs.nodesource.com/node-8.16/db/df7/classv8_1_1_template.html#ae3fbaff137557aa6a0233bc7e52214ac). - - -### Nan::SetPrototypeTemplate() - -Adds properties on an `Object`'s or `Function`'s prototype template. - -Signature: - -```c++ -void Nan::SetPrototypeTemplate(v8::Local templ, - const char *name, - v8::Local value); -void Nan::SetPrototypeTemplate(v8::Local templ, - v8::Local name, - v8::Local value, - v8::PropertyAttribute attributes) -``` - -Calls the `FunctionTemplate`'s _PrototypeTemplate's_ [`Set()`](https://v8docs.nodesource.com/node-8.16/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf). - - -### Nan::SetInstanceTemplate() - -Use to add instance properties on `FunctionTemplate`'s. - -Signature: - -```c++ -void Nan::SetInstanceTemplate(v8::Local templ, - const char *name, - v8::Local value); -void Nan::SetInstanceTemplate(v8::Local templ, - v8::Local name, - v8::Local value, - v8::PropertyAttribute attributes) -``` - -Calls the `FunctionTemplate`'s _InstanceTemplate's_ [`Set()`](https://v8docs.nodesource.com/node-8.16/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf). - - -### Nan::SetCallHandler() - -Set the call-handler callback for a `v8::FunctionTemplate`. -This callback is called whenever the function created from this FunctionTemplate is called. - -Signature: - -```c++ -void Nan::SetCallHandler(v8::Local templ, Nan::FunctionCallback callback, v8::Local data = v8::Local()) -``` - -Calls the `FunctionTemplate`'s [`SetCallHandler()`](https://v8docs.nodesource.com/node-8.16/d8/d83/classv8_1_1_function_template.html#ab7574b298db3c27fbc2ed465c08ea2f8). - - -### Nan::SetCallAsFunctionHandler() - -Sets the callback to be used when calling instances created from the `v8::ObjectTemplate` as a function. -If no callback is set, instances behave like normal JavaScript objects that cannot be called as a function. - -Signature: - -```c++ -void Nan::SetCallAsFunctionHandler(v8::Local templ, Nan::FunctionCallback callback, v8::Local data = v8::Local()) -``` - -Calls the `ObjectTemplate`'s [`SetCallAsFunctionHandler()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#a5e9612fc80bf6db8f2da199b9b0bd04e). - diff --git a/reverse_engineering/node_modules/nan/doc/new.md b/reverse_engineering/node_modules/nan/doc/new.md deleted file mode 100644 index 0f28a0e..0000000 --- a/reverse_engineering/node_modules/nan/doc/new.md +++ /dev/null @@ -1,147 +0,0 @@ -## New - -NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. - - - Nan::New() - - Nan::Undefined() - - Nan::Null() - - Nan::True() - - Nan::False() - - Nan::EmptyString() - - - -### Nan::New() - -`Nan::New()` should be used to instantiate new JavaScript objects. - -Refer to the specific V8 type in the [V8 documentation](https://v8docs.nodesource.com/node-8.16/d1/d83/classv8_1_1_data.html) for information on the types of arguments required for instantiation. - -Signatures: - -Return types are mostly omitted from the signatures for simplicity. In most cases the type will be contained within a `v8::Local`. The following types will be contained within a `Nan::MaybeLocal`: `v8::String`, `v8::Date`, `v8::RegExp`, `v8::Script`, `v8::UnboundScript`. - -Empty objects: - -```c++ -Nan::New(); -``` - -Generic single and multiple-argument: - -```c++ -Nan::New(A0 arg0); -Nan::New(A0 arg0, A1 arg1); -Nan::New(A0 arg0, A1 arg1, A2 arg2); -Nan::New(A0 arg0, A1 arg1, A2 arg2, A3 arg3); -``` - -For creating `v8::FunctionTemplate` and `v8::Function` objects: - -_The definition of `Nan::FunctionCallback` can be found in the [Method declaration](./methods.md#api_nan_method) documentation._ - -```c++ -Nan::New(Nan::FunctionCallback callback, - v8::Local data = v8::Local()); -Nan::New(Nan::FunctionCallback callback, - v8::Local data = v8::Local(), - A2 a2 = A2()); -``` - -Native number types: - -```c++ -v8::Local Nan::New(bool value); -v8::Local Nan::New(int32_t value); -v8::Local Nan::New(uint32_t value); -v8::Local Nan::New(double value); -``` - -String types: - -```c++ -Nan::MaybeLocal Nan::New(std::string const& value); -Nan::MaybeLocal Nan::New(const char * value, int length); -Nan::MaybeLocal Nan::New(const char * value); -Nan::MaybeLocal Nan::New(const uint16_t * value); -Nan::MaybeLocal Nan::New(const uint16_t * value, int length); -``` - -Specialized types: - -```c++ -v8::Local Nan::New(v8::String::ExternalStringResource * value); -v8::Local Nan::New(Nan::ExternalOneByteStringResource * value); -v8::Local Nan::New(v8::Local pattern, v8::RegExp::Flags flags); -``` - -Note that `Nan::ExternalOneByteStringResource` maps to [`v8::String::ExternalOneByteStringResource`](https://v8docs.nodesource.com/node-8.16/d9/db3/classv8_1_1_string_1_1_external_one_byte_string_resource.html), and `v8::String::ExternalAsciiStringResource` in older versions of V8. - - - -### Nan::Undefined() - -A helper method to reference the `v8::Undefined` object in a way that is compatible across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::Undefined() -``` - - -### Nan::Null() - -A helper method to reference the `v8::Null` object in a way that is compatible across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::Null() -``` - - -### Nan::True() - -A helper method to reference the `v8::Boolean` object representing the `true` value in a way that is compatible across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::True() -``` - - -### Nan::False() - -A helper method to reference the `v8::Boolean` object representing the `false` value in a way that is compatible across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::False() -``` - - -### Nan::EmptyString() - -Call [`v8::String::Empty`](https://v8docs.nodesource.com/node-8.16/d2/db3/classv8_1_1_string.html#a7c1bc8886115d7ee46f1d571dd6ebc6d) to reference the empty string in a way that is compatible across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::EmptyString() -``` - - - -### Nan::NewOneByteString() - -An implementation of [`v8::String::NewFromOneByte()`](https://v8docs.nodesource.com/node-8.16/d2/db3/classv8_1_1_string.html#a5264d50b96d2c896ce525a734dc10f09) provided for consistent availability and API across supported versions of V8. Allocates a new string from Latin-1 data. - -Signature: - -```c++ -Nan::MaybeLocal Nan::NewOneByteString(const uint8_t * value, - int length = -1) -``` diff --git a/reverse_engineering/node_modules/nan/doc/node_misc.md b/reverse_engineering/node_modules/nan/doc/node_misc.md deleted file mode 100644 index 17578e3..0000000 --- a/reverse_engineering/node_modules/nan/doc/node_misc.md +++ /dev/null @@ -1,123 +0,0 @@ -## Miscellaneous Node Helpers - - - Nan::AsyncResource - - Nan::MakeCallback() - - NAN_MODULE_INIT() - - Nan::Export() - - -### Nan::AsyncResource - -This class is analogous to the `AsyncResource` JavaScript class exposed by Node's [async_hooks][] API. - -When calling back into JavaScript asynchronously, special care must be taken to ensure that the runtime can properly track -async hops. `Nan::AsyncResource` is a class that provides an RAII wrapper around `node::EmitAsyncInit`, `node::EmitAsyncDestroy`, -and `node::MakeCallback`. Using this mechanism to call back into JavaScript, as opposed to `Nan::MakeCallback` or -`v8::Function::Call` ensures that the callback is executed in the correct async context. This ensures that async mechanisms -such as domains and [async_hooks][] function correctly. - -Definition: - -```c++ -class AsyncResource { - public: - AsyncResource(v8::Local name, - v8::Local resource = New()); - AsyncResource(const char* name, - v8::Local resource = New()); - ~AsyncResource(); - - v8::MaybeLocal runInAsyncScope(v8::Local target, - v8::Local func, - int argc, - v8::Local* argv); - v8::MaybeLocal runInAsyncScope(v8::Local target, - v8::Local symbol, - int argc, - v8::Local* argv); - v8::MaybeLocal runInAsyncScope(v8::Local target, - const char* method, - int argc, - v8::Local* argv); -}; -``` - -* `name`: Identifier for the kind of resource that is being provided for diagnostics information exposed by the [async_hooks][] - API. This will be passed to the possible `init` hook as the `type`. To avoid name collisions with other modules we recommend - that the name include the name of the owning module as a prefix. For example `mysql` module could use something like - `mysql:batch-db-query-resource`. -* `resource`: An optional object associated with the async work that will be passed to the possible [async_hooks][] - `init` hook. If this parameter is omitted, or an empty handle is provided, this object will be created automatically. -* When calling JS on behalf of this resource, one can use `runInAsyncScope`. This will ensure that the callback runs in the - correct async execution context. -* `AsyncDestroy` is automatically called when an AsyncResource object is destroyed. - -For more details, see the Node [async_hooks][] documentation. You might also want to take a look at the documentation for the -[N-API counterpart][napi]. For example usage, see the `asyncresource.cpp` example in the `test/cpp` directory. - - -### Nan::MakeCallback() - -Deprecated wrappers around the legacy `node::MakeCallback()` APIs. Node.js 10+ -has deprecated these legacy APIs as they do not provide a mechanism to preserve -async context. - -We recommend that you use the `AsyncResource` class and `AsyncResource::runInAsyncScope` instead of using `Nan::MakeCallback` or -`v8::Function#Call()` directly. `AsyncResource` properly takes care of running the callback in the correct async execution -context – something that is essential for functionality like domains, async_hooks and async debugging. - -Signatures: - -```c++ -NAN_DEPRECATED -v8::Local Nan::MakeCallback(v8::Local target, - v8::Local func, - int argc, - v8::Local* argv); -NAN_DEPRECATED -v8::Local Nan::MakeCallback(v8::Local target, - v8::Local symbol, - int argc, - v8::Local* argv); -NAN_DEPRECATED -v8::Local Nan::MakeCallback(v8::Local target, - const char* method, - int argc, - v8::Local* argv); -``` - - - -### NAN_MODULE_INIT() - -Used to define the entry point function to a Node add-on. Creates a function with a given `name` that receives a `target` object representing the equivalent of the JavaScript `exports` object. - -See example below. - - -### Nan::Export() - -A simple helper to register a `v8::FunctionTemplate` from a JavaScript-accessible method (see [Methods](./methods.md)) as a property on an object. Can be used in a way similar to assigning properties to `module.exports` in JavaScript. - -Signature: - -```c++ -void Export(v8::Local target, const char *name, Nan::FunctionCallback f) -``` - -Also available as the shortcut `NAN_EXPORT` macro. - -Example: - -```c++ -NAN_METHOD(Foo) { - ... -} - -NAN_MODULE_INIT(Init) { - NAN_EXPORT(target, Foo); -} -``` - -[async_hooks]: https://nodejs.org/dist/latest-v9.x/docs/api/async_hooks.html -[napi]: https://nodejs.org/dist/latest-v9.x/docs/api/n-api.html#n_api_custom_asynchronous_operations diff --git a/reverse_engineering/node_modules/nan/doc/object_wrappers.md b/reverse_engineering/node_modules/nan/doc/object_wrappers.md deleted file mode 100644 index 07d8c05..0000000 --- a/reverse_engineering/node_modules/nan/doc/object_wrappers.md +++ /dev/null @@ -1,263 +0,0 @@ -## Object Wrappers - -The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects. - - - Nan::ObjectWrap - - - -### Nan::ObjectWrap() - -A reimplementation of `node::ObjectWrap` that adds some API not present in older versions of Node. Should be preferred over `node::ObjectWrap` in all cases for consistency. - -Definition: - -```c++ -class ObjectWrap { - public: - ObjectWrap(); - - virtual ~ObjectWrap(); - - template - static inline T* Unwrap(v8::Local handle); - - inline v8::Local handle(); - - inline Nan::Persistent& persistent(); - - protected: - inline void Wrap(v8::Local handle); - - inline void MakeWeak(); - - /* Ref() marks the object as being attached to an event loop. - * Refed objects will not be garbage collected, even if - * all references are lost. - */ - virtual void Ref(); - - /* Unref() marks an object as detached from the event loop. This is its - * default state. When an object with a "weak" reference changes from - * attached to detached state it will be freed. Be careful not to access - * the object after making this call as it might be gone! - * (A "weak reference" means an object that only has a - * persistent handle.) - * - * DO NOT CALL THIS FROM DESTRUCTOR - */ - virtual void Unref(); - - int refs_; // ro -}; -``` - -See the Node documentation on [Wrapping C++ Objects](https://nodejs.org/api/addons.html#addons_wrapping_c_objects) for more details. - -### This vs. Holder - -When calling `Unwrap`, it is important that the argument is indeed some JavaScript object which got wrapped by a `Wrap` call for this class or any derived class. -The `Signature` installed by [`Nan::SetPrototypeMethod()`](methods.md#api_nan_set_prototype_method) does ensure that `info.Holder()` is just such an instance. -In Node 0.12 and later, `info.This()` will also be of such a type, since otherwise the invocation will get rejected. -However, in Node 0.10 and before it was possible to invoke a method on a JavaScript object which just had the extension type in its prototype chain. -In such a situation, calling `Unwrap` on `info.This()` will likely lead to a failed assertion causing a crash, but could lead to even more serious corruption. - -On the other hand, calling `Unwrap` in an [accessor](methods.md#api_nan_set_accessor) should not use `Holder()` if the accessor is defined on the prototype. -So either define your accessors on the instance template, -or use `This()` after verifying that it is indeed a valid object. - -### Examples - -#### Basic - -```c++ -class MyObject : public Nan::ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - v8::Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("MyObject").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - Nan::SetPrototypeMethod(tpl, "getHandle", GetHandle); - Nan::SetPrototypeMethod(tpl, "getValue", GetValue); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - Nan::Set(target, Nan::New("MyObject").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit MyObject(double value = 0) : value_(value) {} - ~MyObject() {} - - static NAN_METHOD(New) { - if (info.IsConstructCall()) { - double value = info[0]->IsUndefined() ? 0 : Nan::To(info[0]).FromJust(); - MyObject *obj = new MyObject(value); - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } else { - const int argc = 1; - v8::Local argv[argc] = {info[0]}; - v8::Local cons = Nan::New(constructor()); - info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); - } - } - - static NAN_METHOD(GetHandle) { - MyObject* obj = Nan::ObjectWrap::Unwrap(info.Holder()); - info.GetReturnValue().Set(obj->handle()); - } - - static NAN_METHOD(GetValue) { - MyObject* obj = Nan::ObjectWrap::Unwrap(info.Holder()); - info.GetReturnValue().Set(obj->value_); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - double value_; -}; - -NODE_MODULE(objectwrapper, MyObject::Init) -``` - -To use in Javascript: - -```Javascript -var objectwrapper = require('bindings')('objectwrapper'); - -var obj = new objectwrapper.MyObject(5); -console.log('Should be 5: ' + obj.getValue()); -``` - -#### Factory of wrapped objects - -```c++ -class MyFactoryObject : public Nan::ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - v8::Local tpl = Nan::New(New); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - Nan::SetPrototypeMethod(tpl, "getValue", GetValue); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - } - - static NAN_METHOD(NewInstance) { - v8::Local cons = Nan::New(constructor()); - double value = info[0]->IsNumber() ? Nan::To(info[0]).FromJust() : 0; - const int argc = 1; - v8::Local argv[1] = {Nan::New(value)}; - info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); - } - - // Needed for the next example: - inline double value() const { - return value_; - } - - private: - explicit MyFactoryObject(double value = 0) : value_(value) {} - ~MyFactoryObject() {} - - static NAN_METHOD(New) { - if (info.IsConstructCall()) { - double value = info[0]->IsNumber() ? Nan::To(info[0]).FromJust() : 0; - MyFactoryObject * obj = new MyFactoryObject(value); - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } else { - const int argc = 1; - v8::Local argv[argc] = {info[0]}; - v8::Local cons = Nan::New(constructor()); - info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); - } - } - - static NAN_METHOD(GetValue) { - MyFactoryObject* obj = ObjectWrap::Unwrap(info.Holder()); - info.GetReturnValue().Set(obj->value_); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - double value_; -}; - -NAN_MODULE_INIT(Init) { - MyFactoryObject::Init(target); - Nan::Set(target, - Nan::New("newFactoryObjectInstance").ToLocalChecked(), - Nan::GetFunction( - Nan::New(MyFactoryObject::NewInstance)).ToLocalChecked() - ); -} - -NODE_MODULE(wrappedobjectfactory, Init) -``` - -To use in Javascript: - -```Javascript -var wrappedobjectfactory = require('bindings')('wrappedobjectfactory'); - -var obj = wrappedobjectfactory.newFactoryObjectInstance(10); -console.log('Should be 10: ' + obj.getValue()); -``` - -#### Passing wrapped objects around - -Use the `MyFactoryObject` class above along with the following: - -```c++ -static NAN_METHOD(Sum) { - Nan::MaybeLocal maybe1 = Nan::To(info[0]); - Nan::MaybeLocal maybe2 = Nan::To(info[1]); - - // Quick check: - if (maybe1.IsEmpty() || maybe2.IsEmpty()) { - // return value is undefined by default - return; - } - - MyFactoryObject* obj1 = - Nan::ObjectWrap::Unwrap(maybe1.ToLocalChecked()); - MyFactoryObject* obj2 = - Nan::ObjectWrap::Unwrap(maybe2.ToLocalChecked()); - - info.GetReturnValue().Set(Nan::New(obj1->value() + obj2->value())); -} - -NAN_MODULE_INIT(Init) { - MyFactoryObject::Init(target); - Nan::Set(target, - Nan::New("newFactoryObjectInstance").ToLocalChecked(), - Nan::GetFunction( - Nan::New(MyFactoryObject::NewInstance)).ToLocalChecked() - ); - Nan::Set(target, - Nan::New("sum").ToLocalChecked(), - Nan::GetFunction(Nan::New(Sum)).ToLocalChecked() - ); -} - -NODE_MODULE(myaddon, Init) -``` - -To use in Javascript: - -```Javascript -var myaddon = require('bindings')('myaddon'); - -var obj1 = myaddon.newFactoryObjectInstance(5); -var obj2 = myaddon.newFactoryObjectInstance(10); -console.log('sum of object values: ' + myaddon.sum(obj1, obj2)); -``` diff --git a/reverse_engineering/node_modules/nan/doc/persistent.md b/reverse_engineering/node_modules/nan/doc/persistent.md deleted file mode 100644 index 2e13f6b..0000000 --- a/reverse_engineering/node_modules/nan/doc/persistent.md +++ /dev/null @@ -1,296 +0,0 @@ -## Persistent references - -An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. - -Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. - - - Nan::PersistentBase & v8::PersistentBase - - Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits - - Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits - - Nan::Persistent - - Nan::Global - - Nan::WeakCallbackInfo - - Nan::WeakCallbackType - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). - - -### Nan::PersistentBase & v8::PersistentBase - -A persistent handle contains a reference to a storage cell in V8 which holds an object value and which is updated by the garbage collector whenever the object is moved. A new storage cell can be created using the constructor or `Nan::PersistentBase::Reset()`. Existing handles can be disposed using an argument-less `Nan::PersistentBase::Reset()`. - -Definition: - -_(note: this is implemented as `Nan::PersistentBase` for older versions of V8 and the native `v8::PersistentBase` is used for newer versions of V8)_ - -```c++ -template class PersistentBase { - public: - /** - * If non-empty, destroy the underlying storage cell - */ - void Reset(); - - /** - * If non-empty, destroy the underlying storage cell and create a new one with - * the contents of another if it is also non-empty - */ - template void Reset(const v8::Local &other); - - /** - * If non-empty, destroy the underlying storage cell and create a new one with - * the contents of another if it is also non-empty - */ - template void Reset(const PersistentBase &other); - - /** Returns true if the handle is empty. */ - bool IsEmpty() const; - - /** - * If non-empty, destroy the underlying storage cell - * IsEmpty() will return true after this call. - */ - void Empty(); - - template bool operator==(const PersistentBase &that); - - template bool operator==(const v8::Local &that); - - template bool operator!=(const PersistentBase &that); - - template bool operator!=(const v8::Local &that); - - /** - * Install a finalization callback on this object. - * NOTE: There is no guarantee as to *when* or even *if* the callback is - * invoked. The invocation is performed solely on a best effort basis. - * As always, GC-based finalization should *not* be relied upon for any - * critical form of resource management! At the moment you can either - * specify a parameter for the callback or the location of two internal - * fields in the dying object. - */ - template - void SetWeak(P *parameter, - typename WeakCallbackInfo

::Callback callback, - WeakCallbackType type); - - void ClearWeak(); - - /** - * Marks the reference to this object independent. Garbage collector is free - * to ignore any object groups containing this object. Weak callback for an - * independent handle should not assume that it will be preceded by a global - * GC prologue callback or followed by a global GC epilogue callback. - */ - void MarkIndependent() const; - - bool IsIndependent() const; - - /** Checks if the handle holds the only reference to an object. */ - bool IsNearDeath() const; - - /** Returns true if the handle's reference is weak. */ - bool IsWeak() const -}; -``` - -See the V8 documentation for [`PersistentBase`](https://v8docs.nodesource.com/node-8.16/d4/dca/classv8_1_1_persistent_base.html) for further information. - -**Tip:** To get a `v8::Local` reference to the original object back from a `PersistentBase` or `Persistent` object: - -```c++ -v8::Local object = Nan::New(persistent); -``` - - -### Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits - -Default traits for `Nan::Persistent`. This class does not allow use of the a copy constructor or assignment operator. At present `kResetInDestructor` is not set, but that will change in a future version. - -Definition: - -_(note: this is implemented as `Nan::NonCopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_ - -```c++ -template class NonCopyablePersistentTraits { - public: - typedef Persistent > NonCopyablePersistent; - - static const bool kResetInDestructor = false; - - template - static void Copy(const Persistent &source, - NonCopyablePersistent *dest); - - template static void Uncompilable(); -}; -``` - -See the V8 documentation for [`NonCopyablePersistentTraits`](https://v8docs.nodesource.com/node-8.16/de/d73/classv8_1_1_non_copyable_persistent_traits.html) for further information. - - -### Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits - -A helper class of traits to allow copying and assignment of `Persistent`. This will clone the contents of storage cell, but not any of the flags, etc.. - -Definition: - -_(note: this is implemented as `Nan::CopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_ - -```c++ -template -class CopyablePersistentTraits { - public: - typedef Persistent > CopyablePersistent; - - static const bool kResetInDestructor = true; - - template - static void Copy(const Persistent &source, - CopyablePersistent *dest); -}; -``` - -See the V8 documentation for [`CopyablePersistentTraits`](https://v8docs.nodesource.com/node-8.16/da/d5c/structv8_1_1_copyable_persistent_traits.html) for further information. - - -### Nan::Persistent - -A type of `PersistentBase` which allows copy and assignment. Copy, assignment and destructor behavior is controlled by the traits class `M`. - -Definition: - -```c++ -template > -class Persistent; - -template class Persistent : public PersistentBase { - public: - /** - * A Persistent with no storage cell. - */ - Persistent(); - - /** - * Construct a Persistent from a v8::Local. When the v8::Local is non-empty, a - * new storage cell is created pointing to the same object, and no flags are - * set. - */ - template Persistent(v8::Local that); - - /** - * Construct a Persistent from a Persistent. When the Persistent is non-empty, - * a new storage cell is created pointing to the same object, and no flags are - * set. - */ - Persistent(const Persistent &that); - - /** - * The copy constructors and assignment operator create a Persistent exactly - * as the Persistent constructor, but the Copy function from the traits class - * is called, allowing the setting of flags based on the copied Persistent. - */ - Persistent &operator=(const Persistent &that); - - template - Persistent &operator=(const Persistent &that); - - /** - * The destructor will dispose the Persistent based on the kResetInDestructor - * flags in the traits class. Since not calling dispose can result in a - * memory leak, it is recommended to always set this flag. - */ - ~Persistent(); -}; -``` - -See the V8 documentation for [`Persistent`](https://v8docs.nodesource.com/node-8.16/d2/d78/classv8_1_1_persistent.html) for further information. - - -### Nan::Global - -A type of `PersistentBase` which has move semantics. - -```c++ -template class Global : public PersistentBase { - public: - /** - * A Global with no storage cell. - */ - Global(); - - /** - * Construct a Global from a v8::Local. When the v8::Local is non-empty, a new - * storage cell is created pointing to the same object, and no flags are set. - */ - template Global(v8::Local that); - /** - * Construct a Global from a PersistentBase. When the Persistent is non-empty, - * a new storage cell is created pointing to the same object, and no flags are - * set. - */ - template Global(const PersistentBase &that); - - /** - * Pass allows returning globals from functions, etc. - */ - Global Pass(); -}; -``` - -See the V8 documentation for [`Global`](https://v8docs.nodesource.com/node-8.16/d5/d40/classv8_1_1_global.html) for further information. - - -### Nan::WeakCallbackInfo - -`Nan::WeakCallbackInfo` is used as an argument when setting a persistent reference as weak. You may need to free any external resources attached to the object. It is a mirror of `v8:WeakCallbackInfo` as found in newer versions of V8. - -Definition: - -```c++ -template class WeakCallbackInfo { - public: - typedef void (*Callback)(const WeakCallbackInfo& data); - - v8::Isolate *GetIsolate() const; - - /** - * Get the parameter that was associated with the weak handle. - */ - T *GetParameter() const; - - /** - * Get pointer from internal field, index can be 0 or 1. - */ - void *GetInternalField(int index) const; -}; -``` - -Example usage: - -```c++ -void weakCallback(const WeakCallbackInfo &data) { - int *parameter = data.GetParameter(); - delete parameter; -} - -Persistent obj; -int *data = new int(0); -obj.SetWeak(data, callback, WeakCallbackType::kParameter); -``` - -See the V8 documentation for [`WeakCallbackInfo`](https://v8docs.nodesource.com/node-8.16/d8/d06/classv8_1_1_weak_callback_info.html) for further information. - - -### Nan::WeakCallbackType - -Represents the type of a weak callback. -A weak callback of type `kParameter` makes the supplied parameter to `Nan::PersistentBase::SetWeak` available through `WeakCallbackInfo::GetParameter`. -A weak callback of type `kInternalFields` uses up to two internal fields at indices 0 and 1 on the `Nan::PersistentBase` being made weak. -Note that only `v8::Object`s and derivatives can have internal fields. - -Definition: - -```c++ -enum class WeakCallbackType { kParameter, kInternalFields }; -``` diff --git a/reverse_engineering/node_modules/nan/doc/scopes.md b/reverse_engineering/node_modules/nan/doc/scopes.md deleted file mode 100644 index 84000ee..0000000 --- a/reverse_engineering/node_modules/nan/doc/scopes.md +++ /dev/null @@ -1,73 +0,0 @@ -## Scopes - -A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. - -A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. - -The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. - - - Nan::HandleScope - - Nan::EscapableHandleScope - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection). - - -### Nan::HandleScope - -A simple wrapper around [`v8::HandleScope`](https://v8docs.nodesource.com/node-8.16/d3/d95/classv8_1_1_handle_scope.html). - -Definition: - -```c++ -class Nan::HandleScope { - public: - Nan::HandleScope(); - static int NumberOfHandles(); -}; -``` - -Allocate a new `Nan::HandleScope` whenever you are creating new V8 JavaScript objects. Note that an implicit `HandleScope` is created for you on JavaScript-accessible methods so you do not need to insert one yourself. - -Example: - -```c++ -// new object is created, it needs a new scope: -void Pointless() { - Nan::HandleScope scope; - v8::Local obj = Nan::New(); -} - -// JavaScript-accessible method already has a HandleScope -NAN_METHOD(Pointless2) { - v8::Local obj = Nan::New(); -} -``` - - -### Nan::EscapableHandleScope - -Similar to [`Nan::HandleScope`](#api_nan_handle_scope) but should be used in cases where a function needs to return a V8 JavaScript type that has been created within it. - -Definition: - -```c++ -class Nan::EscapableHandleScope { - public: - Nan::EscapableHandleScope(); - static int NumberOfHandles(); - template v8::Local Escape(v8::Local value); -} -``` - -Use `Escape(value)` to return the object. - -Example: - -```c++ -v8::Local EmptyObj() { - Nan::EscapableHandleScope scope; - v8::Local obj = Nan::New(); - return scope.Escape(obj); -} -``` - diff --git a/reverse_engineering/node_modules/nan/doc/script.md b/reverse_engineering/node_modules/nan/doc/script.md deleted file mode 100644 index 301c1b3..0000000 --- a/reverse_engineering/node_modules/nan/doc/script.md +++ /dev/null @@ -1,58 +0,0 @@ -## Script - -NAN provides `v8::Script` helpers as the API has changed over the supported versions of V8. - - - Nan::CompileScript() - - Nan::RunScript() - - Nan::ScriptOrigin - - - -### Nan::CompileScript() - -A wrapper around [`v8::ScriptCompiler::Compile()`](https://v8docs.nodesource.com/node-8.16/da/da5/classv8_1_1_script_compiler.html#a93f5072a0db55d881b969e9fc98e564b). - -Note that `Nan::BoundScript` is an alias for `v8::Script`. - -Signature: - -```c++ -Nan::MaybeLocal Nan::CompileScript( - v8::Local s, - const v8::ScriptOrigin& origin); -Nan::MaybeLocal Nan::CompileScript(v8::Local s); -``` - - - -### Nan::RunScript() - -Calls `script->Run()` or `script->BindToCurrentContext()->Run(Nan::GetCurrentContext())`. - -Note that `Nan::BoundScript` is an alias for `v8::Script` and `Nan::UnboundScript` is an alias for `v8::UnboundScript` where available and `v8::Script` on older versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::RunScript(v8::Local script) -Nan::MaybeLocal Nan::RunScript(v8::Local script) -``` - - -### Nan::ScriptOrigin - -A class transparently extending [`v8::ScriptOrigin`](https://v8docs.nodesource.com/node-16.0/db/d84/classv8_1_1_script_origin.html#pub-methods) -to provide backwards compatibility. Only the listed methods are guaranteed to -be available on all versions of Node. - -Declaration: - -```c++ -class Nan::ScriptOrigin : public v8::ScriptOrigin { - public: - ScriptOrigin(v8::Local name, v8::Local line = v8::Local(), v8::Local column = v8::Local()) - v8::Local ResourceName() const; - v8::Local ResourceLineOffset() const; - v8::Local ResourceColumnOffset() const; -} -``` diff --git a/reverse_engineering/node_modules/nan/doc/string_bytes.md b/reverse_engineering/node_modules/nan/doc/string_bytes.md deleted file mode 100644 index 7c1bd32..0000000 --- a/reverse_engineering/node_modules/nan/doc/string_bytes.md +++ /dev/null @@ -1,62 +0,0 @@ -## Strings & Bytes - -Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. - - - Nan::Encoding - - Nan::Encode() - - Nan::DecodeBytes() - - Nan::DecodeWrite() - - - -### Nan::Encoding - -An enum representing the supported encoding types. A copy of `node::encoding` that is consistent across versions of Node. - -Definition: - -```c++ -enum Nan::Encoding { ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER } -``` - - - -### Nan::Encode() - -A wrapper around `node::Encode()` that provides a consistent implementation across supported versions of Node. - -Signature: - -```c++ -v8::Local Nan::Encode(const void *buf, - size_t len, - enum Nan::Encoding encoding = BINARY); -``` - - - -### Nan::DecodeBytes() - -A wrapper around `node::DecodeBytes()` that provides a consistent implementation across supported versions of Node. - -Signature: - -```c++ -ssize_t Nan::DecodeBytes(v8::Local val, - enum Nan::Encoding encoding = BINARY); -``` - - - -### Nan::DecodeWrite() - -A wrapper around `node::DecodeWrite()` that provides a consistent implementation across supported versions of Node. - -Signature: - -```c++ -ssize_t Nan::DecodeWrite(char *buf, - size_t len, - v8::Local val, - enum Nan::Encoding encoding = BINARY); -``` diff --git a/reverse_engineering/node_modules/nan/doc/v8_internals.md b/reverse_engineering/node_modules/nan/doc/v8_internals.md deleted file mode 100644 index 08dd6d0..0000000 --- a/reverse_engineering/node_modules/nan/doc/v8_internals.md +++ /dev/null @@ -1,199 +0,0 @@ -## V8 internals - -The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. - - - NAN_GC_CALLBACK() - - Nan::AddGCEpilogueCallback() - - Nan::RemoveGCEpilogueCallback() - - Nan::AddGCPrologueCallback() - - Nan::RemoveGCPrologueCallback() - - Nan::GetHeapStatistics() - - Nan::SetCounterFunction() - - Nan::SetCreateHistogramFunction() - - Nan::SetAddHistogramSampleFunction() - - Nan::IdleNotification() - - Nan::LowMemoryNotification() - - Nan::ContextDisposedNotification() - - Nan::GetInternalFieldPointer() - - Nan::SetInternalFieldPointer() - - Nan::AdjustExternalMemory() - - - -### NAN_GC_CALLBACK(callbackname) - -Use `NAN_GC_CALLBACK` to declare your callbacks for `Nan::AddGCPrologueCallback()` and `Nan::AddGCEpilogueCallback()`. Your new method receives the arguments `v8::GCType type` and `v8::GCCallbackFlags flags`. - -```c++ -static Nan::Persistent callback; - -NAN_GC_CALLBACK(gcPrologueCallback) { - v8::Local argv[] = { Nan::New("prologue").ToLocalChecked() }; - Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(callback), 1, argv); -} - -NAN_METHOD(Hook) { - callback.Reset(To(args[0]).ToLocalChecked()); - Nan::AddGCPrologueCallback(gcPrologueCallback); - info.GetReturnValue().Set(info.Holder()); -} -``` - - -### Nan::AddGCEpilogueCallback() - -Signature: - -```c++ -void Nan::AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback, v8::GCType gc_type_filter = v8::kGCTypeAll) -``` - -Calls V8's [`AddGCEpilogueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a580f976e4290cead62c2fc4dd396be3e). - - -### Nan::RemoveGCEpilogueCallback() - -Signature: - -```c++ -void Nan::RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback) -``` - -Calls V8's [`RemoveGCEpilogueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#adca9294555a3908e9f23c7bb0f0f284c). - - -### Nan::AddGCPrologueCallback() - -Signature: - -```c++ -void Nan::AddGCPrologueCallback(v8::Isolate::GCPrologueCallback, v8::GCType gc_type_filter callback) -``` - -Calls V8's [`AddGCPrologueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a6dbef303603ebdb03da6998794ea05b8). - - -### Nan::RemoveGCPrologueCallback() - -Signature: - -```c++ -void Nan::RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback) -``` - -Calls V8's [`RemoveGCPrologueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a5f72c7cda21415ce062bbe5c58abe09e). - - -### Nan::GetHeapStatistics() - -Signature: - -```c++ -void Nan::GetHeapStatistics(v8::HeapStatistics *heap_statistics) -``` - -Calls V8's [`GetHeapStatistics()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a5593ac74687b713095c38987e5950b34). - - -### Nan::SetCounterFunction() - -Signature: - -```c++ -void Nan::SetCounterFunction(v8::CounterLookupCallback cb) -``` - -Calls V8's [`SetCounterFunction()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a045d7754e62fa0ec72ae6c259b29af94). - - -### Nan::SetCreateHistogramFunction() - -Signature: - -```c++ -void Nan::SetCreateHistogramFunction(v8::CreateHistogramCallback cb) -``` - -Calls V8's [`SetCreateHistogramFunction()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a542d67e85089cb3f92aadf032f99e732). - - -### Nan::SetAddHistogramSampleFunction() - -Signature: - -```c++ -void Nan::SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) -``` - -Calls V8's [`SetAddHistogramSampleFunction()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#aeb420b690bc2c216882d6fdd00ddd3ea). - - -### Nan::IdleNotification() - -Signature: - -```c++ -bool Nan::IdleNotification(int idle_time_in_ms) -``` - -Calls V8's [`IdleNotification()` or `IdleNotificationDeadline()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#ad6a2a02657f5425ad460060652a5a118) depending on V8 version. - - -### Nan::LowMemoryNotification() - -Signature: - -```c++ -void Nan::LowMemoryNotification() -``` - -Calls V8's [`LowMemoryNotification()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a24647f61d6b41f69668094bdcd6ea91f). - - -### Nan::ContextDisposedNotification() - -Signature: - -```c++ -void Nan::ContextDisposedNotification() -``` - -Calls V8's [`ContextDisposedNotification()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#ad7f5dc559866343fe6cd8db1f134d48b). - - -### Nan::GetInternalFieldPointer() - -Gets a pointer to the internal field with at `index` from a V8 `Object` handle. - -Signature: - -```c++ -void* Nan::GetInternalFieldPointer(v8::Local object, int index) -``` - -Calls the Object's [`GetAlignedPointerFromInternalField()` or `GetPointerFromInternalField()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a580ea84afb26c005d6762eeb9e3c308f) depending on the version of V8. - - -### Nan::SetInternalFieldPointer() - -Sets the value of the internal field at `index` on a V8 `Object` handle. - -Signature: - -```c++ -void Nan::SetInternalFieldPointer(v8::Local object, int index, void* value) -``` - -Calls the Object's [`SetAlignedPointerInInternalField()` or `SetPointerInInternalField()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab3c57184263cf29963ef0017bec82281) depending on the version of V8. - - -### Nan::AdjustExternalMemory() - -Signature: - -```c++ -int Nan::AdjustExternalMemory(int bytesChange) -``` - -Calls V8's [`AdjustAmountOfExternalAllocatedMemory()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#ae1a59cac60409d3922582c4af675473e). - diff --git a/reverse_engineering/node_modules/nan/doc/v8_misc.md b/reverse_engineering/node_modules/nan/doc/v8_misc.md deleted file mode 100644 index 1bd46d3..0000000 --- a/reverse_engineering/node_modules/nan/doc/v8_misc.md +++ /dev/null @@ -1,85 +0,0 @@ -## Miscellaneous V8 Helpers - - - Nan::Utf8String - - Nan::GetCurrentContext() - - Nan::SetIsolateData() - - Nan::GetIsolateData() - - Nan::TypedArrayContents - - - -### Nan::Utf8String - -Converts an object to a UTF-8-encoded character array. If conversion to a string fails (e.g. due to an exception in the toString() method of the object) then the length() method returns 0 and the * operator returns NULL. The underlying memory used for this object is managed by the object. - -An implementation of [`v8::String::Utf8Value`](https://v8docs.nodesource.com/node-8.16/d4/d1b/classv8_1_1_string_1_1_utf8_value.html) that is consistent across all supported versions of V8. - -Definition: - -```c++ -class Nan::Utf8String { - public: - Nan::Utf8String(v8::Local from); - - int length() const; - - char* operator*(); - const char* operator*() const; -}; -``` - - -### Nan::GetCurrentContext() - -A call to [`v8::Isolate::GetCurrent()->GetCurrentContext()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a81c7a1ed7001ae2a65e89107f75fd053) that works across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::GetCurrentContext() -``` - - -### Nan::SetIsolateData() - -A helper to provide a consistent API to [`v8::Isolate#SetData()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a7acadfe7965997e9c386a05f098fbe36). - -Signature: - -```c++ -void Nan::SetIsolateData(v8::Isolate *isolate, T *data) -``` - - - -### Nan::GetIsolateData() - -A helper to provide a consistent API to [`v8::Isolate#GetData()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#aabd223436bc1100a787dadaa024c6257). - -Signature: - -```c++ -T *Nan::GetIsolateData(v8::Isolate *isolate) -``` - - -### Nan::TypedArrayContents - -A helper class for accessing the contents of an ArrayBufferView (aka a typedarray) from C++. If the input array is not a valid typedarray, then the data pointer of TypedArrayContents will default to `NULL` and the length will be 0. If the data pointer is not compatible with the alignment requirements of type, an assertion error will fail. - -Note that you must store a reference to the `array` object while you are accessing its contents. - -Definition: - -```c++ -template -class Nan::TypedArrayContents { - public: - TypedArrayContents(v8::Local array); - - size_t length() const; - - T* const operator*(); - const T* const operator*() const; -}; -``` diff --git a/reverse_engineering/node_modules/nan/include_dirs.js b/reverse_engineering/node_modules/nan/include_dirs.js deleted file mode 100644 index 4f1dfb4..0000000 --- a/reverse_engineering/node_modules/nan/include_dirs.js +++ /dev/null @@ -1 +0,0 @@ -console.log(require('path').relative('.', __dirname)); diff --git a/reverse_engineering/node_modules/nan/nan.h b/reverse_engineering/node_modules/nan/nan.h deleted file mode 100644 index 6c8356c..0000000 --- a/reverse_engineering/node_modules/nan/nan.h +++ /dev/null @@ -1,2904 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors: - * - Rod Vagg - * - Benjamin Byholm - * - Trevor Norris - * - Nathan Rajlich - * - Brett Lawson - * - Ben Noordhuis - * - David Siegel - * - Michael Ira Krufky - * - * MIT License - * - * Version 2.15.0: current Node 16.6.1, Node 0.12: 0.12.18, Node 0.10: 0.10.48, iojs: 3.3.1 - * - * See https://github.com/nodejs/nan for the latest update to this file - **********************************************************************************/ - -#ifndef NAN_H_ -#define NAN_H_ - -#include - -#define NODE_0_10_MODULE_VERSION 11 -#define NODE_0_12_MODULE_VERSION 14 -#define ATOM_0_21_MODULE_VERSION 41 -#define IOJS_1_0_MODULE_VERSION 42 -#define IOJS_1_1_MODULE_VERSION 43 -#define IOJS_2_0_MODULE_VERSION 44 -#define IOJS_3_0_MODULE_VERSION 45 -#define NODE_4_0_MODULE_VERSION 46 -#define NODE_5_0_MODULE_VERSION 47 -#define NODE_6_0_MODULE_VERSION 48 -#define NODE_7_0_MODULE_VERSION 51 -#define NODE_8_0_MODULE_VERSION 57 -#define NODE_9_0_MODULE_VERSION 59 -#define NODE_10_0_MODULE_VERSION 64 -#define NODE_11_0_MODULE_VERSION 67 -#define NODE_12_0_MODULE_VERSION 72 -#define NODE_13_0_MODULE_VERSION 79 -#define NODE_14_0_MODULE_VERSION 83 -#define NODE_15_0_MODULE_VERSION 88 -#define NODE_16_0_MODULE_VERSION 93 - -#ifdef _MSC_VER -# define NAN_HAS_CPLUSPLUS_11 (_MSC_VER >= 1800) -#else -# define NAN_HAS_CPLUSPLUS_11 (__cplusplus >= 201103L) -#endif - -#if NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION && !NAN_HAS_CPLUSPLUS_11 -# error This version of node/NAN/v8 requires a C++11 compiler -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if defined(_MSC_VER) -# pragma warning( push ) -# pragma warning( disable : 4530 ) -# include -# include -# include -# pragma warning( pop ) -#else -# include -# include -# include -#endif - -// uv helpers -#ifdef UV_VERSION_MAJOR -# ifndef UV_VERSION_PATCH -# define UV_VERSION_PATCH 0 -# endif -# define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \ - (UV_VERSION_MINOR << 8) | \ - (UV_VERSION_PATCH)) -#else -# define NAUV_UVVERSION 0x000b00 -#endif - -#if NAUV_UVVERSION < 0x000b0b -# ifdef WIN32 -# include -# else -# include -# endif -#endif - -namespace Nan { - -#define NAN_CONCAT(a, b) NAN_CONCAT_HELPER(a, b) -#define NAN_CONCAT_HELPER(a, b) a##b - -#define NAN_INLINE inline // TODO(bnoordhuis) Remove in v3.0.0. - -#if defined(__GNUC__) && \ - !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) -# define NAN_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) && \ - !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) -# define NAN_DEPRECATED __declspec(deprecated) -#else -# define NAN_DEPRECATED -#endif - -#if NAN_HAS_CPLUSPLUS_11 -# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete; -# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete; -# define NAN_DISALLOW_MOVE(CLASS) \ - CLASS(CLASS&&) = delete; /* NOLINT(build/c++11) */ \ - void operator=(CLASS&&) = delete; -#else -# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&); -# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&); -# define NAN_DISALLOW_MOVE(CLASS) -#endif - -#define NAN_DISALLOW_ASSIGN_COPY(CLASS) \ - NAN_DISALLOW_ASSIGN(CLASS) \ - NAN_DISALLOW_COPY(CLASS) - -#define NAN_DISALLOW_ASSIGN_MOVE(CLASS) \ - NAN_DISALLOW_ASSIGN(CLASS) \ - NAN_DISALLOW_MOVE(CLASS) - -#define NAN_DISALLOW_COPY_MOVE(CLASS) \ - NAN_DISALLOW_COPY(CLASS) \ - NAN_DISALLOW_MOVE(CLASS) - -#define NAN_DISALLOW_ASSIGN_COPY_MOVE(CLASS) \ - NAN_DISALLOW_ASSIGN(CLASS) \ - NAN_DISALLOW_COPY(CLASS) \ - NAN_DISALLOW_MOVE(CLASS) - -#define TYPE_CHECK(T, S) \ - while (false) { \ - *(static_cast(0)) = static_cast(0); \ - } - -//=== RegistrationFunction ===================================================== - -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - typedef v8::Handle ADDON_REGISTER_FUNCTION_ARGS_TYPE; -#else - typedef v8::Local ADDON_REGISTER_FUNCTION_ARGS_TYPE; -#endif - -#define NAN_MODULE_INIT(name) \ - void name(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) - -#if NODE_MAJOR_VERSION >= 10 || \ - NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3 -#define NAN_MODULE_WORKER_ENABLED(module_name, registration) \ - extern "C" NODE_MODULE_EXPORT void \ - NAN_CONCAT(node_register_module_v, NODE_MODULE_VERSION)( \ - v8::Local exports, v8::Local module, \ - v8::Local context) \ - { \ - registration(exports); \ - } -#else -#define NAN_MODULE_WORKER_ENABLED(module_name, registration) \ - NODE_MODULE(module_name, registration) -#endif - -//=== CallbackInfo ============================================================= - -#include "nan_callbacks.h" // NOLINT(build/include) - -//============================================================================== - -#if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION) -typedef v8::Script UnboundScript; -typedef v8::Script BoundScript; -#else -typedef v8::UnboundScript UnboundScript; -typedef v8::Script BoundScript; -#endif - -#if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION) -typedef v8::String::ExternalAsciiStringResource - ExternalOneByteStringResource; -#else -typedef v8::String::ExternalOneByteStringResource - ExternalOneByteStringResource; -#endif - -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) -template -class NonCopyablePersistentTraits : - public v8::NonCopyablePersistentTraits {}; -template -class CopyablePersistentTraits : - public v8::CopyablePersistentTraits {}; - -template -class PersistentBase : - public v8::PersistentBase {}; - -template > -class Persistent; -#else -template class NonCopyablePersistentTraits; -template class PersistentBase; -template class WeakCallbackData; -template > -class Persistent; -#endif // NODE_MODULE_VERSION - -template -class Maybe { - public: - inline bool IsNothing() const { return !has_value_; } - inline bool IsJust() const { return has_value_; } - - inline T ToChecked() const { return FromJust(); } - inline void Check() const { FromJust(); } - - inline bool To(T* out) const { - if (IsJust()) *out = value_; - return IsJust(); - } - - inline T FromJust() const { -#if defined(V8_ENABLE_CHECKS) - assert(IsJust() && "FromJust is Nothing"); -#endif // V8_ENABLE_CHECKS - return value_; - } - - inline T FromMaybe(const T& default_value) const { - return has_value_ ? value_ : default_value; - } - - inline bool operator==(const Maybe &other) const { - return (IsJust() == other.IsJust()) && - (!IsJust() || FromJust() == other.FromJust()); - } - - inline bool operator!=(const Maybe &other) const { - return !operator==(other); - } - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - // Allow implicit conversions from v8::Maybe to Nan::Maybe. - Maybe(const v8::Maybe& that) // NOLINT(runtime/explicit) - : has_value_(that.IsJust()) - , value_(that.FromMaybe(T())) {} -#endif - - private: - Maybe() : has_value_(false) {} - explicit Maybe(const T& t) : has_value_(true), value_(t) {} - bool has_value_; - T value_; - - template - friend Maybe Nothing(); - template - friend Maybe Just(const U& u); -}; - -template -inline Maybe Nothing() { - return Maybe(); -} - -template -inline Maybe Just(const T& t) { - return Maybe(t); -} - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -# include "nan_maybe_43_inl.h" // NOLINT(build/include) -#else -# include "nan_maybe_pre_43_inl.h" // NOLINT(build/include) -#endif - -#include "nan_converters.h" // NOLINT(build/include) -#include "nan_new.h" // NOLINT(build/include) - -#if NAUV_UVVERSION < 0x000b17 -#define NAUV_WORK_CB(func) \ - void func(uv_async_t *async, int) -#else -#define NAUV_WORK_CB(func) \ - void func(uv_async_t *async) -#endif - -#if NAUV_UVVERSION >= 0x000b0b - -typedef uv_key_t nauv_key_t; - -inline int nauv_key_create(nauv_key_t *key) { - return uv_key_create(key); -} - -inline void nauv_key_delete(nauv_key_t *key) { - uv_key_delete(key); -} - -inline void* nauv_key_get(nauv_key_t *key) { - return uv_key_get(key); -} - -inline void nauv_key_set(nauv_key_t *key, void *value) { - uv_key_set(key, value); -} - -#else - -/* Implement thread local storage for older versions of libuv. - * This is essentially a backport of libuv commit 5d2434bf - * written by Ben Noordhuis, adjusted for names and inline. - */ - -#ifndef WIN32 - -typedef pthread_key_t nauv_key_t; - -inline int nauv_key_create(nauv_key_t* key) { - return -pthread_key_create(key, NULL); -} - -inline void nauv_key_delete(nauv_key_t* key) { - if (pthread_key_delete(*key)) - abort(); -} - -inline void* nauv_key_get(nauv_key_t* key) { - return pthread_getspecific(*key); -} - -inline void nauv_key_set(nauv_key_t* key, void* value) { - if (pthread_setspecific(*key, value)) - abort(); -} - -#else - -typedef struct { - DWORD tls_index; -} nauv_key_t; - -inline int nauv_key_create(nauv_key_t* key) { - key->tls_index = TlsAlloc(); - if (key->tls_index == TLS_OUT_OF_INDEXES) - return UV_ENOMEM; - return 0; -} - -inline void nauv_key_delete(nauv_key_t* key) { - if (TlsFree(key->tls_index) == FALSE) - abort(); - key->tls_index = TLS_OUT_OF_INDEXES; -} - -inline void* nauv_key_get(nauv_key_t* key) { - void* value = TlsGetValue(key->tls_index); - if (value == NULL) - if (GetLastError() != ERROR_SUCCESS) - abort(); - return value; -} - -inline void nauv_key_set(nauv_key_t* key, void* value) { - if (TlsSetValue(key->tls_index, value) == FALSE) - abort(); -} - -#endif -#endif - -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION -template -v8::Local New(v8::Handle); -#endif - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - typedef v8::WeakCallbackType WeakCallbackType; -#else -struct WeakCallbackType { - enum E {kParameter, kInternalFields}; - E type; - WeakCallbackType(E other) : type(other) {} // NOLINT(runtime/explicit) - inline bool operator==(E other) { return other == this->type; } - inline bool operator!=(E other) { return !operator==(other); } -}; -#endif - -template class WeakCallbackInfo; - -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION -# include "nan_persistent_12_inl.h" // NOLINT(build/include) -#else -# include "nan_persistent_pre_12_inl.h" // NOLINT(build/include) -#endif - -namespace imp { - static const size_t kMaxLength = 0x3fffffff; - // v8::String::REPLACE_INVALID_UTF8 was introduced - // in node.js v0.10.29 and v0.8.27. -#if NODE_MAJOR_VERSION > 0 || \ - NODE_MINOR_VERSION > 10 || \ - NODE_MINOR_VERSION == 10 && NODE_PATCH_VERSION >= 29 || \ - NODE_MINOR_VERSION == 8 && NODE_PATCH_VERSION >= 27 - static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8; -#else - static const unsigned kReplaceInvalidUtf8 = 0; -#endif -} // end of namespace imp - -//=== HandleScope ============================================================== - -class HandleScope { - v8::HandleScope scope; - - public: -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - inline HandleScope() : scope(v8::Isolate::GetCurrent()) {} - inline static int NumberOfHandles() { - return v8::HandleScope::NumberOfHandles(v8::Isolate::GetCurrent()); - } -#else - inline HandleScope() : scope() {} - inline static int NumberOfHandles() { - return v8::HandleScope::NumberOfHandles(); - } -#endif - - private: - // Make it hard to create heap-allocated or illegal handle scopes by - // disallowing certain operations. - HandleScope(const HandleScope &); - void operator=(const HandleScope &); - void *operator new(size_t size); - void operator delete(void *, size_t) { - abort(); - } -}; - -class EscapableHandleScope { - public: -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - inline EscapableHandleScope() : scope(v8::Isolate::GetCurrent()) {} - - inline static int NumberOfHandles() { - return v8::EscapableHandleScope::NumberOfHandles(v8::Isolate::GetCurrent()); - } - - template - inline v8::Local Escape(v8::Local value) { - return scope.Escape(value); - } - - private: - v8::EscapableHandleScope scope; -#else - inline EscapableHandleScope() : scope() {} - - inline static int NumberOfHandles() { - return v8::HandleScope::NumberOfHandles(); - } - - template - inline v8::Local Escape(v8::Local value) { - return scope.Close(value); - } - - private: - v8::HandleScope scope; -#endif - - private: - // Make it hard to create heap-allocated or illegal handle scopes by - // disallowing certain operations. - EscapableHandleScope(const EscapableHandleScope &); - void operator=(const EscapableHandleScope &); - void *operator new(size_t size); - void operator delete(void *, size_t) { - abort(); - } -}; - -//=== TryCatch ================================================================= - -class TryCatch { - v8::TryCatch try_catch_; - friend void FatalException(const TryCatch&); - - public: -#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION - TryCatch() : try_catch_(v8::Isolate::GetCurrent()) {} -#endif - - inline bool HasCaught() const { return try_catch_.HasCaught(); } - - inline bool CanContinue() const { return try_catch_.CanContinue(); } - - inline v8::Local ReThrow() { -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - return New(try_catch_.ReThrow()); -#else - return try_catch_.ReThrow(); -#endif - } - - inline v8::Local Exception() const { - return try_catch_.Exception(); - } - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - inline v8::MaybeLocal StackTrace() const { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(try_catch_.StackTrace(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); - } -#else - inline MaybeLocal StackTrace() const { - return try_catch_.StackTrace(); - } -#endif - - inline v8::Local Message() const { - return try_catch_.Message(); - } - - inline void Reset() { try_catch_.Reset(); } - - inline void SetVerbose(bool value) { try_catch_.SetVerbose(value); } - - inline void SetCaptureMessage(bool value) { - try_catch_.SetCaptureMessage(value); - } -}; - -v8::Local MakeCallback(v8::Local target, - v8::Local func, - int argc, - v8::Local* argv); -v8::Local MakeCallback(v8::Local target, - v8::Local symbol, - int argc, - v8::Local* argv); -v8::Local MakeCallback(v8::Local target, - const char* method, - int argc, - v8::Local* argv); - -// === AsyncResource =========================================================== - -class AsyncResource { - public: - AsyncResource( - v8::Local name - , v8::Local resource = New()) { -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - - if (resource.IsEmpty()) { - resource = New(); - } - - context = node::EmitAsyncInit(isolate, resource, name); -#endif - } - - AsyncResource( - const char* name - , v8::Local resource = New()) { -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - - if (resource.IsEmpty()) { - resource = New(); - } - - v8::Local name_string = - New(name).ToLocalChecked(); - context = node::EmitAsyncInit(isolate, resource, name_string); -#endif - } - - ~AsyncResource() { -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - node::EmitAsyncDestroy(isolate, context); -#endif - } - - inline MaybeLocal runInAsyncScope( - v8::Local target - , v8::Local func - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION - return MakeCallback(target, func, argc, argv); -#else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, func, argc, argv, context); -#endif - } - - inline MaybeLocal runInAsyncScope( - v8::Local target - , v8::Local symbol - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION - return MakeCallback(target, symbol, argc, argv); -#else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, symbol, argc, argv, context); -#endif - } - - inline MaybeLocal runInAsyncScope( - v8::Local target - , const char* method - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION - return MakeCallback(target, method, argc, argv); -#else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, method, argc, argv, context); -#endif - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncResource) -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - node::async_context context; -#endif -}; - -inline uv_loop_t* GetCurrentEventLoop() { -#if NODE_MAJOR_VERSION >= 10 || \ - NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3 || \ - NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION >= 10 - return node::GetCurrentEventLoop(v8::Isolate::GetCurrent()); -#else - return uv_default_loop(); -#endif -} - -//============ ================================================================= - -/* node 0.12 */ -#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION - inline - void SetCounterFunction(v8::CounterLookupCallback cb) { - v8::Isolate::GetCurrent()->SetCounterFunction(cb); - } - - inline - void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) { - v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb); - } - - inline - void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { - v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb); - } - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - inline bool IdleNotification(int idle_time_in_ms) { - return v8::Isolate::GetCurrent()->IdleNotificationDeadline( - idle_time_in_ms * 0.001); - } -# else - inline bool IdleNotification(int idle_time_in_ms) { - return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms); - } -#endif - - inline void LowMemoryNotification() { - v8::Isolate::GetCurrent()->LowMemoryNotification(); - } - - inline void ContextDisposedNotification() { - v8::Isolate::GetCurrent()->ContextDisposedNotification(); - } -#else - inline - void SetCounterFunction(v8::CounterLookupCallback cb) { - v8::V8::SetCounterFunction(cb); - } - - inline - void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) { - v8::V8::SetCreateHistogramFunction(cb); - } - - inline - void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { - v8::V8::SetAddHistogramSampleFunction(cb); - } - - inline bool IdleNotification(int idle_time_in_ms) { - return v8::V8::IdleNotification(idle_time_in_ms); - } - - inline void LowMemoryNotification() { - v8::V8::LowMemoryNotification(); - } - - inline void ContextDisposedNotification() { - v8::V8::ContextDisposedNotification(); - } -#endif - -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) // Node 0.12 - inline v8::Local Undefined() { -# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(v8::Undefined(v8::Isolate::GetCurrent()))); -# else - return v8::Undefined(v8::Isolate::GetCurrent()); -# endif - } - - inline v8::Local Null() { -# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(v8::Null(v8::Isolate::GetCurrent()))); -# else - return v8::Null(v8::Isolate::GetCurrent()); -# endif - } - - inline v8::Local True() { -# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(v8::True(v8::Isolate::GetCurrent()))); -# else - return v8::True(v8::Isolate::GetCurrent()); -# endif - } - - inline v8::Local False() { -# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(v8::False(v8::Isolate::GetCurrent()))); -# else - return v8::False(v8::Isolate::GetCurrent()); -# endif - } - - inline v8::Local EmptyString() { - return v8::String::Empty(v8::Isolate::GetCurrent()); - } - - inline int AdjustExternalMemory(int bc) { - return static_cast( - v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc)); - } - - inline void SetTemplate( - v8::Local templ - , const char *name - , v8::Local value) { - templ->Set(v8::Isolate::GetCurrent(), name, value); - } - - inline void SetTemplate( - v8::Local templ - , v8::Local name - , v8::Local value - , v8::PropertyAttribute attributes) { - templ->Set(name, value, attributes); - } - - inline v8::Local GetCurrentContext() { - return v8::Isolate::GetCurrent()->GetCurrentContext(); - } - - inline void* GetInternalFieldPointer( - v8::Local object - , int index) { - return object->GetAlignedPointerFromInternalField(index); - } - - inline void SetInternalFieldPointer( - v8::Local object - , int index - , void* value) { - object->SetAlignedPointerInInternalField(index, value); - } - -# define NAN_GC_CALLBACK(name) \ - void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags) - -#if NODE_MODULE_VERSION <= NODE_4_0_MODULE_VERSION - typedef v8::Isolate::GCEpilogueCallback GCEpilogueCallback; - typedef v8::Isolate::GCPrologueCallback GCPrologueCallback; -#else - typedef v8::Isolate::GCCallback GCEpilogueCallback; - typedef v8::Isolate::GCCallback GCPrologueCallback; -#endif - - inline void AddGCEpilogueCallback( - GCEpilogueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter); - } - - inline void RemoveGCEpilogueCallback( - GCEpilogueCallback callback) { - v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback); - } - - inline void AddGCPrologueCallback( - GCPrologueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter); - } - - inline void RemoveGCPrologueCallback( - GCPrologueCallback callback) { - v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback); - } - - inline void GetHeapStatistics( - v8::HeapStatistics *heap_statistics) { - v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics); - } - -# define X(NAME) \ - inline v8::Local NAME(const char *msg) { \ - EscapableHandleScope scope; \ - return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \ - } \ - \ - inline \ - v8::Local NAME(v8::Local msg) { \ - return v8::Exception::NAME(msg); \ - } \ - \ - inline void Throw ## NAME(const char *msg) { \ - HandleScope scope; \ - v8::Isolate::GetCurrent()->ThrowException( \ - v8::Exception::NAME(New(msg).ToLocalChecked())); \ - } \ - \ - inline void Throw ## NAME(v8::Local msg) { \ - HandleScope scope; \ - v8::Isolate::GetCurrent()->ThrowException( \ - v8::Exception::NAME(msg)); \ - } - - X(Error) - X(RangeError) - X(ReferenceError) - X(SyntaxError) - X(TypeError) - -# undef X - - inline void ThrowError(v8::Local error) { - v8::Isolate::GetCurrent()->ThrowException(error); - } - - inline MaybeLocal NewBuffer( - char *data - , size_t length -#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION - , node::Buffer::FreeCallback callback -#else - , node::smalloc::FreeCallback callback -#endif - , void *hint - ) { - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(length <= imp::kMaxLength && "too large buffer"); -#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION - return node::Buffer::New( - v8::Isolate::GetCurrent(), data, length, callback, hint); -#else - return node::Buffer::New(v8::Isolate::GetCurrent(), data, length, callback, - hint); -#endif - } - - inline MaybeLocal CopyBuffer( - const char *data - , uint32_t size - ) { - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(size <= imp::kMaxLength && "too large buffer"); -#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION - return node::Buffer::Copy( - v8::Isolate::GetCurrent(), data, size); -#else - return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); -#endif - } - - inline MaybeLocal NewBuffer(uint32_t size) { - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(size <= imp::kMaxLength && "too large buffer"); -#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION - return node::Buffer::New( - v8::Isolate::GetCurrent(), size); -#else - return node::Buffer::New(v8::Isolate::GetCurrent(), size); -#endif - } - - inline MaybeLocal NewBuffer( - char* data - , uint32_t size - ) { - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(size <= imp::kMaxLength && "too large buffer"); -#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION - return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); -#else - return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); -#endif - } - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - inline MaybeLocal - NewOneByteString(const uint8_t * value, int length = -1) { - return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, - v8::NewStringType::kNormal, length); - } - - inline MaybeLocal CompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::ScriptCompiler::Source source(s, origin); - return scope.Escape( - v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source) - .FromMaybe(v8::Local())); - } - - inline MaybeLocal CompileScript( - v8::Local s - ) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::ScriptCompiler::Source source(s); - return scope.Escape( - v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source) - .FromMaybe(v8::Local())); - } - - inline MaybeLocal RunScript( - v8::Local script - ) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(script->BindToCurrentContext() - ->Run(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); - } - - inline MaybeLocal RunScript( - v8::Local script - ) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(script->Run(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); - } -#else - inline MaybeLocal - NewOneByteString(const uint8_t * value, int length = -1) { - return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); - } - - inline MaybeLocal CompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - v8::ScriptCompiler::Source source(s, origin); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); - } - - inline MaybeLocal CompileScript( - v8::Local s - ) { - v8::ScriptCompiler::Source source(s); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); - } - - inline MaybeLocal RunScript( - v8::Local script - ) { - EscapableHandleScope scope; - return scope.Escape(script->BindToCurrentContext()->Run()); - } - - inline MaybeLocal RunScript( - v8::Local script - ) { - return script->Run(); - } -#endif - - NAN_DEPRECATED inline v8::Local MakeCallback( - v8::Local target - , v8::Local func - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(node::MakeCallback( - v8::Isolate::GetCurrent(), target, func, argc, argv))); -#else -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource res("nan:makeCallback"); - return res.runInAsyncScope(target, func, argc, argv) - .FromMaybe(v8::Local()); -# else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, func, argc, argv); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - } - - NAN_DEPRECATED inline v8::Local MakeCallback( - v8::Local target - , v8::Local symbol - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(node::MakeCallback( - v8::Isolate::GetCurrent(), target, symbol, argc, argv))); -#else -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource res("nan:makeCallback"); - return res.runInAsyncScope(target, symbol, argc, argv) - .FromMaybe(v8::Local()); -# else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, symbol, argc, argv); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - } - - NAN_DEPRECATED inline v8::Local MakeCallback( - v8::Local target - , const char* method - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(node::MakeCallback( - v8::Isolate::GetCurrent(), target, method, argc, argv))); -#else -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource res("nan:makeCallback"); - return res.runInAsyncScope(target, method, argc, argv) - .FromMaybe(v8::Local()); -# else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, method, argc, argv); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - } - - inline void FatalException(const TryCatch& try_catch) { - node::FatalException(v8::Isolate::GetCurrent(), try_catch.try_catch_); - } - - inline v8::Local ErrnoException( - int errorno - , const char* syscall = NULL - , const char* message = NULL - , const char* path = NULL) { - return node::ErrnoException(v8::Isolate::GetCurrent(), errorno, syscall, - message, path); - } - - NAN_DEPRECATED inline v8::Local NanErrnoException( - int errorno - , const char* syscall = NULL - , const char* message = NULL - , const char* path = NULL) { - return ErrnoException(errorno, syscall, message, path); - } - - template - inline void SetIsolateData( - v8::Isolate *isolate - , T *data - ) { - isolate->SetData(0, data); - } - - template - inline T *GetIsolateData( - v8::Isolate *isolate - ) { - return static_cast(isolate->GetData(0)); - } - -class Utf8String { - public: - inline explicit Utf8String(v8::Local from) : - length_(0), str_(str_st_) { - HandleScope scope; - if (!from.IsEmpty()) { -#if NODE_MAJOR_VERSION >= 10 - v8::Local context = GetCurrentContext(); - v8::Local string = - from->ToString(context).FromMaybe(v8::Local()); -#else - v8::Local string = from->ToString(); -#endif - if (!string.IsEmpty()) { - size_t len = 3 * string->Length() + 1; - assert(len <= INT_MAX); - if (len > sizeof (str_st_)) { - str_ = static_cast(malloc(len)); - assert(str_ != 0); - } - const int flags = - v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8; -#if NODE_MAJOR_VERSION >= 11 - length_ = string->WriteUtf8(v8::Isolate::GetCurrent(), str_, - static_cast(len), 0, flags); -#else - // See https://github.com/nodejs/nan/issues/832. - // Disable the warning as there is no way around it. -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4996) -#endif -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - length_ = string->WriteUtf8(str_, static_cast(len), 0, flags); -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif -#ifdef _MSC_VER -#pragma warning(pop) -#endif -#endif // NODE_MAJOR_VERSION < 11 - str_[length_] = '\0'; - } - } - } - - inline int length() const { - return length_; - } - - inline char* operator*() { return str_; } - inline const char* operator*() const { return str_; } - - inline ~Utf8String() { - if (str_ != str_st_) { - free(str_); - } - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String) - - int length_; - char *str_; - char str_st_[1024]; -}; - -#else // Node 0.8 and 0.10 - inline v8::Local Undefined() { - EscapableHandleScope scope; - return scope.Escape(New(v8::Undefined())); - } - - inline v8::Local Null() { - EscapableHandleScope scope; - return scope.Escape(New(v8::Null())); - } - - inline v8::Local True() { - EscapableHandleScope scope; - return scope.Escape(New(v8::True())); - } - - inline v8::Local False() { - EscapableHandleScope scope; - return scope.Escape(New(v8::False())); - } - - inline v8::Local EmptyString() { - return v8::String::Empty(); - } - - inline int AdjustExternalMemory(int bc) { - return static_cast(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc)); - } - - inline void SetTemplate( - v8::Local templ - , const char *name - , v8::Local value) { - templ->Set(name, value); - } - - inline void SetTemplate( - v8::Local templ - , v8::Local name - , v8::Local value - , v8::PropertyAttribute attributes) { - templ->Set(name, value, attributes); - } - - inline v8::Local GetCurrentContext() { - return v8::Context::GetCurrent(); - } - - inline void* GetInternalFieldPointer( - v8::Local object - , int index) { - return object->GetPointerFromInternalField(index); - } - - inline void SetInternalFieldPointer( - v8::Local object - , int index - , void* value) { - object->SetPointerInInternalField(index, value); - } - -# define NAN_GC_CALLBACK(name) \ - void name(v8::GCType type, v8::GCCallbackFlags flags) - - inline void AddGCEpilogueCallback( - v8::GCEpilogueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::V8::AddGCEpilogueCallback(callback, gc_type_filter); - } - inline void RemoveGCEpilogueCallback( - v8::GCEpilogueCallback callback) { - v8::V8::RemoveGCEpilogueCallback(callback); - } - inline void AddGCPrologueCallback( - v8::GCPrologueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::V8::AddGCPrologueCallback(callback, gc_type_filter); - } - inline void RemoveGCPrologueCallback( - v8::GCPrologueCallback callback) { - v8::V8::RemoveGCPrologueCallback(callback); - } - inline void GetHeapStatistics( - v8::HeapStatistics *heap_statistics) { - v8::V8::GetHeapStatistics(heap_statistics); - } - -# define X(NAME) \ - inline v8::Local NAME(const char *msg) { \ - EscapableHandleScope scope; \ - return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \ - } \ - \ - inline \ - v8::Local NAME(v8::Local msg) { \ - return v8::Exception::NAME(msg); \ - } \ - \ - inline void Throw ## NAME(const char *msg) { \ - HandleScope scope; \ - v8::ThrowException(v8::Exception::NAME(New(msg).ToLocalChecked())); \ - } \ - \ - inline \ - void Throw ## NAME(v8::Local errmsg) { \ - HandleScope scope; \ - v8::ThrowException(v8::Exception::NAME(errmsg)); \ - } - - X(Error) - X(RangeError) - X(ReferenceError) - X(SyntaxError) - X(TypeError) - -# undef X - - inline void ThrowError(v8::Local error) { - v8::ThrowException(error); - } - - inline MaybeLocal NewBuffer( - char *data - , size_t length - , node::Buffer::free_callback callback - , void *hint - ) { - EscapableHandleScope scope; - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(length <= imp::kMaxLength && "too large buffer"); - return scope.Escape( - New(node::Buffer::New(data, length, callback, hint)->handle_)); - } - - inline MaybeLocal CopyBuffer( - const char *data - , uint32_t size - ) { - EscapableHandleScope scope; - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(size <= imp::kMaxLength && "too large buffer"); -#if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION - return scope.Escape(New(node::Buffer::New(data, size)->handle_)); -#else - return scope.Escape( - New(node::Buffer::New(const_cast(data), size)->handle_)); -#endif - } - - inline MaybeLocal NewBuffer(uint32_t size) { - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - assert(size <= imp::kMaxLength && "too large buffer"); - return scope.Escape(New(node::Buffer::New(size)->handle_)); - } - - inline void FreeData(char *data, void *hint) { - (void) hint; // unused - delete[] data; - } - - inline MaybeLocal NewBuffer( - char* data - , uint32_t size - ) { - EscapableHandleScope scope; - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(size <= imp::kMaxLength && "too large buffer"); - return scope.Escape( - New(node::Buffer::New(data, size, FreeData, NULL)->handle_)); - } - -namespace imp { -inline void -widenString(std::vector *ws, const uint8_t *s, int l) { - size_t len = static_cast(l); - if (l < 0) { - len = strlen(reinterpret_cast(s)); - } - assert(len <= INT_MAX && "string too long"); - ws->resize(len); - std::copy(s, s + len, ws->begin()); // NOLINT(build/include_what_you_use) -} -} // end of namespace imp - - inline MaybeLocal - NewOneByteString(const uint8_t * value, int length = -1) { - std::vector wideString; // NOLINT(build/include_what_you_use) - imp::widenString(&wideString, value, length); - return v8::String::New(wideString.data(), - static_cast(wideString.size())); - } - - inline MaybeLocal CompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - return v8::Script::Compile(s, const_cast(&origin)); - } - - inline MaybeLocal CompileScript( - v8::Local s - ) { - return v8::Script::Compile(s); - } - - inline - MaybeLocal RunScript(v8::Local script) { - return script->Run(); - } - - inline v8::Local MakeCallback( - v8::Local target - , v8::Local func - , int argc - , v8::Local* argv) { - v8::HandleScope scope; - return scope.Close(New(node::MakeCallback(target, func, argc, argv))); - } - - inline v8::Local MakeCallback( - v8::Local target - , v8::Local symbol - , int argc - , v8::Local* argv) { - v8::HandleScope scope; - return scope.Close(New(node::MakeCallback(target, symbol, argc, argv))); - } - - inline v8::Local MakeCallback( - v8::Local target - , const char* method - , int argc - , v8::Local* argv) { - v8::HandleScope scope; - return scope.Close(New(node::MakeCallback(target, method, argc, argv))); - } - - inline void FatalException(const TryCatch& try_catch) { - node::FatalException(const_cast(try_catch.try_catch_)); - } - - inline v8::Local ErrnoException( - int errorno - , const char* syscall = NULL - , const char* message = NULL - , const char* path = NULL) { - return node::ErrnoException(errorno, syscall, message, path); - } - - NAN_DEPRECATED inline v8::Local NanErrnoException( - int errorno - , const char* syscall = NULL - , const char* message = NULL - , const char* path = NULL) { - return ErrnoException(errorno, syscall, message, path); - } - - - template - inline void SetIsolateData( - v8::Isolate *isolate - , T *data - ) { - isolate->SetData(data); - } - - template - inline T *GetIsolateData( - v8::Isolate *isolate - ) { - return static_cast(isolate->GetData()); - } - -class Utf8String { - public: - inline explicit Utf8String(v8::Local from) : - length_(0), str_(str_st_) { - v8::HandleScope scope; - if (!from.IsEmpty()) { - v8::Local string = from->ToString(); - if (!string.IsEmpty()) { - size_t len = 3 * string->Length() + 1; - assert(len <= INT_MAX); - if (len > sizeof (str_st_)) { - str_ = static_cast(malloc(len)); - assert(str_ != 0); - } - const int flags = - v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8; - length_ = string->WriteUtf8(str_, static_cast(len), 0, flags); - str_[length_] = '\0'; - } - } - } - - inline int length() const { - return length_; - } - - inline char* operator*() { return str_; } - inline const char* operator*() const { return str_; } - - inline ~Utf8String() { - if (str_ != str_st_) { - free(str_); - } - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String) - - int length_; - char *str_; - char str_st_[1024]; -}; - -#endif // NODE_MODULE_VERSION - -typedef void (*FreeCallback)(char *data, void *hint); - -typedef const FunctionCallbackInfo& NAN_METHOD_ARGS_TYPE; -typedef void NAN_METHOD_RETURN_TYPE; - -typedef const PropertyCallbackInfo& NAN_GETTER_ARGS_TYPE; -typedef void NAN_GETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& NAN_SETTER_ARGS_TYPE; -typedef void NAN_SETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_PROPERTY_GETTER_ARGS_TYPE; -typedef void NAN_PROPERTY_GETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_PROPERTY_SETTER_ARGS_TYPE; -typedef void NAN_PROPERTY_SETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_PROPERTY_ENUMERATOR_ARGS_TYPE; -typedef void NAN_PROPERTY_ENUMERATOR_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_PROPERTY_DELETER_ARGS_TYPE; -typedef void NAN_PROPERTY_DELETER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_PROPERTY_QUERY_ARGS_TYPE; -typedef void NAN_PROPERTY_QUERY_RETURN_TYPE; - -typedef const PropertyCallbackInfo& NAN_INDEX_GETTER_ARGS_TYPE; -typedef void NAN_INDEX_GETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& NAN_INDEX_SETTER_ARGS_TYPE; -typedef void NAN_INDEX_SETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_INDEX_ENUMERATOR_ARGS_TYPE; -typedef void NAN_INDEX_ENUMERATOR_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_INDEX_DELETER_ARGS_TYPE; -typedef void NAN_INDEX_DELETER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_INDEX_QUERY_ARGS_TYPE; -typedef void NAN_INDEX_QUERY_RETURN_TYPE; - -#define NAN_METHOD(name) \ - Nan::NAN_METHOD_RETURN_TYPE name(Nan::NAN_METHOD_ARGS_TYPE info) -#define NAN_GETTER(name) \ - Nan::NAN_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , Nan::NAN_GETTER_ARGS_TYPE info) -#define NAN_SETTER(name) \ - Nan::NAN_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , Nan::NAN_SETTER_ARGS_TYPE info) -#define NAN_PROPERTY_GETTER(name) \ - Nan::NAN_PROPERTY_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info) -#define NAN_PROPERTY_SETTER(name) \ - Nan::NAN_PROPERTY_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info) -#define NAN_PROPERTY_ENUMERATOR(name) \ - Nan::NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name( \ - Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info) -#define NAN_PROPERTY_DELETER(name) \ - Nan::NAN_PROPERTY_DELETER_RETURN_TYPE name( \ - v8::Local property \ - , Nan::NAN_PROPERTY_DELETER_ARGS_TYPE info) -#define NAN_PROPERTY_QUERY(name) \ - Nan::NAN_PROPERTY_QUERY_RETURN_TYPE name( \ - v8::Local property \ - , Nan::NAN_PROPERTY_QUERY_ARGS_TYPE info) -# define NAN_INDEX_GETTER(name) \ - Nan::NAN_INDEX_GETTER_RETURN_TYPE name( \ - uint32_t index \ - , Nan::NAN_INDEX_GETTER_ARGS_TYPE info) -#define NAN_INDEX_SETTER(name) \ - Nan::NAN_INDEX_SETTER_RETURN_TYPE name( \ - uint32_t index \ - , v8::Local value \ - , Nan::NAN_INDEX_SETTER_ARGS_TYPE info) -#define NAN_INDEX_ENUMERATOR(name) \ - Nan::NAN_INDEX_ENUMERATOR_RETURN_TYPE \ - name(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info) -#define NAN_INDEX_DELETER(name) \ - Nan::NAN_INDEX_DELETER_RETURN_TYPE name( \ - uint32_t index \ - , Nan::NAN_INDEX_DELETER_ARGS_TYPE info) -#define NAN_INDEX_QUERY(name) \ - Nan::NAN_INDEX_QUERY_RETURN_TYPE name( \ - uint32_t index \ - , Nan::NAN_INDEX_QUERY_ARGS_TYPE info) - -class Callback { - public: - Callback() {} - - explicit Callback(const v8::Local &fn) : handle_(fn) {} - - ~Callback() { - handle_.Reset(); - } - - bool operator==(const Callback &other) const { - return handle_ == other.handle_; - } - - bool operator!=(const Callback &other) const { - return !operator==(other); - } - - inline - v8::Local operator*() const { return GetFunction(); } - - NAN_DEPRECATED inline v8::Local operator()( - v8::Local target - , int argc = 0 - , v8::Local argv[] = 0) const { -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource async("nan:Callback:operator()"); - return Call_(isolate, target, argc, argv, &async) - .FromMaybe(v8::Local()); -# else - return Call_(isolate, target, argc, argv); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#else - return Call_(target, argc, argv); -#endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - } - - NAN_DEPRECATED inline v8::Local operator()( - int argc = 0 - , v8::Local argv[] = 0) const { -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource async("nan:Callback:operator()"); - return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(), - argc, argv, &async) - .FromMaybe(v8::Local())); -# else - return scope.Escape( - Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#else - v8::HandleScope scope; - return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); -#endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - } - - inline MaybeLocal operator()( - AsyncResource* resource - , int argc = 0 - , v8::Local argv[] = 0) const { - return this->Call(argc, argv, resource); - } - - inline MaybeLocal operator()( - AsyncResource* resource - , v8::Local target - , int argc = 0 - , v8::Local argv[] = 0) const { - return this->Call(target, argc, argv, resource); - } - - // TODO(kkoopa): remove - inline void SetFunction(const v8::Local &fn) { - Reset(fn); - } - - inline void Reset(const v8::Local &fn) { - handle_.Reset(fn); - } - - inline void Reset() { - handle_.Reset(); - } - - inline v8::Local GetFunction() const { - return New(handle_); - } - - inline bool IsEmpty() const { - return handle_.IsEmpty(); - } - - // Deprecated: For async callbacks Use the versions that accept an - // AsyncResource. If this callback does not correspond to an async resource, - // that is, it is a synchronous function call on a non-empty JS stack, you - // should Nan::Call instead. - NAN_DEPRECATED inline v8::Local - Call(v8::Local target - , int argc - , v8::Local argv[]) const { -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource async("nan:Callback:Call"); - return Call_(isolate, target, argc, argv, &async) - .FromMaybe(v8::Local()); -# else - return Call_(isolate, target, argc, argv); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#else - return Call_(target, argc, argv); -#endif - } - - // Deprecated: For async callbacks Use the versions that accept an - // AsyncResource. If this callback does not correspond to an async resource, - // that is, it is a synchronous function call on a non-empty JS stack, you - // should Nan::Call instead. - NAN_DEPRECATED inline v8::Local - Call(int argc, v8::Local argv[]) const { -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource async("nan:Callback:Call"); - return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(), - argc, argv, &async) - .FromMaybe(v8::Local())); -# else - return scope.Escape( - Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#else - v8::HandleScope scope; - return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); -#endif - } - - inline MaybeLocal - Call(v8::Local target - , int argc - , v8::Local argv[] - , AsyncResource* resource) const { -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - return Call_(isolate, target, argc, argv, resource); -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - return Call_(isolate, target, argc, argv); -#else - return Call_(target, argc, argv); -#endif - } - - inline MaybeLocal - Call(int argc, v8::Local argv[], AsyncResource* resource) const { -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - return Call(isolate->GetCurrentContext()->Global(), argc, argv, resource); -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); -#else - v8::HandleScope scope; - return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); -#endif - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(Callback) - Persistent handle_; - -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - MaybeLocal Call_(v8::Isolate *isolate - , v8::Local target - , int argc - , v8::Local argv[] - , AsyncResource* resource) const { - EscapableHandleScope scope; - v8::Local func = New(handle_); - auto maybe = resource->runInAsyncScope(target, func, argc, argv); - v8::Local local; - if (!maybe.ToLocal(&local)) return MaybeLocal(); - return scope.Escape(local); - } -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Local Call_(v8::Isolate *isolate - , v8::Local target - , int argc - , v8::Local argv[]) const { - EscapableHandleScope scope; - - v8::Local callback = New(handle_); -# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - return scope.Escape(New(node::MakeCallback( - isolate - , target - , callback - , argc - , argv - ))); -# else - return scope.Escape(node::MakeCallback( - isolate - , target - , callback - , argc - , argv - )); -# endif - } -#else - v8::Local Call_(v8::Local target - , int argc - , v8::Local argv[]) const { - EscapableHandleScope scope; - - v8::Local callback = New(handle_); - return scope.Escape(New(node::MakeCallback( - target - , callback - , argc - , argv - ))); - } -#endif -}; - -inline MaybeLocal Call( - const Nan::Callback& callback - , v8::Local recv - , int argc - , v8::Local argv[]) { - return Call(*callback, recv, argc, argv); -} - -inline MaybeLocal Call( - const Nan::Callback& callback - , int argc - , v8::Local argv[]) { -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - Call(*callback, isolate->GetCurrentContext()->Global(), argc, argv) - .FromMaybe(v8::Local())); -#else - EscapableHandleScope scope; - return scope.Escape( - Call(*callback, v8::Context::GetCurrent()->Global(), argc, argv) - .FromMaybe(v8::Local())); -#endif -} - -inline MaybeLocal Call( - v8::Local symbol - , v8::Local recv - , int argc - , v8::Local argv[]) { - EscapableHandleScope scope; - v8::Local fn_v = - Get(recv, symbol).FromMaybe(v8::Local()); - if (fn_v.IsEmpty() || !fn_v->IsFunction()) return v8::Local(); - v8::Local fn = fn_v.As(); - return scope.Escape( - Call(fn, recv, argc, argv).FromMaybe(v8::Local())); -} - -inline MaybeLocal Call( - const char* method - , v8::Local recv - , int argc - , v8::Local argv[]) { - EscapableHandleScope scope; - v8::Local method_string = - New(method).ToLocalChecked(); - return scope.Escape( - Call(method_string, recv, argc, argv).FromMaybe(v8::Local())); -} - -/* abstract */ class AsyncWorker { - public: - explicit AsyncWorker(Callback *callback_, - const char* resource_name = "nan:AsyncWorker") - : callback(callback_), errmsg_(NULL) { - request.data = this; - - HandleScope scope; - v8::Local obj = New(); - persistentHandle.Reset(obj); - async_resource = new AsyncResource(resource_name, obj); - } - - virtual ~AsyncWorker() { - HandleScope scope; - - if (!persistentHandle.IsEmpty()) - persistentHandle.Reset(); - delete callback; - delete[] errmsg_; - delete async_resource; - } - - virtual void WorkComplete() { - HandleScope scope; - - if (errmsg_ == NULL) - HandleOKCallback(); - else - HandleErrorCallback(); - delete callback; - callback = NULL; - } - - inline void SaveToPersistent( - const char *key, const v8::Local &value) { - HandleScope scope; - Set(New(persistentHandle), New(key).ToLocalChecked(), value).FromJust(); - } - - inline void SaveToPersistent( - const v8::Local &key, const v8::Local &value) { - HandleScope scope; - Set(New(persistentHandle), key, value).FromJust(); - } - - inline void SaveToPersistent( - uint32_t index, const v8::Local &value) { - HandleScope scope; - Set(New(persistentHandle), index, value).FromJust(); - } - - inline v8::Local GetFromPersistent(const char *key) const { - EscapableHandleScope scope; - return scope.Escape( - Get(New(persistentHandle), New(key).ToLocalChecked()) - .FromMaybe(v8::Local())); - } - - inline v8::Local - GetFromPersistent(const v8::Local &key) const { - EscapableHandleScope scope; - return scope.Escape( - Get(New(persistentHandle), key) - .FromMaybe(v8::Local())); - } - - inline v8::Local GetFromPersistent(uint32_t index) const { - EscapableHandleScope scope; - return scope.Escape( - Get(New(persistentHandle), index) - .FromMaybe(v8::Local())); - } - - virtual void Execute() = 0; - - uv_work_t request; - - virtual void Destroy() { - delete this; - } - - protected: - Persistent persistentHandle; - Callback *callback; - AsyncResource *async_resource; - - virtual void HandleOKCallback() { - HandleScope scope; - - callback->Call(0, NULL, async_resource); - } - - virtual void HandleErrorCallback() { - HandleScope scope; - - v8::Local argv[] = { - v8::Exception::Error(New(ErrorMessage()).ToLocalChecked()) - }; - callback->Call(1, argv, async_resource); - } - - void SetErrorMessage(const char *msg) { - delete[] errmsg_; - - size_t size = strlen(msg) + 1; - errmsg_ = new char[size]; - memcpy(errmsg_, msg, size); - } - - const char* ErrorMessage() const { - return errmsg_; - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncWorker) - char *errmsg_; -}; - -/* abstract */ class AsyncBareProgressWorkerBase : public AsyncWorker { - public: - explicit AsyncBareProgressWorkerBase( - Callback *callback_, - const char* resource_name = "nan:AsyncBareProgressWorkerBase") - : AsyncWorker(callback_, resource_name) { - uv_async_init( - GetCurrentEventLoop() - , &async - , AsyncProgress_ - ); - async.data = this; - } - - virtual ~AsyncBareProgressWorkerBase() { - } - - virtual void WorkProgress() = 0; - - virtual void Destroy() { - uv_close(reinterpret_cast(&async), AsyncClose_); - } - - private: - inline static NAUV_WORK_CB(AsyncProgress_) { - AsyncBareProgressWorkerBase *worker = - static_cast(async->data); - worker->WorkProgress(); - } - - inline static void AsyncClose_(uv_handle_t* handle) { - AsyncBareProgressWorkerBase *worker = - static_cast(handle->data); - delete worker; - } - - protected: - uv_async_t async; -}; - -template -/* abstract */ -class AsyncBareProgressWorker : public AsyncBareProgressWorkerBase { - public: - explicit AsyncBareProgressWorker( - Callback *callback_, - const char* resource_name = "nan:AsyncBareProgressWorker") - : AsyncBareProgressWorkerBase(callback_, resource_name) { - uv_mutex_init(&async_lock); - } - - virtual ~AsyncBareProgressWorker() { - uv_mutex_destroy(&async_lock); - } - - class ExecutionProgress { - friend class AsyncBareProgressWorker; - public: - void Signal() const { - uv_mutex_lock(&that_->async_lock); - uv_async_send(&that_->async); - uv_mutex_unlock(&that_->async_lock); - } - - void Send(const T* data, size_t count) const { - that_->SendProgress_(data, count); - } - - private: - explicit ExecutionProgress(AsyncBareProgressWorker *that) : that_(that) {} - NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress) - AsyncBareProgressWorker* const that_; - }; - - virtual void Execute(const ExecutionProgress& progress) = 0; - virtual void HandleProgressCallback(const T *data, size_t size) = 0; - - protected: - uv_mutex_t async_lock; - - private: - void Execute() /*final override*/ { - ExecutionProgress progress(this); - Execute(progress); - } - - virtual void SendProgress_(const T *data, size_t count) = 0; -}; - -template -/* abstract */ -class AsyncProgressWorkerBase : public AsyncBareProgressWorker { - public: - explicit AsyncProgressWorkerBase( - Callback *callback_, - const char* resource_name = "nan:AsyncProgressWorkerBase") - : AsyncBareProgressWorker(callback_, resource_name), asyncdata_(NULL), - asyncsize_(0) { - } - - virtual ~AsyncProgressWorkerBase() { - delete[] asyncdata_; - } - - void WorkProgress() { - uv_mutex_lock(&this->async_lock); - T *data = asyncdata_; - size_t size = asyncsize_; - asyncdata_ = NULL; - asyncsize_ = 0; - uv_mutex_unlock(&this->async_lock); - - // Don't send progress events after we've already completed. - if (this->callback) { - this->HandleProgressCallback(data, size); - } - delete[] data; - } - - private: - void SendProgress_(const T *data, size_t count) { - T *new_data = new T[count]; - std::copy(data, data + count, new_data); - - uv_mutex_lock(&this->async_lock); - T *old_data = asyncdata_; - asyncdata_ = new_data; - asyncsize_ = count; - uv_async_send(&this->async); - uv_mutex_unlock(&this->async_lock); - - delete[] old_data; - } - - T *asyncdata_; - size_t asyncsize_; -}; - -// This ensures compatibility to the previous un-templated AsyncProgressWorker -// class definition. -typedef AsyncProgressWorkerBase AsyncProgressWorker; - -template -/* abstract */ -class AsyncBareProgressQueueWorker : public AsyncBareProgressWorkerBase { - public: - explicit AsyncBareProgressQueueWorker( - Callback *callback_, - const char* resource_name = "nan:AsyncBareProgressQueueWorker") - : AsyncBareProgressWorkerBase(callback_, resource_name) { - } - - virtual ~AsyncBareProgressQueueWorker() { - } - - class ExecutionProgress { - friend class AsyncBareProgressQueueWorker; - public: - void Send(const T* data, size_t count) const { - that_->SendProgress_(data, count); - } - - private: - explicit ExecutionProgress(AsyncBareProgressQueueWorker *that) - : that_(that) {} - NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress) - AsyncBareProgressQueueWorker* const that_; - }; - - virtual void Execute(const ExecutionProgress& progress) = 0; - virtual void HandleProgressCallback(const T *data, size_t size) = 0; - - private: - void Execute() /*final override*/ { - ExecutionProgress progress(this); - Execute(progress); - } - - virtual void SendProgress_(const T *data, size_t count) = 0; -}; - -template -/* abstract */ -class AsyncProgressQueueWorker : public AsyncBareProgressQueueWorker { - public: - explicit AsyncProgressQueueWorker( - Callback *callback_, - const char* resource_name = "nan:AsyncProgressQueueWorker") - : AsyncBareProgressQueueWorker(callback_) { - uv_mutex_init(&async_lock); - } - - virtual ~AsyncProgressQueueWorker() { - uv_mutex_lock(&async_lock); - - while (!asyncdata_.empty()) { - std::pair &datapair = asyncdata_.front(); - T *data = datapair.first; - - asyncdata_.pop(); - - delete[] data; - } - - uv_mutex_unlock(&async_lock); - uv_mutex_destroy(&async_lock); - } - - void WorkComplete() { - WorkProgress(); - AsyncWorker::WorkComplete(); - } - - void WorkProgress() { - uv_mutex_lock(&async_lock); - - while (!asyncdata_.empty()) { - std::pair &datapair = asyncdata_.front(); - - T *data = datapair.first; - size_t size = datapair.second; - - asyncdata_.pop(); - uv_mutex_unlock(&async_lock); - - // Don't send progress events after we've already completed. - if (this->callback) { - this->HandleProgressCallback(data, size); - } - - delete[] data; - - uv_mutex_lock(&async_lock); - } - - uv_mutex_unlock(&async_lock); - } - - private: - void SendProgress_(const T *data, size_t count) { - T *new_data = new T[count]; - std::copy(data, data + count, new_data); - - uv_mutex_lock(&async_lock); - asyncdata_.push(std::pair(new_data, count)); - uv_mutex_unlock(&async_lock); - - uv_async_send(&this->async); - } - - uv_mutex_t async_lock; - std::queue > asyncdata_; -}; - -inline void AsyncExecute (uv_work_t* req) { - AsyncWorker *worker = static_cast(req->data); - worker->Execute(); -} - -/* uv_after_work_cb has 1 argument before node-v0.9.4 and - * 2 arguments since node-v0.9.4 - * https://github.com/libuv/libuv/commit/92fb84b751e18f032c02609467f44bfe927b80c5 - */ -inline void AsyncExecuteComplete(uv_work_t *req) { - AsyncWorker* worker = static_cast(req->data); - worker->WorkComplete(); - worker->Destroy(); -} -inline void AsyncExecuteComplete (uv_work_t* req, int status) { - AsyncExecuteComplete(req); -} - -inline void AsyncQueueWorker (AsyncWorker* worker) { - uv_queue_work( - GetCurrentEventLoop() - , &worker->request - , AsyncExecute - , AsyncExecuteComplete - ); -} - -namespace imp { - -inline -ExternalOneByteStringResource const* -GetExternalResource(v8::Local str) { -#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION - return str->GetExternalAsciiStringResource(); -#else - return str->GetExternalOneByteStringResource(); -#endif -} - -inline -bool -IsExternal(v8::Local str) { -#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION - return str->IsExternalAscii(); -#else - return str->IsExternalOneByte(); -#endif -} - -} // end of namespace imp - -enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; - -#if NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION -# include "nan_string_bytes.h" // NOLINT(build/include) -#endif - -inline v8::Local Encode( - const void *buf, size_t len, enum Encoding encoding = BINARY) { -#if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION) - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - node::encoding node_enc = static_cast(encoding); - - if (encoding == UCS2) { - return node::Encode( - isolate - , reinterpret_cast(buf) - , len / 2); - } else { - return node::Encode( - isolate - , reinterpret_cast(buf) - , len - , node_enc); - } -#elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - return node::Encode( - v8::Isolate::GetCurrent() - , buf, len - , static_cast(encoding)); -#else -# if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION - return node::Encode(buf, len, static_cast(encoding)); -# else - return imp::Encode(reinterpret_cast(buf), len, encoding); -# endif -#endif -} - -inline ssize_t DecodeBytes( - v8::Local val, enum Encoding encoding = BINARY) { -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - return node::DecodeBytes( - v8::Isolate::GetCurrent() - , val - , static_cast(encoding)); -#else -# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) - if (encoding == BUFFER) { - return node::DecodeBytes(val, node::BINARY); - } -# endif - return node::DecodeBytes(val, static_cast(encoding)); -#endif -} - -inline ssize_t DecodeWrite( - char *buf - , size_t len - , v8::Local val - , enum Encoding encoding = BINARY) { -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - return node::DecodeWrite( - v8::Isolate::GetCurrent() - , buf - , len - , val - , static_cast(encoding)); -#else -# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) - if (encoding == BUFFER) { - return node::DecodeWrite(buf, len, val, node::BINARY); - } -# endif - return node::DecodeWrite( - buf - , len - , val - , static_cast(encoding)); -#endif -} - -inline void SetPrototypeTemplate( - v8::Local templ - , const char *name - , v8::Local value -) { - HandleScope scope; - SetTemplate(templ->PrototypeTemplate(), name, value); -} - -inline void SetPrototypeTemplate( - v8::Local templ - , v8::Local name - , v8::Local value - , v8::PropertyAttribute attributes -) { - HandleScope scope; - SetTemplate(templ->PrototypeTemplate(), name, value, attributes); -} - -inline void SetInstanceTemplate( - v8::Local templ - , const char *name - , v8::Local value -) { - HandleScope scope; - SetTemplate(templ->InstanceTemplate(), name, value); -} - -inline void SetInstanceTemplate( - v8::Local templ - , v8::Local name - , v8::Local value - , v8::PropertyAttribute attributes -) { - HandleScope scope; - SetTemplate(templ->InstanceTemplate(), name, value, attributes); -} - -namespace imp { - -// Note(@agnat): Helper to distinguish different receiver types. The first -// version deals with receivers derived from v8::Template. The second version -// handles everything else. The final argument only serves as discriminator and -// is unused. -template -inline -void -SetMethodAux(T recv, - v8::Local name, - v8::Local tpl, - v8::Template *) { - recv->Set(name, tpl); -} - -template -inline -void -SetMethodAux(T recv, - v8::Local name, - v8::Local tpl, - ...) { - Set(recv, name, GetFunction(tpl).ToLocalChecked()); -} - -} // end of namespace imp - -template class HandleType> -inline void SetMethod( - HandleType recv - , const char *name - , FunctionCallback callback - , v8::Local data = v8::Local()) { - HandleScope scope; - v8::Local t = New(callback, data); - v8::Local fn_name = New(name).ToLocalChecked(); - t->SetClassName(fn_name); - // Note(@agnat): Pass an empty T* as discriminator. See note on - // SetMethodAux(...) above - imp::SetMethodAux(recv, fn_name, t, static_cast(0)); -} - -inline void SetPrototypeMethod( - v8::Local recv - , const char* name - , FunctionCallback callback - , v8::Local data = v8::Local()) { - HandleScope scope; - v8::Local t = New( - callback - , data - , New(recv)); - v8::Local fn_name = New(name).ToLocalChecked(); - recv->PrototypeTemplate()->Set(fn_name, t); - t->SetClassName(fn_name); -} - -//=== Accessors and Such ======================================================= - -inline void SetAccessor( - v8::Local tpl - , v8::Local name - , GetterCallback getter - , SetterCallback setter = 0 - , v8::Local data = v8::Local() - , v8::AccessControl settings = v8::DEFAULT - , v8::PropertyAttribute attribute = v8::None - , imp::Sig signature = imp::Sig()) { - HandleScope scope; - - imp::NativeGetter getter_ = - imp::GetterCallbackWrapper; - imp::NativeSetter setter_ = - setter ? imp::SetterCallbackWrapper : 0; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kAccessorFieldCount); - v8::Local obj = NewInstance(otpl).ToLocalChecked(); - - obj->SetInternalField( - imp::kGetterIndex - , New(reinterpret_cast(getter))); - - if (setter != 0) { - obj->SetInternalField( - imp::kSetterIndex - , New(reinterpret_cast(setter))); - } - - if (!data.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, data); - } - - tpl->SetAccessor( - name - , getter_ - , setter_ - , obj - , settings - , attribute - , signature); -} - -inline bool SetAccessor( - v8::Local obj - , v8::Local name - , GetterCallback getter - , SetterCallback setter = 0 - , v8::Local data = v8::Local() - , v8::AccessControl settings = v8::DEFAULT - , v8::PropertyAttribute attribute = v8::None) { - HandleScope scope; - - imp::NativeGetter getter_ = - imp::GetterCallbackWrapper; - imp::NativeSetter setter_ = - setter ? imp::SetterCallbackWrapper : 0; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kAccessorFieldCount); - v8::Local dataobj = NewInstance(otpl).ToLocalChecked(); - - dataobj->SetInternalField( - imp::kGetterIndex - , New(reinterpret_cast(getter))); - - if (!data.IsEmpty()) { - dataobj->SetInternalField(imp::kDataIndex, data); - } - - if (setter) { - dataobj->SetInternalField( - imp::kSetterIndex - , New(reinterpret_cast(setter))); - } - -#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) - return obj->SetAccessor( - GetCurrentContext() - , name - , getter_ - , setter_ - , dataobj - , settings - , attribute).FromMaybe(false); -#else - return obj->SetAccessor( - name - , getter_ - , setter_ - , dataobj - , settings - , attribute); -#endif -} - -inline void SetNamedPropertyHandler( - v8::Local tpl - , PropertyGetterCallback getter - , PropertySetterCallback setter = 0 - , PropertyQueryCallback query = 0 - , PropertyDeleterCallback deleter = 0 - , PropertyEnumeratorCallback enumerator = 0 - , v8::Local data = v8::Local()) { - HandleScope scope; - - imp::NativePropertyGetter getter_ = - imp::PropertyGetterCallbackWrapper; - imp::NativePropertySetter setter_ = - setter ? imp::PropertySetterCallbackWrapper : 0; - imp::NativePropertyQuery query_ = - query ? imp::PropertyQueryCallbackWrapper : 0; - imp::NativePropertyDeleter *deleter_ = - deleter ? imp::PropertyDeleterCallbackWrapper : 0; - imp::NativePropertyEnumerator enumerator_ = - enumerator ? imp::PropertyEnumeratorCallbackWrapper : 0; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kPropertyFieldCount); - v8::Local obj = NewInstance(otpl).ToLocalChecked(); - obj->SetInternalField( - imp::kPropertyGetterIndex - , New(reinterpret_cast(getter))); - - if (setter) { - obj->SetInternalField( - imp::kPropertySetterIndex - , New(reinterpret_cast(setter))); - } - - if (query) { - obj->SetInternalField( - imp::kPropertyQueryIndex - , New(reinterpret_cast(query))); - } - - if (deleter) { - obj->SetInternalField( - imp::kPropertyDeleterIndex - , New(reinterpret_cast(deleter))); - } - - if (enumerator) { - obj->SetInternalField( - imp::kPropertyEnumeratorIndex - , New(reinterpret_cast(enumerator))); - } - - if (!data.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, data); - } - -#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION - tpl->SetHandler(v8::NamedPropertyHandlerConfiguration( - getter_, setter_, query_, deleter_, enumerator_, obj)); -#else - tpl->SetNamedPropertyHandler( - getter_ - , setter_ - , query_ - , deleter_ - , enumerator_ - , obj); -#endif -} - -inline void SetIndexedPropertyHandler( - v8::Local tpl - , IndexGetterCallback getter - , IndexSetterCallback setter = 0 - , IndexQueryCallback query = 0 - , IndexDeleterCallback deleter = 0 - , IndexEnumeratorCallback enumerator = 0 - , v8::Local data = v8::Local()) { - HandleScope scope; - - imp::NativeIndexGetter getter_ = - imp::IndexGetterCallbackWrapper; - imp::NativeIndexSetter setter_ = - setter ? imp::IndexSetterCallbackWrapper : 0; - imp::NativeIndexQuery query_ = - query ? imp::IndexQueryCallbackWrapper : 0; - imp::NativeIndexDeleter deleter_ = - deleter ? imp::IndexDeleterCallbackWrapper : 0; - imp::NativeIndexEnumerator enumerator_ = - enumerator ? imp::IndexEnumeratorCallbackWrapper : 0; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kIndexPropertyFieldCount); - v8::Local obj = NewInstance(otpl).ToLocalChecked(); - obj->SetInternalField( - imp::kIndexPropertyGetterIndex - , New(reinterpret_cast(getter))); - - if (setter) { - obj->SetInternalField( - imp::kIndexPropertySetterIndex - , New(reinterpret_cast(setter))); - } - - if (query) { - obj->SetInternalField( - imp::kIndexPropertyQueryIndex - , New(reinterpret_cast(query))); - } - - if (deleter) { - obj->SetInternalField( - imp::kIndexPropertyDeleterIndex - , New(reinterpret_cast(deleter))); - } - - if (enumerator) { - obj->SetInternalField( - imp::kIndexPropertyEnumeratorIndex - , New(reinterpret_cast(enumerator))); - } - - if (!data.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, data); - } - -#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION - tpl->SetHandler(v8::IndexedPropertyHandlerConfiguration( - getter_, setter_, query_, deleter_, enumerator_, obj)); -#else - tpl->SetIndexedPropertyHandler( - getter_ - , setter_ - , query_ - , deleter_ - , enumerator_ - , obj); -#endif -} - -inline void SetCallHandler( - v8::Local tpl - , FunctionCallback callback - , v8::Local data = v8::Local()) { - HandleScope scope; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kFunctionFieldCount); - v8::Local obj = NewInstance(otpl).ToLocalChecked(); - - obj->SetInternalField( - imp::kFunctionIndex - , New(reinterpret_cast(callback))); - - if (!data.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, data); - } - - tpl->SetCallHandler(imp::FunctionCallbackWrapper, obj); -} - - -inline void SetCallAsFunctionHandler( - v8::Local tpl, - FunctionCallback callback, - v8::Local data = v8::Local()) { - HandleScope scope; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kFunctionFieldCount); - v8::Local obj = NewInstance(otpl).ToLocalChecked(); - - obj->SetInternalField( - imp::kFunctionIndex - , New(reinterpret_cast(callback))); - - if (!data.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, data); - } - - tpl->SetCallAsFunctionHandler(imp::FunctionCallbackWrapper, obj); -} - -//=== Weak Persistent Handling ================================================= - -#include "nan_weak.h" // NOLINT(build/include) - -//=== ObjectWrap =============================================================== - -#include "nan_object_wrap.h" // NOLINT(build/include) - -//=== HiddenValue/Private ====================================================== - -#include "nan_private.h" // NOLINT(build/include) - -//=== Export ================================================================== - -inline -void -Export(ADDON_REGISTER_FUNCTION_ARGS_TYPE target, const char *name, - FunctionCallback f) { - HandleScope scope; - - Set(target, New(name).ToLocalChecked(), - GetFunction(New(f)).ToLocalChecked()); -} - -//=== Tap Reverse Binding ===================================================== - -struct Tap { - explicit Tap(v8::Local t) : t_() { - HandleScope scope; - - t_.Reset(To(t).ToLocalChecked()); - } - - ~Tap() { t_.Reset(); } // not sure if necessary - - inline void plan(int i) { - HandleScope scope; - v8::Local arg = New(i); - Call("plan", New(t_), 1, &arg); - } - - inline void ok(bool isOk, const char *msg = NULL) { - HandleScope scope; - v8::Local args[2]; - args[0] = New(isOk); - if (msg) args[1] = New(msg).ToLocalChecked(); - Call("ok", New(t_), msg ? 2 : 1, args); - } - - inline void pass(const char * msg = NULL) { - HandleScope scope; - v8::Local hmsg; - if (msg) hmsg = New(msg).ToLocalChecked(); - Call("pass", New(t_), msg ? 1 : 0, &hmsg); - } - - inline void end() { - HandleScope scope; - Call("end", New(t_), 0, NULL); - } - - private: - Persistent t_; -}; - -#define NAN_STRINGIZE2(x) #x -#define NAN_STRINGIZE(x) NAN_STRINGIZE2(x) -#define NAN_TEST_EXPRESSION(expression) \ - ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression - -#define NAN_EXPORT(target, function) Export(target, #function, function) - -#undef TYPE_CHECK - -//=== Generic Maybefication =================================================== - -namespace imp { - -template struct Maybefier; - -template struct Maybefier > { - inline static MaybeLocal convert(v8::Local v) { - return v; - } -}; - -template struct Maybefier > { - inline static MaybeLocal convert(MaybeLocal v) { - return v; - } -}; - -} // end of namespace imp - -template class MaybeMaybe> -inline MaybeLocal -MakeMaybe(MaybeMaybe v) { - return imp::Maybefier >::convert(v); -} - -//=== TypedArrayContents ======================================================= - -#include "nan_typedarray_contents.h" // NOLINT(build/include) - -//=== JSON ===================================================================== - -#include "nan_json.h" // NOLINT(build/include) - -//=== ScriptOrigin ============================================================= - -#include "nan_scriptorigin.h" // NOLINT(build/include) - -} // end of namespace Nan - -#endif // NAN_H_ diff --git a/reverse_engineering/node_modules/nan/nan_callbacks.h b/reverse_engineering/node_modules/nan/nan_callbacks.h deleted file mode 100644 index 53ede84..0000000 --- a/reverse_engineering/node_modules/nan/nan_callbacks.h +++ /dev/null @@ -1,88 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CALLBACKS_H_ -#define NAN_CALLBACKS_H_ - -template class FunctionCallbackInfo; -template class PropertyCallbackInfo; -template class Global; - -typedef void(*FunctionCallback)(const FunctionCallbackInfo&); -typedef void(*GetterCallback) - (v8::Local, const PropertyCallbackInfo&); -typedef void(*SetterCallback)( - v8::Local, - v8::Local, - const PropertyCallbackInfo&); -typedef void(*PropertyGetterCallback)( - v8::Local, - const PropertyCallbackInfo&); -typedef void(*PropertySetterCallback)( - v8::Local, - v8::Local, - const PropertyCallbackInfo&); -typedef void(*PropertyEnumeratorCallback) - (const PropertyCallbackInfo&); -typedef void(*PropertyDeleterCallback)( - v8::Local, - const PropertyCallbackInfo&); -typedef void(*PropertyQueryCallback)( - v8::Local, - const PropertyCallbackInfo&); -typedef void(*IndexGetterCallback)( - uint32_t, - const PropertyCallbackInfo&); -typedef void(*IndexSetterCallback)( - uint32_t, - v8::Local, - const PropertyCallbackInfo&); -typedef void(*IndexEnumeratorCallback) - (const PropertyCallbackInfo&); -typedef void(*IndexDeleterCallback)( - uint32_t, - const PropertyCallbackInfo&); -typedef void(*IndexQueryCallback)( - uint32_t, - const PropertyCallbackInfo&); - -namespace imp { -typedef v8::Local Sig; - -static const int kDataIndex = 0; - -static const int kFunctionIndex = 1; -static const int kFunctionFieldCount = 2; - -static const int kGetterIndex = 1; -static const int kSetterIndex = 2; -static const int kAccessorFieldCount = 3; - -static const int kPropertyGetterIndex = 1; -static const int kPropertySetterIndex = 2; -static const int kPropertyEnumeratorIndex = 3; -static const int kPropertyDeleterIndex = 4; -static const int kPropertyQueryIndex = 5; -static const int kPropertyFieldCount = 6; - -static const int kIndexPropertyGetterIndex = 1; -static const int kIndexPropertySetterIndex = 2; -static const int kIndexPropertyEnumeratorIndex = 3; -static const int kIndexPropertyDeleterIndex = 4; -static const int kIndexPropertyQueryIndex = 5; -static const int kIndexPropertyFieldCount = 6; - -} // end of namespace imp - -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION -# include "nan_callbacks_12_inl.h" // NOLINT(build/include) -#else -# include "nan_callbacks_pre_12_inl.h" // NOLINT(build/include) -#endif - -#endif // NAN_CALLBACKS_H_ diff --git a/reverse_engineering/node_modules/nan/nan_callbacks_12_inl.h b/reverse_engineering/node_modules/nan/nan_callbacks_12_inl.h deleted file mode 100644 index c27b18d..0000000 --- a/reverse_engineering/node_modules/nan/nan_callbacks_12_inl.h +++ /dev/null @@ -1,514 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CALLBACKS_12_INL_H_ -#define NAN_CALLBACKS_12_INL_H_ - -template -class ReturnValue { - v8::ReturnValue value_; - - public: - template - explicit inline ReturnValue(const v8::ReturnValue &value) : - value_(value) {} - template - explicit inline ReturnValue(const ReturnValue& that) - : value_(that.value_) { - TYPE_CHECK(T, S); - } - - // Handle setters - template inline void Set(const v8::Local &handle) { - TYPE_CHECK(T, S); - value_.Set(handle); - } - - template inline void Set(const Global &handle) { - TYPE_CHECK(T, S); -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && \ - (V8_MINOR_VERSION > 5 || (V8_MINOR_VERSION == 5 && \ - defined(V8_BUILD_NUMBER) && V8_BUILD_NUMBER >= 8)))) - value_.Set(handle); -#else - value_.Set(*reinterpret_cast*>(&handle)); - const_cast &>(handle).Reset(); -#endif - } - - // Fast primitive setters - inline void Set(bool value) { - TYPE_CHECK(T, v8::Boolean); - value_.Set(value); - } - - inline void Set(double i) { - TYPE_CHECK(T, v8::Number); - value_.Set(i); - } - - inline void Set(int32_t i) { - TYPE_CHECK(T, v8::Integer); - value_.Set(i); - } - - inline void Set(uint32_t i) { - TYPE_CHECK(T, v8::Integer); - value_.Set(i); - } - - // Fast JS primitive setters - inline void SetNull() { - TYPE_CHECK(T, v8::Primitive); - value_.SetNull(); - } - - inline void SetUndefined() { - TYPE_CHECK(T, v8::Primitive); - value_.SetUndefined(); - } - - inline void SetEmptyString() { - TYPE_CHECK(T, v8::String); - value_.SetEmptyString(); - } - - // Convenience getter for isolate - inline v8::Isolate *GetIsolate() const { - return value_.GetIsolate(); - } - - // Pointer setter: Uncompilable to prevent inadvertent misuse. - template - inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); } -}; - -template -class FunctionCallbackInfo { - const v8::FunctionCallbackInfo &info_; - const v8::Local data_; - - public: - explicit inline FunctionCallbackInfo( - const v8::FunctionCallbackInfo &info - , v8::Local data) : - info_(info) - , data_(data) {} - - inline ReturnValue GetReturnValue() const { - return ReturnValue(info_.GetReturnValue()); - } - -#if NODE_MAJOR_VERSION < 10 - inline v8::Local Callee() const { return info_.Callee(); } -#endif - inline v8::Local Data() const { return data_; } - inline v8::Local Holder() const { return info_.Holder(); } - inline bool IsConstructCall() const { return info_.IsConstructCall(); } - inline int Length() const { return info_.Length(); } - inline v8::Local operator[](int i) const { return info_[i]; } - inline v8::Local This() const { return info_.This(); } - inline v8::Isolate *GetIsolate() const { return info_.GetIsolate(); } - - - protected: - static const int kHolderIndex = 0; - static const int kIsolateIndex = 1; - static const int kReturnValueDefaultValueIndex = 2; - static const int kReturnValueIndex = 3; - static const int kDataIndex = 4; - static const int kCalleeIndex = 5; - static const int kContextSaveIndex = 6; - static const int kArgsLength = 7; - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo) -}; - -template -class PropertyCallbackInfo { - const v8::PropertyCallbackInfo &info_; - const v8::Local data_; - - public: - explicit inline PropertyCallbackInfo( - const v8::PropertyCallbackInfo &info - , const v8::Local data) : - info_(info) - , data_(data) {} - - inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); } - inline v8::Local Data() const { return data_; } - inline v8::Local This() const { return info_.This(); } - inline v8::Local Holder() const { return info_.Holder(); } - inline ReturnValue GetReturnValue() const { - return ReturnValue(info_.GetReturnValue()); - } - - protected: - static const int kHolderIndex = 0; - static const int kIsolateIndex = 1; - static const int kReturnValueDefaultValueIndex = 2; - static const int kReturnValueIndex = 3; - static const int kDataIndex = 4; - static const int kThisIndex = 5; - static const int kArgsLength = 6; - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfo) -}; - -namespace imp { -static -void FunctionCallbackWrapper(const v8::FunctionCallbackInfo &info) { - v8::Local obj = info.Data().As(); - FunctionCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kFunctionIndex).As()->Value())); - FunctionCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - callback(cbinfo); -} - -typedef void (*NativeFunction)(const v8::FunctionCallbackInfo &); - -#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION -static -void GetterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - GetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kGetterIndex).As()->Value())); - callback(property.As(), cbinfo); -} - -typedef void (*NativeGetter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void SetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - SetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kSetterIndex).As()->Value())); - callback(property.As(), value, cbinfo); -} - -typedef void (*NativeSetter)( - v8::Local - , v8::Local - , const v8::PropertyCallbackInfo &); -#else -static -void GetterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - GetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kGetterIndex).As()->Value())); - callback(property, cbinfo); -} - -typedef void (*NativeGetter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void SetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - SetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kSetterIndex).As()->Value())); - callback(property, value, cbinfo); -} - -typedef void (*NativeSetter)( - v8::Local - , v8::Local - , const v8::PropertyCallbackInfo &); -#endif - -#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION -static -void PropertyGetterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyGetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyGetterIndex) - .As()->Value())); - callback(property.As(), cbinfo); -} - -typedef void (*NativePropertyGetter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void PropertySetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertySetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertySetterIndex) - .As()->Value())); - callback(property.As(), value, cbinfo); -} - -typedef void (*NativePropertySetter)( - v8::Local - , v8::Local - , const v8::PropertyCallbackInfo &); - -static -void PropertyEnumeratorCallbackWrapper( - const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyEnumeratorCallback callback = - reinterpret_cast(reinterpret_cast( - obj->GetInternalField(kPropertyEnumeratorIndex) - .As()->Value())); - callback(cbinfo); -} - -typedef void (*NativePropertyEnumerator) - (const v8::PropertyCallbackInfo &); - -static -void PropertyDeleterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyDeleterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyDeleterIndex) - .As()->Value())); - callback(property.As(), cbinfo); -} - -typedef void (NativePropertyDeleter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void PropertyQueryCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyQueryCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyQueryIndex) - .As()->Value())); - callback(property.As(), cbinfo); -} - -typedef void (*NativePropertyQuery) - (v8::Local, const v8::PropertyCallbackInfo &); -#else -static -void PropertyGetterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyGetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyGetterIndex) - .As()->Value())); - callback(property, cbinfo); -} - -typedef void (*NativePropertyGetter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void PropertySetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertySetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertySetterIndex) - .As()->Value())); - callback(property, value, cbinfo); -} - -typedef void (*NativePropertySetter)( - v8::Local - , v8::Local - , const v8::PropertyCallbackInfo &); - -static -void PropertyEnumeratorCallbackWrapper( - const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyEnumeratorCallback callback = - reinterpret_cast(reinterpret_cast( - obj->GetInternalField(kPropertyEnumeratorIndex) - .As()->Value())); - callback(cbinfo); -} - -typedef void (*NativePropertyEnumerator) - (const v8::PropertyCallbackInfo &); - -static -void PropertyDeleterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyDeleterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyDeleterIndex) - .As()->Value())); - callback(property, cbinfo); -} - -typedef void (NativePropertyDeleter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void PropertyQueryCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyQueryCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyQueryIndex) - .As()->Value())); - callback(property, cbinfo); -} - -typedef void (*NativePropertyQuery) - (v8::Local, const v8::PropertyCallbackInfo &); -#endif - -static -void IndexGetterCallbackWrapper( - uint32_t index, const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexGetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyGetterIndex) - .As()->Value())); - callback(index, cbinfo); -} - -typedef void (*NativeIndexGetter) - (uint32_t, const v8::PropertyCallbackInfo &); - -static -void IndexSetterCallbackWrapper( - uint32_t index - , v8::Local value - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexSetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertySetterIndex) - .As()->Value())); - callback(index, value, cbinfo); -} - -typedef void (*NativeIndexSetter)( - uint32_t - , v8::Local - , const v8::PropertyCallbackInfo &); - -static -void IndexEnumeratorCallbackWrapper( - const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexEnumeratorCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField( - kIndexPropertyEnumeratorIndex).As()->Value())); - callback(cbinfo); -} - -typedef void (*NativeIndexEnumerator) - (const v8::PropertyCallbackInfo &); - -static -void IndexDeleterCallbackWrapper( - uint32_t index, const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexDeleterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyDeleterIndex) - .As()->Value())); - callback(index, cbinfo); -} - -typedef void (*NativeIndexDeleter) - (uint32_t, const v8::PropertyCallbackInfo &); - -static -void IndexQueryCallbackWrapper( - uint32_t index, const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexQueryCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyQueryIndex) - .As()->Value())); - callback(index, cbinfo); -} - -typedef void (*NativeIndexQuery) - (uint32_t, const v8::PropertyCallbackInfo &); -} // end of namespace imp - -#endif // NAN_CALLBACKS_12_INL_H_ diff --git a/reverse_engineering/node_modules/nan/nan_callbacks_pre_12_inl.h b/reverse_engineering/node_modules/nan/nan_callbacks_pre_12_inl.h deleted file mode 100644 index c9ba499..0000000 --- a/reverse_engineering/node_modules/nan/nan_callbacks_pre_12_inl.h +++ /dev/null @@ -1,520 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CALLBACKS_PRE_12_INL_H_ -#define NAN_CALLBACKS_PRE_12_INL_H_ - -namespace imp { -template class ReturnValueImp; -} // end of namespace imp - -template -class ReturnValue { - v8::Isolate *isolate_; - v8::Persistent *value_; - friend class imp::ReturnValueImp; - - public: - template - explicit inline ReturnValue(v8::Isolate *isolate, v8::Persistent *p) : - isolate_(isolate), value_(p) {} - template - explicit inline ReturnValue(const ReturnValue& that) - : isolate_(that.isolate_), value_(that.value_) { - TYPE_CHECK(T, S); - } - - // Handle setters - template inline void Set(const v8::Local &handle) { - TYPE_CHECK(T, S); - value_->Dispose(); - *value_ = v8::Persistent::New(handle); - } - - template inline void Set(const Global &handle) { - TYPE_CHECK(T, S); - value_->Dispose(); - *value_ = v8::Persistent::New(handle.persistent); - const_cast &>(handle).Reset(); - } - - // Fast primitive setters - inline void Set(bool value) { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Boolean); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Boolean::New(value)); - } - - inline void Set(double i) { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Number); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Number::New(i)); - } - - inline void Set(int32_t i) { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Integer); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Int32::New(i)); - } - - inline void Set(uint32_t i) { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Integer); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Uint32::NewFromUnsigned(i)); - } - - // Fast JS primitive setters - inline void SetNull() { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Primitive); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Null()); - } - - inline void SetUndefined() { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Primitive); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Undefined()); - } - - inline void SetEmptyString() { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::String); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::String::Empty()); - } - - // Convenience getter for isolate - inline v8::Isolate *GetIsolate() const { - return isolate_; - } - - // Pointer setter: Uncompilable to prevent inadvertent misuse. - template - inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); } -}; - -template -class FunctionCallbackInfo { - const v8::Arguments &args_; - v8::Local data_; - ReturnValue return_value_; - v8::Persistent retval_; - - public: - explicit inline FunctionCallbackInfo( - const v8::Arguments &args - , v8::Local data) : - args_(args) - , data_(data) - , return_value_(args.GetIsolate(), &retval_) - , retval_(v8::Persistent::New(v8::Undefined())) {} - - inline ~FunctionCallbackInfo() { - retval_.Dispose(); - retval_.Clear(); - } - - inline ReturnValue GetReturnValue() const { - return ReturnValue(return_value_); - } - - inline v8::Local Callee() const { return args_.Callee(); } - inline v8::Local Data() const { return data_; } - inline v8::Local Holder() const { return args_.Holder(); } - inline bool IsConstructCall() const { return args_.IsConstructCall(); } - inline int Length() const { return args_.Length(); } - inline v8::Local operator[](int i) const { return args_[i]; } - inline v8::Local This() const { return args_.This(); } - inline v8::Isolate *GetIsolate() const { return args_.GetIsolate(); } - - - protected: - static const int kHolderIndex = 0; - static const int kIsolateIndex = 1; - static const int kReturnValueDefaultValueIndex = 2; - static const int kReturnValueIndex = 3; - static const int kDataIndex = 4; - static const int kCalleeIndex = 5; - static const int kContextSaveIndex = 6; - static const int kArgsLength = 7; - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo) -}; - -template -class PropertyCallbackInfoBase { - const v8::AccessorInfo &info_; - const v8::Local data_; - - public: - explicit inline PropertyCallbackInfoBase( - const v8::AccessorInfo &info - , const v8::Local data) : - info_(info) - , data_(data) {} - - inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); } - inline v8::Local Data() const { return data_; } - inline v8::Local This() const { return info_.This(); } - inline v8::Local Holder() const { return info_.Holder(); } - - protected: - static const int kHolderIndex = 0; - static const int kIsolateIndex = 1; - static const int kReturnValueDefaultValueIndex = 2; - static const int kReturnValueIndex = 3; - static const int kDataIndex = 4; - static const int kThisIndex = 5; - static const int kArgsLength = 6; - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfoBase) -}; - -template -class PropertyCallbackInfo : public PropertyCallbackInfoBase { - ReturnValue return_value_; - v8::Persistent retval_; - - public: - explicit inline PropertyCallbackInfo( - const v8::AccessorInfo &info - , const v8::Local data) : - PropertyCallbackInfoBase(info, data) - , return_value_(info.GetIsolate(), &retval_) - , retval_(v8::Persistent::New(v8::Undefined())) {} - - inline ~PropertyCallbackInfo() { - retval_.Dispose(); - retval_.Clear(); - } - - inline ReturnValue GetReturnValue() const { return return_value_; } -}; - -template<> -class PropertyCallbackInfo : - public PropertyCallbackInfoBase { - ReturnValue return_value_; - v8::Persistent retval_; - - public: - explicit inline PropertyCallbackInfo( - const v8::AccessorInfo &info - , const v8::Local data) : - PropertyCallbackInfoBase(info, data) - , return_value_(info.GetIsolate(), &retval_) - , retval_(v8::Persistent::New(v8::Local())) {} - - inline ~PropertyCallbackInfo() { - retval_.Dispose(); - retval_.Clear(); - } - - inline ReturnValue GetReturnValue() const { - return return_value_; - } -}; - -template<> -class PropertyCallbackInfo : - public PropertyCallbackInfoBase { - ReturnValue return_value_; - v8::Persistent retval_; - - public: - explicit inline PropertyCallbackInfo( - const v8::AccessorInfo &info - , const v8::Local data) : - PropertyCallbackInfoBase(info, data) - , return_value_(info.GetIsolate(), &retval_) - , retval_(v8::Persistent::New(v8::Local())) {} - - inline ~PropertyCallbackInfo() { - retval_.Dispose(); - retval_.Clear(); - } - - inline ReturnValue GetReturnValue() const { - return return_value_; - } -}; - -template<> -class PropertyCallbackInfo : - public PropertyCallbackInfoBase { - ReturnValue return_value_; - v8::Persistent retval_; - - public: - explicit inline PropertyCallbackInfo( - const v8::AccessorInfo &info - , const v8::Local data) : - PropertyCallbackInfoBase(info, data) - , return_value_(info.GetIsolate(), &retval_) - , retval_(v8::Persistent::New(v8::Local())) {} - - inline ~PropertyCallbackInfo() { - retval_.Dispose(); - retval_.Clear(); - } - - inline ReturnValue GetReturnValue() const { - return return_value_; - } -}; - -namespace imp { -template -class ReturnValueImp : public ReturnValue { - public: - explicit ReturnValueImp(ReturnValue that) : - ReturnValue(that) {} - inline v8::Handle Value() { - return *ReturnValue::value_; - } -}; - -static -v8::Handle FunctionCallbackWrapper(const v8::Arguments &args) { - v8::Local obj = args.Data().As(); - FunctionCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kFunctionIndex).As()->Value())); - FunctionCallbackInfo - cbinfo(args, obj->GetInternalField(kDataIndex)); - callback(cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeFunction)(const v8::Arguments &); - -static -v8::Handle GetterCallbackWrapper( - v8::Local property, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - GetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kGetterIndex).As()->Value())); - callback(property, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeGetter) - (v8::Local, const v8::AccessorInfo &); - -static -void SetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - SetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kSetterIndex).As()->Value())); - callback(property, value, cbinfo); -} - -typedef void (*NativeSetter) - (v8::Local, v8::Local, const v8::AccessorInfo &); - -static -v8::Handle PropertyGetterCallbackWrapper( - v8::Local property, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyGetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyGetterIndex) - .As()->Value())); - callback(property, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativePropertyGetter) - (v8::Local, const v8::AccessorInfo &); - -static -v8::Handle PropertySetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertySetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertySetterIndex) - .As()->Value())); - callback(property, value, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativePropertySetter) - (v8::Local, v8::Local, const v8::AccessorInfo &); - -static -v8::Handle PropertyEnumeratorCallbackWrapper( - const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyEnumeratorCallback callback = - reinterpret_cast(reinterpret_cast( - obj->GetInternalField(kPropertyEnumeratorIndex) - .As()->Value())); - callback(cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativePropertyEnumerator) - (const v8::AccessorInfo &); - -static -v8::Handle PropertyDeleterCallbackWrapper( - v8::Local property - , const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyDeleterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyDeleterIndex) - .As()->Value())); - callback(property, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (NativePropertyDeleter) - (v8::Local, const v8::AccessorInfo &); - -static -v8::Handle PropertyQueryCallbackWrapper( - v8::Local property, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyQueryCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyQueryIndex) - .As()->Value())); - callback(property, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativePropertyQuery) - (v8::Local, const v8::AccessorInfo &); - -static -v8::Handle IndexGetterCallbackWrapper( - uint32_t index, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexGetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyGetterIndex) - .As()->Value())); - callback(index, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeIndexGetter) - (uint32_t, const v8::AccessorInfo &); - -static -v8::Handle IndexSetterCallbackWrapper( - uint32_t index - , v8::Local value - , const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexSetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertySetterIndex) - .As()->Value())); - callback(index, value, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeIndexSetter) - (uint32_t, v8::Local, const v8::AccessorInfo &); - -static -v8::Handle IndexEnumeratorCallbackWrapper( - const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexEnumeratorCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyEnumeratorIndex) - .As()->Value())); - callback(cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeIndexEnumerator) - (const v8::AccessorInfo &); - -static -v8::Handle IndexDeleterCallbackWrapper( - uint32_t index, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexDeleterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyDeleterIndex) - .As()->Value())); - callback(index, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeIndexDeleter) - (uint32_t, const v8::AccessorInfo &); - -static -v8::Handle IndexQueryCallbackWrapper( - uint32_t index, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexQueryCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyQueryIndex) - .As()->Value())); - callback(index, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeIndexQuery) - (uint32_t, const v8::AccessorInfo &); -} // end of namespace imp - -#endif // NAN_CALLBACKS_PRE_12_INL_H_ diff --git a/reverse_engineering/node_modules/nan/nan_converters.h b/reverse_engineering/node_modules/nan/nan_converters.h deleted file mode 100644 index c0b3272..0000000 --- a/reverse_engineering/node_modules/nan/nan_converters.h +++ /dev/null @@ -1,72 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CONVERTERS_H_ -#define NAN_CONVERTERS_H_ - -namespace imp { -template struct ToFactoryBase { - typedef MaybeLocal return_t; -}; -template struct ValueFactoryBase { typedef Maybe return_t; }; - -template struct ToFactory; - -template<> -struct ToFactory : ToFactoryBase { - static inline return_t convert(v8::Local val) { - if (val.IsEmpty() || !val->IsFunction()) return MaybeLocal(); - return MaybeLocal(val.As()); - } -}; - -#define X(TYPE) \ - template<> \ - struct ToFactory : ToFactoryBase { \ - static inline return_t convert(v8::Local val); \ - }; - -X(Boolean) -X(Number) -X(String) -X(Object) -X(Integer) -X(Uint32) -X(Int32) - -#undef X - -#define X(TYPE) \ - template<> \ - struct ToFactory : ValueFactoryBase { \ - static inline return_t convert(v8::Local val); \ - }; - -X(bool) -X(double) -X(int64_t) -X(uint32_t) -X(int32_t) - -#undef X -} // end of namespace imp - -template -inline -typename imp::ToFactory::return_t To(v8::Local val) { - return imp::ToFactory::convert(val); -} - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -# include "nan_converters_43_inl.h" -#else -# include "nan_converters_pre_43_inl.h" -#endif - -#endif // NAN_CONVERTERS_H_ diff --git a/reverse_engineering/node_modules/nan/nan_converters_43_inl.h b/reverse_engineering/node_modules/nan/nan_converters_43_inl.h deleted file mode 100644 index 41b72de..0000000 --- a/reverse_engineering/node_modules/nan/nan_converters_43_inl.h +++ /dev/null @@ -1,68 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CONVERTERS_43_INL_H_ -#define NAN_CONVERTERS_43_INL_H_ - -#define X(TYPE) \ -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ - v8::EscapableHandleScope scope(isolate); \ - return scope.Escape( \ - val->To ## TYPE(isolate->GetCurrentContext()) \ - .FromMaybe(v8::Local())); \ -} - -X(Number) -X(String) -X(Object) -X(Integer) -X(Uint32) -X(Int32) -// V8 <= 7.0 -#if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0) -X(Boolean) -#else -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ - v8::EscapableHandleScope scope(isolate); \ - return scope.Escape(val->ToBoolean(isolate)); \ -} -#endif - -#undef X - -#define X(TYPE, NAME) \ -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ - v8::HandleScope scope(isolate); \ - return val->NAME ## Value(isolate->GetCurrentContext()); \ -} - -X(double, Number) -X(int64_t, Integer) -X(uint32_t, Uint32) -X(int32_t, Int32) -// V8 <= 7.0 -#if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0) -X(bool, Boolean) -#else -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ - v8::HandleScope scope(isolate); \ - return Just(val->BooleanValue(isolate)); \ -} -#endif - -#undef X - -#endif // NAN_CONVERTERS_43_INL_H_ diff --git a/reverse_engineering/node_modules/nan/nan_converters_pre_43_inl.h b/reverse_engineering/node_modules/nan/nan_converters_pre_43_inl.h deleted file mode 100644 index ae0518a..0000000 --- a/reverse_engineering/node_modules/nan/nan_converters_pre_43_inl.h +++ /dev/null @@ -1,42 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CONVERTERS_PRE_43_INL_H_ -#define NAN_CONVERTERS_PRE_43_INL_H_ - -#define X(TYPE) \ -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - return val->To ## TYPE(); \ -} - -X(Boolean) -X(Number) -X(String) -X(Object) -X(Integer) -X(Uint32) -X(Int32) - -#undef X - -#define X(TYPE, NAME) \ -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - return Just(val->NAME ## Value()); \ -} - -X(bool, Boolean) -X(double, Number) -X(int64_t, Integer) -X(uint32_t, Uint32) -X(int32_t, Int32) - -#undef X - -#endif // NAN_CONVERTERS_PRE_43_INL_H_ diff --git a/reverse_engineering/node_modules/nan/nan_define_own_property_helper.h b/reverse_engineering/node_modules/nan/nan_define_own_property_helper.h deleted file mode 100644 index d710ef2..0000000 --- a/reverse_engineering/node_modules/nan/nan_define_own_property_helper.h +++ /dev/null @@ -1,29 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_DEFINE_OWN_PROPERTY_HELPER_H_ -#define NAN_DEFINE_OWN_PROPERTY_HELPER_H_ - -namespace imp { - -inline Maybe DefineOwnPropertyHelper( - v8::PropertyAttribute current - , v8::Handle obj - , v8::Handle key - , v8::Handle value - , v8::PropertyAttribute attribs = v8::None) { - return !(current & v8::DontDelete) || // configurable OR - (!(current & v8::ReadOnly) && // writable AND - !((attribs ^ current) & ~v8::ReadOnly)) // same excluding RO - ? Just(obj->ForceSet(key, value, attribs)) - : Nothing(); -} - -} // end of namespace imp - -#endif // NAN_DEFINE_OWN_PROPERTY_HELPER_H_ diff --git a/reverse_engineering/node_modules/nan/nan_implementation_12_inl.h b/reverse_engineering/node_modules/nan/nan_implementation_12_inl.h deleted file mode 100644 index 255293a..0000000 --- a/reverse_engineering/node_modules/nan/nan_implementation_12_inl.h +++ /dev/null @@ -1,430 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_IMPLEMENTATION_12_INL_H_ -#define NAN_IMPLEMENTATION_12_INL_H_ -//============================================================================== -// node v0.11 implementation -//============================================================================== - -namespace imp { - -//=== Array ==================================================================== - -Factory::return_t -Factory::New() { - return v8::Array::New(v8::Isolate::GetCurrent()); -} - -Factory::return_t -Factory::New(int length) { - return v8::Array::New(v8::Isolate::GetCurrent(), length); -} - -//=== Boolean ================================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::Boolean::New(v8::Isolate::GetCurrent(), value); -} - -//=== Boolean Object =========================================================== - -Factory::return_t -Factory::New(bool value) { -#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) - return v8::BooleanObject::New( - v8::Isolate::GetCurrent(), value).As(); -#else - return v8::BooleanObject::New(value).As(); -#endif -} - -//=== Context ================================================================== - -Factory::return_t -Factory::New( v8::ExtensionConfiguration* extensions - , v8::Local tmpl - , v8::Local obj) { - return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj); -} - -//=== Date ===================================================================== - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -Factory::return_t -Factory::New(double value) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(v8::Date::New(isolate->GetCurrentContext(), value) - .FromMaybe(v8::Local()).As()); -} -#else -Factory::return_t -Factory::New(double value) { - return v8::Date::New(v8::Isolate::GetCurrent(), value).As(); -} -#endif - -//=== External ================================================================= - -Factory::return_t -Factory::New(void * value) { - return v8::External::New(v8::Isolate::GetCurrent(), value); -} - -//=== Function ================================================================= - -Factory::return_t -Factory::New( FunctionCallback callback - , v8::Local data) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::Local tpl = v8::ObjectTemplate::New(isolate); - tpl->SetInternalFieldCount(imp::kFunctionFieldCount); - v8::Local obj = NewInstance(tpl).ToLocalChecked(); - - obj->SetInternalField( - imp::kFunctionIndex - , v8::External::New(isolate, reinterpret_cast(callback))); - - v8::Local val = v8::Local::New(isolate, data); - - if (!val.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, val); - } - -#if NODE_MAJOR_VERSION >= 10 - v8::Local context = isolate->GetCurrentContext(); - v8::Local function = - v8::Function::New(context, imp::FunctionCallbackWrapper, obj) - .ToLocalChecked(); -#else - v8::Local function = - v8::Function::New(isolate, imp::FunctionCallbackWrapper, obj); -#endif - - return scope.Escape(function); -} - -//=== Function Template ======================================================== - -Factory::return_t -Factory::New( FunctionCallback callback - , v8::Local data - , v8::Local signature) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - if (callback) { - v8::EscapableHandleScope scope(isolate); - v8::Local tpl = v8::ObjectTemplate::New(isolate); - tpl->SetInternalFieldCount(imp::kFunctionFieldCount); - v8::Local obj = NewInstance(tpl).ToLocalChecked(); - - obj->SetInternalField( - imp::kFunctionIndex - , v8::External::New(isolate, reinterpret_cast(callback))); - v8::Local val = v8::Local::New(isolate, data); - - if (!val.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, val); - } - - return scope.Escape(v8::FunctionTemplate::New( isolate - , imp::FunctionCallbackWrapper - , obj - , signature)); - } else { - return v8::FunctionTemplate::New(isolate, 0, data, signature); - } -} - -//=== Number =================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Number::New(v8::Isolate::GetCurrent(), value); -} - -//=== Number Object ============================================================ - -Factory::return_t -Factory::New(double value) { - return v8::NumberObject::New( v8::Isolate::GetCurrent() - , value).As(); -} - -//=== Integer, Int32 and Uint32 ================================================ - -template -typename IntegerFactory::return_t -IntegerFactory::New(int32_t value) { - return To(T::New(v8::Isolate::GetCurrent(), value)); -} - -template -typename IntegerFactory::return_t -IntegerFactory::New(uint32_t value) { - return To(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -Factory::return_t -Factory::New(int32_t value) { - return To( - v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -Factory::return_t -Factory::New(uint32_t value) { - return To( - v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -//=== Object =================================================================== - -Factory::return_t -Factory::New() { - return v8::Object::New(v8::Isolate::GetCurrent()); -} - -//=== Object Template ========================================================== - -Factory::return_t -Factory::New() { - return v8::ObjectTemplate::New(v8::Isolate::GetCurrent()); -} - -//=== RegExp =================================================================== - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -Factory::return_t -Factory::New( - v8::Local pattern - , v8::RegExp::Flags flags) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - v8::RegExp::New(isolate->GetCurrentContext(), pattern, flags) - .FromMaybe(v8::Local())); -} -#else -Factory::return_t -Factory::New( - v8::Local pattern - , v8::RegExp::Flags flags) { - return v8::RegExp::New(pattern, flags); -} -#endif - -//=== Script =================================================================== - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -Factory::return_t -Factory::New( v8::Local source) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::ScriptCompiler::Source src(source); - return scope.Escape( - v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src) - .FromMaybe(v8::Local())); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::ScriptCompiler::Source src(source, origin); - return scope.Escape( - v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src) - .FromMaybe(v8::Local())); -} -#else -Factory::return_t -Factory::New( v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); -} -#endif - -//=== Signature ================================================================ - -Factory::return_t -Factory::New(Factory::FTH receiver) { - return v8::Signature::New(v8::Isolate::GetCurrent(), receiver); -} - -//=== String =================================================================== - -Factory::return_t -Factory::New() { - return v8::String::Empty(v8::Isolate::GetCurrent()); -} - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::NewFromUtf8( - v8::Isolate::GetCurrent(), value, v8::NewStringType::kNormal, length); -} - -Factory::return_t -Factory::New(std::string const& value) { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), - value.data(), v8::NewStringType::kNormal, static_cast(value.size())); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, - v8::NewStringType::kNormal, length); -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternalTwoByte(v8::Isolate::GetCurrent(), value); -} - -Factory::return_t -Factory::New(ExternalOneByteStringResource * value) { - return v8::String::NewExternalOneByte(v8::Isolate::GetCurrent(), value); -} -#else -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New( - std::string const& value) /* NOLINT(build/include_what_you_use) */ { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value.data(), - v8::String::kNormalString, - static_cast(value.size())); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); -} - -Factory::return_t -Factory::New(ExternalOneByteStringResource * value) { - return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); -} -#endif - -//=== String Object ============================================================ - -// See https://github.com/nodejs/nan/pull/811#discussion_r224594980. -// Disable the warning as there is no way around it. -// TODO(bnoordhuis) Use isolate-based version in Node.js v12. -Factory::return_t -Factory::New(v8::Local value) { -// V8 > 7.0 -#if V8_MAJOR_VERSION > 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION > 0) - return v8::StringObject::New(v8::Isolate::GetCurrent(), value) - .As(); -#else -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4996) -#endif -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - return v8::StringObject::New(value).As(); -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif -#ifdef _MSC_VER -#pragma warning(pop) -#endif -#endif -} - -//=== Unbound Script =========================================================== - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -Factory::return_t -Factory::New(v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::CompileUnboundScript( - v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::CompileUnboundScript( - v8::Isolate::GetCurrent(), &src); -} -#else -Factory::return_t -Factory::New(v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); -} -#endif - -} // end of namespace imp - -//=== Presistents and Handles ================================================== - -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION -template -inline v8::Local New(v8::Handle h) { - return v8::Local::New(v8::Isolate::GetCurrent(), h); -} -#endif - -template -inline v8::Local New(v8::Persistent const& p) { - return v8::Local::New(v8::Isolate::GetCurrent(), p); -} - -template -inline v8::Local New(Persistent const& p) { - return v8::Local::New(v8::Isolate::GetCurrent(), p); -} - -template -inline v8::Local New(Global const& p) { - return v8::Local::New(v8::Isolate::GetCurrent(), p); -} - -#endif // NAN_IMPLEMENTATION_12_INL_H_ diff --git a/reverse_engineering/node_modules/nan/nan_implementation_pre_12_inl.h b/reverse_engineering/node_modules/nan/nan_implementation_pre_12_inl.h deleted file mode 100644 index 1472421..0000000 --- a/reverse_engineering/node_modules/nan/nan_implementation_pre_12_inl.h +++ /dev/null @@ -1,263 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_ -#define NAN_IMPLEMENTATION_PRE_12_INL_H_ - -//============================================================================== -// node v0.10 implementation -//============================================================================== - -namespace imp { - -//=== Array ==================================================================== - -Factory::return_t -Factory::New() { - return v8::Array::New(); -} - -Factory::return_t -Factory::New(int length) { - return v8::Array::New(length); -} - -//=== Boolean ================================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::Boolean::New(value)->ToBoolean(); -} - -//=== Boolean Object =========================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::BooleanObject::New(value).As(); -} - -//=== Context ================================================================== - -Factory::return_t -Factory::New( v8::ExtensionConfiguration* extensions - , v8::Local tmpl - , v8::Local obj) { - v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); - v8::Local lctx = v8::Local::New(ctx); - ctx.Dispose(); - return lctx; -} - -//=== Date ===================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Date::New(value).As(); -} - -//=== External ================================================================= - -Factory::return_t -Factory::New(void * value) { - return v8::External::New(value); -} - -//=== Function ================================================================= - -Factory::return_t -Factory::New( FunctionCallback callback - , v8::Local data) { - v8::HandleScope scope; - - return scope.Close(Factory::New( - callback, data, v8::Local()) - ->GetFunction()); -} - - -//=== FunctionTemplate ========================================================= - -Factory::return_t -Factory::New( FunctionCallback callback - , v8::Local data - , v8::Local signature) { - if (callback) { - v8::HandleScope scope; - - v8::Local tpl = v8::ObjectTemplate::New(); - tpl->SetInternalFieldCount(imp::kFunctionFieldCount); - v8::Local obj = tpl->NewInstance(); - - obj->SetInternalField( - imp::kFunctionIndex - , v8::External::New(reinterpret_cast(callback))); - - v8::Local val = v8::Local::New(data); - - if (!val.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, val); - } - - // Note(agnat): Emulate length argument here. Unfortunately, I couldn't find - // a way. Have at it though... - return scope.Close( - v8::FunctionTemplate::New(imp::FunctionCallbackWrapper - , obj - , signature)); - } else { - return v8::FunctionTemplate::New(0, data, signature); - } -} - -//=== Number =================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Number::New(value); -} - -//=== Number Object ============================================================ - -Factory::return_t -Factory::New(double value) { - return v8::NumberObject::New(value).As(); -} - -//=== Integer, Int32 and Uint32 ================================================ - -template -typename IntegerFactory::return_t -IntegerFactory::New(int32_t value) { - return To(T::New(value)); -} - -template -typename IntegerFactory::return_t -IntegerFactory::New(uint32_t value) { - return To(T::NewFromUnsigned(value)); -} - -Factory::return_t -Factory::New(int32_t value) { - return To(v8::Uint32::NewFromUnsigned(value)); -} - -Factory::return_t -Factory::New(uint32_t value) { - return To(v8::Uint32::NewFromUnsigned(value)); -} - - -//=== Object =================================================================== - -Factory::return_t -Factory::New() { - return v8::Object::New(); -} - -//=== Object Template ========================================================== - -Factory::return_t -Factory::New() { - return v8::ObjectTemplate::New(); -} - -//=== RegExp =================================================================== - -Factory::return_t -Factory::New( - v8::Local pattern - , v8::RegExp::Flags flags) { - return v8::RegExp::New(pattern, flags); -} - -//=== Script =================================================================== - -Factory::return_t -Factory::New( v8::Local source) { - return v8::Script::New(source); -} -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - return v8::Script::New(source, const_cast(&origin)); -} - -//=== Signature ================================================================ - -Factory::return_t -Factory::New(Factory::FTH receiver) { - return v8::Signature::New(receiver); -} - -//=== String =================================================================== - -Factory::return_t -Factory::New() { - return v8::String::Empty(); -} - -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::New(value, length); -} - -Factory::return_t -Factory::New( - std::string const& value) /* NOLINT(build/include_what_you_use) */ { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::New(value.data(), static_cast(value.size())); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::New(value, length); -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternal(value); -} - -Factory::return_t -Factory::New(v8::String::ExternalAsciiStringResource * value) { - return v8::String::NewExternal(value); -} - -//=== String Object ============================================================ - -Factory::return_t -Factory::New(v8::Local value) { - return v8::StringObject::New(value).As(); -} - -} // end of namespace imp - -//=== Presistents and Handles ================================================== - -template -inline v8::Local New(v8::Handle h) { - return v8::Local::New(h); -} - -template -inline v8::Local New(v8::Persistent const& p) { - return v8::Local::New(p); -} - -template -inline v8::Local New(Persistent const& p) { - return v8::Local::New(p.persistent); -} - -template -inline v8::Local New(Global const& p) { - return v8::Local::New(p.persistent); -} - -#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_ diff --git a/reverse_engineering/node_modules/nan/nan_json.h b/reverse_engineering/node_modules/nan/nan_json.h deleted file mode 100644 index 33ac8ba..0000000 --- a/reverse_engineering/node_modules/nan/nan_json.h +++ /dev/null @@ -1,166 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_JSON_H_ -#define NAN_JSON_H_ - -#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION -#define NAN_JSON_H_NEED_PARSE 1 -#else -#define NAN_JSON_H_NEED_PARSE 0 -#endif // NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION - -#if NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION -#define NAN_JSON_H_NEED_STRINGIFY 0 -#else -#define NAN_JSON_H_NEED_STRINGIFY 1 -#endif // NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION - -class JSON { - public: - JSON() { -#if NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY - Nan::HandleScope scope; - - Nan::MaybeLocal maybe_global_json = Nan::Get( - Nan::GetCurrentContext()->Global(), - Nan::New("JSON").ToLocalChecked() - ); - - assert(!maybe_global_json.IsEmpty() && "global JSON is empty"); - v8::Local val_global_json = maybe_global_json.ToLocalChecked(); - - assert(val_global_json->IsObject() && "global JSON is not an object"); - Nan::MaybeLocal maybe_obj_global_json = - Nan::To(val_global_json); - - assert(!maybe_obj_global_json.IsEmpty() && "global JSON object is empty"); - v8::Local global_json = maybe_obj_global_json.ToLocalChecked(); - -#if NAN_JSON_H_NEED_PARSE - Nan::MaybeLocal maybe_parse_method = Nan::Get( - global_json, Nan::New("parse").ToLocalChecked() - ); - - assert(!maybe_parse_method.IsEmpty() && "JSON.parse is empty"); - v8::Local parse_method = maybe_parse_method.ToLocalChecked(); - - assert(parse_method->IsFunction() && "JSON.parse is not a function"); - parse_cb_.Reset(parse_method.As()); -#endif // NAN_JSON_H_NEED_PARSE - -#if NAN_JSON_H_NEED_STRINGIFY - Nan::MaybeLocal maybe_stringify_method = Nan::Get( - global_json, Nan::New("stringify").ToLocalChecked() - ); - - assert(!maybe_stringify_method.IsEmpty() && "JSON.stringify is empty"); - v8::Local stringify_method = - maybe_stringify_method.ToLocalChecked(); - - assert( - stringify_method->IsFunction() && "JSON.stringify is not a function" - ); - stringify_cb_.Reset(stringify_method.As()); -#endif // NAN_JSON_H_NEED_STRINGIFY -#endif // NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY - } - - inline - Nan::MaybeLocal Parse(v8::Local json_string) { - Nan::EscapableHandleScope scope; -#if NAN_JSON_H_NEED_PARSE - return scope.Escape(parse(json_string)); -#else - Nan::MaybeLocal result; -#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION && \ - NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION - result = v8::JSON::Parse(json_string); -#else -#if NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION - v8::Local context_or_isolate = Nan::GetCurrentContext(); -#else - v8::Isolate* context_or_isolate = v8::Isolate::GetCurrent(); -#endif // NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION - result = v8::JSON::Parse(context_or_isolate, json_string); -#endif // NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION && - // NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION - if (result.IsEmpty()) return v8::Local(); - return scope.Escape(result.ToLocalChecked()); -#endif // NAN_JSON_H_NEED_PARSE - } - - inline - Nan::MaybeLocal Stringify(v8::Local json_object) { - Nan::EscapableHandleScope scope; - Nan::MaybeLocal result = -#if NAN_JSON_H_NEED_STRINGIFY - Nan::To(stringify(json_object)); -#else - v8::JSON::Stringify(Nan::GetCurrentContext(), json_object); -#endif // NAN_JSON_H_NEED_STRINGIFY - if (result.IsEmpty()) return v8::Local(); - return scope.Escape(result.ToLocalChecked()); - } - - inline - Nan::MaybeLocal Stringify(v8::Local json_object, - v8::Local gap) { - Nan::EscapableHandleScope scope; - Nan::MaybeLocal result = -#if NAN_JSON_H_NEED_STRINGIFY - Nan::To(stringify(json_object, gap)); -#else - v8::JSON::Stringify(Nan::GetCurrentContext(), json_object, gap); -#endif // NAN_JSON_H_NEED_STRINGIFY - if (result.IsEmpty()) return v8::Local(); - return scope.Escape(result.ToLocalChecked()); - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(JSON) -#if NAN_JSON_H_NEED_PARSE - Nan::Callback parse_cb_; -#endif // NAN_JSON_H_NEED_PARSE -#if NAN_JSON_H_NEED_STRINGIFY - Nan::Callback stringify_cb_; -#endif // NAN_JSON_H_NEED_STRINGIFY - -#if NAN_JSON_H_NEED_PARSE - inline v8::Local parse(v8::Local arg) { - assert(!parse_cb_.IsEmpty() && "parse_cb_ is empty"); - AsyncResource resource("nan:JSON.parse"); - return parse_cb_.Call(1, &arg, &resource).FromMaybe(v8::Local()); - } -#endif // NAN_JSON_H_NEED_PARSE - -#if NAN_JSON_H_NEED_STRINGIFY - inline v8::Local stringify(v8::Local arg) { - assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty"); - AsyncResource resource("nan:JSON.stringify"); - return stringify_cb_.Call(1, &arg, &resource) - .FromMaybe(v8::Local()); - } - - inline v8::Local stringify(v8::Local arg, - v8::Local gap) { - assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty"); - - v8::Local argv[] = { - arg, - Nan::Null(), - gap - }; - AsyncResource resource("nan:JSON.stringify"); - return stringify_cb_.Call(3, argv, &resource) - .FromMaybe(v8::Local()); - } -#endif // NAN_JSON_H_NEED_STRINGIFY -}; - -#endif // NAN_JSON_H_ diff --git a/reverse_engineering/node_modules/nan/nan_maybe_43_inl.h b/reverse_engineering/node_modules/nan/nan_maybe_43_inl.h deleted file mode 100644 index c04ce30..0000000 --- a/reverse_engineering/node_modules/nan/nan_maybe_43_inl.h +++ /dev/null @@ -1,356 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_MAYBE_43_INL_H_ -#define NAN_MAYBE_43_INL_H_ - -template -using MaybeLocal = v8::MaybeLocal; - -inline -MaybeLocal ToDetailString(v8::Local val) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(val->ToDetailString(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal ToArrayIndex(v8::Local val) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(val->ToArrayIndex(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline -Maybe Equals(v8::Local a, v8::Local(b)) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return a->Equals(isolate->GetCurrentContext(), b); -} - -inline -MaybeLocal NewInstance(v8::Local h) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(h->NewInstance(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal NewInstance( - v8::Local h - , int argc - , v8::Local argv[]) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(h->NewInstance(isolate->GetCurrentContext(), argc, argv) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal NewInstance(v8::Local h) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(h->NewInstance(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - - -inline MaybeLocal GetFunction( - v8::Local t) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(t->GetFunction(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline Maybe Set( - v8::Local obj - , v8::Local key - , v8::Local value) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Set(isolate->GetCurrentContext(), key, value); -} - -inline Maybe Set( - v8::Local obj - , uint32_t index - , v8::Local value) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Set(isolate->GetCurrentContext(), index, value); -} - -#if NODE_MODULE_VERSION < NODE_4_0_MODULE_VERSION -#include "nan_define_own_property_helper.h" // NOLINT(build/include) -#endif - -inline Maybe DefineOwnProperty( - v8::Local obj - , v8::Local key - , v8::Local value - , v8::PropertyAttribute attribs = v8::None) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); -#if NODE_MODULE_VERSION >= NODE_4_0_MODULE_VERSION - return obj->DefineOwnProperty(isolate->GetCurrentContext(), key, value, - attribs); -#else - Maybe maybeCurrent = - obj->GetPropertyAttributes(isolate->GetCurrentContext(), key); - if (maybeCurrent.IsNothing()) { - return Nothing(); - } - v8::PropertyAttribute current = maybeCurrent.FromJust(); - return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs); -#endif -} - -NAN_DEPRECATED inline Maybe ForceSet( - v8::Local obj - , v8::Local key - , v8::Local value - , v8::PropertyAttribute attribs = v8::None) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - return key->IsName() - ? obj->DefineOwnProperty(isolate->GetCurrentContext(), - key.As(), value, attribs) - : Nothing(); -#else - return obj->ForceSet(isolate->GetCurrentContext(), key, value, attribs); -#endif -} - -inline MaybeLocal Get( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->Get(isolate->GetCurrentContext(), key) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal Get(v8::Local obj, uint32_t index) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->Get(isolate->GetCurrentContext(), index) - .FromMaybe(v8::Local())); -} - -inline v8::PropertyAttribute GetPropertyAttributes( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->GetPropertyAttributes(isolate->GetCurrentContext(), key) - .FromJust(); -} - -inline Maybe Has( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Has(isolate->GetCurrentContext(), key); -} - -inline Maybe Has(v8::Local obj, uint32_t index) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Has(isolate->GetCurrentContext(), index); -} - -inline Maybe Delete( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Delete(isolate->GetCurrentContext(), key); -} - -inline -Maybe Delete(v8::Local obj, uint32_t index) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Delete(isolate->GetCurrentContext(), index); -} - -inline -MaybeLocal GetPropertyNames(v8::Local obj) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->GetPropertyNames(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal GetOwnPropertyNames(v8::Local obj) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->GetOwnPropertyNames(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline Maybe SetPrototype( - v8::Local obj - , v8::Local prototype) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->SetPrototype(isolate->GetCurrentContext(), prototype); -} - -inline MaybeLocal ObjectProtoToString( - v8::Local obj) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->ObjectProtoToString(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline Maybe HasOwnProperty( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->HasOwnProperty(isolate->GetCurrentContext(), key); -} - -inline Maybe HasRealNamedProperty( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->HasRealNamedProperty(isolate->GetCurrentContext(), key); -} - -inline Maybe HasRealIndexedProperty( - v8::Local obj - , uint32_t index) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->HasRealIndexedProperty(isolate->GetCurrentContext(), index); -} - -inline Maybe HasRealNamedCallbackProperty( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->HasRealNamedCallbackProperty(isolate->GetCurrentContext(), key); -} - -inline MaybeLocal GetRealNamedPropertyInPrototypeChain( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->GetRealNamedPropertyInPrototypeChain( - isolate->GetCurrentContext(), key) - .FromMaybe(v8::Local())); -} - -inline MaybeLocal GetRealNamedProperty( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - obj->GetRealNamedProperty(isolate->GetCurrentContext(), key) - .FromMaybe(v8::Local())); -} - -inline MaybeLocal CallAsFunction( - v8::Local obj - , v8::Local recv - , int argc - , v8::Local argv[]) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - obj->CallAsFunction(isolate->GetCurrentContext(), recv, argc, argv) - .FromMaybe(v8::Local())); -} - -inline MaybeLocal CallAsConstructor( - v8::Local obj - , int argc, v8::Local argv[]) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - obj->CallAsConstructor(isolate->GetCurrentContext(), argc, argv) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal GetSourceLine(v8::Local msg) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(msg->GetSourceLine(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline Maybe GetLineNumber(v8::Local msg) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return msg->GetLineNumber(isolate->GetCurrentContext()); -} - -inline Maybe GetStartColumn(v8::Local msg) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return msg->GetStartColumn(isolate->GetCurrentContext()); -} - -inline Maybe GetEndColumn(v8::Local msg) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return msg->GetEndColumn(isolate->GetCurrentContext()); -} - -inline MaybeLocal CloneElementAt( - v8::Local array - , uint32_t index) { -#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::Local context = isolate->GetCurrentContext(); - v8::Local elem; - v8::Local obj; - if (!array->Get(context, index).ToLocal(&elem)) { - return scope.Escape(obj); - } - if (!elem->ToObject(context).ToLocal(&obj)) { - return scope.Escape(v8::Local()); - } - return scope.Escape(obj->Clone()); -#else - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(array->CloneElementAt(isolate->GetCurrentContext(), index) - .FromMaybe(v8::Local())); -#endif -} - -inline MaybeLocal Call( - v8::Local fun - , v8::Local recv - , int argc - , v8::Local argv[]) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(fun->Call(isolate->GetCurrentContext(), recv, argc, argv) - .FromMaybe(v8::Local())); -} - -#endif // NAN_MAYBE_43_INL_H_ diff --git a/reverse_engineering/node_modules/nan/nan_maybe_pre_43_inl.h b/reverse_engineering/node_modules/nan/nan_maybe_pre_43_inl.h deleted file mode 100644 index 83325ae..0000000 --- a/reverse_engineering/node_modules/nan/nan_maybe_pre_43_inl.h +++ /dev/null @@ -1,268 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_MAYBE_PRE_43_INL_H_ -#define NAN_MAYBE_PRE_43_INL_H_ - -template -class MaybeLocal { - public: - inline MaybeLocal() : val_(v8::Local()) {} - - template -# if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION - inline - MaybeLocal(v8::Local that) : val_(that) {} // NOLINT(runtime/explicit) -# else - inline - MaybeLocal(v8::Local that) : // NOLINT(runtime/explicit) - val_(*reinterpret_cast*>(&that)) {} -# endif - - inline bool IsEmpty() const { return val_.IsEmpty(); } - - template - inline bool ToLocal(v8::Local *out) const { - *out = val_; - return !IsEmpty(); - } - - inline v8::Local ToLocalChecked() const { -#if defined(V8_ENABLE_CHECKS) - assert(!IsEmpty() && "ToLocalChecked is Empty"); -#endif // V8_ENABLE_CHECKS - return val_; - } - - template - inline v8::Local FromMaybe(v8::Local default_value) const { - return IsEmpty() ? default_value : v8::Local(val_); - } - - private: - v8::Local val_; -}; - -inline -MaybeLocal ToDetailString(v8::Handle val) { - return MaybeLocal(val->ToDetailString()); -} - -inline -MaybeLocal ToArrayIndex(v8::Handle val) { - return MaybeLocal(val->ToArrayIndex()); -} - -inline -Maybe Equals(v8::Handle a, v8::Handle(b)) { - return Just(a->Equals(b)); -} - -inline -MaybeLocal NewInstance(v8::Handle h) { - return MaybeLocal(h->NewInstance()); -} - -inline -MaybeLocal NewInstance( - v8::Local h - , int argc - , v8::Local argv[]) { - return MaybeLocal(h->NewInstance(argc, argv)); -} - -inline -MaybeLocal NewInstance(v8::Handle h) { - return MaybeLocal(h->NewInstance()); -} - -inline -MaybeLocal GetFunction(v8::Handle t) { - return MaybeLocal(t->GetFunction()); -} - -inline Maybe Set( - v8::Handle obj - , v8::Handle key - , v8::Handle value) { - return Just(obj->Set(key, value)); -} - -inline Maybe Set( - v8::Handle obj - , uint32_t index - , v8::Handle value) { - return Just(obj->Set(index, value)); -} - -#include "nan_define_own_property_helper.h" // NOLINT(build/include) - -inline Maybe DefineOwnProperty( - v8::Handle obj - , v8::Handle key - , v8::Handle value - , v8::PropertyAttribute attribs = v8::None) { - v8::PropertyAttribute current = obj->GetPropertyAttributes(key); - return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs); -} - -NAN_DEPRECATED inline Maybe ForceSet( - v8::Handle obj - , v8::Handle key - , v8::Handle value - , v8::PropertyAttribute attribs = v8::None) { - return Just(obj->ForceSet(key, value, attribs)); -} - -inline MaybeLocal Get( - v8::Handle obj - , v8::Handle key) { - return MaybeLocal(obj->Get(key)); -} - -inline MaybeLocal Get( - v8::Handle obj - , uint32_t index) { - return MaybeLocal(obj->Get(index)); -} - -inline Maybe GetPropertyAttributes( - v8::Handle obj - , v8::Handle key) { - return Just(obj->GetPropertyAttributes(key)); -} - -inline Maybe Has( - v8::Handle obj - , v8::Handle key) { - return Just(obj->Has(key)); -} - -inline Maybe Has( - v8::Handle obj - , uint32_t index) { - return Just(obj->Has(index)); -} - -inline Maybe Delete( - v8::Handle obj - , v8::Handle key) { - return Just(obj->Delete(key)); -} - -inline Maybe Delete( - v8::Handle obj - , uint32_t index) { - return Just(obj->Delete(index)); -} - -inline -MaybeLocal GetPropertyNames(v8::Handle obj) { - return MaybeLocal(obj->GetPropertyNames()); -} - -inline -MaybeLocal GetOwnPropertyNames(v8::Handle obj) { - return MaybeLocal(obj->GetOwnPropertyNames()); -} - -inline Maybe SetPrototype( - v8::Handle obj - , v8::Handle prototype) { - return Just(obj->SetPrototype(prototype)); -} - -inline MaybeLocal ObjectProtoToString( - v8::Handle obj) { - return MaybeLocal(obj->ObjectProtoToString()); -} - -inline Maybe HasOwnProperty( - v8::Handle obj - , v8::Handle key) { - return Just(obj->HasOwnProperty(key)); -} - -inline Maybe HasRealNamedProperty( - v8::Handle obj - , v8::Handle key) { - return Just(obj->HasRealNamedProperty(key)); -} - -inline Maybe HasRealIndexedProperty( - v8::Handle obj - , uint32_t index) { - return Just(obj->HasRealIndexedProperty(index)); -} - -inline Maybe HasRealNamedCallbackProperty( - v8::Handle obj - , v8::Handle key) { - return Just(obj->HasRealNamedCallbackProperty(key)); -} - -inline MaybeLocal GetRealNamedPropertyInPrototypeChain( - v8::Handle obj - , v8::Handle key) { - return MaybeLocal( - obj->GetRealNamedPropertyInPrototypeChain(key)); -} - -inline MaybeLocal GetRealNamedProperty( - v8::Handle obj - , v8::Handle key) { - return MaybeLocal(obj->GetRealNamedProperty(key)); -} - -inline MaybeLocal CallAsFunction( - v8::Handle obj - , v8::Handle recv - , int argc - , v8::Handle argv[]) { - return MaybeLocal(obj->CallAsFunction(recv, argc, argv)); -} - -inline MaybeLocal CallAsConstructor( - v8::Handle obj - , int argc - , v8::Local argv[]) { - return MaybeLocal(obj->CallAsConstructor(argc, argv)); -} - -inline -MaybeLocal GetSourceLine(v8::Handle msg) { - return MaybeLocal(msg->GetSourceLine()); -} - -inline Maybe GetLineNumber(v8::Handle msg) { - return Just(msg->GetLineNumber()); -} - -inline Maybe GetStartColumn(v8::Handle msg) { - return Just(msg->GetStartColumn()); -} - -inline Maybe GetEndColumn(v8::Handle msg) { - return Just(msg->GetEndColumn()); -} - -inline MaybeLocal CloneElementAt( - v8::Handle array - , uint32_t index) { - return MaybeLocal(array->CloneElementAt(index)); -} - -inline MaybeLocal Call( - v8::Local fun - , v8::Local recv - , int argc - , v8::Local argv[]) { - return MaybeLocal(fun->Call(recv, argc, argv)); -} - -#endif // NAN_MAYBE_PRE_43_INL_H_ diff --git a/reverse_engineering/node_modules/nan/nan_new.h b/reverse_engineering/node_modules/nan/nan_new.h deleted file mode 100644 index cdf8bbe..0000000 --- a/reverse_engineering/node_modules/nan/nan_new.h +++ /dev/null @@ -1,340 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_NEW_H_ -#define NAN_NEW_H_ - -namespace imp { // scnr - -// TODO(agnat): Generalize -template v8::Local To(v8::Local i); - -template <> -inline -v8::Local -To(v8::Local i) { - return Nan::To(i).ToLocalChecked(); -} - -template <> -inline -v8::Local -To(v8::Local i) { - return Nan::To(i).ToLocalChecked(); -} - -template <> -inline -v8::Local -To(v8::Local i) { - return Nan::To(i).ToLocalChecked(); -} - -template struct FactoryBase { - typedef v8::Local return_t; -}; - -template struct MaybeFactoryBase { - typedef MaybeLocal return_t; -}; - -template struct Factory; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); - static inline return_t New(int length); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(bool value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(bool value); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( v8::ExtensionConfiguration* extensions = NULL - , v8::Local tmpl = v8::Local() - , v8::Local obj = v8::Local()); -}; - -template <> -struct Factory : MaybeFactoryBase { - static inline return_t New(double value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(void *value); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( FunctionCallback callback - , v8::Local data = v8::Local()); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( FunctionCallback callback = NULL - , v8::Local data = v8::Local() - , v8::Local signature = v8::Local()); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template -struct IntegerFactory : FactoryBase { - typedef typename FactoryBase::return_t return_t; - static inline return_t New(int32_t value); - static inline return_t New(uint32_t value); -}; - -template <> -struct Factory : IntegerFactory {}; - -template <> -struct Factory : IntegerFactory {}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(int32_t value); - static inline return_t New(uint32_t value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); -}; - -template <> -struct Factory : MaybeFactoryBase { - static inline return_t New( - v8::Local pattern, v8::RegExp::Flags flags); -}; - -template <> -struct Factory : MaybeFactoryBase { - static inline return_t New( v8::Local source); - static inline return_t New( v8::Local source - , v8::ScriptOrigin const& origin); -}; - -template <> -struct Factory : FactoryBase { - typedef v8::Local FTH; - static inline return_t New(FTH receiver = FTH()); -}; - -template <> -struct Factory : MaybeFactoryBase { - static inline return_t New(); - static inline return_t New(const char *value, int length = -1); - static inline return_t New(const uint16_t *value, int length = -1); - static inline return_t New(std::string const& value); - - static inline return_t New(v8::String::ExternalStringResource * value); - static inline return_t New(ExternalOneByteStringResource * value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(v8::Local value); -}; - -} // end of namespace imp - -#if (NODE_MODULE_VERSION >= 12) - -namespace imp { - -template <> -struct Factory : MaybeFactoryBase { - static inline return_t New( v8::Local source); - static inline return_t New( v8::Local source - , v8::ScriptOrigin const& origin); -}; - -} // end of namespace imp - -# include "nan_implementation_12_inl.h" - -#else // NODE_MODULE_VERSION >= 12 - -# include "nan_implementation_pre_12_inl.h" - -#endif - -//=== API ====================================================================== - -template -typename imp::Factory::return_t -New() { - return imp::Factory::New(); -} - -template -typename imp::Factory::return_t -New(A0 arg0) { - return imp::Factory::New(arg0); -} - -template -typename imp::Factory::return_t -New(A0 arg0, A1 arg1) { - return imp::Factory::New(arg0, arg1); -} - -template -typename imp::Factory::return_t -New(A0 arg0, A1 arg1, A2 arg2) { - return imp::Factory::New(arg0, arg1, arg2); -} - -template -typename imp::Factory::return_t -New(A0 arg0, A1 arg1, A2 arg2, A3 arg3) { - return imp::Factory::New(arg0, arg1, arg2, arg3); -} - -// Note(agnat): When passing overloaded function pointers to template functions -// as generic arguments the compiler needs help in picking the right overload. -// These two functions handle New and New with -// all argument variations. - -// v8::Function and v8::FunctionTemplate with one or two arguments -template -typename imp::Factory::return_t -New( FunctionCallback callback - , v8::Local data = v8::Local()) { - return imp::Factory::New(callback, data); -} - -// v8::Function and v8::FunctionTemplate with three arguments -template -typename imp::Factory::return_t -New( FunctionCallback callback - , v8::Local data = v8::Local() - , A2 a2 = A2()) { - return imp::Factory::New(callback, data, a2); -} - -// Convenience - -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION -template inline v8::Local New(v8::Handle h); -#endif - -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION -template - inline v8::Local New(v8::Persistent const& p); -#else -template inline v8::Local New(v8::Persistent const& p); -#endif -template -inline v8::Local New(Persistent const& p); -template -inline v8::Local New(Global const& p); - -inline -imp::Factory::return_t -New(bool value) { - return New(value); -} - -inline -imp::Factory::return_t -New(int32_t value) { - return New(value); -} - -inline -imp::Factory::return_t -New(uint32_t value) { - return New(value); -} - -inline -imp::Factory::return_t -New(double value) { - return New(value); -} - -inline -imp::Factory::return_t -New(std::string const& value) { // NOLINT(build/include_what_you_use) - return New(value); -} - -inline -imp::Factory::return_t -New(const char * value, int length) { - return New(value, length); -} - -inline -imp::Factory::return_t -New(const uint16_t * value, int length) { - return New(value, length); -} - -inline -imp::Factory::return_t -New(const char * value) { - return New(value); -} - -inline -imp::Factory::return_t -New(const uint16_t * value) { - return New(value); -} - -inline -imp::Factory::return_t -New(v8::String::ExternalStringResource * value) { - return New(value); -} - -inline -imp::Factory::return_t -New(ExternalOneByteStringResource * value) { - return New(value); -} - -inline -imp::Factory::return_t -New(v8::Local pattern, v8::RegExp::Flags flags) { - return New(pattern, flags); -} - -#endif // NAN_NEW_H_ diff --git a/reverse_engineering/node_modules/nan/nan_object_wrap.h b/reverse_engineering/node_modules/nan/nan_object_wrap.h deleted file mode 100644 index 78712f9..0000000 --- a/reverse_engineering/node_modules/nan/nan_object_wrap.h +++ /dev/null @@ -1,156 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_OBJECT_WRAP_H_ -#define NAN_OBJECT_WRAP_H_ - -class ObjectWrap { - public: - ObjectWrap() { - refs_ = 0; - } - - - virtual ~ObjectWrap() { - if (persistent().IsEmpty()) { - return; - } - - persistent().ClearWeak(); - persistent().Reset(); - } - - - template - static inline T* Unwrap(v8::Local object) { - assert(!object.IsEmpty()); - assert(object->InternalFieldCount() > 0); - // Cast to ObjectWrap before casting to T. A direct cast from void - // to T won't work right when T has more than one base class. - void* ptr = GetInternalFieldPointer(object, 0); - ObjectWrap* wrap = static_cast(ptr); - return static_cast(wrap); - } - - - inline v8::Local handle() const { - return New(handle_); - } - - - inline Persistent& persistent() { - return handle_; - } - - - protected: - inline void Wrap(v8::Local object) { - assert(persistent().IsEmpty()); - assert(object->InternalFieldCount() > 0); - SetInternalFieldPointer(object, 0, this); - persistent().Reset(object); - MakeWeak(); - } - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - - inline void MakeWeak() { - persistent().v8::PersistentBase::SetWeak( - this, WeakCallback, v8::WeakCallbackType::kParameter); -#if NODE_MAJOR_VERSION < 10 - // FIXME(bnoordhuis) Probably superfluous in older Node.js versions too. - persistent().MarkIndependent(); -#endif - } - -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - - inline void MakeWeak() { - persistent().v8::PersistentBase::SetWeak(this, WeakCallback); - persistent().MarkIndependent(); - } - -#else - - inline void MakeWeak() { - persistent().persistent.MakeWeak(this, WeakCallback); - persistent().MarkIndependent(); - } - -#endif - - /* Ref() marks the object as being attached to an event loop. - * Refed objects will not be garbage collected, even if - * all references are lost. - */ - virtual void Ref() { - assert(!persistent().IsEmpty()); - persistent().ClearWeak(); - refs_++; - } - - /* Unref() marks an object as detached from the event loop. This is its - * default state. When an object with a "weak" reference changes from - * attached to detached state it will be freed. Be careful not to access - * the object after making this call as it might be gone! - * (A "weak reference" means an object that only has a - * persistent handle.) - * - * DO NOT CALL THIS FROM DESTRUCTOR - */ - virtual void Unref() { - assert(!persistent().IsEmpty()); - assert(!persistent().IsWeak()); - assert(refs_ > 0); - if (--refs_ == 0) - MakeWeak(); - } - - int refs_; // ro - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(ObjectWrap) -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - - static void - WeakCallback(v8::WeakCallbackInfo const& info) { - ObjectWrap* wrap = info.GetParameter(); - assert(wrap->refs_ == 0); - wrap->handle_.Reset(); - delete wrap; - } - -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - - static void - WeakCallback(v8::WeakCallbackData const& data) { - ObjectWrap* wrap = data.GetParameter(); - assert(wrap->refs_ == 0); - assert(wrap->handle_.IsNearDeath()); - wrap->handle_.Reset(); - delete wrap; - } - -#else - - static void WeakCallback(v8::Persistent value, void *data) { - ObjectWrap *wrap = static_cast(data); - assert(wrap->refs_ == 0); - assert(wrap->handle_.IsNearDeath()); - wrap->handle_.Reset(); - delete wrap; - } - -#endif - Persistent handle_; -}; - - -#endif // NAN_OBJECT_WRAP_H_ diff --git a/reverse_engineering/node_modules/nan/nan_persistent_12_inl.h b/reverse_engineering/node_modules/nan/nan_persistent_12_inl.h deleted file mode 100644 index d9649e8..0000000 --- a/reverse_engineering/node_modules/nan/nan_persistent_12_inl.h +++ /dev/null @@ -1,132 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_PERSISTENT_12_INL_H_ -#define NAN_PERSISTENT_12_INL_H_ - -template class Persistent : - public v8::Persistent { - public: - inline Persistent() : v8::Persistent() {} - - template inline Persistent(v8::Local that) : - v8::Persistent(v8::Isolate::GetCurrent(), that) {} - - template - inline - Persistent(const v8::Persistent &that) : // NOLINT(runtime/explicit) - v8::Persistent(v8::Isolate::GetCurrent(), that) {} - - inline void Reset() { v8::PersistentBase::Reset(); } - - template - inline void Reset(const v8::Local &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void Reset(const v8::PersistentBase &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type); - - private: - inline T *operator*() const { return *PersistentBase::persistent; } - - template - inline void Copy(const Persistent &that) { - TYPE_CHECK(T, S); - - this->Reset(); - - if (!that.IsEmpty()) { - this->Reset(that); - M::Copy(that, this); - } - } -}; - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -template -class Global : public v8::Global { - public: - inline Global() : v8::Global() {} - - template inline Global(v8::Local that) : - v8::Global(v8::Isolate::GetCurrent(), that) {} - - template - inline - Global(const v8::PersistentBase &that) : // NOLINT(runtime/explicit) - v8::Global(v8::Isolate::GetCurrent(), that) {} - - inline void Reset() { v8::PersistentBase::Reset(); } - - template - inline void Reset(const v8::Local &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void Reset(const v8::PersistentBase &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - reinterpret_cast*>(this)->SetWeak( - parameter, callback, type); - } -}; -#else -template -class Global : public v8::UniquePersistent { - public: - inline Global() : v8::UniquePersistent() {} - - template inline Global(v8::Local that) : - v8::UniquePersistent(v8::Isolate::GetCurrent(), that) {} - - template - inline - Global(const v8::PersistentBase &that) : // NOLINT(runtime/explicit) - v8::UniquePersistent(v8::Isolate::GetCurrent(), that) {} - - inline void Reset() { v8::PersistentBase::Reset(); } - - template - inline void Reset(const v8::Local &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void Reset(const v8::PersistentBase &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - reinterpret_cast*>(this)->SetWeak( - parameter, callback, type); - } -}; -#endif - -#endif // NAN_PERSISTENT_12_INL_H_ diff --git a/reverse_engineering/node_modules/nan/nan_persistent_pre_12_inl.h b/reverse_engineering/node_modules/nan/nan_persistent_pre_12_inl.h deleted file mode 100644 index 4c9c59d..0000000 --- a/reverse_engineering/node_modules/nan/nan_persistent_pre_12_inl.h +++ /dev/null @@ -1,242 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_PERSISTENT_PRE_12_INL_H_ -#define NAN_PERSISTENT_PRE_12_INL_H_ - -template -class PersistentBase { - v8::Persistent persistent; - template - friend v8::Local New(const PersistentBase &p); - template - friend v8::Local New(const Persistent &p); - template - friend v8::Local New(const Global &p); - template friend class ReturnValue; - - public: - inline PersistentBase() : - persistent() {} - - inline void Reset() { - persistent.Dispose(); - persistent.Clear(); - } - - template - inline void Reset(const v8::Local &other) { - TYPE_CHECK(T, S); - - if (!persistent.IsEmpty()) { - persistent.Dispose(); - } - - if (other.IsEmpty()) { - persistent.Clear(); - } else { - persistent = v8::Persistent::New(other); - } - } - - template - inline void Reset(const PersistentBase &other) { - TYPE_CHECK(T, S); - - if (!persistent.IsEmpty()) { - persistent.Dispose(); - } - - if (other.IsEmpty()) { - persistent.Clear(); - } else { - persistent = v8::Persistent::New(other.persistent); - } - } - - inline bool IsEmpty() const { return persistent.IsEmpty(); } - - inline void Empty() { persistent.Clear(); } - - template - inline bool operator==(const PersistentBase &that) const { - return this->persistent == that.persistent; - } - - template - inline bool operator==(const v8::Local &that) const { - return this->persistent == that; - } - - template - inline bool operator!=(const PersistentBase &that) const { - return !operator==(that); - } - - template - inline bool operator!=(const v8::Local &that) const { - return !operator==(that); - } - - template - inline void SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type); - - inline void ClearWeak() { persistent.ClearWeak(); } - - inline void MarkIndependent() { persistent.MarkIndependent(); } - - inline bool IsIndependent() const { return persistent.IsIndependent(); } - - inline bool IsNearDeath() const { return persistent.IsNearDeath(); } - - inline bool IsWeak() const { return persistent.IsWeak(); } - - private: - inline explicit PersistentBase(v8::Persistent that) : - persistent(that) { } - inline explicit PersistentBase(T *val) : persistent(val) {} - template friend class Persistent; - template friend class Global; - friend class ObjectWrap; -}; - -template -class NonCopyablePersistentTraits { - public: - typedef Persistent > - NonCopyablePersistent; - static const bool kResetInDestructor = false; - template - inline static void Copy(const Persistent &source, - NonCopyablePersistent *dest) { - Uncompilable(); - } - - template inline static void Uncompilable() { - TYPE_CHECK(O, v8::Primitive); - } -}; - -template -struct CopyablePersistentTraits { - typedef Persistent > CopyablePersistent; - static const bool kResetInDestructor = true; - template - static inline void Copy(const Persistent &source, - CopyablePersistent *dest) {} -}; - -template class Persistent : - public PersistentBase { - public: - inline Persistent() {} - - template inline Persistent(v8::Handle that) - : PersistentBase(v8::Persistent::New(that)) { - TYPE_CHECK(T, S); - } - - inline Persistent(const Persistent &that) : PersistentBase() { - Copy(that); - } - - template - inline Persistent(const Persistent &that) : - PersistentBase() { - Copy(that); - } - - inline Persistent &operator=(const Persistent &that) { - Copy(that); - return *this; - } - - template - inline Persistent &operator=(const Persistent &that) { - Copy(that); - return *this; - } - - inline ~Persistent() { - if (M::kResetInDestructor) this->Reset(); - } - - private: - inline T *operator*() const { return *PersistentBase::persistent; } - - template - inline void Copy(const Persistent &that) { - TYPE_CHECK(T, S); - - this->Reset(); - - if (!that.IsEmpty()) { - this->persistent = v8::Persistent::New(that.persistent); - M::Copy(that, this); - } - } -}; - -template -class Global : public PersistentBase { - struct RValue { - inline explicit RValue(Global* obj) : object(obj) {} - Global* object; - }; - - public: - inline Global() : PersistentBase(0) { } - - template - inline Global(v8::Local that) // NOLINT(runtime/explicit) - : PersistentBase(v8::Persistent::New(that)) { - TYPE_CHECK(T, S); - } - - template - inline Global(const PersistentBase &that) // NOLINT(runtime/explicit) - : PersistentBase(that) { - TYPE_CHECK(T, S); - } - /** - * Move constructor. - */ - inline Global(RValue rvalue) // NOLINT(runtime/explicit) - : PersistentBase(rvalue.object->persistent) { - rvalue.object->Reset(); - } - inline ~Global() { this->Reset(); } - /** - * Move via assignment. - */ - template - inline Global &operator=(Global rhs) { - TYPE_CHECK(T, S); - this->Reset(rhs.persistent); - rhs.Reset(); - return *this; - } - /** - * Cast operator for moves. - */ - inline operator RValue() { return RValue(this); } - /** - * Pass allows returning uniques from functions, etc. - */ - Global Pass() { return Global(RValue(this)); } - - private: - Global(Global &); - void operator=(Global &); - template friend class ReturnValue; -}; - -#endif // NAN_PERSISTENT_PRE_12_INL_H_ diff --git a/reverse_engineering/node_modules/nan/nan_private.h b/reverse_engineering/node_modules/nan/nan_private.h deleted file mode 100644 index 15f44cc..0000000 --- a/reverse_engineering/node_modules/nan/nan_private.h +++ /dev/null @@ -1,73 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_PRIVATE_H_ -#define NAN_PRIVATE_H_ - -inline Maybe -HasPrivate(v8::Local object, v8::Local key) { - HandleScope scope; -#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::Local context = isolate->GetCurrentContext(); - v8::Local private_key = v8::Private::ForApi(isolate, key); - return object->HasPrivate(context, private_key); -#else - return Just(!object->GetHiddenValue(key).IsEmpty()); -#endif -} - -inline MaybeLocal -GetPrivate(v8::Local object, v8::Local key) { -#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::Local context = isolate->GetCurrentContext(); - v8::Local private_key = v8::Private::ForApi(isolate, key); - v8::MaybeLocal v = object->GetPrivate(context, private_key); - return scope.Escape(v.ToLocalChecked()); -#else - EscapableHandleScope scope; - v8::Local v = object->GetHiddenValue(key); - if (v.IsEmpty()) { - v = Undefined(); - } - return scope.Escape(v); -#endif -} - -inline Maybe SetPrivate( - v8::Local object, - v8::Local key, - v8::Local value) { -#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION - HandleScope scope; - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::Local context = isolate->GetCurrentContext(); - v8::Local private_key = v8::Private::ForApi(isolate, key); - return object->SetPrivate(context, private_key, value); -#else - return Just(object->SetHiddenValue(key, value)); -#endif -} - -inline Maybe DeletePrivate( - v8::Local object, - v8::Local key) { -#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION - HandleScope scope; - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::Local private_key = v8::Private::ForApi(isolate, key); - return object->DeletePrivate(isolate->GetCurrentContext(), private_key); -#else - return Just(object->DeleteHiddenValue(key)); -#endif -} - -#endif // NAN_PRIVATE_H_ - diff --git a/reverse_engineering/node_modules/nan/nan_scriptorigin.h b/reverse_engineering/node_modules/nan/nan_scriptorigin.h deleted file mode 100644 index ce79cdf..0000000 --- a/reverse_engineering/node_modules/nan/nan_scriptorigin.h +++ /dev/null @@ -1,76 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2021 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_SCRIPTORIGIN_H_ -#define NAN_SCRIPTORIGIN_H_ - -class ScriptOrigin : public v8::ScriptOrigin { - public: -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 9 || \ - (V8_MAJOR_VERSION == 9 && (defined(V8_MINOR_VERSION) && (V8_MINOR_VERSION > 0\ - || (V8_MINOR_VERSION == 0 && defined(V8_BUILD_NUMBER) \ - && V8_BUILD_NUMBER >= 1))))) - explicit ScriptOrigin(v8::Local name) : - v8::ScriptOrigin(v8::Isolate::GetCurrent(), name) {} - - ScriptOrigin(v8::Local name - , v8::Local line) : - v8::ScriptOrigin(v8::Isolate::GetCurrent() - , name - , To(line).FromMaybe(0)) {} - - ScriptOrigin(v8::Local name - , v8::Local line - , v8::Local column) : - v8::ScriptOrigin(v8::Isolate::GetCurrent() - , name - , To(line).FromMaybe(0) - , To(column).FromMaybe(0)) {} -#elif defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 8 || \ - (V8_MAJOR_VERSION == 8 && (defined(V8_MINOR_VERSION) && (V8_MINOR_VERSION > 9\ - || (V8_MINOR_VERSION == 9 && defined(V8_BUILD_NUMBER) \ - && V8_BUILD_NUMBER >= 45))))) - explicit ScriptOrigin(v8::Local name) : v8::ScriptOrigin(name) {} - - ScriptOrigin(v8::Local name - , v8::Local line) : - v8::ScriptOrigin(name, To(line).FromMaybe(0)) {} - - ScriptOrigin(v8::Local name - , v8::Local line - , v8::Local column) : - v8::ScriptOrigin(name - , To(line).FromMaybe(0) - , To(column).FromMaybe(0)) {} -#else - explicit ScriptOrigin(v8::Local name) : v8::ScriptOrigin(name) {} - - ScriptOrigin(v8::Local name - , v8::Local line) : v8::ScriptOrigin(name, line) {} - - ScriptOrigin(v8::Local name - , v8::Local line - , v8::Local column) : - v8::ScriptOrigin(name, line, column) {} -#endif - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 8 || \ - (V8_MAJOR_VERSION == 8 && (defined(V8_MINOR_VERSION) && (V8_MINOR_VERSION > 9\ - || (V8_MINOR_VERSION == 9 && defined(V8_BUILD_NUMBER) \ - && V8_BUILD_NUMBER >= 45))))) - v8::Local ResourceLineOffset() const { - return New(LineOffset()); - } - - v8::Local ResourceColumnOffset() const { - return New(ColumnOffset()); - } -#endif -}; - -#endif // NAN_SCRIPTORIGIN_H_ diff --git a/reverse_engineering/node_modules/nan/nan_string_bytes.h b/reverse_engineering/node_modules/nan/nan_string_bytes.h deleted file mode 100644 index a2e6437..0000000 --- a/reverse_engineering/node_modules/nan/nan_string_bytes.h +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -#ifndef NAN_STRING_BYTES_H_ -#define NAN_STRING_BYTES_H_ - -// Decodes a v8::Local or Buffer to a raw char* - -namespace imp { - -using v8::Local; -using v8::Object; -using v8::String; -using v8::Value; - - -//// Base 64 //// - -#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) - - - -//// HEX //// - -static bool contains_non_ascii_slow(const char* buf, size_t len) { - for (size_t i = 0; i < len; ++i) { - if (buf[i] & 0x80) return true; - } - return false; -} - - -static bool contains_non_ascii(const char* src, size_t len) { - if (len < 16) { - return contains_non_ascii_slow(src, len); - } - - const unsigned bytes_per_word = sizeof(void*); - const unsigned align_mask = bytes_per_word - 1; - const unsigned unaligned = reinterpret_cast(src) & align_mask; - - if (unaligned > 0) { - const unsigned n = bytes_per_word - unaligned; - if (contains_non_ascii_slow(src, n)) return true; - src += n; - len -= n; - } - - -#if defined(__x86_64__) || defined(_WIN64) - const uintptr_t mask = 0x8080808080808080ll; -#else - const uintptr_t mask = 0x80808080l; -#endif - - const uintptr_t* srcw = reinterpret_cast(src); - - for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { - if (srcw[i] & mask) return true; - } - - const unsigned remainder = len & align_mask; - if (remainder > 0) { - const size_t offset = len - remainder; - if (contains_non_ascii_slow(src + offset, remainder)) return true; - } - - return false; -} - - -static void force_ascii_slow(const char* src, char* dst, size_t len) { - for (size_t i = 0; i < len; ++i) { - dst[i] = src[i] & 0x7f; - } -} - - -static void force_ascii(const char* src, char* dst, size_t len) { - if (len < 16) { - force_ascii_slow(src, dst, len); - return; - } - - const unsigned bytes_per_word = sizeof(void*); - const unsigned align_mask = bytes_per_word - 1; - const unsigned src_unalign = reinterpret_cast(src) & align_mask; - const unsigned dst_unalign = reinterpret_cast(dst) & align_mask; - - if (src_unalign > 0) { - if (src_unalign == dst_unalign) { - const unsigned unalign = bytes_per_word - src_unalign; - force_ascii_slow(src, dst, unalign); - src += unalign; - dst += unalign; - len -= src_unalign; - } else { - force_ascii_slow(src, dst, len); - return; - } - } - -#if defined(__x86_64__) || defined(_WIN64) - const uintptr_t mask = ~0x8080808080808080ll; -#else - const uintptr_t mask = ~0x80808080l; -#endif - - const uintptr_t* srcw = reinterpret_cast(src); - uintptr_t* dstw = reinterpret_cast(dst); - - for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { - dstw[i] = srcw[i] & mask; - } - - const unsigned remainder = len & align_mask; - if (remainder > 0) { - const size_t offset = len - remainder; - force_ascii_slow(src + offset, dst + offset, remainder); - } -} - - -static size_t base64_encode(const char* src, - size_t slen, - char* dst, - size_t dlen) { - // We know how much we'll write, just make sure that there's space. - assert(dlen >= base64_encoded_size(slen) && - "not enough space provided for base64 encode"); - - dlen = base64_encoded_size(slen); - - unsigned a; - unsigned b; - unsigned c; - unsigned i; - unsigned k; - unsigned n; - - static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - - i = 0; - k = 0; - n = slen / 3 * 3; - - while (i < n) { - a = src[i + 0] & 0xff; - b = src[i + 1] & 0xff; - c = src[i + 2] & 0xff; - - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; - dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)]; - dst[k + 3] = table[c & 0x3f]; - - i += 3; - k += 4; - } - - if (n != slen) { - switch (slen - n) { - case 1: - a = src[i + 0] & 0xff; - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[(a & 3) << 4]; - dst[k + 2] = '='; - dst[k + 3] = '='; - break; - - case 2: - a = src[i + 0] & 0xff; - b = src[i + 1] & 0xff; - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; - dst[k + 2] = table[(b & 0x0f) << 2]; - dst[k + 3] = '='; - break; - } - } - - return dlen; -} - - -static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) { - // We know how much we'll write, just make sure that there's space. - assert(dlen >= slen * 2 && - "not enough space provided for hex encode"); - - dlen = slen * 2; - for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) { - static const char hex[] = "0123456789abcdef"; - uint8_t val = static_cast(src[i]); - dst[k + 0] = hex[val >> 4]; - dst[k + 1] = hex[val & 15]; - } - - return dlen; -} - - - -static Local Encode(const char* buf, - size_t buflen, - enum Encoding encoding) { - assert(buflen <= node::Buffer::kMaxLength); - if (!buflen && encoding != BUFFER) - return New("").ToLocalChecked(); - - Local val; - switch (encoding) { - case BUFFER: - return CopyBuffer(buf, buflen).ToLocalChecked(); - - case ASCII: - if (contains_non_ascii(buf, buflen)) { - char* out = new char[buflen]; - force_ascii(buf, out, buflen); - val = New(out, buflen).ToLocalChecked(); - delete[] out; - } else { - val = New(buf, buflen).ToLocalChecked(); - } - break; - - case UTF8: - val = New(buf, buflen).ToLocalChecked(); - break; - - case BINARY: { - // TODO(isaacs) use ExternalTwoByteString? - const unsigned char *cbuf = reinterpret_cast(buf); - uint16_t * twobytebuf = new uint16_t[buflen]; - for (size_t i = 0; i < buflen; i++) { - // XXX is the following line platform independent? - twobytebuf[i] = cbuf[i]; - } - val = New(twobytebuf, buflen).ToLocalChecked(); - delete[] twobytebuf; - break; - } - - case BASE64: { - size_t dlen = base64_encoded_size(buflen); - char* dst = new char[dlen]; - - size_t written = base64_encode(buf, buflen, dst, dlen); - assert(written == dlen); - - val = New(dst, dlen).ToLocalChecked(); - delete[] dst; - break; - } - - case UCS2: { - const uint16_t* data = reinterpret_cast(buf); - val = New(data, buflen / 2).ToLocalChecked(); - break; - } - - case HEX: { - size_t dlen = buflen * 2; - char* dst = new char[dlen]; - size_t written = hex_encode(buf, buflen, dst, dlen); - assert(written == dlen); - - val = New(dst, dlen).ToLocalChecked(); - delete[] dst; - break; - } - - default: - assert(0 && "unknown encoding"); - break; - } - - return val; -} - -#undef base64_encoded_size - -} // end of namespace imp - -#endif // NAN_STRING_BYTES_H_ diff --git a/reverse_engineering/node_modules/nan/nan_typedarray_contents.h b/reverse_engineering/node_modules/nan/nan_typedarray_contents.h deleted file mode 100644 index c6ac8a4..0000000 --- a/reverse_engineering/node_modules/nan/nan_typedarray_contents.h +++ /dev/null @@ -1,96 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_TYPEDARRAY_CONTENTS_H_ -#define NAN_TYPEDARRAY_CONTENTS_H_ - -template -class TypedArrayContents { - public: - inline explicit TypedArrayContents(v8::Local from) : - length_(0), data_(NULL) { - HandleScope scope; - - size_t length = 0; - void* data = NULL; - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - - if (from->IsArrayBufferView()) { - v8::Local array = - v8::Local::Cast(from); - - const size_t byte_length = array->ByteLength(); - const ptrdiff_t byte_offset = array->ByteOffset(); - v8::Local buffer = array->Buffer(); - - length = byte_length / sizeof(T); -// Actually it's 7.9 here but this would lead to ABI issues with Node.js 13 -// using 7.8 till 13.2.0. -#if (V8_MAJOR_VERSION >= 8) - data = static_cast(buffer->GetBackingStore()->Data()) + byte_offset; -#else - data = static_cast(buffer->GetContents().Data()) + byte_offset; -#endif - } - -#else - - if (from->IsObject() && !from->IsNull()) { - v8::Local array = v8::Local::Cast(from); - - MaybeLocal buffer = Get(array, - New("buffer").ToLocalChecked()); - MaybeLocal byte_length = Get(array, - New("byteLength").ToLocalChecked()); - MaybeLocal byte_offset = Get(array, - New("byteOffset").ToLocalChecked()); - - if (!buffer.IsEmpty() && - !byte_length.IsEmpty() && byte_length.ToLocalChecked()->IsUint32() && - !byte_offset.IsEmpty() && byte_offset.ToLocalChecked()->IsUint32()) { - data = array->GetIndexedPropertiesExternalArrayData(); - if(data) { - length = byte_length.ToLocalChecked()->Uint32Value() / sizeof(T); - } - } - } - -#endif - -#if defined(_MSC_VER) && _MSC_VER >= 1900 || __cplusplus >= 201103L - assert(reinterpret_cast(data) % alignof (T) == 0); -#elif defined(_MSC_VER) && _MSC_VER >= 1600 || defined(__GNUC__) - assert(reinterpret_cast(data) % __alignof(T) == 0); -#else - assert(reinterpret_cast(data) % sizeof (T) == 0); -#endif - - length_ = length; - data_ = static_cast(data); - } - - inline size_t length() const { return length_; } - inline T* operator*() { return data_; } - inline const T* operator*() const { return data_; } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(TypedArrayContents) - - //Disable heap allocation - void *operator new(size_t size); - void operator delete(void *, size_t) { - abort(); - } - - size_t length_; - T* data_; -}; - -#endif // NAN_TYPEDARRAY_CONTENTS_H_ diff --git a/reverse_engineering/node_modules/nan/nan_weak.h b/reverse_engineering/node_modules/nan/nan_weak.h deleted file mode 100644 index 7e7ab07..0000000 --- a/reverse_engineering/node_modules/nan/nan_weak.h +++ /dev/null @@ -1,437 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_WEAK_H_ -#define NAN_WEAK_H_ - -static const int kInternalFieldsInWeakCallback = 2; -static const int kNoInternalFieldIndex = -1; - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ - v8::WeakCallbackInfo > const& -# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ - NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ -#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION -# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ - v8::PhantomCallbackData > const& -# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ - NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ -#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION -# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ - v8::PhantomCallbackData > const& -# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ - v8::InternalFieldsCallbackData, void> const& -# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION -# define NAN_WEAK_CALLBACK_DATA_TYPE_ \ - v8::WeakCallbackData > const& -# define NAN_WEAK_CALLBACK_SIG_ NAN_WEAK_CALLBACK_DATA_TYPE_ -#else -# define NAN_WEAK_CALLBACK_DATA_TYPE_ void * -# define NAN_WEAK_CALLBACK_SIG_ \ - v8::Persistent, NAN_WEAK_CALLBACK_DATA_TYPE_ -#endif - -template -class WeakCallbackInfo { - public: - typedef void (*Callback)(const WeakCallbackInfo& data); - WeakCallbackInfo( - Persistent *persistent - , Callback callback - , void *parameter - , void *field1 = 0 - , void *field2 = 0) : - callback_(callback), isolate_(0), parameter_(parameter) { - std::memcpy(&persistent_, persistent, sizeof (v8::Persistent)); - internal_fields_[0] = field1; - internal_fields_[1] = field2; - } - inline v8::Isolate *GetIsolate() const { return isolate_; } - inline T *GetParameter() const { return static_cast(parameter_); } - inline void *GetInternalField(int index) const { - assert((index == 0 || index == 1) && "internal field index out of bounds"); - if (index == 0) { - return internal_fields_[0]; - } else { - return internal_fields_[1]; - } - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(WeakCallbackInfo) - Callback callback_; - v8::Isolate *isolate_; - void *parameter_; - void *internal_fields_[kInternalFieldsInWeakCallback]; - v8::Persistent persistent_; - template friend class Persistent; - template friend class PersistentBase; -#if NODE_MODULE_VERSION <= NODE_0_12_MODULE_VERSION -# if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - template - static void invoke(NAN_WEAK_CALLBACK_SIG_ data); - template - static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data); -# else - static void invoke(NAN_WEAK_CALLBACK_SIG_ data); - static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data); -# endif -#else -# if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - template - static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data); - template - static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data); -# else - static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data); - static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data); -# endif - static WeakCallbackInfo *unwrapparameter( - NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data); - static WeakCallbackInfo *unwraptwofield( - NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data); -#endif -}; - - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - -template -template -void -WeakCallbackInfo::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwrapparameter(data); - if (isFirstPass) { - cbinfo->persistent_.Reset(); - data.SetSecondPassCallback(invokeparameter); - } else { - cbinfo->callback_(*cbinfo); - delete cbinfo; - } -} - -template -template -void -WeakCallbackInfo::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwraptwofield(data); - if (isFirstPass) { - cbinfo->persistent_.Reset(); - data.SetSecondPassCallback(invoketwofield); - } else { - cbinfo->callback_(*cbinfo); - delete cbinfo; - } -} - -template -WeakCallbackInfo *WeakCallbackInfo::unwrapparameter( - NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) { - WeakCallbackInfo *cbinfo = - static_cast*>(data.GetParameter()); - cbinfo->isolate_ = data.GetIsolate(); - return cbinfo; -} - -template -WeakCallbackInfo *WeakCallbackInfo::unwraptwofield( - NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) { - WeakCallbackInfo *cbinfo = - static_cast*>(data.GetInternalField(0)); - cbinfo->isolate_ = data.GetIsolate(); - return cbinfo; -} - -#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_ -#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_ -#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ -# elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION - -template -void -WeakCallbackInfo::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwrapparameter(data); - cbinfo->persistent_.Reset(); - cbinfo->callback_(*cbinfo); - delete cbinfo; -} - -template -void -WeakCallbackInfo::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwraptwofield(data); - cbinfo->persistent_.Reset(); - cbinfo->callback_(*cbinfo); - delete cbinfo; -} - -template -WeakCallbackInfo *WeakCallbackInfo::unwrapparameter( - NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) { - WeakCallbackInfo *cbinfo = - static_cast*>(data.GetParameter()); - cbinfo->isolate_ = data.GetIsolate(); - return cbinfo; -} - -template -WeakCallbackInfo *WeakCallbackInfo::unwraptwofield( - NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) { - WeakCallbackInfo *cbinfo = - static_cast*>(data.GetInternalField1()); - cbinfo->isolate_ = data.GetIsolate(); - return cbinfo; -} - -#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_ -#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_ -#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - -template -template -void WeakCallbackInfo::invoke(NAN_WEAK_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwrap(data); - cbinfo->persistent_.Reset(); - cbinfo->callback_(*cbinfo); - delete cbinfo; -} - -template -template -WeakCallbackInfo *WeakCallbackInfo::unwrap( - NAN_WEAK_CALLBACK_DATA_TYPE_ data) { - void *parameter = data.GetParameter(); - WeakCallbackInfo *cbinfo = - static_cast*>(parameter); - cbinfo->isolate_ = data.GetIsolate(); - return cbinfo; -} - -#undef NAN_WEAK_CALLBACK_SIG_ -#undef NAN_WEAK_CALLBACK_DATA_TYPE_ -#else - -template -void WeakCallbackInfo::invoke(NAN_WEAK_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwrap(data); - cbinfo->persistent_.Dispose(); - cbinfo->persistent_.Clear(); - cbinfo->callback_(*cbinfo); - delete cbinfo; -} - -template -WeakCallbackInfo *WeakCallbackInfo::unwrap( - NAN_WEAK_CALLBACK_DATA_TYPE_ data) { - WeakCallbackInfo *cbinfo = - static_cast*>(data); - cbinfo->isolate_ = v8::Isolate::GetCurrent(); - return cbinfo; -} - -#undef NAN_WEAK_CALLBACK_SIG_ -#undef NAN_WEAK_CALLBACK_DATA_TYPE_ -#endif - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -template -template -inline void Persistent::SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - WeakCallbackInfo

*wcbd; - if (type == WeakCallbackType::kParameter) { - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , parameter); - v8::PersistentBase::SetWeak( - wcbd - , WeakCallbackInfo

::template invokeparameter - , type); - } else { - v8::Local* self_v(reinterpret_cast*>(this)); - assert((*self_v)->IsObject()); - v8::Local self((*self_v).As()); - int count = self->InternalFieldCount(); - void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; - for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { - internal_fields[i] = self->GetAlignedPointerFromInternalField(i); - } - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , 0 - , internal_fields[0] - , internal_fields[1]); - self->SetAlignedPointerInInternalField(0, wcbd); - v8::PersistentBase::SetWeak( - static_cast*>(0) - , WeakCallbackInfo

::template invoketwofield - , type); - } -} -#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION -template -template -inline void Persistent::SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - WeakCallbackInfo

*wcbd; - if (type == WeakCallbackType::kParameter) { - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , parameter); - v8::PersistentBase::SetPhantom( - wcbd - , WeakCallbackInfo

::invokeparameter); - } else { - v8::Local* self_v(reinterpret_cast*>(this)); - assert((*self_v)->IsObject()); - v8::Local self((*self_v).As()); - int count = self->InternalFieldCount(); - void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; - for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { - internal_fields[i] = self->GetAlignedPointerFromInternalField(i); - } - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , 0 - , internal_fields[0] - , internal_fields[1]); - self->SetAlignedPointerInInternalField(0, wcbd); - v8::PersistentBase::SetPhantom( - static_cast*>(0) - , WeakCallbackInfo

::invoketwofield - , 0 - , count > 1 ? 1 : kNoInternalFieldIndex); - } -} -#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION -template -template -inline void Persistent::SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - WeakCallbackInfo

*wcbd; - if (type == WeakCallbackType::kParameter) { - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , parameter); - v8::PersistentBase::SetPhantom( - wcbd - , WeakCallbackInfo

::invokeparameter); - } else { - v8::Local* self_v(reinterpret_cast*>(this)); - assert((*self_v)->IsObject()); - v8::Local self((*self_v).As()); - int count = self->InternalFieldCount(); - void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; - for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { - internal_fields[i] = self->GetAlignedPointerFromInternalField(i); - } - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , 0 - , internal_fields[0] - , internal_fields[1]); - self->SetAlignedPointerInInternalField(0, wcbd); - v8::PersistentBase::SetPhantom( - WeakCallbackInfo

::invoketwofield - , 0 - , count > 1 ? 1 : kNoInternalFieldIndex); - } -} -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION -template -template -inline void Persistent::SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - WeakCallbackInfo

*wcbd; - if (type == WeakCallbackType::kParameter) { - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , parameter); - v8::PersistentBase::SetWeak(wcbd, WeakCallbackInfo

::invoke); - } else { - v8::Local* self_v(reinterpret_cast*>(this)); - assert((*self_v)->IsObject()); - v8::Local self((*self_v).As()); - int count = self->InternalFieldCount(); - void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; - for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { - internal_fields[i] = self->GetAlignedPointerFromInternalField(i); - } - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , 0 - , internal_fields[0] - , internal_fields[1]); - v8::PersistentBase::SetWeak(wcbd, WeakCallbackInfo

::invoke); - } -} -#else -template -template -inline void PersistentBase::SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - WeakCallbackInfo

*wcbd; - if (type == WeakCallbackType::kParameter) { - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , parameter); - persistent.MakeWeak(wcbd, WeakCallbackInfo

::invoke); - } else { - v8::Local* self_v(reinterpret_cast*>(this)); - assert((*self_v)->IsObject()); - v8::Local self((*self_v).As()); - int count = self->InternalFieldCount(); - void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; - for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { - internal_fields[i] = self->GetPointerFromInternalField(i); - } - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , 0 - , internal_fields[0] - , internal_fields[1]); - persistent.MakeWeak(wcbd, WeakCallbackInfo

::invoke); - } -} -#endif - -#endif // NAN_WEAK_H_ diff --git a/reverse_engineering/node_modules/nan/package.json b/reverse_engineering/node_modules/nan/package.json deleted file mode 100644 index 0520a55..0000000 --- a/reverse_engineering/node_modules/nan/package.json +++ /dev/null @@ -1,99 +0,0 @@ -{ - "_from": "nan@^2.15.0", - "_id": "nan@2.15.0", - "_inBundle": false, - "_integrity": "sha512-8ZtvEnA2c5aYCZYd1cvgdnU6cqwixRoYg70xPLWUws5ORTa/lnw+u4amixRS/Ac5U5mQVgp9pnlSUnbNWFaWZQ==", - "_location": "/nan", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "nan@^2.15.0", - "name": "nan", - "escapedName": "nan", - "rawSpec": "^2.15.0", - "saveSpec": null, - "fetchSpec": "^2.15.0" - }, - "_requiredBy": [ - "/cpu-features", - "/ssh2" - ], - "_resolved": "https://registry.npmjs.org/nan/-/nan-2.15.0.tgz", - "_shasum": "3f34a473ff18e15c1b5626b62903b5ad6e665fee", - "_spec": "nan@^2.15.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/ssh2", - "bugs": { - "url": "https://github.com/nodejs/nan/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Rod Vagg", - "email": "r@va.gg", - "url": "https://github.com/rvagg" - }, - { - "name": "Benjamin Byholm", - "email": "bbyholm@abo.fi", - "url": "https://github.com/kkoopa/" - }, - { - "name": "Trevor Norris", - "email": "trev.norris@gmail.com", - "url": "https://github.com/trevnorris" - }, - { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "https://github.com/TooTallNate" - }, - { - "name": "Brett Lawson", - "email": "brett19@gmail.com", - "url": "https://github.com/brett19" - }, - { - "name": "Ben Noordhuis", - "email": "info@bnoordhuis.nl", - "url": "https://github.com/bnoordhuis" - }, - { - "name": "David Siegel", - "email": "david@artcom.de", - "url": "https://github.com/agnat" - }, - { - "name": "Michael Ira Krufky", - "email": "mkrufky@gmail.com", - "url": "https://github.com/mkrufky" - } - ], - "deprecated": false, - "description": "Native Abstractions for Node.js: C++ header for Node 0.8 -> 14 compatibility", - "devDependencies": { - "bindings": "~1.2.1", - "commander": "^2.8.1", - "glob": "^5.0.14", - "node-gyp": "~3.6.2", - "readable-stream": "^2.1.4", - "request": "=2.81.0", - "tap": "~0.7.1", - "xtend": "~4.0.0" - }, - "homepage": "https://github.com/nodejs/nan#readme", - "license": "MIT", - "main": "include_dirs.js", - "name": "nan", - "repository": { - "type": "git", - "url": "git://github.com/nodejs/nan.git" - }, - "scripts": { - "docs": "doc/.build.sh", - "rebuild-tests": "node-gyp rebuild --msvs_version=2015 --directory test", - "test": "tap --gc --stderr test/js/*-test.js", - "test:worker": "node --experimental-worker test/tap-as-worker.js --gc --stderr test/js/*-test.js" - }, - "version": "2.15.0" -} diff --git a/reverse_engineering/node_modules/nan/tools/1to2.js b/reverse_engineering/node_modules/nan/tools/1to2.js deleted file mode 100644 index 6af2505..0000000 --- a/reverse_engineering/node_modules/nan/tools/1to2.js +++ /dev/null @@ -1,412 +0,0 @@ -#!/usr/bin/env node -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -var commander = require('commander'), - fs = require('fs'), - glob = require('glob'), - groups = [], - total = 0, - warning1 = '/* ERROR: Rewrite using Buffer */\n', - warning2 = '\\/\\* ERROR\\: Rewrite using Buffer \\*\\/\\n', - length, - i; - -fs.readFile(__dirname + '/package.json', 'utf8', function (err, data) { - if (err) { - throw err; - } - - commander - .version(JSON.parse(data).version) - .usage('[options] ') - .parse(process.argv); - - if (!process.argv.slice(2).length) { - commander.outputHelp(); - } -}); - -/* construct strings representing regular expressions - each expression contains a unique group allowing for identification of the match - the index of this key group, relative to the regular expression in question, - is indicated by the first array member */ - -/* simple substistutions, key group is the entire match, 0 */ -groups.push([0, [ - '_NAN_', - 'NODE_SET_METHOD', - 'NODE_SET_PROTOTYPE_METHOD', - 'NanAsciiString', - 'NanEscapeScope', - 'NanReturnValue', - 'NanUcs2String'].join('|')]); - -/* substitutions of parameterless macros, key group is 1 */ -groups.push([1, ['(', [ - 'NanEscapableScope', - 'NanReturnNull', - 'NanReturnUndefined', - 'NanScope'].join('|'), ')\\(\\)'].join('')]); - -/* replace TryCatch with NanTryCatch once, gobbling possible namespace, key group 2 */ -groups.push([2, '(?:(?:v8\\:\\:)?|(Nan)?)(TryCatch)']); - -/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ -groups.push([1, ['(NanNew)', '(\\("[^\\"]*"[^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]); - -/* Removed v8 APIs, warn that the code needs rewriting using node::Buffer, key group 2 */ -groups.push([2, ['(', warning2, ')?', '^.*?(', [ - 'GetIndexedPropertiesExternalArrayDataLength', - 'GetIndexedPropertiesExternalArrayData', - 'GetIndexedPropertiesExternalArrayDataType', - 'GetIndexedPropertiesPixelData', - 'GetIndexedPropertiesPixelDataLength', - 'HasIndexedPropertiesInExternalArrayData', - 'HasIndexedPropertiesInPixelData', - 'SetIndexedPropertiesToExternalArrayData', - 'SetIndexedPropertiesToPixelData'].join('|'), ')'].join('')]); - -/* No need for NanScope in V8-exposed methods, key group 2 */ -groups.push([2, ['((', [ - 'NAN_METHOD', - 'NAN_GETTER', - 'NAN_SETTER', - 'NAN_PROPERTY_GETTER', - 'NAN_PROPERTY_SETTER', - 'NAN_PROPERTY_ENUMERATOR', - 'NAN_PROPERTY_DELETER', - 'NAN_PROPERTY_QUERY', - 'NAN_INDEX_GETTER', - 'NAN_INDEX_SETTER', - 'NAN_INDEX_ENUMERATOR', - 'NAN_INDEX_DELETER', - 'NAN_INDEX_QUERY'].join('|'), ')\\([^\\)]*\\)\\s*\\{)\\s*NanScope\\(\\)\\s*;'].join('')]); - -/* v8::Value::ToXXXXXXX returns v8::MaybeLocal, key group 3 */ -groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->(', [ - 'Boolean', - 'Number', - 'String', - 'Object', - 'Integer', - 'Uint32', - 'Int32'].join('|'), ')\\('].join('')]); - -/* v8::Value::XXXXXXXValue returns v8::Maybe, key group 3 */ -groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->((?:', [ - 'Boolean', - 'Number', - 'Integer', - 'Uint32', - 'Int32'].join('|'), ')Value)\\('].join('')]); - -/* NAN_WEAK_CALLBACK macro was removed, write out callback definition, key group 1 */ -groups.push([1, '(NAN_WEAK_CALLBACK)\\(([^\\s\\)]+)\\)']); - -/* node::ObjectWrap and v8::Persistent have been replaced with Nan implementations, key group 1 */ -groups.push([1, ['(', [ - 'NanDisposePersistent', - 'NanObjectWrapHandle'].join('|'), ')\\s*\\(\\s*([^\\s\\)]+)'].join('')]); - -/* Since NanPersistent there is no need for NanMakeWeakPersistent, key group 1 */ -groups.push([1, '(NanMakeWeakPersistent)\\s*\\(\\s*([^\\s,]+)\\s*,\\s*']); - -/* Many methods of v8::Object and others now return v8::MaybeLocal, key group 3 */ -groups.push([3, ['([\\s])([^\\s]+)->(', [ - 'GetEndColumn', - 'GetFunction', - 'GetLineNumber', - 'NewInstance', - 'GetPropertyNames', - 'GetOwnPropertyNames', - 'GetSourceLine', - 'GetStartColumn', - 'ObjectProtoToString', - 'ToArrayIndex', - 'ToDetailString', - 'CallAsConstructor', - 'CallAsFunction', - 'CloneElementAt', - 'Delete', - 'ForceSet', - 'Get', - 'GetPropertyAttributes', - 'GetRealNamedProperty', - 'GetRealNamedPropertyInPrototypeChain', - 'Has', - 'HasOwnProperty', - 'HasRealIndexedProperty', - 'HasRealNamedCallbackProperty', - 'HasRealNamedProperty', - 'Set', - 'SetAccessor', - 'SetIndexedPropertyHandler', - 'SetNamedPropertyHandler', - 'SetPrototype'].join('|'), ')\\('].join('')]); - -/* You should get an error if any of these fail anyways, - or handle the error better, it is indicated either way, key group 2 */ -groups.push([2, ['NanNew(<(?:v8\\:\\:)?(', ['Date', 'String', 'RegExp'].join('|'), ')>)(\\([^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]); - -/* v8::Value::Equals now returns a v8::Maybe, key group 3 */ -groups.push([3, '([\\s\\(\\)])([^\\s\\(\\)]+)->(Equals)\\(([^\\s\\)]+)']); - -/* NanPersistent makes this unnecessary, key group 1 */ -groups.push([1, '(NanAssignPersistent)(?:]+>)?\\(([^,]+),\\s*']); - -/* args has been renamed to info, key group 2 */ -groups.push([2, '(\\W)(args)(\\W)']) - -/* node::ObjectWrap was replaced with NanObjectWrap, key group 2 */ -groups.push([2, '(\\W)(?:node\\:\\:)?(ObjectWrap)(\\W)']); - -/* v8::Persistent was replaced with NanPersistent, key group 2 */ -groups.push([2, '(\\W)(?:v8\\:\\:)?(Persistent)(\\W)']); - -/* counts the number of capturing groups in a well-formed regular expression, - ignoring non-capturing groups and escaped parentheses */ -function groupcount(s) { - var positive = s.match(/\((?!\?)/g), - negative = s.match(/\\\(/g); - return (positive ? positive.length : 0) - (negative ? negative.length : 0); -} - -/* compute the absolute position of each key group in the joined master RegExp */ -for (i = 1, length = groups.length; i < length; i++) { - total += groupcount(groups[i - 1][1]); - groups[i][0] += total; -} - -/* create the master RegExp, whis is the union of all the groups' expressions */ -master = new RegExp(groups.map(function (a) { return a[1]; }).join('|'), 'gm'); - -/* replacement function for String.replace, receives 21 arguments */ -function replace() { - /* simple expressions */ - switch (arguments[groups[0][0]]) { - case '_NAN_': - return 'NAN_'; - case 'NODE_SET_METHOD': - return 'NanSetMethod'; - case 'NODE_SET_PROTOTYPE_METHOD': - return 'NanSetPrototypeMethod'; - case 'NanAsciiString': - return 'NanUtf8String'; - case 'NanEscapeScope': - return 'scope.Escape'; - case 'NanReturnNull': - return 'info.GetReturnValue().SetNull'; - case 'NanReturnValue': - return 'info.GetReturnValue().Set'; - case 'NanUcs2String': - return 'v8::String::Value'; - default: - } - - /* macros without arguments */ - switch (arguments[groups[1][0]]) { - case 'NanEscapableScope': - return 'NanEscapableScope scope' - case 'NanReturnUndefined': - return 'return'; - case 'NanScope': - return 'NanScope scope'; - default: - } - - /* TryCatch, emulate negative backref */ - if (arguments[groups[2][0]] === 'TryCatch') { - return arguments[groups[2][0] - 1] ? arguments[0] : 'NanTryCatch'; - } - - /* NanNew("foo") --> NanNew("foo").ToLocalChecked() */ - if (arguments[groups[3][0]] === 'NanNew') { - return [arguments[0], '.ToLocalChecked()'].join(''); - } - - /* insert warning for removed functions as comment on new line above */ - switch (arguments[groups[4][0]]) { - case 'GetIndexedPropertiesExternalArrayData': - case 'GetIndexedPropertiesExternalArrayDataLength': - case 'GetIndexedPropertiesExternalArrayDataType': - case 'GetIndexedPropertiesPixelData': - case 'GetIndexedPropertiesPixelDataLength': - case 'HasIndexedPropertiesInExternalArrayData': - case 'HasIndexedPropertiesInPixelData': - case 'SetIndexedPropertiesToExternalArrayData': - case 'SetIndexedPropertiesToPixelData': - return arguments[groups[4][0] - 1] ? arguments[0] : [warning1, arguments[0]].join(''); - default: - } - - /* remove unnecessary NanScope() */ - switch (arguments[groups[5][0]]) { - case 'NAN_GETTER': - case 'NAN_METHOD': - case 'NAN_SETTER': - case 'NAN_INDEX_DELETER': - case 'NAN_INDEX_ENUMERATOR': - case 'NAN_INDEX_GETTER': - case 'NAN_INDEX_QUERY': - case 'NAN_INDEX_SETTER': - case 'NAN_PROPERTY_DELETER': - case 'NAN_PROPERTY_ENUMERATOR': - case 'NAN_PROPERTY_GETTER': - case 'NAN_PROPERTY_QUERY': - case 'NAN_PROPERTY_SETTER': - return arguments[groups[5][0] - 1]; - default: - } - - /* Value conversion */ - switch (arguments[groups[6][0]]) { - case 'Boolean': - case 'Int32': - case 'Integer': - case 'Number': - case 'Object': - case 'String': - case 'Uint32': - return [arguments[groups[6][0] - 2], 'NanTo(', arguments[groups[6][0] - 1]].join(''); - default: - } - - /* other value conversion */ - switch (arguments[groups[7][0]]) { - case 'BooleanValue': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'Int32Value': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'IntegerValue': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'Uint32Value': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - default: - } - - /* NAN_WEAK_CALLBACK */ - if (arguments[groups[8][0]] === 'NAN_WEAK_CALLBACK') { - return ['template\nvoid ', - arguments[groups[8][0] + 1], '(const NanWeakCallbackInfo &data)'].join(''); - } - - /* use methods on NAN classes instead */ - switch (arguments[groups[9][0]]) { - case 'NanDisposePersistent': - return [arguments[groups[9][0] + 1], '.Reset('].join(''); - case 'NanObjectWrapHandle': - return [arguments[groups[9][0] + 1], '->handle('].join(''); - default: - } - - /* use method on NanPersistent instead */ - if (arguments[groups[10][0]] === 'NanMakeWeakPersistent') { - return arguments[groups[10][0] + 1] + '.SetWeak('; - } - - /* These return Maybes, the upper ones take no arguments */ - switch (arguments[groups[11][0]]) { - case 'GetEndColumn': - case 'GetFunction': - case 'GetLineNumber': - case 'GetOwnPropertyNames': - case 'GetPropertyNames': - case 'GetSourceLine': - case 'GetStartColumn': - case 'NewInstance': - case 'ObjectProtoToString': - case 'ToArrayIndex': - case 'ToDetailString': - return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1]].join(''); - case 'CallAsConstructor': - case 'CallAsFunction': - case 'CloneElementAt': - case 'Delete': - case 'ForceSet': - case 'Get': - case 'GetPropertyAttributes': - case 'GetRealNamedProperty': - case 'GetRealNamedPropertyInPrototypeChain': - case 'Has': - case 'HasOwnProperty': - case 'HasRealIndexedProperty': - case 'HasRealNamedCallbackProperty': - case 'HasRealNamedProperty': - case 'Set': - case 'SetAccessor': - case 'SetIndexedPropertyHandler': - case 'SetNamedPropertyHandler': - case 'SetPrototype': - return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1], ', '].join(''); - default: - } - - /* Automatic ToLocalChecked(), take it or leave it */ - switch (arguments[groups[12][0]]) { - case 'Date': - case 'String': - case 'RegExp': - return ['NanNew', arguments[groups[12][0] - 1], arguments[groups[12][0] + 1], '.ToLocalChecked()'].join(''); - default: - } - - /* NanEquals is now required for uniformity */ - if (arguments[groups[13][0]] === 'Equals') { - return [arguments[groups[13][0] - 1], 'NanEquals(', arguments[groups[13][0] - 1], ', ', arguments[groups[13][0] + 1]].join(''); - } - - /* use method on replacement class instead */ - if (arguments[groups[14][0]] === 'NanAssignPersistent') { - return [arguments[groups[14][0] + 1], '.Reset('].join(''); - } - - /* args --> info */ - if (arguments[groups[15][0]] === 'args') { - return [arguments[groups[15][0] - 1], 'info', arguments[groups[15][0] + 1]].join(''); - } - - /* ObjectWrap --> NanObjectWrap */ - if (arguments[groups[16][0]] === 'ObjectWrap') { - return [arguments[groups[16][0] - 1], 'NanObjectWrap', arguments[groups[16][0] + 1]].join(''); - } - - /* Persistent --> NanPersistent */ - if (arguments[groups[17][0]] === 'Persistent') { - return [arguments[groups[17][0] - 1], 'NanPersistent', arguments[groups[17][0] + 1]].join(''); - } - - /* This should not happen. A switch is probably missing a case if it does. */ - throw 'Unhandled match: ' + arguments[0]; -} - -/* reads a file, runs replacement and writes it back */ -function processFile(file) { - fs.readFile(file, {encoding: 'utf8'}, function (err, data) { - if (err) { - throw err; - } - - /* run replacement twice, might need more runs */ - fs.writeFile(file, data.replace(master, replace).replace(master, replace), function (err) { - if (err) { - throw err; - } - }); - }); -} - -/* process file names from command line and process the identified files */ -for (i = 2, length = process.argv.length; i < length; i++) { - glob(process.argv[i], function (err, matches) { - if (err) { - throw err; - } - matches.forEach(processFile); - }); -} diff --git a/reverse_engineering/node_modules/nan/tools/README.md b/reverse_engineering/node_modules/nan/tools/README.md deleted file mode 100644 index 7f07e4b..0000000 --- a/reverse_engineering/node_modules/nan/tools/README.md +++ /dev/null @@ -1,14 +0,0 @@ -1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions, -false positives and missed opportunities. The input files are rewritten in place. Make sure that -you have backups. You will have to manually review the changes afterwards and do some touchups. - -```sh -$ tools/1to2.js - - Usage: 1to2 [options] - - Options: - - -h, --help output usage information - -V, --version output the version number -``` diff --git a/reverse_engineering/node_modules/nan/tools/package.json b/reverse_engineering/node_modules/nan/tools/package.json deleted file mode 100644 index 2dcdd78..0000000 --- a/reverse_engineering/node_modules/nan/tools/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "1to2", - "version": "1.0.0", - "description": "NAN 1 -> 2 Migration Script", - "main": "1to2.js", - "repository": { - "type": "git", - "url": "git://github.com/nodejs/nan.git" - }, - "contributors": [ - "Benjamin Byholm (https://github.com/kkoopa/)", - "Mathias Küsel (https://github.com/mathiask88/)" - ], - "dependencies": { - "glob": "~5.0.10", - "commander": "~2.8.1" - }, - "license": "MIT" -} diff --git a/reverse_engineering/node_modules/packet-reader/.travis.yml b/reverse_engineering/node_modules/packet-reader/.travis.yml deleted file mode 100644 index ac2e9ee..0000000 --- a/reverse_engineering/node_modules/packet-reader/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: node_js - -node_js: "10" -matrix: - include: - - node_js: "4" - - node_js: "6" - - node_js: "8" diff --git a/reverse_engineering/node_modules/packet-reader/README.md b/reverse_engineering/node_modules/packet-reader/README.md deleted file mode 100644 index 5ae3ef8..0000000 --- a/reverse_engineering/node_modules/packet-reader/README.md +++ /dev/null @@ -1,87 +0,0 @@ -node-packet-reader -================== - -Handy little well tested module for reading length-prefixed binary packets. - -Since buffers come off a socket in randomly sized chunks you can't expect them to cleanly -break on packet boundaries. This module allows you to push buffers in and read -full packets out the other side, so you can get to parsing right away and not have -to manage concatenating partial buffers and searching through them for packets. - -## install - -` $ npm install packet-reader ` - -## example - -```js -var Reader = require('packet-reader') - -var reader = new Reader() -//assuming you have a socket emitting `data` events -socket.on('data', function(buffer) { - reader.addChunk(buffer) - var packet = reader.read() - while(packet) { - //do something with fully parsed packet - } -}) -``` - - -here's a more full featured example: - -let's assume our "packet" for our protocol is 32-bit Big Endian length-prefixed strings -so a "hello world" packet would look something like [length, string] -`[0, 0, 0 0x0B, h, e, l, l, o, w, o, r, l, d]` - -```js -var Transform = require('stream').Transform -var Reader = require('packet-reader') -var reader = new Reader() -var parser = new Transform() -parser._transform = function(chunk, encoding, cb) { - reader.addChunk(chunk) - var packet = reader.read() - while(packet) { - this.push(packet.toString('utf8')) - packet = reader.read() - } - cb() -} - -var server = net.createServer(function(socket) { - socket.pipe(parser).pipe(stdout) -}) - -``` - -There are a few config options for setting optional pre-length padding byte. Read the tests for details. - -## License - -MIT - -Copyright 2015 Brian M. Carlson -All rights reserved. - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/packet-reader/index.js b/reverse_engineering/node_modules/packet-reader/index.js deleted file mode 100644 index 5e97e21..0000000 --- a/reverse_engineering/node_modules/packet-reader/index.js +++ /dev/null @@ -1,65 +0,0 @@ -var assert = require('assert') - -var Reader = module.exports = function(options) { - //TODO - remove for version 1.0 - if(typeof options == 'number') { - options = { headerSize: options } - } - options = options || {} - this.offset = 0 - this.lastChunk = false - this.chunk = null - this.chunkLength = 0 - this.headerSize = options.headerSize || 0 - this.lengthPadding = options.lengthPadding || 0 - this.header = null - assert(this.headerSize < 2, 'pre-length header of more than 1 byte length not currently supported') -} - -Reader.prototype.addChunk = function(chunk) { - if (!this.chunk || this.offset === this.chunkLength) { - this.chunk = chunk - this.chunkLength = chunk.length - this.offset = 0 - return - } - - var newChunkLength = chunk.length - var newLength = this.chunkLength + newChunkLength - - if (newLength > this.chunk.length) { - var newBufferLength = this.chunk.length * 2 - while (newLength >= newBufferLength) { - newBufferLength *= 2 - } - var newBuffer = Buffer.alloc(newBufferLength) - this.chunk.copy(newBuffer) - this.chunk = newBuffer - } - chunk.copy(this.chunk, this.chunkLength) - this.chunkLength = newLength -} - -Reader.prototype.read = function() { - if(this.chunkLength < (this.headerSize + 4 + this.offset)) { - return false - } - - if(this.headerSize) { - this.header = this.chunk[this.offset] - } - - //read length of next item - var length = this.chunk.readUInt32BE(this.offset + this.headerSize) + this.lengthPadding - - //next item spans more chunks than we have - var remaining = this.chunkLength - (this.offset + 4 + this.headerSize) - if(length > remaining) { - return false - } - - this.offset += (this.headerSize + 4) - var result = this.chunk.slice(this.offset, this.offset + length) - this.offset += length - return result -} diff --git a/reverse_engineering/node_modules/packet-reader/package.json b/reverse_engineering/node_modules/packet-reader/package.json deleted file mode 100644 index 37c48c4..0000000 --- a/reverse_engineering/node_modules/packet-reader/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "_from": "packet-reader@1.0.0", - "_id": "packet-reader@1.0.0", - "_inBundle": false, - "_integrity": "sha512-HAKu/fG3HpHFO0AA8WE8q2g+gBJaZ9MG7fcKk+IJPLTGAD6Psw4443l+9DGRbOIh3/aXr7Phy0TjilYivJo5XQ==", - "_location": "/packet-reader", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "packet-reader@1.0.0", - "name": "packet-reader", - "escapedName": "packet-reader", - "rawSpec": "1.0.0", - "saveSpec": null, - "fetchSpec": "1.0.0" - }, - "_requiredBy": [ - "/pg" - ], - "_resolved": "https://registry.npmjs.org/packet-reader/-/packet-reader-1.0.0.tgz", - "_shasum": "9238e5480dedabacfe1fe3f2771063f164157d74", - "_spec": "packet-reader@1.0.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg", - "author": { - "name": "Brian M. Carlson" - }, - "bugs": { - "url": "https://github.com/brianc/node-packet-reader/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Read binary packets...", - "devDependencies": { - "mocha": "~1.21.5" - }, - "directories": { - "test": "test" - }, - "homepage": "https://github.com/brianc/node-packet-reader", - "license": "MIT", - "main": "index.js", - "name": "packet-reader", - "repository": { - "type": "git", - "url": "git://github.com/brianc/node-packet-reader.git" - }, - "scripts": { - "test": "mocha" - }, - "version": "1.0.0" -} diff --git a/reverse_engineering/node_modules/packet-reader/test/index.js b/reverse_engineering/node_modules/packet-reader/test/index.js deleted file mode 100644 index 0e2eedb..0000000 --- a/reverse_engineering/node_modules/packet-reader/test/index.js +++ /dev/null @@ -1,148 +0,0 @@ -var assert = require('assert') -var Reader = require('../') -describe('packet-reader', function() { - beforeEach(function() { - this.reader = new Reader(1) - }) - - it('reads perfect 1 length buffer', function() { - this.reader.addChunk(Buffer.from([0, 0, 0, 0, 1, 1])) - var result = this.reader.read() - assert.equal(result.length, 1) - assert.equal(result[0], 1) - assert.strictEqual(false, this.reader.read()) - }) - - it('reads perfect longer buffer', function() { - this.reader.addChunk(Buffer.from([0, 0, 0, 0, 4, 1, 2, 3, 4])) - var result = this.reader.read() - assert.equal(result.length, 4) - assert.strictEqual(false, this.reader.read()) - }) - - it('reads two parts', function() { - this.reader.addChunk(Buffer.from([0, 0, 0, 0, 1])) - var result = this.reader.read() - assert.strictEqual(false, result) - this.reader.addChunk(Buffer.from([2])) - var result = this.reader.read() - assert.equal(result.length, 1, 'should return 1 length buffer') - assert.equal(result[0], 2) - assert.strictEqual(this.reader.read(), false) - }) - - it('reads multi-part', function() { - this.reader.addChunk(Buffer.from([0, 0, 0, 0, 16])) - assert.equal(false, this.reader.read()) - this.reader.addChunk(Buffer.from([1, 2, 3, 4, 5, 6, 7, 8])) - assert.equal(false, this.reader.read()) - this.reader.addChunk(Buffer.from([9, 10, 11, 12, 13, 14, 15, 16])) - var result = this.reader.read() - assert.equal(result.length, 16) - }) - - it('resets internal buffer at end of packet', function() { - this.reader.addChunk(Buffer.from([0, 0, 0, 0, 16])) - this.reader.addChunk(Buffer.from([1, 2, 3, 4, 5, 6, 7, 8])) - this.reader.addChunk(Buffer.from([9, 10, 11, 12, 13, 14, 15, 16])) - var result = this.reader.read() - assert.equal(result.length, 16) - - var newChunk = Buffer.from([0, 0, 0, 0, 16]) - this.reader.addChunk(newChunk) - assert.equal(this.reader.offset, 0, 'should have been reset to 0.') - assert.strictEqual(this.reader.chunk, newChunk) - }) - - it('reads multiple messages from single chunk', function() { - this.reader.addChunk(Buffer.from([0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 2, 1, 2])) - var result = this.reader.read() - assert.equal(result.length, 1, 'should have 1 length buffer') - assert.equal(result[0], 1) - var result = this.reader.read() - assert.equal(result.length, 2, 'should have 2 length buffer but was ' + result.length) - assert.equal(result[0], 1) - assert.equal(result[1], 2) - assert.strictEqual(false, this.reader.read()) - }) - - it('reads 1 and a split', function() { - this.reader.addChunk(Buffer.from([0, 0, 0, 0, 1, 1, 0, 0]))//, 0, 0, 2, 1, 2])) - var result = this.reader.read() - assert.equal(result.length, 1, 'should have 1 length buffer') - assert.equal(result[0], 1) - var result = this.reader.read() - assert.strictEqual(result, false) - - this.reader.addChunk(Buffer.from([0, 0, 2, 1, 2])) - var result = this.reader.read() - assert.equal(result.length, 2, 'should have 2 length buffer but was ' + result.length) - assert.equal(result[0], 1) - assert.equal(result[1], 2) - assert.strictEqual(false, this.reader.read()) - }) -}) - -describe('variable length header', function() { - beforeEach(function() { - this.reader = new Reader() - }) - - it('reads double message buffers', function() { - this.reader.addChunk(Buffer.from([ - 0, 0, 0, 1, 1, - 0, 0, 0, 2, 1, 2])) - var result = this.reader.read() - assert(result) - assert.equal(result.length, 1) - assert.equal(result[0], 1) - result = this.reader.read() - assert(result) - assert.equal(result.length, 2) - assert.equal(result[0], 1) - assert.equal(result[1], 2) - assert.strictEqual(this.reader.read(), false) - }) -}) - -describe('1 length code', function() { - beforeEach(function() { - this.reader = new Reader(1) - }) - - it('reads code', function() { - this.reader.addChunk(Buffer.from([9, 0, 0, 0, 1, 1])) - var result = this.reader.read() - assert(result) - assert.equal(this.reader.header, 9) - assert.equal(result.length, 1) - assert.equal(result[0], 1) - }) - - it('is set on uncompleted read', function() { - assert.equal(this.reader.header, null) - this.reader.addChunk(Buffer.from([2, 0, 0, 0, 1])) - assert.strictEqual(this.reader.read(), false) - assert.equal(this.reader.header, 2) - }) -}) - -describe('postgres style packet', function() { - beforeEach(function() { - this.reader = new Reader({ - headerSize: 1, - lengthPadding: -4 - }) - }) - - it('reads with padded length', function() { - this.reader.addChunk(Buffer.from([1, 0, 0, 0, 8, 0, 0, 2, 0])) - var result = this.reader.read() - assert(result) - assert.equal(result.length, 4) - assert.equal(result[0], 0) - assert.equal(result[1], 0) - assert.equal(result[2], 2) - assert.equal(result[3], 0) - }) -}) diff --git a/reverse_engineering/node_modules/pg-connection-string/LICENSE b/reverse_engineering/node_modules/pg-connection-string/LICENSE deleted file mode 100644 index b068a6c..0000000 --- a/reverse_engineering/node_modules/pg-connection-string/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Iced Development - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-connection-string/README.md b/reverse_engineering/node_modules/pg-connection-string/README.md deleted file mode 100644 index 360505e..0000000 --- a/reverse_engineering/node_modules/pg-connection-string/README.md +++ /dev/null @@ -1,77 +0,0 @@ -pg-connection-string -==================== - -[![NPM](https://nodei.co/npm/pg-connection-string.png?compact=true)](https://nodei.co/npm/pg-connection-string/) - -[![Build Status](https://travis-ci.org/iceddev/pg-connection-string.svg?branch=master)](https://travis-ci.org/iceddev/pg-connection-string) -[![Coverage Status](https://coveralls.io/repos/github/iceddev/pg-connection-string/badge.svg?branch=master)](https://coveralls.io/github/iceddev/pg-connection-string?branch=master) - -Functions for dealing with a PostgresSQL connection string - -`parse` method taken from [node-postgres](https://github.com/brianc/node-postgres.git) -Copyright (c) 2010-2014 Brian Carlson (brian.m.carlson@gmail.com) -MIT License - -## Usage - -```js -var parse = require('pg-connection-string').parse; - -var config = parse('postgres://someuser:somepassword@somehost:381/somedatabase') -``` - -The resulting config contains a subset of the following properties: - -* `host` - Postgres server hostname or, for UNIX domain sockets, the socket filename -* `port` - port on which to connect -* `user` - User with which to authenticate to the server -* `password` - Corresponding password -* `database` - Database name within the server -* `client_encoding` - string encoding the client will use -* `ssl`, either a boolean or an object with properties - * `rejectUnauthorized` - * `cert` - * `key` - * `ca` -* any other query parameters (for example, `application_name`) are preserved intact. - -## Connection Strings - -The short summary of acceptable URLs is: - - * `socket:?` - UNIX domain socket - * `postgres://:@:/?` - TCP connection - -But see below for more details. - -### UNIX Domain Sockets - -When user and password are not given, the socket path follows `socket:`, as in `socket:/var/run/pgsql`. -This form can be shortened to just a path: `/var/run/pgsql`. - -When user and password are given, they are included in the typical URL positions, with an empty `host`, as in `socket://user:pass@/var/run/pgsql`. - -Query parameters follow a `?` character, including the following special query parameters: - - * `db=` - sets the database name (urlencoded) - * `encoding=` - sets the `client_encoding` property - -### TCP Connections - -TCP connections to the Postgres server are indicated with `pg:` or `postgres:` schemes (in fact, any scheme but `socket:` is accepted). -If username and password are included, they should be urlencoded. -The database name, however, should *not* be urlencoded. - -Query parameters follow a `?` character, including the following special query parameters: - * `host=` - sets `host` property, overriding the URL's host - * `encoding=` - sets the `client_encoding` property - * `ssl=1`, `ssl=true`, `ssl=0`, `ssl=false` - sets `ssl` to true or false, accordingly - * `sslmode=` - * `sslmode=disable` - sets `ssl` to false - * `sslmode=no-verify` - sets `ssl` to `{ rejectUnauthorized: false }` - * `sslmode=prefer`, `sslmode=require`, `sslmode=verify-ca`, `sslmode=verify-full` - sets `ssl` to true - * `sslcert=` - reads data from the given file and includes the result as `ssl.cert` - * `sslkey=` - reads data from the given file and includes the result as `ssl.key` - * `sslrootcert=` - reads data from the given file and includes the result as `ssl.ca` - -A bare relative URL, such as `salesdata`, will indicate a database name while leaving other properties empty. diff --git a/reverse_engineering/node_modules/pg-connection-string/index.d.ts b/reverse_engineering/node_modules/pg-connection-string/index.d.ts deleted file mode 100644 index 3081270..0000000 --- a/reverse_engineering/node_modules/pg-connection-string/index.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -export function parse(connectionString: string): ConnectionOptions - -export interface ConnectionOptions { - host: string | null - password?: string - user?: string - port?: string | null - database: string | null | undefined - client_encoding?: string - ssl?: boolean | string - - application_name?: string - fallback_application_name?: string - options?: string -} diff --git a/reverse_engineering/node_modules/pg-connection-string/index.js b/reverse_engineering/node_modules/pg-connection-string/index.js deleted file mode 100644 index 995ff06..0000000 --- a/reverse_engineering/node_modules/pg-connection-string/index.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict' - -var url = require('url') -var fs = require('fs') - -//Parse method copied from https://github.com/brianc/node-postgres -//Copyright (c) 2010-2014 Brian Carlson (brian.m.carlson@gmail.com) -//MIT License - -//parses a connection string -function parse(str) { - //unix socket - if (str.charAt(0) === '/') { - var config = str.split(' ') - return { host: config[0], database: config[1] } - } - - // url parse expects spaces encoded as %20 - var result = url.parse( - / |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str) ? encodeURI(str).replace(/\%25(\d\d)/g, '%$1') : str, - true - ) - var config = result.query - for (var k in config) { - if (Array.isArray(config[k])) { - config[k] = config[k][config[k].length - 1] - } - } - - var auth = (result.auth || ':').split(':') - config.user = auth[0] - config.password = auth.splice(1).join(':') - - config.port = result.port - if (result.protocol == 'socket:') { - config.host = decodeURI(result.pathname) - config.database = result.query.db - config.client_encoding = result.query.encoding - return config - } - if (!config.host) { - // Only set the host if there is no equivalent query param. - config.host = result.hostname - } - - // If the host is missing it might be a URL-encoded path to a socket. - var pathname = result.pathname - if (!config.host && pathname && /^%2f/i.test(pathname)) { - var pathnameSplit = pathname.split('/') - config.host = decodeURIComponent(pathnameSplit[0]) - pathname = pathnameSplit.splice(1).join('/') - } - // result.pathname is not always guaranteed to have a '/' prefix (e.g. relative urls) - // only strip the slash if it is present. - if (pathname && pathname.charAt(0) === '/') { - pathname = pathname.slice(1) || null - } - config.database = pathname && decodeURI(pathname) - - if (config.ssl === 'true' || config.ssl === '1') { - config.ssl = true - } - - if (config.ssl === '0') { - config.ssl = false - } - - if (config.sslcert || config.sslkey || config.sslrootcert || config.sslmode) { - config.ssl = {} - } - - if (config.sslcert) { - config.ssl.cert = fs.readFileSync(config.sslcert).toString() - } - - if (config.sslkey) { - config.ssl.key = fs.readFileSync(config.sslkey).toString() - } - - if (config.sslrootcert) { - config.ssl.ca = fs.readFileSync(config.sslrootcert).toString() - } - - switch (config.sslmode) { - case 'disable': { - config.ssl = false - break - } - case 'prefer': - case 'require': - case 'verify-ca': - case 'verify-full': { - break - } - case 'no-verify': { - config.ssl.rejectUnauthorized = false - break - } - } - - return config -} - -module.exports = parse - -parse.parse = parse diff --git a/reverse_engineering/node_modules/pg-connection-string/package.json b/reverse_engineering/node_modules/pg-connection-string/package.json deleted file mode 100644 index 6b2380d..0000000 --- a/reverse_engineering/node_modules/pg-connection-string/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "pg-connection-string@^2.5.0", - "_id": "pg-connection-string@2.5.0", - "_inBundle": false, - "_integrity": "sha512-r5o/V/ORTA6TmUnyWZR9nCj1klXCO2CEKNRlVuJptZe85QuhFayC7WeMic7ndayT5IRIR0S0xFxFi2ousartlQ==", - "_location": "/pg-connection-string", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "pg-connection-string@^2.5.0", - "name": "pg-connection-string", - "escapedName": "pg-connection-string", - "rawSpec": "^2.5.0", - "saveSpec": null, - "fetchSpec": "^2.5.0" - }, - "_requiredBy": [ - "/pg" - ], - "_resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.5.0.tgz", - "_shasum": "538cadd0f7e603fc09a12590f3b8a452c2c0cf34", - "_spec": "pg-connection-string@^2.5.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg", - "author": { - "name": "Blaine Bublitz", - "email": "blaine@iceddev.com", - "url": "http://iceddev.com/" - }, - "bugs": { - "url": "https://github.com/brianc/node-postgres/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Functions for dealing with a PostgresSQL connection string", - "devDependencies": { - "chai": "^4.1.1", - "coveralls": "^3.0.4", - "istanbul": "^0.4.5", - "mocha": "^7.1.2" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "gitHead": "d45947938263bec30a1e3252452f04177b785f66", - "homepage": "https://github.com/brianc/node-postgres/tree/master/packages/pg-connection-string", - "keywords": [ - "pg", - "connection", - "string", - "parse" - ], - "license": "MIT", - "main": "./index.js", - "name": "pg-connection-string", - "repository": { - "type": "git", - "url": "git://github.com/brianc/node-postgres.git", - "directory": "packages/pg-connection-string" - }, - "scripts": { - "check-coverage": "istanbul check-coverage --statements 100 --branches 100 --lines 100 --functions 100", - "coveralls": "cat ./coverage/lcov.info | ./node_modules/.bin/coveralls", - "test": "istanbul cover _mocha && npm run check-coverage" - }, - "types": "./index.d.ts", - "version": "2.5.0" -} diff --git a/reverse_engineering/node_modules/pg-int8/LICENSE b/reverse_engineering/node_modules/pg-int8/LICENSE deleted file mode 100644 index c56c973..0000000 --- a/reverse_engineering/node_modules/pg-int8/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright © 2017, Charmander <~@charmander.me> - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/pg-int8/README.md b/reverse_engineering/node_modules/pg-int8/README.md deleted file mode 100644 index ef2e608..0000000 --- a/reverse_engineering/node_modules/pg-int8/README.md +++ /dev/null @@ -1,16 +0,0 @@ -[![Build status][ci image]][ci] - -64-bit big-endian signed integer-to-string conversion designed for [pg][]. - -```js -const readInt8 = require('pg-int8'); - -readInt8(Buffer.from([0, 1, 2, 3, 4, 5, 6, 7])) -// '283686952306183' -``` - - - [pg]: https://github.com/brianc/node-postgres - - [ci]: https://travis-ci.org/charmander/pg-int8 - [ci image]: https://api.travis-ci.org/charmander/pg-int8.svg diff --git a/reverse_engineering/node_modules/pg-int8/index.js b/reverse_engineering/node_modules/pg-int8/index.js deleted file mode 100644 index db77975..0000000 --- a/reverse_engineering/node_modules/pg-int8/index.js +++ /dev/null @@ -1,100 +0,0 @@ -'use strict'; - -// selected so (BASE - 1) * 0x100000000 + 0xffffffff is a safe integer -var BASE = 1000000; - -function readInt8(buffer) { - var high = buffer.readInt32BE(0); - var low = buffer.readUInt32BE(4); - var sign = ''; - - if (high < 0) { - high = ~high + (low === 0); - low = (~low + 1) >>> 0; - sign = '-'; - } - - var result = ''; - var carry; - var t; - var digits; - var pad; - var l; - var i; - - { - carry = high % BASE; - high = high / BASE >>> 0; - - t = 0x100000000 * carry + low; - low = t / BASE >>> 0; - digits = '' + (t - BASE * low); - - if (low === 0 && high === 0) { - return sign + digits + result; - } - - pad = ''; - l = 6 - digits.length; - - for (i = 0; i < l; i++) { - pad += '0'; - } - - result = pad + digits + result; - } - - { - carry = high % BASE; - high = high / BASE >>> 0; - - t = 0x100000000 * carry + low; - low = t / BASE >>> 0; - digits = '' + (t - BASE * low); - - if (low === 0 && high === 0) { - return sign + digits + result; - } - - pad = ''; - l = 6 - digits.length; - - for (i = 0; i < l; i++) { - pad += '0'; - } - - result = pad + digits + result; - } - - { - carry = high % BASE; - high = high / BASE >>> 0; - - t = 0x100000000 * carry + low; - low = t / BASE >>> 0; - digits = '' + (t - BASE * low); - - if (low === 0 && high === 0) { - return sign + digits + result; - } - - pad = ''; - l = 6 - digits.length; - - for (i = 0; i < l; i++) { - pad += '0'; - } - - result = pad + digits + result; - } - - { - carry = high % BASE; - t = 0x100000000 * carry + low; - digits = '' + t % BASE; - - return sign + digits + result; - } -} - -module.exports = readInt8; diff --git a/reverse_engineering/node_modules/pg-int8/package.json b/reverse_engineering/node_modules/pg-int8/package.json deleted file mode 100644 index 769354d..0000000 --- a/reverse_engineering/node_modules/pg-int8/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "_from": "pg-int8@1.0.1", - "_id": "pg-int8@1.0.1", - "_inBundle": false, - "_integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", - "_location": "/pg-int8", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "pg-int8@1.0.1", - "name": "pg-int8", - "escapedName": "pg-int8", - "rawSpec": "1.0.1", - "saveSpec": null, - "fetchSpec": "1.0.1" - }, - "_requiredBy": [ - "/pg-types" - ], - "_resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", - "_shasum": "943bd463bf5b71b4170115f80f8efc9a0c0eb78c", - "_spec": "pg-int8@1.0.1", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg-types", - "bugs": { - "url": "https://github.com/charmander/pg-int8/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "64-bit big-endian signed integer-to-string conversion", - "devDependencies": { - "@charmander/eslint-config-base": "1.0.2", - "tap": "10.7.3" - }, - "engines": { - "node": ">=4.0.0" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/charmander/pg-int8#readme", - "license": "ISC", - "name": "pg-int8", - "repository": { - "type": "git", - "url": "git+https://github.com/charmander/pg-int8.git" - }, - "scripts": { - "test": "tap test" - }, - "version": "1.0.1" -} diff --git a/reverse_engineering/node_modules/pg-pool/LICENSE b/reverse_engineering/node_modules/pg-pool/LICENSE deleted file mode 100644 index 4e90581..0000000 --- a/reverse_engineering/node_modules/pg-pool/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 Brian M. Carlson - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/reverse_engineering/node_modules/pg-pool/README.md b/reverse_engineering/node_modules/pg-pool/README.md deleted file mode 100644 index c6d7e92..0000000 --- a/reverse_engineering/node_modules/pg-pool/README.md +++ /dev/null @@ -1,376 +0,0 @@ -# pg-pool -[![Build Status](https://travis-ci.org/brianc/node-pg-pool.svg?branch=master)](https://travis-ci.org/brianc/node-pg-pool) - -A connection pool for node-postgres - -## install -```sh -npm i pg-pool pg -``` - -## use - -### create - -to use pg-pool you must first create an instance of a pool - -```js -var Pool = require('pg-pool') - -// by default the pool uses the same -// configuration as whatever `pg` version you have installed -var pool = new Pool() - -// you can pass properties to the pool -// these properties are passed unchanged to both the node-postgres Client constructor -// and the node-pool (https://github.com/coopernurse/node-pool) constructor -// allowing you to fully configure the behavior of both -var pool2 = new Pool({ - database: 'postgres', - user: 'brianc', - password: 'secret!', - port: 5432, - ssl: true, - max: 20, // set pool max size to 20 - idleTimeoutMillis: 1000, // close idle clients after 1 second - connectionTimeoutMillis: 1000, // return an error after 1 second if connection could not be established - maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion) -}) - -//you can supply a custom client constructor -//if you want to use the native postgres client -var NativeClient = require('pg').native.Client -var nativePool = new Pool({ Client: NativeClient }) - -//you can even pool pg-native clients directly -var PgNativeClient = require('pg-native') -var pgNativePool = new Pool({ Client: PgNativeClient }) -``` - -##### Note: -The Pool constructor does not support passing a Database URL as the parameter. To use pg-pool on heroku, for example, you need to parse the URL into a config object. Here is an example of how to parse a Database URL. - -```js -const Pool = require('pg-pool'); -const url = require('url') - -const params = url.parse(process.env.DATABASE_URL); -const auth = params.auth.split(':'); - -const config = { - user: auth[0], - password: auth[1], - host: params.hostname, - port: params.port, - database: params.pathname.split('/')[1], - ssl: true -}; - -const pool = new Pool(config); - -/* - Transforms, 'postgres://DBuser:secret@DBHost:#####/myDB', into - config = { - user: 'DBuser', - password: 'secret', - host: 'DBHost', - port: '#####', - database: 'myDB', - ssl: true - } -*/ -``` - -### acquire clients with a promise - -pg-pool supports a fully promise-based api for acquiring clients - -```js -var pool = new Pool() -pool.connect().then(client => { - client.query('select $1::text as name', ['pg-pool']).then(res => { - client.release() - console.log('hello from', res.rows[0].name) - }) - .catch(e => { - client.release() - console.error('query error', e.message, e.stack) - }) -}) -``` - -### plays nice with async/await - -this ends up looking much nicer if you're using [co](https://github.com/tj/co) or async/await: - -```js -// with async/await -(async () => { - var pool = new Pool() - var client = await pool.connect() - try { - var result = await client.query('select $1::text as name', ['brianc']) - console.log('hello from', result.rows[0]) - } finally { - client.release() - } -})().catch(e => console.error(e.message, e.stack)) - -// with co -co(function * () { - var client = yield pool.connect() - try { - var result = yield client.query('select $1::text as name', ['brianc']) - console.log('hello from', result.rows[0]) - } finally { - client.release() - } -}).catch(e => console.error(e.message, e.stack)) -``` - -### your new favorite helper method - -because its so common to just run a query and return the client to the pool afterward pg-pool has this built-in: - -```js -var pool = new Pool() -var time = await pool.query('SELECT NOW()') -var name = await pool.query('select $1::text as name', ['brianc']) -console.log(name.rows[0].name, 'says hello at', time.rows[0].name) -``` - -you can also use a callback here if you'd like: - -```js -var pool = new Pool() -pool.query('SELECT $1::text as name', ['brianc'], function (err, res) { - console.log(res.rows[0].name) // brianc -}) -``` - -__pro tip:__ unless you need to run a transaction (which requires a single client for multiple queries) or you -have some other edge case like [streaming rows](https://github.com/brianc/node-pg-query-stream) or using a [cursor](https://github.com/brianc/node-pg-cursor) -you should almost always just use `pool.query`. Its easy, it does the right thing :tm:, and wont ever forget to return -clients back to the pool after the query is done. - -### drop-in backwards compatible - -pg-pool still and will always support the traditional callback api for acquiring a client. This is the exact API node-postgres has shipped with for years: - -```js -var pool = new Pool() -pool.connect((err, client, done) => { - if (err) return done(err) - - client.query('SELECT $1::text as name', ['pg-pool'], (err, res) => { - done() - if (err) { - return console.error('query error', e.message, e.stack) - } - console.log('hello from', res.rows[0].name) - }) -}) -``` - -### shut it down - -When you are finished with the pool if all the clients are idle the pool will close them after `config.idleTimeoutMillis` and your app -will shutdown gracefully. If you don't want to wait for the timeout you can end the pool as follows: - -```js -var pool = new Pool() -var client = await pool.connect() -console.log(await client.query('select now()')) -client.release() -await pool.end() -``` - -### a note on instances - -The pool should be a __long-lived object__ in your application. Generally you'll want to instantiate one pool when your app starts up and use the same instance of the pool throughout the lifetime of your application. If you are frequently creating a new pool within your code you likely don't have your pool initialization code in the correct place. Example: - -```js -// assume this is a file in your program at ./your-app/lib/db.js - -// correct usage: create the pool and let it live -// 'globally' here, controlling access to it through exported methods -var pool = new pg.Pool() - -// this is the right way to export the query method -module.exports.query = (text, values) => { - console.log('query:', text, values) - return pool.query(text, values) -} - -// this would be the WRONG way to export the connect method -module.exports.connect = () => { - // notice how we would be creating a pool instance here - // every time we called 'connect' to get a new client? - // that's a bad thing & results in creating an unbounded - // number of pools & therefore connections - var aPool = new pg.Pool() - return aPool.connect() -} -``` - -### events - -Every instance of a `Pool` is an event emitter. These instances emit the following events: - -#### error - -Emitted whenever an idle client in the pool encounters an error. This is common when your PostgreSQL server shuts down, reboots, or a network partition otherwise causes it to become unavailable while your pool has connected clients. - -Example: - -```js -const Pool = require('pg-pool') -const pool = new Pool() - -// attach an error handler to the pool for when a connected, idle client -// receives an error by being disconnected, etc -pool.on('error', function(error, client) { - // handle this in the same way you would treat process.on('uncaughtException') - // it is supplied the error as well as the idle client which received the error -}) -``` - -#### connect - -Fired whenever the pool creates a __new__ `pg.Client` instance and successfully connects it to the backend. - -Example: - -```js -const Pool = require('pg-pool') -const pool = new Pool() - -var count = 0 - -pool.on('connect', client => { - client.count = count++ -}) - -pool - .connect() - .then(client => { - return client - .query('SELECT $1::int AS "clientCount"', [client.count]) - .then(res => console.log(res.rows[0].clientCount)) // outputs 0 - .then(() => client) - }) - .then(client => client.release()) - -``` - -#### acquire - -Fired whenever the a client is acquired from the pool - -Example: - -This allows you to count the number of clients which have ever been acquired from the pool. - -```js -var Pool = require('pg-pool') -var pool = new Pool() - -var acquireCount = 0 -pool.on('acquire', function (client) { - acquireCount++ -}) - -var connectCount = 0 -pool.on('connect', function () { - connectCount++ -}) - -for (var i = 0; i < 200; i++) { - pool.query('SELECT NOW()') -} - -setTimeout(function () { - console.log('connect count:', connectCount) // output: connect count: 10 - console.log('acquire count:', acquireCount) // output: acquire count: 200 -}, 100) - -``` - -### environment variables - -pg-pool & node-postgres support some of the same environment variables as `psql` supports. The most common are: - -``` -PGDATABASE=my_db -PGUSER=username -PGPASSWORD="my awesome password" -PGPORT=5432 -PGSSLMODE=require -``` - -Usually I will export these into my local environment via a `.env` file with environment settings or export them in `~/.bash_profile` or something similar. This way I get configurability which works with both the postgres suite of tools (`psql`, `pg_dump`, `pg_restore`) and node, I can vary the environment variables locally and in production, and it supports the concept of a [12-factor app](http://12factor.net/) out of the box. - -## bring your own promise - -In versions of node `<=0.12.x` there is no native promise implementation available globally. You can polyfill the promise globally like this: - -```js -// first run `npm install promise-polyfill --save -if (typeof Promise == 'undefined') { - global.Promise = require('promise-polyfill') -} -``` - -You can use any other promise implementation you'd like. The pool also allows you to configure the promise implementation on a per-pool level: - -```js -var bluebirdPool = new Pool({ - Promise: require('bluebird') -}) -``` - -__please note:__ in node `<=0.12.x` the pool will throw if you do not provide a promise constructor in one of the two ways mentioned above. In node `>=4.0.0` the pool will use the native promise implementation by default; however, the two methods above still allow you to "bring your own." - -## maxUses and read-replica autoscaling (e.g. AWS Aurora) - -The maxUses config option can help an application instance rebalance load against a replica set that has been auto-scaled after the connection pool is already full of healthy connections. - -The mechanism here is that a connection is considered "expended" after it has been acquired and released `maxUses` number of times. Depending on the load on your system, this means there will be an approximate time in which any given connection will live, thus creating a window for rebalancing. - -Imagine a scenario where you have 10 app instances providing an API running against a replica cluster of 3 that are accessed via a round-robin DNS entry. Each instance runs a connection pool size of 20. With an ambient load of 50 requests per second, the connection pool will likely fill up in a few minutes with healthy connections. - -If you have weekly bursts of traffic which peak at 1,000 requests per second, you might want to grow your replicas to 10 during this period. Without setting `maxUses`, the new replicas will not be adopted by the app servers without an intervention -- namely, restarting each in turn in order to build up new connection pools that are balanced against all the replicas. Adding additional app server instances will help to some extent because they will adopt all the replicas in an even way, but the initial app servers will continue to focus additional load on the original replicas. - -This is where the `maxUses` configuration option comes into play. Setting `maxUses` to 7500 will ensure that over a period of 30 minutes or so the new replicas will be adopted as the pre-existing connections are closed and replaced with new ones, thus creating a window for eventual balance. - -You'll want to test based on your own scenarios, but one way to make a first guess at `maxUses` is to identify an acceptable window for rebalancing and then solve for the value: - -``` -maxUses = rebalanceWindowSeconds * totalRequestsPerSecond / numAppInstances / poolSize -``` - -In the example above, assuming we acquire and release 1 connection per request and we are aiming for a 30 minute rebalancing window: - -``` -maxUses = rebalanceWindowSeconds * totalRequestsPerSecond / numAppInstances / poolSize - 7200 = 1800 * 1000 / 10 / 25 -``` - -## tests - -To run tests clone the repo, `npm i` in the working dir, and then run `npm test` - -## contributions - -I love contributions. Please make sure they have tests, and submit a PR. If you're not sure if the issue is worth it or will be accepted it never hurts to open an issue to begin the conversation. If you're interested in keeping up with node-postgres releated stuff, you can follow me on twitter at [@briancarlson](https://twitter.com/briancarlson) - I generally announce any noteworthy updates there. - -## license - -The MIT License (MIT) -Copyright (c) 2016 Brian M. Carlson - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/pg-pool/index.js b/reverse_engineering/node_modules/pg-pool/index.js deleted file mode 100644 index 48bf5c7..0000000 --- a/reverse_engineering/node_modules/pg-pool/index.js +++ /dev/null @@ -1,421 +0,0 @@ -'use strict' -const EventEmitter = require('events').EventEmitter - -const NOOP = function () {} - -const removeWhere = (list, predicate) => { - const i = list.findIndex(predicate) - - return i === -1 ? undefined : list.splice(i, 1)[0] -} - -class IdleItem { - constructor(client, idleListener, timeoutId) { - this.client = client - this.idleListener = idleListener - this.timeoutId = timeoutId - } -} - -class PendingItem { - constructor(callback) { - this.callback = callback - } -} - -function throwOnDoubleRelease() { - throw new Error('Release called on client which has already been released to the pool.') -} - -function promisify(Promise, callback) { - if (callback) { - return { callback: callback, result: undefined } - } - let rej - let res - const cb = function (err, client) { - err ? rej(err) : res(client) - } - const result = new Promise(function (resolve, reject) { - res = resolve - rej = reject - }) - return { callback: cb, result: result } -} - -function makeIdleListener(pool, client) { - return function idleListener(err) { - err.client = client - - client.removeListener('error', idleListener) - client.on('error', () => { - pool.log('additional client error after disconnection due to error', err) - }) - pool._remove(client) - // TODO - document that once the pool emits an error - // the client has already been closed & purged and is unusable - pool.emit('error', err, client) - } -} - -class Pool extends EventEmitter { - constructor(options, Client) { - super() - this.options = Object.assign({}, options) - - if (options != null && 'password' in options) { - // "hiding" the password so it doesn't show up in stack traces - // or if the client is console.logged - Object.defineProperty(this.options, 'password', { - configurable: true, - enumerable: false, - writable: true, - value: options.password, - }) - } - if (options != null && options.ssl && options.ssl.key) { - // "hiding" the ssl->key so it doesn't show up in stack traces - // or if the client is console.logged - Object.defineProperty(this.options.ssl, 'key', { - enumerable: false, - }) - } - - this.options.max = this.options.max || this.options.poolSize || 10 - this.options.maxUses = this.options.maxUses || Infinity - this.options.allowExitOnIdle = this.options.allowExitOnIdle || false - this.log = this.options.log || function () {} - this.Client = this.options.Client || Client || require('pg').Client - this.Promise = this.options.Promise || global.Promise - - if (typeof this.options.idleTimeoutMillis === 'undefined') { - this.options.idleTimeoutMillis = 10000 - } - - this._clients = [] - this._idle = [] - this._pendingQueue = [] - this._endCallback = undefined - this.ending = false - this.ended = false - } - - _isFull() { - return this._clients.length >= this.options.max - } - - _pulseQueue() { - this.log('pulse queue') - if (this.ended) { - this.log('pulse queue ended') - return - } - if (this.ending) { - this.log('pulse queue on ending') - if (this._idle.length) { - this._idle.slice().map((item) => { - this._remove(item.client) - }) - } - if (!this._clients.length) { - this.ended = true - this._endCallback() - } - return - } - // if we don't have any waiting, do nothing - if (!this._pendingQueue.length) { - this.log('no queued requests') - return - } - // if we don't have any idle clients and we have no more room do nothing - if (!this._idle.length && this._isFull()) { - return - } - const pendingItem = this._pendingQueue.shift() - if (this._idle.length) { - const idleItem = this._idle.pop() - clearTimeout(idleItem.timeoutId) - const client = idleItem.client - client.ref && client.ref() - const idleListener = idleItem.idleListener - - return this._acquireClient(client, pendingItem, idleListener, false) - } - if (!this._isFull()) { - return this.newClient(pendingItem) - } - throw new Error('unexpected condition') - } - - _remove(client) { - const removed = removeWhere(this._idle, (item) => item.client === client) - - if (removed !== undefined) { - clearTimeout(removed.timeoutId) - } - - this._clients = this._clients.filter((c) => c !== client) - client.end() - this.emit('remove', client) - } - - connect(cb) { - if (this.ending) { - const err = new Error('Cannot use a pool after calling end on the pool') - return cb ? cb(err) : this.Promise.reject(err) - } - - const response = promisify(this.Promise, cb) - const result = response.result - - // if we don't have to connect a new client, don't do so - if (this._isFull() || this._idle.length) { - // if we have idle clients schedule a pulse immediately - if (this._idle.length) { - process.nextTick(() => this._pulseQueue()) - } - - if (!this.options.connectionTimeoutMillis) { - this._pendingQueue.push(new PendingItem(response.callback)) - return result - } - - const queueCallback = (err, res, done) => { - clearTimeout(tid) - response.callback(err, res, done) - } - - const pendingItem = new PendingItem(queueCallback) - - // set connection timeout on checking out an existing client - const tid = setTimeout(() => { - // remove the callback from pending waiters because - // we're going to call it with a timeout error - removeWhere(this._pendingQueue, (i) => i.callback === queueCallback) - pendingItem.timedOut = true - response.callback(new Error('timeout exceeded when trying to connect')) - }, this.options.connectionTimeoutMillis) - - this._pendingQueue.push(pendingItem) - return result - } - - this.newClient(new PendingItem(response.callback)) - - return result - } - - newClient(pendingItem) { - const client = new this.Client(this.options) - this._clients.push(client) - const idleListener = makeIdleListener(this, client) - - this.log('checking client timeout') - - // connection timeout logic - let tid - let timeoutHit = false - if (this.options.connectionTimeoutMillis) { - tid = setTimeout(() => { - this.log('ending client due to timeout') - timeoutHit = true - // force kill the node driver, and let libpq do its teardown - client.connection ? client.connection.stream.destroy() : client.end() - }, this.options.connectionTimeoutMillis) - } - - this.log('connecting new client') - client.connect((err) => { - if (tid) { - clearTimeout(tid) - } - client.on('error', idleListener) - if (err) { - this.log('client failed to connect', err) - // remove the dead client from our list of clients - this._clients = this._clients.filter((c) => c !== client) - if (timeoutHit) { - err.message = 'Connection terminated due to connection timeout' - } - - // this client won’t be released, so move on immediately - this._pulseQueue() - - if (!pendingItem.timedOut) { - pendingItem.callback(err, undefined, NOOP) - } - } else { - this.log('new client connected') - - return this._acquireClient(client, pendingItem, idleListener, true) - } - }) - } - - // acquire a client for a pending work item - _acquireClient(client, pendingItem, idleListener, isNew) { - if (isNew) { - this.emit('connect', client) - } - - this.emit('acquire', client) - - client.release = this._releaseOnce(client, idleListener) - - client.removeListener('error', idleListener) - - if (!pendingItem.timedOut) { - if (isNew && this.options.verify) { - this.options.verify(client, (err) => { - if (err) { - client.release(err) - return pendingItem.callback(err, undefined, NOOP) - } - - pendingItem.callback(undefined, client, client.release) - }) - } else { - pendingItem.callback(undefined, client, client.release) - } - } else { - if (isNew && this.options.verify) { - this.options.verify(client, client.release) - } else { - client.release() - } - } - } - - // returns a function that wraps _release and throws if called more than once - _releaseOnce(client, idleListener) { - let released = false - - return (err) => { - if (released) { - throwOnDoubleRelease() - } - - released = true - this._release(client, idleListener, err) - } - } - - // release a client back to the poll, include an error - // to remove it from the pool - _release(client, idleListener, err) { - client.on('error', idleListener) - - client._poolUseCount = (client._poolUseCount || 0) + 1 - - // TODO(bmc): expose a proper, public interface _queryable and _ending - if (err || this.ending || !client._queryable || client._ending || client._poolUseCount >= this.options.maxUses) { - if (client._poolUseCount >= this.options.maxUses) { - this.log('remove expended client') - } - this._remove(client) - this._pulseQueue() - return - } - - // idle timeout - let tid - if (this.options.idleTimeoutMillis) { - tid = setTimeout(() => { - this.log('remove idle client') - this._remove(client) - }, this.options.idleTimeoutMillis) - - if (this.options.allowExitOnIdle) { - // allow Node to exit if this is all that's left - tid.unref() - } - } - - if (this.options.allowExitOnIdle) { - client.unref() - } - - this._idle.push(new IdleItem(client, idleListener, tid)) - this._pulseQueue() - } - - query(text, values, cb) { - // guard clause against passing a function as the first parameter - if (typeof text === 'function') { - const response = promisify(this.Promise, text) - setImmediate(function () { - return response.callback(new Error('Passing a function as the first parameter to pool.query is not supported')) - }) - return response.result - } - - // allow plain text query without values - if (typeof values === 'function') { - cb = values - values = undefined - } - const response = promisify(this.Promise, cb) - cb = response.callback - - this.connect((err, client) => { - if (err) { - return cb(err) - } - - let clientReleased = false - const onError = (err) => { - if (clientReleased) { - return - } - clientReleased = true - client.release(err) - cb(err) - } - - client.once('error', onError) - this.log('dispatching query') - client.query(text, values, (err, res) => { - this.log('query dispatched') - client.removeListener('error', onError) - if (clientReleased) { - return - } - clientReleased = true - client.release(err) - if (err) { - return cb(err) - } else { - return cb(undefined, res) - } - }) - }) - return response.result - } - - end(cb) { - this.log('ending') - if (this.ending) { - const err = new Error('Called end on pool more than once') - return cb ? cb(err) : this.Promise.reject(err) - } - this.ending = true - const promised = promisify(this.Promise, cb) - this._endCallback = promised.callback - this._pulseQueue() - return promised.result - } - - get waitingCount() { - return this._pendingQueue.length - } - - get idleCount() { - return this._idle.length - } - - get totalCount() { - return this._clients.length - } -} -module.exports = Pool diff --git a/reverse_engineering/node_modules/pg-pool/package.json b/reverse_engineering/node_modules/pg-pool/package.json deleted file mode 100644 index 240c4ee..0000000 --- a/reverse_engineering/node_modules/pg-pool/package.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "_from": "pg-pool@^3.4.1", - "_id": "pg-pool@3.4.1", - "_inBundle": false, - "_integrity": "sha512-TVHxR/gf3MeJRvchgNHxsYsTCHQ+4wm3VIHSS19z8NC0+gioEhq1okDY1sm/TYbfoP6JLFx01s0ShvZ3puP/iQ==", - "_location": "/pg-pool", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "pg-pool@^3.4.1", - "name": "pg-pool", - "escapedName": "pg-pool", - "rawSpec": "^3.4.1", - "saveSpec": null, - "fetchSpec": "^3.4.1" - }, - "_requiredBy": [ - "/pg" - ], - "_resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.4.1.tgz", - "_shasum": "0e71ce2c67b442a5e862a9c182172c37eda71e9c", - "_spec": "pg-pool@^3.4.1", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg", - "author": { - "name": "Brian M. Carlson" - }, - "bugs": { - "url": "https://github.com/brianc/node-pg-pool/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Connection pool for node-postgres", - "devDependencies": { - "bluebird": "3.4.1", - "co": "4.6.0", - "expect.js": "0.3.1", - "lodash": "^4.17.11", - "mocha": "^7.1.2", - "pg-cursor": "^1.3.0" - }, - "directories": { - "test": "test" - }, - "gitHead": "92b4d37926c276d343bfe56447ff6f526af757cf", - "homepage": "https://github.com/brianc/node-pg-pool#readme", - "keywords": [ - "pg", - "postgres", - "pool", - "database" - ], - "license": "MIT", - "main": "index.js", - "name": "pg-pool", - "peerDependencies": { - "pg": ">=8.0" - }, - "repository": { - "type": "git", - "url": "git://github.com/brianc/node-postgres.git", - "directory": "packages/pg-pool" - }, - "scripts": { - "test": " node_modules/.bin/mocha" - }, - "version": "3.4.1" -} diff --git a/reverse_engineering/node_modules/pg-pool/test/bring-your-own-promise.js b/reverse_engineering/node_modules/pg-pool/test/bring-your-own-promise.js deleted file mode 100644 index e905ccc..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/bring-your-own-promise.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict' -const co = require('co') -const expect = require('expect.js') - -const describe = require('mocha').describe -const it = require('mocha').it -const BluebirdPromise = require('bluebird') - -const Pool = require('../') - -const checkType = (promise) => { - expect(promise).to.be.a(BluebirdPromise) - return promise.catch((e) => undefined) -} - -describe('Bring your own promise', function () { - it( - 'uses supplied promise for operations', - co.wrap(function* () { - const pool = new Pool({ Promise: BluebirdPromise }) - const client1 = yield checkType(pool.connect()) - client1.release() - yield checkType(pool.query('SELECT NOW()')) - const client2 = yield checkType(pool.connect()) - // TODO - make sure pg supports BYOP as well - client2.release() - yield checkType(pool.end()) - }) - ) - - it( - 'uses promises in errors', - co.wrap(function* () { - const pool = new Pool({ Promise: BluebirdPromise, port: 48484 }) - yield checkType(pool.connect()) - yield checkType(pool.end()) - yield checkType(pool.connect()) - yield checkType(pool.query()) - yield checkType(pool.end()) - }) - ) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/connection-strings.js b/reverse_engineering/node_modules/pg-pool/test/connection-strings.js deleted file mode 100644 index de45830..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/connection-strings.js +++ /dev/null @@ -1,29 +0,0 @@ -const expect = require('expect.js') -const describe = require('mocha').describe -const it = require('mocha').it -const Pool = require('../') - -describe('Connection strings', function () { - it('pool delegates connectionString property to client', function (done) { - const connectionString = 'postgres://foo:bar@baz:1234/xur' - - const pool = new Pool({ - // use a fake client so we can check we're passed the connectionString - Client: function (args) { - expect(args.connectionString).to.equal(connectionString) - return { - connect: function (cb) { - cb(new Error('testing')) - }, - on: function () {}, - } - }, - connectionString: connectionString, - }) - - pool.connect(function (err, client) { - expect(err).to.not.be(undefined) - done() - }) - }) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/connection-timeout.js b/reverse_engineering/node_modules/pg-pool/test/connection-timeout.js deleted file mode 100644 index 05e8931..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/connection-timeout.js +++ /dev/null @@ -1,229 +0,0 @@ -'use strict' -const net = require('net') -const co = require('co') -const expect = require('expect.js') - -const describe = require('mocha').describe -const it = require('mocha').it -const before = require('mocha').before -const after = require('mocha').after - -const Pool = require('../') - -describe('connection timeout', () => { - const connectionFailure = new Error('Temporary connection failure') - - before((done) => { - this.server = net.createServer((socket) => { - socket.on('data', () => { - // discard any buffered data or the server wont terminate - }) - }) - - this.server.listen(() => { - this.port = this.server.address().port - done() - }) - }) - - after((done) => { - this.server.close(done) - }) - - it('should callback with an error if timeout is passed', (done) => { - const pool = new Pool({ connectionTimeoutMillis: 10, port: this.port, host: 'localhost' }) - pool.connect((err, client, release) => { - expect(err).to.be.an(Error) - expect(err.message).to.contain('timeout') - expect(client).to.equal(undefined) - expect(pool.idleCount).to.equal(0) - done() - }) - }) - - it('should reject promise with an error if timeout is passed', (done) => { - const pool = new Pool({ connectionTimeoutMillis: 10, port: this.port, host: 'localhost' }) - pool.connect().catch((err) => { - expect(err).to.be.an(Error) - expect(err.message).to.contain('timeout') - expect(pool.idleCount).to.equal(0) - done() - }) - }) - - it( - 'should handle multiple timeouts', - co.wrap( - function* () { - const errors = [] - const pool = new Pool({ connectionTimeoutMillis: 1, port: this.port, host: 'localhost' }) - for (var i = 0; i < 15; i++) { - try { - yield pool.connect() - } catch (e) { - errors.push(e) - } - } - expect(errors).to.have.length(15) - }.bind(this) - ) - ) - - it('should timeout on checkout of used connection', (done) => { - const pool = new Pool({ connectionTimeoutMillis: 100, max: 1 }) - pool.connect((err, client, release) => { - expect(err).to.be(undefined) - expect(client).to.not.be(undefined) - pool.connect((err, client) => { - expect(err).to.be.an(Error) - expect(client).to.be(undefined) - release() - pool.end(done) - }) - }) - }) - - it('should not break further pending checkouts on a timeout', (done) => { - const pool = new Pool({ connectionTimeoutMillis: 200, max: 1 }) - pool.connect((err, client, releaseOuter) => { - expect(err).to.be(undefined) - - pool.connect((err, client) => { - expect(err).to.be.an(Error) - expect(client).to.be(undefined) - releaseOuter() - }) - - setTimeout(() => { - pool.connect((err, client, releaseInner) => { - expect(err).to.be(undefined) - expect(client).to.not.be(undefined) - releaseInner() - pool.end(done) - }) - }, 100) - }) - }) - - it('should timeout on query if all clients are busy', (done) => { - const pool = new Pool({ connectionTimeoutMillis: 100, max: 1 }) - pool.connect((err, client, release) => { - expect(err).to.be(undefined) - expect(client).to.not.be(undefined) - pool.query('select now()', (err, result) => { - expect(err).to.be.an(Error) - expect(result).to.be(undefined) - release() - pool.end(done) - }) - }) - }) - - it('should recover from timeout errors', (done) => { - const pool = new Pool({ connectionTimeoutMillis: 100, max: 1 }) - pool.connect((err, client, release) => { - expect(err).to.be(undefined) - expect(client).to.not.be(undefined) - pool.query('select now()', (err, result) => { - expect(err).to.be.an(Error) - expect(result).to.be(undefined) - release() - pool.query('select $1::text as name', ['brianc'], (err, res) => { - expect(err).to.be(undefined) - expect(res.rows).to.have.length(1) - pool.end(done) - }) - }) - }) - }) - - it('continues processing after a connection failure', (done) => { - const Client = require('pg').Client - const orgConnect = Client.prototype.connect - let called = false - - Client.prototype.connect = function (cb) { - // Simulate a failure on first call - if (!called) { - called = true - - return setTimeout(() => { - cb(connectionFailure) - }, 100) - } - // And pass-through the second call - orgConnect.call(this, cb) - } - - const pool = new Pool({ - Client: Client, - connectionTimeoutMillis: 1000, - max: 1, - }) - - pool.connect((err, client, release) => { - expect(err).to.be(connectionFailure) - - pool.query('select $1::text as name', ['brianc'], (err, res) => { - expect(err).to.be(undefined) - expect(res.rows).to.have.length(1) - pool.end(done) - }) - }) - }) - - it('releases newly connected clients if the queued already timed out', (done) => { - const Client = require('pg').Client - - const orgConnect = Client.prototype.connect - - let connection = 0 - - Client.prototype.connect = function (cb) { - // Simulate a failure on first call - if (connection === 0) { - connection++ - - return setTimeout(() => { - cb(connectionFailure) - }, 300) - } - - // And second connect taking > connection timeout - if (connection === 1) { - connection++ - - return setTimeout(() => { - orgConnect.call(this, cb) - }, 1000) - } - - orgConnect.call(this, cb) - } - - const pool = new Pool({ - Client: Client, - connectionTimeoutMillis: 1000, - max: 1, - }) - - // Direct connect - pool.connect((err, client, release) => { - expect(err).to.be(connectionFailure) - }) - - // Queued - let called = 0 - pool.connect((err, client, release) => { - // Verify the callback is only called once - expect(called++).to.be(0) - expect(err).to.be.an(Error) - - pool.query('select $1::text as name', ['brianc'], (err, res) => { - expect(err).to.be(undefined) - expect(res.rows).to.have.length(1) - pool.end(done) - }) - }) - }) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/ending.js b/reverse_engineering/node_modules/pg-pool/test/ending.js deleted file mode 100644 index e1839b4..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/ending.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict' -const co = require('co') -const expect = require('expect.js') - -const describe = require('mocha').describe -const it = require('mocha').it - -const Pool = require('../') - -describe('pool ending', () => { - it('ends without being used', (done) => { - const pool = new Pool() - pool.end(done) - }) - - it('ends with a promise', () => { - return new Pool().end() - }) - - it( - 'ends with clients', - co.wrap(function* () { - const pool = new Pool() - const res = yield pool.query('SELECT $1::text as name', ['brianc']) - expect(res.rows[0].name).to.equal('brianc') - return pool.end() - }) - ) - - it( - 'allows client to finish', - co.wrap(function* () { - const pool = new Pool() - const query = pool.query('SELECT $1::text as name', ['brianc']) - yield pool.end() - const res = yield query - expect(res.rows[0].name).to.equal('brianc') - }) - ) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/error-handling.js b/reverse_engineering/node_modules/pg-pool/test/error-handling.js deleted file mode 100644 index 0a996b8..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/error-handling.js +++ /dev/null @@ -1,248 +0,0 @@ -'use strict' -const net = require('net') -const co = require('co') -const expect = require('expect.js') - -const describe = require('mocha').describe -const it = require('mocha').it - -const Pool = require('../') - -describe('pool error handling', function () { - it('Should complete these queries without dying', function (done) { - const pool = new Pool() - let errors = 0 - let shouldGet = 0 - function runErrorQuery() { - shouldGet++ - return new Promise(function (resolve, reject) { - pool - .query("SELECT 'asd'+1 ") - .then(function (res) { - reject(res) // this should always error - }) - .catch(function (err) { - errors++ - resolve(err) - }) - }) - } - const ps = [] - for (let i = 0; i < 5; i++) { - ps.push(runErrorQuery()) - } - Promise.all(ps).then(function () { - expect(shouldGet).to.eql(errors) - pool.end(done) - }) - }) - - describe('calling release more than once', () => { - it( - 'should throw each time', - co.wrap(function* () { - const pool = new Pool() - const client = yield pool.connect() - client.release() - expect(() => client.release()).to.throwError() - expect(() => client.release()).to.throwError() - return yield pool.end() - }) - ) - - it('should throw each time with callbacks', function (done) { - const pool = new Pool() - - pool.connect(function (err, client, clientDone) { - expect(err).not.to.be.an(Error) - clientDone() - - expect(() => clientDone()).to.throwError() - expect(() => clientDone()).to.throwError() - - pool.end(done) - }) - }) - }) - - describe('using an ended pool', () => { - it('rejects all additional promises', (done) => { - const pool = new Pool() - const promises = [] - pool.end().then(() => { - const squash = (promise) => promise.catch((e) => 'okay!') - promises.push(squash(pool.connect())) - promises.push(squash(pool.query('SELECT NOW()'))) - promises.push(squash(pool.end())) - Promise.all(promises).then((res) => { - expect(res).to.eql(['okay!', 'okay!', 'okay!']) - done() - }) - }) - }) - - it('returns an error on all additional callbacks', (done) => { - const pool = new Pool() - pool.end(() => { - pool.query('SELECT *', (err) => { - expect(err).to.be.an(Error) - pool.connect((err) => { - expect(err).to.be.an(Error) - pool.end((err) => { - expect(err).to.be.an(Error) - done() - }) - }) - }) - }) - }) - }) - - describe('error from idle client', () => { - it( - 'removes client from pool', - co.wrap(function* () { - const pool = new Pool() - const client = yield pool.connect() - expect(pool.totalCount).to.equal(1) - expect(pool.waitingCount).to.equal(0) - expect(pool.idleCount).to.equal(0) - client.release() - yield new Promise((resolve, reject) => { - process.nextTick(() => { - let poolError - pool.once('error', (err) => { - poolError = err - }) - - let clientError - client.once('error', (err) => { - clientError = err - }) - - client.emit('error', new Error('expected')) - - expect(clientError.message).to.equal('expected') - expect(poolError.message).to.equal('expected') - expect(pool.idleCount).to.equal(0) - expect(pool.totalCount).to.equal(0) - pool.end().then(resolve, reject) - }) - }) - }) - ) - }) - - describe('error from in-use client', () => { - it( - 'keeps the client in the pool', - co.wrap(function* () { - const pool = new Pool() - const client = yield pool.connect() - expect(pool.totalCount).to.equal(1) - expect(pool.waitingCount).to.equal(0) - expect(pool.idleCount).to.equal(0) - - yield new Promise((resolve, reject) => { - process.nextTick(() => { - let poolError - pool.once('error', (err) => { - poolError = err - }) - - let clientError - client.once('error', (err) => { - clientError = err - }) - - client.emit('error', new Error('expected')) - - expect(clientError.message).to.equal('expected') - expect(poolError).not.to.be.ok() - expect(pool.idleCount).to.equal(0) - expect(pool.totalCount).to.equal(1) - client.release() - pool.end().then(resolve, reject) - }) - }) - }) - ) - }) - - describe('passing a function to pool.query', () => { - it('calls back with error', (done) => { - const pool = new Pool() - console.log('passing fn to query') - pool.query((err) => { - expect(err).to.be.an(Error) - pool.end(done) - }) - }) - }) - - describe('pool with lots of errors', () => { - it( - 'continues to work and provide new clients', - co.wrap(function* () { - const pool = new Pool({ max: 1 }) - const errors = [] - for (var i = 0; i < 20; i++) { - try { - yield pool.query('invalid sql') - } catch (err) { - errors.push(err) - } - } - expect(errors).to.have.length(20) - expect(pool.idleCount).to.equal(0) - expect(pool.query).to.be.a(Function) - const res = yield pool.query('SELECT $1::text as name', ['brianc']) - expect(res.rows).to.have.length(1) - expect(res.rows[0].name).to.equal('brianc') - return pool.end() - }) - ) - }) - - it('should continue with queued items after a connection failure', (done) => { - const closeServer = net - .createServer((socket) => { - socket.destroy() - }) - .unref() - - closeServer.listen(() => { - const pool = new Pool({ max: 1, port: closeServer.address().port, host: 'localhost' }) - pool.connect((err) => { - expect(err).to.be.an(Error) - if (err.code) { - expect(err.code).to.be('ECONNRESET') - } - }) - pool.connect((err) => { - expect(err).to.be.an(Error) - if (err.code) { - expect(err.code).to.be('ECONNRESET') - } - closeServer.close(() => { - pool.end(done) - }) - }) - }) - }) - - it('handles post-checkout client failures in pool.query', (done) => { - const pool = new Pool({ max: 1 }) - pool.on('error', () => { - // We double close the connection in this test, prevent exception caused by that - }) - pool.query('SELECT pg_sleep(5)', [], (err) => { - expect(err).to.be.an(Error) - done() - }) - - setTimeout(() => { - pool._clients[0].end() - }, 1000) - }) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/events.js b/reverse_engineering/node_modules/pg-pool/test/events.js deleted file mode 100644 index 6197924..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/events.js +++ /dev/null @@ -1,86 +0,0 @@ -'use strict' - -const expect = require('expect.js') -const EventEmitter = require('events').EventEmitter -const describe = require('mocha').describe -const it = require('mocha').it -const Pool = require('../') - -describe('events', function () { - it('emits connect before callback', function (done) { - const pool = new Pool() - let emittedClient = false - pool.on('connect', function (client) { - emittedClient = client - }) - - pool.connect(function (err, client, release) { - if (err) return done(err) - release() - pool.end() - expect(client).to.be(emittedClient) - done() - }) - }) - - it('emits "connect" only with a successful connection', function () { - const pool = new Pool({ - // This client will always fail to connect - Client: mockClient({ - connect: function (cb) { - process.nextTick(() => { - cb(new Error('bad news')) - }) - }, - }), - }) - pool.on('connect', function () { - throw new Error('should never get here') - }) - return pool.connect().catch((e) => expect(e.message).to.equal('bad news')) - }) - - it('emits acquire every time a client is acquired', function (done) { - const pool = new Pool() - let acquireCount = 0 - pool.on('acquire', function (client) { - expect(client).to.be.ok() - acquireCount++ - }) - for (let i = 0; i < 10; i++) { - pool.connect(function (err, client, release) { - if (err) return done(err) - release() - }) - pool.query('SELECT now()') - } - setTimeout(function () { - expect(acquireCount).to.be(20) - pool.end(done) - }, 100) - }) - - it('emits error and client if an idle client in the pool hits an error', function (done) { - const pool = new Pool() - pool.connect(function (err, client) { - expect(err).to.equal(undefined) - client.release() - setImmediate(function () { - client.emit('error', new Error('problem')) - }) - pool.once('error', function (err, errClient) { - expect(err.message).to.equal('problem') - expect(errClient).to.equal(client) - done() - }) - }) - }) -}) - -function mockClient(methods) { - return function () { - const client = new EventEmitter() - Object.assign(client, methods) - return client - } -} diff --git a/reverse_engineering/node_modules/pg-pool/test/idle-timeout-exit.js b/reverse_engineering/node_modules/pg-pool/test/idle-timeout-exit.js deleted file mode 100644 index 1292634..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/idle-timeout-exit.js +++ /dev/null @@ -1,16 +0,0 @@ -// This test is meant to be spawned from idle-timeout.js -if (module === require.main) { - const allowExitOnIdle = process.env.ALLOW_EXIT_ON_IDLE === '1' - const Pool = require('../index') - - const pool = new Pool({ idleTimeoutMillis: 200, ...(allowExitOnIdle ? { allowExitOnIdle: true } : {}) }) - pool.query('SELECT NOW()', (err, res) => console.log('completed first')) - pool.on('remove', () => { - console.log('removed') - done() - }) - - setTimeout(() => { - pool.query('SELECT * from generate_series(0, 1000)', (err, res) => console.log('completed second')) - }, 50) -} diff --git a/reverse_engineering/node_modules/pg-pool/test/idle-timeout.js b/reverse_engineering/node_modules/pg-pool/test/idle-timeout.js deleted file mode 100644 index 0bb0975..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/idle-timeout.js +++ /dev/null @@ -1,118 +0,0 @@ -'use strict' -const co = require('co') -const expect = require('expect.js') - -const describe = require('mocha').describe -const it = require('mocha').it -const { fork } = require('child_process') -const path = require('path') - -const Pool = require('../') - -const wait = (time) => new Promise((resolve) => setTimeout(resolve, time)) - -describe('idle timeout', () => { - it('should timeout and remove the client', (done) => { - const pool = new Pool({ idleTimeoutMillis: 10 }) - pool.query('SELECT NOW()') - pool.on('remove', () => { - expect(pool.idleCount).to.equal(0) - expect(pool.totalCount).to.equal(0) - done() - }) - }) - - it( - 'times out and removes clients when others are also removed', - co.wrap(function* () { - const pool = new Pool({ idleTimeoutMillis: 10 }) - const clientA = yield pool.connect() - const clientB = yield pool.connect() - clientA.release() - clientB.release(new Error()) - - const removal = new Promise((resolve) => { - pool.on('remove', () => { - expect(pool.idleCount).to.equal(0) - expect(pool.totalCount).to.equal(0) - resolve() - }) - }) - - const timeout = wait(100).then(() => Promise.reject(new Error('Idle timeout failed to occur'))) - - try { - yield Promise.race([removal, timeout]) - } finally { - pool.end() - } - }) - ) - - it( - 'can remove idle clients and recreate them', - co.wrap(function* () { - const pool = new Pool({ idleTimeoutMillis: 1 }) - const results = [] - for (var i = 0; i < 20; i++) { - let query = pool.query('SELECT NOW()') - expect(pool.idleCount).to.equal(0) - expect(pool.totalCount).to.equal(1) - results.push(yield query) - yield wait(2) - expect(pool.idleCount).to.equal(0) - expect(pool.totalCount).to.equal(0) - } - expect(results).to.have.length(20) - }) - ) - - it( - 'does not time out clients which are used', - co.wrap(function* () { - const pool = new Pool({ idleTimeoutMillis: 1 }) - const results = [] - for (var i = 0; i < 20; i++) { - let client = yield pool.connect() - expect(pool.totalCount).to.equal(1) - expect(pool.idleCount).to.equal(0) - yield wait(10) - results.push(yield client.query('SELECT NOW()')) - client.release() - expect(pool.idleCount).to.equal(1) - expect(pool.totalCount).to.equal(1) - } - expect(results).to.have.length(20) - return pool.end() - }) - ) - - it('unrefs the connections and timeouts so the program can exit when idle when the allowExitOnIdle option is set', function (done) { - const child = fork(path.join(__dirname, 'idle-timeout-exit.js'), [], { - silent: true, - env: { ...process.env, ALLOW_EXIT_ON_IDLE: '1' }, - }) - let result = '' - child.stdout.setEncoding('utf8') - child.stdout.on('data', (chunk) => (result += chunk)) - child.on('error', (err) => done(err)) - child.on('close', () => { - expect(result).to.equal('completed first\ncompleted second\n') - done() - }) - }) - - it('keeps old behavior when allowExitOnIdle option is not set', function (done) { - const child = fork(path.join(__dirname, 'idle-timeout-exit.js'), [], { - silent: true, - }) - let result = '' - child.stdout.setEncoding('utf8') - child.stdout.on('data', (chunk) => (result += chunk)) - child.on('error', (err) => done(err)) - child.on('close', () => { - expect(result).to.equal('completed first\ncompleted second\nremoved\n') - done() - }) - }) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/index.js b/reverse_engineering/node_modules/pg-pool/test/index.js deleted file mode 100644 index 57a68e0..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/index.js +++ /dev/null @@ -1,226 +0,0 @@ -'use strict' -const expect = require('expect.js') -const _ = require('lodash') - -const describe = require('mocha').describe -const it = require('mocha').it - -const Pool = require('../') - -describe('pool', function () { - describe('with callbacks', function () { - it('works totally unconfigured', function (done) { - const pool = new Pool() - pool.connect(function (err, client, release) { - if (err) return done(err) - client.query('SELECT NOW()', function (err, res) { - release() - if (err) return done(err) - expect(res.rows).to.have.length(1) - pool.end(done) - }) - }) - }) - - it('passes props to clients', function (done) { - const pool = new Pool({ binary: true }) - pool.connect(function (err, client, release) { - release() - if (err) return done(err) - expect(client.binary).to.eql(true) - pool.end(done) - }) - }) - - it('can run a query with a callback without parameters', function (done) { - const pool = new Pool() - pool.query('SELECT 1 as num', function (err, res) { - expect(res.rows[0]).to.eql({ num: 1 }) - pool.end(function () { - done(err) - }) - }) - }) - - it('can run a query with a callback', function (done) { - const pool = new Pool() - pool.query('SELECT $1::text as name', ['brianc'], function (err, res) { - expect(res.rows[0]).to.eql({ name: 'brianc' }) - pool.end(function () { - done(err) - }) - }) - }) - - it('passes connection errors to callback', function (done) { - const pool = new Pool({ port: 53922 }) - pool.query('SELECT $1::text as name', ['brianc'], function (err, res) { - expect(res).to.be(undefined) - expect(err).to.be.an(Error) - // a connection error should not polute the pool with a dead client - expect(pool.totalCount).to.equal(0) - pool.end(function (err) { - done(err) - }) - }) - }) - - it('does not pass client to error callback', function (done) { - const pool = new Pool({ port: 58242 }) - pool.connect(function (err, client, release) { - expect(err).to.be.an(Error) - expect(client).to.be(undefined) - expect(release).to.be.a(Function) - pool.end(done) - }) - }) - - it('removes client if it errors in background', function (done) { - const pool = new Pool() - pool.connect(function (err, client, release) { - release() - if (err) return done(err) - client.testString = 'foo' - setTimeout(function () { - client.emit('error', new Error('on purpose')) - }, 10) - }) - pool.on('error', function (err) { - expect(err.message).to.be('on purpose') - expect(err.client).to.not.be(undefined) - expect(err.client.testString).to.be('foo') - err.client.connection.stream.on('end', function () { - pool.end(done) - }) - }) - }) - - it('should not change given options', function (done) { - const options = { max: 10 } - const pool = new Pool(options) - pool.connect(function (err, client, release) { - release() - if (err) return done(err) - expect(options).to.eql({ max: 10 }) - pool.end(done) - }) - }) - - it('does not create promises when connecting', function (done) { - const pool = new Pool() - const returnValue = pool.connect(function (err, client, release) { - release() - if (err) return done(err) - pool.end(done) - }) - expect(returnValue).to.be(undefined) - }) - - it('does not create promises when querying', function (done) { - const pool = new Pool() - const returnValue = pool.query('SELECT 1 as num', function (err) { - pool.end(function () { - done(err) - }) - }) - expect(returnValue).to.be(undefined) - }) - - it('does not create promises when ending', function (done) { - const pool = new Pool() - const returnValue = pool.end(done) - expect(returnValue).to.be(undefined) - }) - - it('never calls callback syncronously', function (done) { - const pool = new Pool() - pool.connect((err, client) => { - if (err) throw err - client.release() - setImmediate(() => { - let called = false - pool.connect((err, client) => { - if (err) throw err - called = true - client.release() - setImmediate(() => { - pool.end(done) - }) - }) - expect(called).to.equal(false) - }) - }) - }) - }) - - describe('with promises', function () { - it('connects, queries, and disconnects', function () { - const pool = new Pool() - return pool.connect().then(function (client) { - return client.query('select $1::text as name', ['hi']).then(function (res) { - expect(res.rows).to.eql([{ name: 'hi' }]) - client.release() - return pool.end() - }) - }) - }) - - it('executes a query directly', () => { - const pool = new Pool() - return pool.query('SELECT $1::text as name', ['hi']).then((res) => { - expect(res.rows).to.have.length(1) - expect(res.rows[0].name).to.equal('hi') - return pool.end() - }) - }) - - it('properly pools clients', function () { - const pool = new Pool({ poolSize: 9 }) - const promises = _.times(30, function () { - return pool.connect().then(function (client) { - return client.query('select $1::text as name', ['hi']).then(function (res) { - client.release() - return res - }) - }) - }) - return Promise.all(promises).then(function (res) { - expect(res).to.have.length(30) - expect(pool.totalCount).to.be(9) - return pool.end() - }) - }) - - it('supports just running queries', function () { - const pool = new Pool({ poolSize: 9 }) - const text = 'select $1::text as name' - const values = ['hi'] - const query = { text: text, values: values } - const promises = _.times(30, () => pool.query(query)) - return Promise.all(promises).then(function (queries) { - expect(queries).to.have.length(30) - return pool.end() - }) - }) - - it('recovers from query errors', function () { - const pool = new Pool() - - const errors = [] - const promises = _.times(30, () => { - return pool.query('SELECT asldkfjasldkf').catch(function (e) { - errors.push(e) - }) - }) - return Promise.all(promises).then(() => { - expect(errors).to.have.length(30) - expect(pool.totalCount).to.equal(0) - expect(pool.idleCount).to.equal(0) - return pool.query('SELECT $1::text as name', ['hi']).then(function (res) { - expect(res.rows).to.eql([{ name: 'hi' }]) - return pool.end() - }) - }) - }) - }) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/logging.js b/reverse_engineering/node_modules/pg-pool/test/logging.js deleted file mode 100644 index 839603b..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/logging.js +++ /dev/null @@ -1,20 +0,0 @@ -const expect = require('expect.js') - -const describe = require('mocha').describe -const it = require('mocha').it - -const Pool = require('../') - -describe('logging', function () { - it('logs to supplied log function if given', function () { - const messages = [] - const log = function (msg) { - messages.push(msg) - } - const pool = new Pool({ log: log }) - return pool.query('SELECT NOW()').then(function () { - expect(messages.length).to.be.greaterThan(0) - return pool.end() - }) - }) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/max-uses.js b/reverse_engineering/node_modules/pg-pool/test/max-uses.js deleted file mode 100644 index c94ddec..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/max-uses.js +++ /dev/null @@ -1,98 +0,0 @@ -const expect = require('expect.js') -const co = require('co') -const _ = require('lodash') - -const describe = require('mocha').describe -const it = require('mocha').it - -const Pool = require('../') - -describe('maxUses', () => { - it( - 'can create a single client and use it once', - co.wrap(function* () { - const pool = new Pool({ maxUses: 2 }) - expect(pool.waitingCount).to.equal(0) - const client = yield pool.connect() - const res = yield client.query('SELECT $1::text as name', ['hi']) - expect(res.rows[0].name).to.equal('hi') - client.release() - pool.end() - }) - ) - - it( - 'getting a connection a second time returns the same connection and releasing it also closes it', - co.wrap(function* () { - const pool = new Pool({ maxUses: 2 }) - expect(pool.waitingCount).to.equal(0) - const client = yield pool.connect() - client.release() - const client2 = yield pool.connect() - expect(client).to.equal(client2) - expect(client2._ending).to.equal(false) - client2.release() - expect(client2._ending).to.equal(true) - return yield pool.end() - }) - ) - - it( - 'getting a connection a third time returns a new connection', - co.wrap(function* () { - const pool = new Pool({ maxUses: 2 }) - expect(pool.waitingCount).to.equal(0) - const client = yield pool.connect() - client.release() - const client2 = yield pool.connect() - expect(client).to.equal(client2) - client2.release() - const client3 = yield pool.connect() - expect(client3).not.to.equal(client2) - client3.release() - return yield pool.end() - }) - ) - - it( - 'getting a connection from a pending request gets a fresh client when the released candidate is expended', - co.wrap(function* () { - const pool = new Pool({ max: 1, maxUses: 2 }) - expect(pool.waitingCount).to.equal(0) - const client1 = yield pool.connect() - pool.connect().then((client2) => { - expect(client2).to.equal(client1) - expect(pool.waitingCount).to.equal(1) - // Releasing the client this time should also expend it since maxUses is 2, causing client3 to be a fresh client - client2.release() - }) - const client3Promise = pool.connect().then((client3) => { - // client3 should be a fresh client since client2's release caused the first client to be expended - expect(pool.waitingCount).to.equal(0) - expect(client3).not.to.equal(client1) - return client3.release() - }) - // There should be two pending requests since we have 3 connect requests but a max size of 1 - expect(pool.waitingCount).to.equal(2) - // Releasing the client should not yet expend it since maxUses is 2 - client1.release() - yield client3Promise - return yield pool.end() - }) - ) - - it( - 'logs when removing an expended client', - co.wrap(function* () { - const messages = [] - const log = function (msg) { - messages.push(msg) - } - const pool = new Pool({ maxUses: 1, log }) - const client = yield pool.connect() - client.release() - expect(messages).to.contain('remove expended client') - return yield pool.end() - }) - ) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/releasing-clients.js b/reverse_engineering/node_modules/pg-pool/test/releasing-clients.js deleted file mode 100644 index da8e09c..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/releasing-clients.js +++ /dev/null @@ -1,54 +0,0 @@ -const Pool = require('../') - -const expect = require('expect.js') -const net = require('net') - -describe('releasing clients', () => { - it('removes a client which cannot be queried', async () => { - // make a pool w/ only 1 client - const pool = new Pool({ max: 1 }) - expect(pool.totalCount).to.eql(0) - const client = await pool.connect() - expect(pool.totalCount).to.eql(1) - expect(pool.idleCount).to.eql(0) - // reach into the client and sever its connection - client.connection.end() - - // wait for the client to error out - const err = await new Promise((resolve) => client.once('error', resolve)) - expect(err).to.be.ok() - expect(pool.totalCount).to.eql(1) - expect(pool.idleCount).to.eql(0) - - // try to return it to the pool - this removes it because its broken - client.release() - expect(pool.totalCount).to.eql(0) - expect(pool.idleCount).to.eql(0) - - // make sure pool still works - const { rows } = await pool.query('SELECT NOW()') - expect(rows).to.have.length(1) - await pool.end() - }) - - it('removes a client which is ending', async () => { - // make a pool w/ only 1 client - const pool = new Pool({ max: 1 }) - expect(pool.totalCount).to.eql(0) - const client = await pool.connect() - expect(pool.totalCount).to.eql(1) - expect(pool.idleCount).to.eql(0) - // end the client gracefully (but you shouldn't do this with pooled clients) - client.end() - - // try to return it to the pool - client.release() - expect(pool.totalCount).to.eql(0) - expect(pool.idleCount).to.eql(0) - - // make sure pool still works - const { rows } = await pool.query('SELECT NOW()') - expect(rows).to.have.length(1) - await pool.end() - }) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/setup.js b/reverse_engineering/node_modules/pg-pool/test/setup.js deleted file mode 100644 index 811e956..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/setup.js +++ /dev/null @@ -1,10 +0,0 @@ -const crash = (reason) => { - process.on(reason, (err) => { - console.error(reason, err.stack) - process.exit(-1) - }) -} - -crash('unhandledRejection') -crash('uncaughtError') -crash('warning') diff --git a/reverse_engineering/node_modules/pg-pool/test/sizing.js b/reverse_engineering/node_modules/pg-pool/test/sizing.js deleted file mode 100644 index e7863ba..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/sizing.js +++ /dev/null @@ -1,58 +0,0 @@ -const expect = require('expect.js') -const co = require('co') -const _ = require('lodash') - -const describe = require('mocha').describe -const it = require('mocha').it - -const Pool = require('../') - -describe('pool size of 1', () => { - it( - 'can create a single client and use it once', - co.wrap(function* () { - const pool = new Pool({ max: 1 }) - expect(pool.waitingCount).to.equal(0) - const client = yield pool.connect() - const res = yield client.query('SELECT $1::text as name', ['hi']) - expect(res.rows[0].name).to.equal('hi') - client.release() - pool.end() - }) - ) - - it( - 'can create a single client and use it multiple times', - co.wrap(function* () { - const pool = new Pool({ max: 1 }) - expect(pool.waitingCount).to.equal(0) - const client = yield pool.connect() - const wait = pool.connect() - expect(pool.waitingCount).to.equal(1) - client.release() - const client2 = yield wait - expect(client).to.equal(client2) - client2.release() - return yield pool.end() - }) - ) - - it( - 'can only send 1 query at a time', - co.wrap(function* () { - const pool = new Pool({ max: 1 }) - - // the query text column name changed in PostgreSQL 9.2 - const versionResult = yield pool.query('SHOW server_version_num') - const version = parseInt(versionResult.rows[0].server_version_num, 10) - const queryColumn = version < 90200 ? 'current_query' : 'query' - - const queryText = 'SELECT COUNT(*) as counts FROM pg_stat_activity WHERE ' + queryColumn + ' = $1' - const queries = _.times(20, () => pool.query(queryText, [queryText])) - const results = yield Promise.all(queries) - const counts = results.map((res) => parseInt(res.rows[0].counts, 10)) - expect(counts).to.eql(_.times(20, (i) => 1)) - return yield pool.end() - }) - ) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/submittable.js b/reverse_engineering/node_modules/pg-pool/test/submittable.js deleted file mode 100644 index 7a1574d..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/submittable.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict' -const Cursor = require('pg-cursor') -const expect = require('expect.js') -const describe = require('mocha').describe -const it = require('mocha').it - -const Pool = require('../') - -describe('submittle', () => { - it('is returned from the query method', false, (done) => { - const pool = new Pool() - const cursor = pool.query(new Cursor('SELECT * from generate_series(0, 1000)')) - cursor.read((err, rows) => { - expect(err).to.be(undefined) - expect(!!rows).to.be.ok() - cursor.close(done) - }) - }) -}) diff --git a/reverse_engineering/node_modules/pg-pool/test/timeout.js b/reverse_engineering/node_modules/pg-pool/test/timeout.js deleted file mode 100644 index e69de29..0000000 diff --git a/reverse_engineering/node_modules/pg-pool/test/verify.js b/reverse_engineering/node_modules/pg-pool/test/verify.js deleted file mode 100644 index 9331e1a..0000000 --- a/reverse_engineering/node_modules/pg-pool/test/verify.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict' -const expect = require('expect.js') - -const describe = require('mocha').describe -const it = require('mocha').it - -const Pool = require('../') - -describe('verify', () => { - it('verifies a client with a callback', (done) => { - const pool = new Pool({ - verify: (client, cb) => { - cb(new Error('nope')) - }, - }) - - pool.connect((err, client) => { - expect(err).to.be.an(Error) - expect(err.message).to.be('nope') - pool.end() - done() - }) - }) -}) diff --git a/reverse_engineering/node_modules/pg-protocol/LICENSE b/reverse_engineering/node_modules/pg-protocol/LICENSE deleted file mode 100644 index 5c14056..0000000 --- a/reverse_engineering/node_modules/pg-protocol/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2010 - 2021 Brian Carlson - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/reverse_engineering/node_modules/pg-protocol/README.md b/reverse_engineering/node_modules/pg-protocol/README.md deleted file mode 100644 index 8c52e40..0000000 --- a/reverse_engineering/node_modules/pg-protocol/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# pg-protocol - -Low level postgres wire protocol parser and serializer written in Typescript. Used by node-postgres. Needs more documentation. :smile: diff --git a/reverse_engineering/node_modules/pg-protocol/dist/b.d.ts b/reverse_engineering/node_modules/pg-protocol/dist/b.d.ts deleted file mode 100644 index cb0ff5c..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/b.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/reverse_engineering/node_modules/pg-protocol/dist/b.js b/reverse_engineering/node_modules/pg-protocol/dist/b.js deleted file mode 100644 index 5f5efb8..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/b.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -// file for microbenchmarking -Object.defineProperty(exports, "__esModule", { value: true }); -const buffer_writer_1 = require("./buffer-writer"); -const buffer_reader_1 = require("./buffer-reader"); -const LOOPS = 1000; -let count = 0; -let start = Date.now(); -const writer = new buffer_writer_1.Writer(); -const reader = new buffer_reader_1.BufferReader(); -const buffer = Buffer.from([33, 33, 33, 33, 33, 33, 33, 0]); -const run = () => { - if (count > LOOPS) { - console.log(Date.now() - start); - return; - } - count++; - for (let i = 0; i < LOOPS; i++) { - reader.setBuffer(0, buffer); - reader.cstring(); - } - setImmediate(run); -}; -run(); -//# sourceMappingURL=b.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/b.js.map b/reverse_engineering/node_modules/pg-protocol/dist/b.js.map deleted file mode 100644 index cddd15e..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/b.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"b.js","sourceRoot":"","sources":["../src/b.ts"],"names":[],"mappings":";AAAA,6BAA6B;;AAE7B,mDAAwC;AAExC,mDAA8C;AAE9C,MAAM,KAAK,GAAG,IAAI,CAAA;AAClB,IAAI,KAAK,GAAG,CAAC,CAAA;AACb,IAAI,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;AACtB,MAAM,MAAM,GAAG,IAAI,sBAAM,EAAE,CAAA;AAE3B,MAAM,MAAM,GAAG,IAAI,4BAAY,EAAE,CAAA;AACjC,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAA;AAE3D,MAAM,GAAG,GAAG,GAAG,EAAE;IACf,IAAI,KAAK,GAAG,KAAK,EAAE;QACjB,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,CAAA;QAC/B,OAAM;KACP;IACD,KAAK,EAAE,CAAA;IACP,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;QAC9B,MAAM,CAAC,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;QAC3B,MAAM,CAAC,OAAO,EAAE,CAAA;KACjB;IACD,YAAY,CAAC,GAAG,CAAC,CAAA;AACnB,CAAC,CAAA;AAED,GAAG,EAAE,CAAA"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/buffer-reader.d.ts b/reverse_engineering/node_modules/pg-protocol/dist/buffer-reader.d.ts deleted file mode 100644 index 8970d77..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/buffer-reader.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -/// -export declare class BufferReader { - private offset; - private buffer; - private encoding; - constructor(offset?: number); - setBuffer(offset: number, buffer: Buffer): void; - int16(): number; - byte(): number; - int32(): number; - string(length: number): string; - cstring(): string; - bytes(length: number): Buffer; -} diff --git a/reverse_engineering/node_modules/pg-protocol/dist/buffer-reader.js b/reverse_engineering/node_modules/pg-protocol/dist/buffer-reader.js deleted file mode 100644 index ef633b1..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/buffer-reader.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BufferReader = void 0; -const emptyBuffer = Buffer.allocUnsafe(0); -class BufferReader { - constructor(offset = 0) { - this.offset = offset; - this.buffer = emptyBuffer; - // TODO(bmc): support non-utf8 encoding? - this.encoding = 'utf-8'; - } - setBuffer(offset, buffer) { - this.offset = offset; - this.buffer = buffer; - } - int16() { - const result = this.buffer.readInt16BE(this.offset); - this.offset += 2; - return result; - } - byte() { - const result = this.buffer[this.offset]; - this.offset++; - return result; - } - int32() { - const result = this.buffer.readInt32BE(this.offset); - this.offset += 4; - return result; - } - string(length) { - const result = this.buffer.toString(this.encoding, this.offset, this.offset + length); - this.offset += length; - return result; - } - cstring() { - const start = this.offset; - let end = start; - while (this.buffer[end++] !== 0) { } - this.offset = end; - return this.buffer.toString(this.encoding, start, end - 1); - } - bytes(length) { - const result = this.buffer.slice(this.offset, this.offset + length); - this.offset += length; - return result; - } -} -exports.BufferReader = BufferReader; -//# sourceMappingURL=buffer-reader.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/buffer-reader.js.map b/reverse_engineering/node_modules/pg-protocol/dist/buffer-reader.js.map deleted file mode 100644 index 04d5b1d..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/buffer-reader.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"buffer-reader.js","sourceRoot":"","sources":["../src/buffer-reader.ts"],"names":[],"mappings":";;;AAAA,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAA;AAEzC,MAAa,YAAY;IAMvB,YAAoB,SAAiB,CAAC;QAAlB,WAAM,GAAN,MAAM,CAAY;QAL9B,WAAM,GAAW,WAAW,CAAA;QAEpC,wCAAwC;QAChC,aAAQ,GAAW,OAAO,CAAA;IAEO,CAAC;IAEnC,SAAS,CAAC,MAAc,EAAE,MAAc;QAC7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAEM,KAAK;QACV,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;QACnD,IAAI,CAAC,MAAM,IAAI,CAAC,CAAA;QAChB,OAAO,MAAM,CAAA;IACf,CAAC;IAEM,IAAI;QACT,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;QACvC,IAAI,CAAC,MAAM,EAAE,CAAA;QACb,OAAO,MAAM,CAAA;IACf,CAAC;IAEM,KAAK;QACV,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;QACnD,IAAI,CAAC,MAAM,IAAI,CAAC,CAAA;QAChB,OAAO,MAAM,CAAA;IACf,CAAC;IAEM,MAAM,CAAC,MAAc;QAC1B,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,CAAA;QACrF,IAAI,CAAC,MAAM,IAAI,MAAM,CAAA;QACrB,OAAO,MAAM,CAAA;IACf,CAAC;IAEM,OAAO;QACZ,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAA;QACzB,IAAI,GAAG,GAAG,KAAK,CAAA;QACf,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,EAAE,GAAE;QACnC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAA;QACjB,OAAO,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,GAAG,GAAG,CAAC,CAAC,CAAA;IAC5D,CAAC;IAEM,KAAK,CAAC,MAAc;QACzB,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,CAAA;QACnE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAA;QACrB,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAlDD,oCAkDC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/buffer-writer.d.ts b/reverse_engineering/node_modules/pg-protocol/dist/buffer-writer.d.ts deleted file mode 100644 index 4ac41e6..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/buffer-writer.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -/// -export declare class Writer { - private size; - private buffer; - private offset; - private headerPosition; - constructor(size?: number); - private ensure; - addInt32(num: number): Writer; - addInt16(num: number): Writer; - addCString(string: string): Writer; - addString(string?: string): Writer; - add(otherBuffer: Buffer): Writer; - private join; - flush(code?: number): Buffer; -} diff --git a/reverse_engineering/node_modules/pg-protocol/dist/buffer-writer.js b/reverse_engineering/node_modules/pg-protocol/dist/buffer-writer.js deleted file mode 100644 index 16fd616..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/buffer-writer.js +++ /dev/null @@ -1,81 +0,0 @@ -"use strict"; -//binary data writer tuned for encoding binary specific to the postgres binary protocol -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Writer = void 0; -class Writer { - constructor(size = 256) { - this.size = size; - this.offset = 5; - this.headerPosition = 0; - this.buffer = Buffer.allocUnsafe(size); - } - ensure(size) { - var remaining = this.buffer.length - this.offset; - if (remaining < size) { - var oldBuffer = this.buffer; - // exponential growth factor of around ~ 1.5 - // https://stackoverflow.com/questions/2269063/buffer-growth-strategy - var newSize = oldBuffer.length + (oldBuffer.length >> 1) + size; - this.buffer = Buffer.allocUnsafe(newSize); - oldBuffer.copy(this.buffer); - } - } - addInt32(num) { - this.ensure(4); - this.buffer[this.offset++] = (num >>> 24) & 0xff; - this.buffer[this.offset++] = (num >>> 16) & 0xff; - this.buffer[this.offset++] = (num >>> 8) & 0xff; - this.buffer[this.offset++] = (num >>> 0) & 0xff; - return this; - } - addInt16(num) { - this.ensure(2); - this.buffer[this.offset++] = (num >>> 8) & 0xff; - this.buffer[this.offset++] = (num >>> 0) & 0xff; - return this; - } - addCString(string) { - if (!string) { - this.ensure(1); - } - else { - var len = Buffer.byteLength(string); - this.ensure(len + 1); // +1 for null terminator - this.buffer.write(string, this.offset, 'utf-8'); - this.offset += len; - } - this.buffer[this.offset++] = 0; // null terminator - return this; - } - addString(string = '') { - var len = Buffer.byteLength(string); - this.ensure(len); - this.buffer.write(string, this.offset); - this.offset += len; - return this; - } - add(otherBuffer) { - this.ensure(otherBuffer.length); - otherBuffer.copy(this.buffer, this.offset); - this.offset += otherBuffer.length; - return this; - } - join(code) { - if (code) { - this.buffer[this.headerPosition] = code; - //length is everything in this packet minus the code - const length = this.offset - (this.headerPosition + 1); - this.buffer.writeInt32BE(length, this.headerPosition + 1); - } - return this.buffer.slice(code ? 0 : 5, this.offset); - } - flush(code) { - var result = this.join(code); - this.offset = 5; - this.headerPosition = 0; - this.buffer = Buffer.allocUnsafe(this.size); - return result; - } -} -exports.Writer = Writer; -//# sourceMappingURL=buffer-writer.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/buffer-writer.js.map b/reverse_engineering/node_modules/pg-protocol/dist/buffer-writer.js.map deleted file mode 100644 index fc6e650..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/buffer-writer.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"buffer-writer.js","sourceRoot":"","sources":["../src/buffer-writer.ts"],"names":[],"mappings":";AAAA,uFAAuF;;;AAEvF,MAAa,MAAM;IAIjB,YAAoB,OAAO,GAAG;QAAV,SAAI,GAAJ,IAAI,CAAM;QAFtB,WAAM,GAAW,CAAC,CAAA;QAClB,mBAAc,GAAW,CAAC,CAAA;QAEhC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAA;IACxC,CAAC;IAEO,MAAM,CAAC,IAAY;QACzB,IAAI,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;QAChD,IAAI,SAAS,GAAG,IAAI,EAAE;YACpB,IAAI,SAAS,GAAG,IAAI,CAAC,MAAM,CAAA;YAC3B,4CAA4C;YAC5C,qEAAqE;YACrE,IAAI,OAAO,GAAG,SAAS,CAAC,MAAM,GAAG,CAAC,SAAS,CAAC,MAAM,IAAI,CAAC,CAAC,GAAG,IAAI,CAAA;YAC/D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;YACzC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;SAC5B;IACH,CAAC;IAEM,QAAQ,CAAC,GAAW;QACzB,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;QACd,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,IAAI,CAAA;QAChD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,IAAI,CAAA;QAChD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,IAAI,CAAA;QAC/C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,IAAI,CAAA;QAC/C,OAAO,IAAI,CAAA;IACb,CAAC;IAEM,QAAQ,CAAC,GAAW;QACzB,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;QACd,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,IAAI,CAAA;QAC/C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,IAAI,CAAA;QAC/C,OAAO,IAAI,CAAA;IACb,CAAC;IAEM,UAAU,CAAC,MAAc;QAC9B,IAAI,CAAC,MAAM,EAAE;YACX,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;SACf;aAAM;YACL,IAAI,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAA;YACnC,IAAI,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC,CAAC,CAAA,CAAC,yBAAyB;YAC9C,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;YAC/C,IAAI,CAAC,MAAM,IAAI,GAAG,CAAA;SACnB;QAED,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAA,CAAC,kBAAkB;QACjD,OAAO,IAAI,CAAA;IACb,CAAC;IAEM,SAAS,CAAC,SAAiB,EAAE;QAClC,IAAI,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAA;QACnC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;QAChB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;QACtC,IAAI,CAAC,MAAM,IAAI,GAAG,CAAA;QAClB,OAAO,IAAI,CAAA;IACb,CAAC;IAEM,GAAG,CAAC,WAAmB;QAC5B,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAA;QAC/B,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;QAC1C,IAAI,CAAC,MAAM,IAAI,WAAW,CAAC,MAAM,CAAA;QACjC,OAAO,IAAI,CAAA;IACb,CAAC;IAEO,IAAI,CAAC,IAAa;QACxB,IAAI,IAAI,EAAE;YACR,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,IAAI,CAAA;YACvC,oDAAoD;YACpD,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,cAAc,GAAG,CAAC,CAAC,CAAA;YACtD,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,cAAc,GAAG,CAAC,CAAC,CAAA;SAC1D;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;IACrD,CAAC;IAEM,KAAK,CAAC,IAAa;QACxB,IAAI,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAC5B,IAAI,CAAC,MAAM,GAAG,CAAC,CAAA;QACf,IAAI,CAAC,cAAc,GAAG,CAAC,CAAA;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAC3C,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAlFD,wBAkFC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/inbound-parser.test.d.ts b/reverse_engineering/node_modules/pg-protocol/dist/inbound-parser.test.d.ts deleted file mode 100644 index cb0ff5c..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/inbound-parser.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/reverse_engineering/node_modules/pg-protocol/dist/inbound-parser.test.js b/reverse_engineering/node_modules/pg-protocol/dist/inbound-parser.test.js deleted file mode 100644 index 3423c96..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/inbound-parser.test.js +++ /dev/null @@ -1,511 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const test_buffers_1 = __importDefault(require("./testing/test-buffers")); -const buffer_list_1 = __importDefault(require("./testing/buffer-list")); -const _1 = require("."); -const assert_1 = __importDefault(require("assert")); -const stream_1 = require("stream"); -var authOkBuffer = test_buffers_1.default.authenticationOk(); -var paramStatusBuffer = test_buffers_1.default.parameterStatus('client_encoding', 'UTF8'); -var readyForQueryBuffer = test_buffers_1.default.readyForQuery(); -var backendKeyDataBuffer = test_buffers_1.default.backendKeyData(1, 2); -var commandCompleteBuffer = test_buffers_1.default.commandComplete('SELECT 3'); -var parseCompleteBuffer = test_buffers_1.default.parseComplete(); -var bindCompleteBuffer = test_buffers_1.default.bindComplete(); -var portalSuspendedBuffer = test_buffers_1.default.portalSuspended(); -var addRow = function (bufferList, name, offset) { - return bufferList - .addCString(name) // field name - .addInt32(offset++) // table id - .addInt16(offset++) // attribute of column number - .addInt32(offset++) // objectId of field's data type - .addInt16(offset++) // datatype size - .addInt32(offset++) // type modifier - .addInt16(0); // format code, 0 => text -}; -var row1 = { - name: 'id', - tableID: 1, - attributeNumber: 2, - dataTypeID: 3, - dataTypeSize: 4, - typeModifier: 5, - formatCode: 0, -}; -var oneRowDescBuff = test_buffers_1.default.rowDescription([row1]); -row1.name = 'bang'; -var twoRowBuf = test_buffers_1.default.rowDescription([ - row1, - { - name: 'whoah', - tableID: 10, - attributeNumber: 11, - dataTypeID: 12, - dataTypeSize: 13, - typeModifier: 14, - formatCode: 0, - }, -]); -var emptyRowFieldBuf = new buffer_list_1.default().addInt16(0).join(true, 'D'); -var emptyRowFieldBuf = test_buffers_1.default.dataRow([]); -var oneFieldBuf = new buffer_list_1.default() - .addInt16(1) // number of fields - .addInt32(5) // length of bytes of fields - .addCString('test') - .join(true, 'D'); -var oneFieldBuf = test_buffers_1.default.dataRow(['test']); -var expectedAuthenticationOkayMessage = { - name: 'authenticationOk', - length: 8, -}; -var expectedParameterStatusMessage = { - name: 'parameterStatus', - parameterName: 'client_encoding', - parameterValue: 'UTF8', - length: 25, -}; -var expectedBackendKeyDataMessage = { - name: 'backendKeyData', - processID: 1, - secretKey: 2, -}; -var expectedReadyForQueryMessage = { - name: 'readyForQuery', - length: 5, - status: 'I', -}; -var expectedCommandCompleteMessage = { - name: 'commandComplete', - length: 13, - text: 'SELECT 3', -}; -var emptyRowDescriptionBuffer = new buffer_list_1.default() - .addInt16(0) // number of fields - .join(true, 'T'); -var expectedEmptyRowDescriptionMessage = { - name: 'rowDescription', - length: 6, - fieldCount: 0, - fields: [], -}; -var expectedOneRowMessage = { - name: 'rowDescription', - length: 27, - fieldCount: 1, - fields: [ - { - name: 'id', - tableID: 1, - columnID: 2, - dataTypeID: 3, - dataTypeSize: 4, - dataTypeModifier: 5, - format: 'text', - }, - ], -}; -var expectedTwoRowMessage = { - name: 'rowDescription', - length: 53, - fieldCount: 2, - fields: [ - { - name: 'bang', - tableID: 1, - columnID: 2, - dataTypeID: 3, - dataTypeSize: 4, - dataTypeModifier: 5, - format: 'text', - }, - { - name: 'whoah', - tableID: 10, - columnID: 11, - dataTypeID: 12, - dataTypeSize: 13, - dataTypeModifier: 14, - format: 'text', - }, - ], -}; -var emptyParameterDescriptionBuffer = new buffer_list_1.default() - .addInt16(0) // number of parameters - .join(true, 't'); -var oneParameterDescBuf = test_buffers_1.default.parameterDescription([1111]); -var twoParameterDescBuf = test_buffers_1.default.parameterDescription([2222, 3333]); -var expectedEmptyParameterDescriptionMessage = { - name: 'parameterDescription', - length: 6, - parameterCount: 0, - dataTypeIDs: [], -}; -var expectedOneParameterMessage = { - name: 'parameterDescription', - length: 10, - parameterCount: 1, - dataTypeIDs: [1111], -}; -var expectedTwoParameterMessage = { - name: 'parameterDescription', - length: 14, - parameterCount: 2, - dataTypeIDs: [2222, 3333], -}; -var testForMessage = function (buffer, expectedMessage) { - it('recieves and parses ' + expectedMessage.name, () => __awaiter(this, void 0, void 0, function* () { - const messages = yield parseBuffers([buffer]); - const [lastMessage] = messages; - for (const key in expectedMessage) { - assert_1.default.deepEqual(lastMessage[key], expectedMessage[key]); - } - })); -}; -var plainPasswordBuffer = test_buffers_1.default.authenticationCleartextPassword(); -var md5PasswordBuffer = test_buffers_1.default.authenticationMD5Password(); -var SASLBuffer = test_buffers_1.default.authenticationSASL(); -var SASLContinueBuffer = test_buffers_1.default.authenticationSASLContinue(); -var SASLFinalBuffer = test_buffers_1.default.authenticationSASLFinal(); -var expectedPlainPasswordMessage = { - name: 'authenticationCleartextPassword', -}; -var expectedMD5PasswordMessage = { - name: 'authenticationMD5Password', - salt: Buffer.from([1, 2, 3, 4]), -}; -var expectedSASLMessage = { - name: 'authenticationSASL', - mechanisms: ['SCRAM-SHA-256'], -}; -var expectedSASLContinueMessage = { - name: 'authenticationSASLContinue', - data: 'data', -}; -var expectedSASLFinalMessage = { - name: 'authenticationSASLFinal', - data: 'data', -}; -var notificationResponseBuffer = test_buffers_1.default.notification(4, 'hi', 'boom'); -var expectedNotificationResponseMessage = { - name: 'notification', - processId: 4, - channel: 'hi', - payload: 'boom', -}; -const parseBuffers = (buffers) => __awaiter(void 0, void 0, void 0, function* () { - const stream = new stream_1.PassThrough(); - for (const buffer of buffers) { - stream.write(buffer); - } - stream.end(); - const msgs = []; - yield _1.parse(stream, (msg) => msgs.push(msg)); - return msgs; -}); -describe('PgPacketStream', function () { - testForMessage(authOkBuffer, expectedAuthenticationOkayMessage); - testForMessage(plainPasswordBuffer, expectedPlainPasswordMessage); - testForMessage(md5PasswordBuffer, expectedMD5PasswordMessage); - testForMessage(SASLBuffer, expectedSASLMessage); - testForMessage(SASLContinueBuffer, expectedSASLContinueMessage); - // this exercises a found bug in the parser: - // https://github.com/brianc/node-postgres/pull/2210#issuecomment-627626084 - // and adds a test which is deterministic, rather than relying on network packet chunking - const extendedSASLContinueBuffer = Buffer.concat([SASLContinueBuffer, Buffer.from([1, 2, 3, 4])]); - testForMessage(extendedSASLContinueBuffer, expectedSASLContinueMessage); - testForMessage(SASLFinalBuffer, expectedSASLFinalMessage); - // this exercises a found bug in the parser: - // https://github.com/brianc/node-postgres/pull/2210#issuecomment-627626084 - // and adds a test which is deterministic, rather than relying on network packet chunking - const extendedSASLFinalBuffer = Buffer.concat([SASLFinalBuffer, Buffer.from([1, 2, 4, 5])]); - testForMessage(extendedSASLFinalBuffer, expectedSASLFinalMessage); - testForMessage(paramStatusBuffer, expectedParameterStatusMessage); - testForMessage(backendKeyDataBuffer, expectedBackendKeyDataMessage); - testForMessage(readyForQueryBuffer, expectedReadyForQueryMessage); - testForMessage(commandCompleteBuffer, expectedCommandCompleteMessage); - testForMessage(notificationResponseBuffer, expectedNotificationResponseMessage); - testForMessage(test_buffers_1.default.emptyQuery(), { - name: 'emptyQuery', - length: 4, - }); - testForMessage(Buffer.from([0x6e, 0, 0, 0, 4]), { - name: 'noData', - }); - describe('rowDescription messages', function () { - testForMessage(emptyRowDescriptionBuffer, expectedEmptyRowDescriptionMessage); - testForMessage(oneRowDescBuff, expectedOneRowMessage); - testForMessage(twoRowBuf, expectedTwoRowMessage); - }); - describe('parameterDescription messages', function () { - testForMessage(emptyParameterDescriptionBuffer, expectedEmptyParameterDescriptionMessage); - testForMessage(oneParameterDescBuf, expectedOneParameterMessage); - testForMessage(twoParameterDescBuf, expectedTwoParameterMessage); - }); - describe('parsing rows', function () { - describe('parsing empty row', function () { - testForMessage(emptyRowFieldBuf, { - name: 'dataRow', - fieldCount: 0, - }); - }); - describe('parsing data row with fields', function () { - testForMessage(oneFieldBuf, { - name: 'dataRow', - fieldCount: 1, - fields: ['test'], - }); - }); - }); - describe('notice message', function () { - // this uses the same logic as error message - var buff = test_buffers_1.default.notice([{ type: 'C', value: 'code' }]); - testForMessage(buff, { - name: 'notice', - code: 'code', - }); - }); - testForMessage(test_buffers_1.default.error([]), { - name: 'error', - }); - describe('with all the fields', function () { - var buffer = test_buffers_1.default.error([ - { - type: 'S', - value: 'ERROR', - }, - { - type: 'C', - value: 'code', - }, - { - type: 'M', - value: 'message', - }, - { - type: 'D', - value: 'details', - }, - { - type: 'H', - value: 'hint', - }, - { - type: 'P', - value: '100', - }, - { - type: 'p', - value: '101', - }, - { - type: 'q', - value: 'query', - }, - { - type: 'W', - value: 'where', - }, - { - type: 'F', - value: 'file', - }, - { - type: 'L', - value: 'line', - }, - { - type: 'R', - value: 'routine', - }, - { - type: 'Z', - value: 'alsdkf', - }, - ]); - testForMessage(buffer, { - name: 'error', - severity: 'ERROR', - code: 'code', - message: 'message', - detail: 'details', - hint: 'hint', - position: '100', - internalPosition: '101', - internalQuery: 'query', - where: 'where', - file: 'file', - line: 'line', - routine: 'routine', - }); - }); - testForMessage(parseCompleteBuffer, { - name: 'parseComplete', - }); - testForMessage(bindCompleteBuffer, { - name: 'bindComplete', - }); - testForMessage(bindCompleteBuffer, { - name: 'bindComplete', - }); - testForMessage(test_buffers_1.default.closeComplete(), { - name: 'closeComplete', - }); - describe('parses portal suspended message', function () { - testForMessage(portalSuspendedBuffer, { - name: 'portalSuspended', - }); - }); - describe('parses replication start message', function () { - testForMessage(Buffer.from([0x57, 0x00, 0x00, 0x00, 0x04]), { - name: 'replicationStart', - length: 4, - }); - }); - describe('copy', () => { - testForMessage(test_buffers_1.default.copyIn(0), { - name: 'copyInResponse', - length: 7, - binary: false, - columnTypes: [], - }); - testForMessage(test_buffers_1.default.copyIn(2), { - name: 'copyInResponse', - length: 11, - binary: false, - columnTypes: [0, 1], - }); - testForMessage(test_buffers_1.default.copyOut(0), { - name: 'copyOutResponse', - length: 7, - binary: false, - columnTypes: [], - }); - testForMessage(test_buffers_1.default.copyOut(3), { - name: 'copyOutResponse', - length: 13, - binary: false, - columnTypes: [0, 1, 2], - }); - testForMessage(test_buffers_1.default.copyDone(), { - name: 'copyDone', - length: 4, - }); - testForMessage(test_buffers_1.default.copyData(Buffer.from([5, 6, 7])), { - name: 'copyData', - length: 7, - chunk: Buffer.from([5, 6, 7]), - }); - }); - // since the data message on a stream can randomly divide the incomming - // tcp packets anywhere, we need to make sure we can parse every single - // split on a tcp message - describe('split buffer, single message parsing', function () { - var fullBuffer = test_buffers_1.default.dataRow([null, 'bang', 'zug zug', null, '!']); - it('parses when full buffer comes in', function () { - return __awaiter(this, void 0, void 0, function* () { - const messages = yield parseBuffers([fullBuffer]); - const message = messages[0]; - assert_1.default.equal(message.fields.length, 5); - assert_1.default.equal(message.fields[0], null); - assert_1.default.equal(message.fields[1], 'bang'); - assert_1.default.equal(message.fields[2], 'zug zug'); - assert_1.default.equal(message.fields[3], null); - assert_1.default.equal(message.fields[4], '!'); - }); - }); - var testMessageRecievedAfterSpiltAt = function (split) { - return __awaiter(this, void 0, void 0, function* () { - var firstBuffer = Buffer.alloc(fullBuffer.length - split); - var secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length); - fullBuffer.copy(firstBuffer, 0, 0); - fullBuffer.copy(secondBuffer, 0, firstBuffer.length); - const messages = yield parseBuffers([fullBuffer]); - const message = messages[0]; - assert_1.default.equal(message.fields.length, 5); - assert_1.default.equal(message.fields[0], null); - assert_1.default.equal(message.fields[1], 'bang'); - assert_1.default.equal(message.fields[2], 'zug zug'); - assert_1.default.equal(message.fields[3], null); - assert_1.default.equal(message.fields[4], '!'); - }); - }; - it('parses when split in the middle', function () { - testMessageRecievedAfterSpiltAt(6); - }); - it('parses when split at end', function () { - testMessageRecievedAfterSpiltAt(2); - }); - it('parses when split at beginning', function () { - testMessageRecievedAfterSpiltAt(fullBuffer.length - 2); - testMessageRecievedAfterSpiltAt(fullBuffer.length - 1); - testMessageRecievedAfterSpiltAt(fullBuffer.length - 5); - }); - }); - describe('split buffer, multiple message parsing', function () { - var dataRowBuffer = test_buffers_1.default.dataRow(['!']); - var readyForQueryBuffer = test_buffers_1.default.readyForQuery(); - var fullBuffer = Buffer.alloc(dataRowBuffer.length + readyForQueryBuffer.length); - dataRowBuffer.copy(fullBuffer, 0, 0); - readyForQueryBuffer.copy(fullBuffer, dataRowBuffer.length, 0); - var verifyMessages = function (messages) { - assert_1.default.strictEqual(messages.length, 2); - assert_1.default.deepEqual(messages[0], { - name: 'dataRow', - fieldCount: 1, - length: 11, - fields: ['!'], - }); - assert_1.default.equal(messages[0].fields[0], '!'); - assert_1.default.deepEqual(messages[1], { - name: 'readyForQuery', - length: 5, - status: 'I', - }); - }; - // sanity check - it('recieves both messages when packet is not split', function () { - return __awaiter(this, void 0, void 0, function* () { - const messages = yield parseBuffers([fullBuffer]); - verifyMessages(messages); - }); - }); - var splitAndVerifyTwoMessages = function (split) { - return __awaiter(this, void 0, void 0, function* () { - var firstBuffer = Buffer.alloc(fullBuffer.length - split); - var secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length); - fullBuffer.copy(firstBuffer, 0, 0); - fullBuffer.copy(secondBuffer, 0, firstBuffer.length); - const messages = yield parseBuffers([firstBuffer, secondBuffer]); - verifyMessages(messages); - }); - }; - describe('recieves both messages when packet is split', function () { - it('in the middle', function () { - return splitAndVerifyTwoMessages(11); - }); - it('at the front', function () { - return Promise.all([ - splitAndVerifyTwoMessages(fullBuffer.length - 1), - splitAndVerifyTwoMessages(fullBuffer.length - 4), - splitAndVerifyTwoMessages(fullBuffer.length - 6), - ]); - }); - it('at the end', function () { - return Promise.all([splitAndVerifyTwoMessages(8), splitAndVerifyTwoMessages(1)]); - }); - }); - }); -}); -//# sourceMappingURL=inbound-parser.test.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/inbound-parser.test.js.map b/reverse_engineering/node_modules/pg-protocol/dist/inbound-parser.test.js.map deleted file mode 100644 index b026ac4..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/inbound-parser.test.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inbound-parser.test.js","sourceRoot":"","sources":["../src/inbound-parser.test.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,0EAA4C;AAC5C,wEAA8C;AAC9C,wBAAyB;AACzB,oDAA2B;AAC3B,mCAAoC;AAGpC,IAAI,YAAY,GAAG,sBAAO,CAAC,gBAAgB,EAAE,CAAA;AAC7C,IAAI,iBAAiB,GAAG,sBAAO,CAAC,eAAe,CAAC,iBAAiB,EAAE,MAAM,CAAC,CAAA;AAC1E,IAAI,mBAAmB,GAAG,sBAAO,CAAC,aAAa,EAAE,CAAA;AACjD,IAAI,oBAAoB,GAAG,sBAAO,CAAC,cAAc,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;AACvD,IAAI,qBAAqB,GAAG,sBAAO,CAAC,eAAe,CAAC,UAAU,CAAC,CAAA;AAC/D,IAAI,mBAAmB,GAAG,sBAAO,CAAC,aAAa,EAAE,CAAA;AACjD,IAAI,kBAAkB,GAAG,sBAAO,CAAC,YAAY,EAAE,CAAA;AAC/C,IAAI,qBAAqB,GAAG,sBAAO,CAAC,eAAe,EAAE,CAAA;AAErD,IAAI,MAAM,GAAG,UAAU,UAAsB,EAAE,IAAY,EAAE,MAAc;IACzE,OAAO,UAAU;SACd,UAAU,CAAC,IAAI,CAAC,CAAC,aAAa;SAC9B,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,WAAW;SAC9B,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,6BAA6B;SAChD,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,gCAAgC;SACnD,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,gBAAgB;SACnC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,gBAAgB;SACnC,QAAQ,CAAC,CAAC,CAAC,CAAA,CAAC,yBAAyB;AAC1C,CAAC,CAAA;AAED,IAAI,IAAI,GAAG;IACT,IAAI,EAAE,IAAI;IACV,OAAO,EAAE,CAAC;IACV,eAAe,EAAE,CAAC;IAClB,UAAU,EAAE,CAAC;IACb,YAAY,EAAE,CAAC;IACf,YAAY,EAAE,CAAC;IACf,UAAU,EAAE,CAAC;CACd,CAAA;AACD,IAAI,cAAc,GAAG,sBAAO,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;AACnD,IAAI,CAAC,IAAI,GAAG,MAAM,CAAA;AAElB,IAAI,SAAS,GAAG,sBAAO,CAAC,cAAc,CAAC;IACrC,IAAI;IACJ;QACE,IAAI,EAAE,OAAO;QACb,OAAO,EAAE,EAAE;QACX,eAAe,EAAE,EAAE;QACnB,UAAU,EAAE,EAAE;QACd,YAAY,EAAE,EAAE;QAChB,YAAY,EAAE,EAAE;QAChB,UAAU,EAAE,CAAC;KACd;CACF,CAAC,CAAA;AAEF,IAAI,gBAAgB,GAAG,IAAI,qBAAU,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;AAEnE,IAAI,gBAAgB,GAAG,sBAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;AAE1C,IAAI,WAAW,GAAG,IAAI,qBAAU,EAAE;KAC/B,QAAQ,CAAC,CAAC,CAAC,CAAC,mBAAmB;KAC/B,QAAQ,CAAC,CAAC,CAAC,CAAC,4BAA4B;KACxC,UAAU,CAAC,MAAM,CAAC;KAClB,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;AAElB,IAAI,WAAW,GAAG,sBAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAA;AAE3C,IAAI,iCAAiC,GAAG;IACtC,IAAI,EAAE,kBAAkB;IACxB,MAAM,EAAE,CAAC;CACV,CAAA;AAED,IAAI,8BAA8B,GAAG;IACnC,IAAI,EAAE,iBAAiB;IACvB,aAAa,EAAE,iBAAiB;IAChC,cAAc,EAAE,MAAM;IACtB,MAAM,EAAE,EAAE;CACX,CAAA;AAED,IAAI,6BAA6B,GAAG;IAClC,IAAI,EAAE,gBAAgB;IACtB,SAAS,EAAE,CAAC;IACZ,SAAS,EAAE,CAAC;CACb,CAAA;AAED,IAAI,4BAA4B,GAAG;IACjC,IAAI,EAAE,eAAe;IACrB,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,GAAG;CACZ,CAAA;AAED,IAAI,8BAA8B,GAAG;IACnC,IAAI,EAAE,iBAAiB;IACvB,MAAM,EAAE,EAAE;IACV,IAAI,EAAE,UAAU;CACjB,CAAA;AACD,IAAI,yBAAyB,GAAG,IAAI,qBAAU,EAAE;KAC7C,QAAQ,CAAC,CAAC,CAAC,CAAC,mBAAmB;KAC/B,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;AAElB,IAAI,kCAAkC,GAAG;IACvC,IAAI,EAAE,gBAAgB;IACtB,MAAM,EAAE,CAAC;IACT,UAAU,EAAE,CAAC;IACb,MAAM,EAAE,EAAE;CACX,CAAA;AACD,IAAI,qBAAqB,GAAG;IAC1B,IAAI,EAAE,gBAAgB;IACtB,MAAM,EAAE,EAAE;IACV,UAAU,EAAE,CAAC;IACb,MAAM,EAAE;QACN;YACE,IAAI,EAAE,IAAI;YACV,OAAO,EAAE,CAAC;YACV,QAAQ,EAAE,CAAC;YACX,UAAU,EAAE,CAAC;YACb,YAAY,EAAE,CAAC;YACf,gBAAgB,EAAE,CAAC;YACnB,MAAM,EAAE,MAAM;SACf;KACF;CACF,CAAA;AAED,IAAI,qBAAqB,GAAG;IAC1B,IAAI,EAAE,gBAAgB;IACtB,MAAM,EAAE,EAAE;IACV,UAAU,EAAE,CAAC;IACb,MAAM,EAAE;QACN;YACE,IAAI,EAAE,MAAM;YACZ,OAAO,EAAE,CAAC;YACV,QAAQ,EAAE,CAAC;YACX,UAAU,EAAE,CAAC;YACb,YAAY,EAAE,CAAC;YACf,gBAAgB,EAAE,CAAC;YACnB,MAAM,EAAE,MAAM;SACf;QACD;YACE,IAAI,EAAE,OAAO;YACb,OAAO,EAAE,EAAE;YACX,QAAQ,EAAE,EAAE;YACZ,UAAU,EAAE,EAAE;YACd,YAAY,EAAE,EAAE;YAChB,gBAAgB,EAAE,EAAE;YACpB,MAAM,EAAE,MAAM;SACf;KACF;CACF,CAAA;AAED,IAAI,+BAA+B,GAAG,IAAI,qBAAU,EAAE;KACnD,QAAQ,CAAC,CAAC,CAAC,CAAC,uBAAuB;KACnC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;AAElB,IAAI,mBAAmB,GAAG,sBAAO,CAAC,oBAAoB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;AAE9D,IAAI,mBAAmB,GAAG,sBAAO,CAAC,oBAAoB,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;AAEpE,IAAI,wCAAwC,GAAG;IAC7C,IAAI,EAAE,sBAAsB;IAC5B,MAAM,EAAE,CAAC;IACT,cAAc,EAAE,CAAC;IACjB,WAAW,EAAE,EAAE;CAChB,CAAA;AAED,IAAI,2BAA2B,GAAG;IAChC,IAAI,EAAE,sBAAsB;IAC5B,MAAM,EAAE,EAAE;IACV,cAAc,EAAE,CAAC;IACjB,WAAW,EAAE,CAAC,IAAI,CAAC;CACpB,CAAA;AAED,IAAI,2BAA2B,GAAG;IAChC,IAAI,EAAE,sBAAsB;IAC5B,MAAM,EAAE,EAAE;IACV,cAAc,EAAE,CAAC;IACjB,WAAW,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;CAC1B,CAAA;AAED,IAAI,cAAc,GAAG,UAAU,MAAc,EAAE,eAAoB;IACjE,EAAE,CAAC,sBAAsB,GAAG,eAAe,CAAC,IAAI,EAAE,GAAS,EAAE;QAC3D,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC,CAAA;QAC7C,MAAM,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAA;QAE9B,KAAK,MAAM,GAAG,IAAI,eAAe,EAAE;YACjC,gBAAM,CAAC,SAAS,CAAE,WAAmB,CAAC,GAAG,CAAC,EAAE,eAAe,CAAC,GAAG,CAAC,CAAC,CAAA;SAClE;IACH,CAAC,CAAA,CAAC,CAAA;AACJ,CAAC,CAAA;AAED,IAAI,mBAAmB,GAAG,sBAAO,CAAC,+BAA+B,EAAE,CAAA;AACnE,IAAI,iBAAiB,GAAG,sBAAO,CAAC,yBAAyB,EAAE,CAAA;AAC3D,IAAI,UAAU,GAAG,sBAAO,CAAC,kBAAkB,EAAE,CAAA;AAC7C,IAAI,kBAAkB,GAAG,sBAAO,CAAC,0BAA0B,EAAE,CAAA;AAC7D,IAAI,eAAe,GAAG,sBAAO,CAAC,uBAAuB,EAAE,CAAA;AAEvD,IAAI,4BAA4B,GAAG;IACjC,IAAI,EAAE,iCAAiC;CACxC,CAAA;AAED,IAAI,0BAA0B,GAAG;IAC/B,IAAI,EAAE,2BAA2B;IACjC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;CAChC,CAAA;AAED,IAAI,mBAAmB,GAAG;IACxB,IAAI,EAAE,oBAAoB;IAC1B,UAAU,EAAE,CAAC,eAAe,CAAC;CAC9B,CAAA;AAED,IAAI,2BAA2B,GAAG;IAChC,IAAI,EAAE,4BAA4B;IAClC,IAAI,EAAE,MAAM;CACb,CAAA;AAED,IAAI,wBAAwB,GAAG;IAC7B,IAAI,EAAE,yBAAyB;IAC/B,IAAI,EAAE,MAAM;CACb,CAAA;AAED,IAAI,0BAA0B,GAAG,sBAAO,CAAC,YAAY,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAA;AACtE,IAAI,mCAAmC,GAAG;IACxC,IAAI,EAAE,cAAc;IACpB,SAAS,EAAE,CAAC;IACZ,OAAO,EAAE,IAAI;IACb,OAAO,EAAE,MAAM;CAChB,CAAA;AAED,MAAM,YAAY,GAAG,CAAO,OAAiB,EAA6B,EAAE;IAC1E,MAAM,MAAM,GAAG,IAAI,oBAAW,EAAE,CAAA;IAChC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;QAC5B,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;KACrB;IACD,MAAM,CAAC,GAAG,EAAE,CAAA;IACZ,MAAM,IAAI,GAAqB,EAAE,CAAA;IACjC,MAAM,QAAK,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;IAC5C,OAAO,IAAI,CAAA;AACb,CAAC,CAAA,CAAA;AAED,QAAQ,CAAC,gBAAgB,EAAE;IACzB,cAAc,CAAC,YAAY,EAAE,iCAAiC,CAAC,CAAA;IAC/D,cAAc,CAAC,mBAAmB,EAAE,4BAA4B,CAAC,CAAA;IACjE,cAAc,CAAC,iBAAiB,EAAE,0BAA0B,CAAC,CAAA;IAC7D,cAAc,CAAC,UAAU,EAAE,mBAAmB,CAAC,CAAA;IAC/C,cAAc,CAAC,kBAAkB,EAAE,2BAA2B,CAAC,CAAA;IAE/D,4CAA4C;IAC5C,2EAA2E;IAC3E,yFAAyF;IACzF,MAAM,0BAA0B,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,kBAAkB,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACjG,cAAc,CAAC,0BAA0B,EAAE,2BAA2B,CAAC,CAAA;IAEvE,cAAc,CAAC,eAAe,EAAE,wBAAwB,CAAC,CAAA;IAEzD,4CAA4C;IAC5C,2EAA2E;IAC3E,yFAAyF;IACzF,MAAM,uBAAuB,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,eAAe,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAC3F,cAAc,CAAC,uBAAuB,EAAE,wBAAwB,CAAC,CAAA;IAEjE,cAAc,CAAC,iBAAiB,EAAE,8BAA8B,CAAC,CAAA;IACjE,cAAc,CAAC,oBAAoB,EAAE,6BAA6B,CAAC,CAAA;IACnE,cAAc,CAAC,mBAAmB,EAAE,4BAA4B,CAAC,CAAA;IACjE,cAAc,CAAC,qBAAqB,EAAE,8BAA8B,CAAC,CAAA;IACrE,cAAc,CAAC,0BAA0B,EAAE,mCAAmC,CAAC,CAAA;IAC/E,cAAc,CAAC,sBAAO,CAAC,UAAU,EAAE,EAAE;QACnC,IAAI,EAAE,YAAY;QAClB,MAAM,EAAE,CAAC;KACV,CAAC,CAAA;IAEF,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE;QAC9C,IAAI,EAAE,QAAQ;KACf,CAAC,CAAA;IAEF,QAAQ,CAAC,yBAAyB,EAAE;QAClC,cAAc,CAAC,yBAAyB,EAAE,kCAAkC,CAAC,CAAA;QAC7E,cAAc,CAAC,cAAc,EAAE,qBAAqB,CAAC,CAAA;QACrD,cAAc,CAAC,SAAS,EAAE,qBAAqB,CAAC,CAAA;IAClD,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,+BAA+B,EAAE;QACxC,cAAc,CAAC,+BAA+B,EAAE,wCAAwC,CAAC,CAAA;QACzF,cAAc,CAAC,mBAAmB,EAAE,2BAA2B,CAAC,CAAA;QAChE,cAAc,CAAC,mBAAmB,EAAE,2BAA2B,CAAC,CAAA;IAClE,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,cAAc,EAAE;QACvB,QAAQ,CAAC,mBAAmB,EAAE;YAC5B,cAAc,CAAC,gBAAgB,EAAE;gBAC/B,IAAI,EAAE,SAAS;gBACf,UAAU,EAAE,CAAC;aACd,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QAEF,QAAQ,CAAC,8BAA8B,EAAE;YACvC,cAAc,CAAC,WAAW,EAAE;gBAC1B,IAAI,EAAE,SAAS;gBACf,UAAU,EAAE,CAAC;gBACb,MAAM,EAAE,CAAC,MAAM,CAAC;aACjB,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,gBAAgB,EAAE;QACzB,4CAA4C;QAC5C,IAAI,IAAI,GAAG,sBAAO,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC,CAAA;QACzD,cAAc,CAAC,IAAI,EAAE;YACnB,IAAI,EAAE,QAAQ;YACd,IAAI,EAAE,MAAM;SACb,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,cAAc,CAAC,sBAAO,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE;QAChC,IAAI,EAAE,OAAO;KACd,CAAC,CAAA;IAEF,QAAQ,CAAC,qBAAqB,EAAE;QAC9B,IAAI,MAAM,GAAG,sBAAO,CAAC,KAAK,CAAC;YACzB;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,OAAO;aACf;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,MAAM;aACd;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,SAAS;aACjB;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,SAAS;aACjB;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,MAAM;aACd;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,KAAK;aACb;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,KAAK;aACb;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,OAAO;aACf;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,OAAO;aACf;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,MAAM;aACd;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,MAAM;aACd;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,SAAS;aACjB;YACD;gBACE,IAAI,EAAE,GAAG;gBACT,KAAK,EAAE,QAAQ;aAChB;SACF,CAAC,CAAA;QAEF,cAAc,CAAC,MAAM,EAAE;YACrB,IAAI,EAAE,OAAO;YACb,QAAQ,EAAE,OAAO;YACjB,IAAI,EAAE,MAAM;YACZ,OAAO,EAAE,SAAS;YAClB,MAAM,EAAE,SAAS;YACjB,IAAI,EAAE,MAAM;YACZ,QAAQ,EAAE,KAAK;YACf,gBAAgB,EAAE,KAAK;YACvB,aAAa,EAAE,OAAO;YACtB,KAAK,EAAE,OAAO;YACd,IAAI,EAAE,MAAM;YACZ,IAAI,EAAE,MAAM;YACZ,OAAO,EAAE,SAAS;SACnB,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,cAAc,CAAC,mBAAmB,EAAE;QAClC,IAAI,EAAE,eAAe;KACtB,CAAC,CAAA;IAEF,cAAc,CAAC,kBAAkB,EAAE;QACjC,IAAI,EAAE,cAAc;KACrB,CAAC,CAAA;IAEF,cAAc,CAAC,kBAAkB,EAAE;QACjC,IAAI,EAAE,cAAc;KACrB,CAAC,CAAA;IAEF,cAAc,CAAC,sBAAO,CAAC,aAAa,EAAE,EAAE;QACtC,IAAI,EAAE,eAAe;KACtB,CAAC,CAAA;IAEF,QAAQ,CAAC,iCAAiC,EAAE;QAC1C,cAAc,CAAC,qBAAqB,EAAE;YACpC,IAAI,EAAE,iBAAiB;SACxB,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,kCAAkC,EAAE;QAC3C,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,EAAE;YAC1D,IAAI,EAAE,kBAAkB;YACxB,MAAM,EAAE,CAAC;SACV,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,MAAM,EAAE,GAAG,EAAE;QACpB,cAAc,CAAC,sBAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE;YAChC,IAAI,EAAE,gBAAgB;YACtB,MAAM,EAAE,CAAC;YACT,MAAM,EAAE,KAAK;YACb,WAAW,EAAE,EAAE;SAChB,CAAC,CAAA;QAEF,cAAc,CAAC,sBAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE;YAChC,IAAI,EAAE,gBAAgB;YACtB,MAAM,EAAE,EAAE;YACV,MAAM,EAAE,KAAK;YACb,WAAW,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;SACpB,CAAC,CAAA;QAEF,cAAc,CAAC,sBAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;YACjC,IAAI,EAAE,iBAAiB;YACvB,MAAM,EAAE,CAAC;YACT,MAAM,EAAE,KAAK;YACb,WAAW,EAAE,EAAE;SAChB,CAAC,CAAA;QAEF,cAAc,CAAC,sBAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;YACjC,IAAI,EAAE,iBAAiB;YACvB,MAAM,EAAE,EAAE;YACV,MAAM,EAAE,KAAK;YACb,WAAW,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;SACvB,CAAC,CAAA;QAEF,cAAc,CAAC,sBAAO,CAAC,QAAQ,EAAE,EAAE;YACjC,IAAI,EAAE,UAAU;YAChB,MAAM,EAAE,CAAC;SACV,CAAC,CAAA;QAEF,cAAc,CAAC,sBAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE;YACvD,IAAI,EAAE,UAAU;YAChB,MAAM,EAAE,CAAC;YACT,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;SAC9B,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,uEAAuE;IACvE,uEAAuE;IACvE,yBAAyB;IACzB,QAAQ,CAAC,sCAAsC,EAAE;QAC/C,IAAI,UAAU,GAAG,sBAAO,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;QAEtE,EAAE,CAAC,kCAAkC,EAAE;;gBACrC,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC,CAAC,UAAU,CAAC,CAAC,CAAA;gBACjD,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAQ,CAAA;gBAClC,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;gBACtC,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;gBACrC,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;gBACvC,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,CAAA;gBAC1C,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;gBACrC,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAA;YACtC,CAAC;SAAA,CAAC,CAAA;QAEF,IAAI,+BAA+B,GAAG,UAAgB,KAAa;;gBACjE,IAAI,WAAW,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,KAAK,CAAC,CAAA;gBACzD,IAAI,YAAY,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,CAAA;gBACvE,UAAU,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;gBAClC,UAAU,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAA;gBACpD,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC,CAAC,UAAU,CAAC,CAAC,CAAA;gBACjD,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAQ,CAAA;gBAClC,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;gBACtC,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;gBACrC,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;gBACvC,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,CAAA;gBAC1C,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;gBACrC,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAA;YACtC,CAAC;SAAA,CAAA;QAED,EAAE,CAAC,iCAAiC,EAAE;YACpC,+BAA+B,CAAC,CAAC,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,0BAA0B,EAAE;YAC7B,+BAA+B,CAAC,CAAC,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,gCAAgC,EAAE;YACnC,+BAA+B,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;YACtD,+BAA+B,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;YACtD,+BAA+B,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;QACxD,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,wCAAwC,EAAE;QACjD,IAAI,aAAa,GAAG,sBAAO,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAA;QAC1C,IAAI,mBAAmB,GAAG,sBAAO,CAAC,aAAa,EAAE,CAAA;QACjD,IAAI,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,aAAa,CAAC,MAAM,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAA;QAChF,aAAa,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;QACpC,mBAAmB,CAAC,IAAI,CAAC,UAAU,EAAE,aAAa,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;QAE7D,IAAI,cAAc,GAAG,UAAU,QAAe;YAC5C,gBAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;YACtC,gBAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE;gBAC5B,IAAI,EAAE,SAAS;gBACf,UAAU,EAAE,CAAC;gBACb,MAAM,EAAE,EAAE;gBACV,MAAM,EAAE,CAAC,GAAG,CAAC;aACd,CAAC,CAAA;YACF,gBAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAA;YACxC,gBAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE;gBAC5B,IAAI,EAAE,eAAe;gBACrB,MAAM,EAAE,CAAC;gBACT,MAAM,EAAE,GAAG;aACZ,CAAC,CAAA;QACJ,CAAC,CAAA;QACD,eAAe;QACf,EAAE,CAAC,iDAAiD,EAAE;;gBACpD,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC,CAAC,UAAU,CAAC,CAAC,CAAA;gBACjD,cAAc,CAAC,QAAQ,CAAC,CAAA;YAC1B,CAAC;SAAA,CAAC,CAAA;QAEF,IAAI,yBAAyB,GAAG,UAAgB,KAAa;;gBAC3D,IAAI,WAAW,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,KAAK,CAAC,CAAA;gBACzD,IAAI,YAAY,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,CAAA;gBACvE,UAAU,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;gBAClC,UAAU,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAA;gBACpD,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC,CAAA;gBAChE,cAAc,CAAC,QAAQ,CAAC,CAAA;YAC1B,CAAC;SAAA,CAAA;QAED,QAAQ,CAAC,6CAA6C,EAAE;YACtD,EAAE,CAAC,eAAe,EAAE;gBAClB,OAAO,yBAAyB,CAAC,EAAE,CAAC,CAAA;YACtC,CAAC,CAAC,CAAA;YACF,EAAE,CAAC,cAAc,EAAE;gBACjB,OAAO,OAAO,CAAC,GAAG,CAAC;oBACjB,yBAAyB,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC;oBAChD,yBAAyB,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC;oBAChD,yBAAyB,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC;iBACjD,CAAC,CAAA;YACJ,CAAC,CAAC,CAAA;YAEF,EAAE,CAAC,YAAY,EAAE;gBACf,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC,EAAE,yBAAyB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YAClF,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/index.d.ts b/reverse_engineering/node_modules/pg-protocol/dist/index.d.ts deleted file mode 100644 index 3961def..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/index.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/// -import { DatabaseError } from './messages'; -import { serialize } from './serializer'; -import { MessageCallback } from './parser'; -export declare function parse(stream: NodeJS.ReadableStream, callback: MessageCallback): Promise; -export { serialize, DatabaseError }; diff --git a/reverse_engineering/node_modules/pg-protocol/dist/index.js b/reverse_engineering/node_modules/pg-protocol/dist/index.js deleted file mode 100644 index 7eca3bf..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/index.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DatabaseError = exports.serialize = exports.parse = void 0; -const messages_1 = require("./messages"); -Object.defineProperty(exports, "DatabaseError", { enumerable: true, get: function () { return messages_1.DatabaseError; } }); -const serializer_1 = require("./serializer"); -Object.defineProperty(exports, "serialize", { enumerable: true, get: function () { return serializer_1.serialize; } }); -const parser_1 = require("./parser"); -function parse(stream, callback) { - const parser = new parser_1.Parser(); - stream.on('data', (buffer) => parser.parse(buffer, callback)); - return new Promise((resolve) => stream.on('end', () => resolve())); -} -exports.parse = parse; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/index.js.map b/reverse_engineering/node_modules/pg-protocol/dist/index.js.map deleted file mode 100644 index 5db25b6..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,yCAA0D;AAUtC,8FAVK,wBAAa,OAUL;AATjC,6CAAwC;AAS/B,0FATA,sBAAS,OASA;AARlB,qCAAkD;AAElD,SAAgB,KAAK,CAAC,MAA6B,EAAE,QAAyB;IAC5E,MAAM,MAAM,GAAG,IAAI,eAAM,EAAE,CAAA;IAC3B,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,MAAc,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAA;IACrE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;AACpE,CAAC;AAJD,sBAIC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/messages.d.ts b/reverse_engineering/node_modules/pg-protocol/dist/messages.d.ts deleted file mode 100644 index f8f2e63..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/messages.d.ts +++ /dev/null @@ -1,162 +0,0 @@ -/// -export declare type Mode = 'text' | 'binary'; -export declare type MessageName = 'parseComplete' | 'bindComplete' | 'closeComplete' | 'noData' | 'portalSuspended' | 'replicationStart' | 'emptyQuery' | 'copyDone' | 'copyData' | 'rowDescription' | 'parameterDescription' | 'parameterStatus' | 'backendKeyData' | 'notification' | 'readyForQuery' | 'commandComplete' | 'dataRow' | 'copyInResponse' | 'copyOutResponse' | 'authenticationOk' | 'authenticationMD5Password' | 'authenticationCleartextPassword' | 'authenticationSASL' | 'authenticationSASLContinue' | 'authenticationSASLFinal' | 'error' | 'notice'; -export interface BackendMessage { - name: MessageName; - length: number; -} -export declare const parseComplete: BackendMessage; -export declare const bindComplete: BackendMessage; -export declare const closeComplete: BackendMessage; -export declare const noData: BackendMessage; -export declare const portalSuspended: BackendMessage; -export declare const replicationStart: BackendMessage; -export declare const emptyQuery: BackendMessage; -export declare const copyDone: BackendMessage; -interface NoticeOrError { - message: string | undefined; - severity: string | undefined; - code: string | undefined; - detail: string | undefined; - hint: string | undefined; - position: string | undefined; - internalPosition: string | undefined; - internalQuery: string | undefined; - where: string | undefined; - schema: string | undefined; - table: string | undefined; - column: string | undefined; - dataType: string | undefined; - constraint: string | undefined; - file: string | undefined; - line: string | undefined; - routine: string | undefined; -} -export declare class DatabaseError extends Error implements NoticeOrError { - readonly length: number; - readonly name: MessageName; - severity: string | undefined; - code: string | undefined; - detail: string | undefined; - hint: string | undefined; - position: string | undefined; - internalPosition: string | undefined; - internalQuery: string | undefined; - where: string | undefined; - schema: string | undefined; - table: string | undefined; - column: string | undefined; - dataType: string | undefined; - constraint: string | undefined; - file: string | undefined; - line: string | undefined; - routine: string | undefined; - constructor(message: string, length: number, name: MessageName); -} -export declare class CopyDataMessage { - readonly length: number; - readonly chunk: Buffer; - readonly name = "copyData"; - constructor(length: number, chunk: Buffer); -} -export declare class CopyResponse { - readonly length: number; - readonly name: MessageName; - readonly binary: boolean; - readonly columnTypes: number[]; - constructor(length: number, name: MessageName, binary: boolean, columnCount: number); -} -export declare class Field { - readonly name: string; - readonly tableID: number; - readonly columnID: number; - readonly dataTypeID: number; - readonly dataTypeSize: number; - readonly dataTypeModifier: number; - readonly format: Mode; - constructor(name: string, tableID: number, columnID: number, dataTypeID: number, dataTypeSize: number, dataTypeModifier: number, format: Mode); -} -export declare class RowDescriptionMessage { - readonly length: number; - readonly fieldCount: number; - readonly name: MessageName; - readonly fields: Field[]; - constructor(length: number, fieldCount: number); -} -export declare class ParameterDescriptionMessage { - readonly length: number; - readonly parameterCount: number; - readonly name: MessageName; - readonly dataTypeIDs: number[]; - constructor(length: number, parameterCount: number); -} -export declare class ParameterStatusMessage { - readonly length: number; - readonly parameterName: string; - readonly parameterValue: string; - readonly name: MessageName; - constructor(length: number, parameterName: string, parameterValue: string); -} -export declare class AuthenticationMD5Password implements BackendMessage { - readonly length: number; - readonly salt: Buffer; - readonly name: MessageName; - constructor(length: number, salt: Buffer); -} -export declare class BackendKeyDataMessage { - readonly length: number; - readonly processID: number; - readonly secretKey: number; - readonly name: MessageName; - constructor(length: number, processID: number, secretKey: number); -} -export declare class NotificationResponseMessage { - readonly length: number; - readonly processId: number; - readonly channel: string; - readonly payload: string; - readonly name: MessageName; - constructor(length: number, processId: number, channel: string, payload: string); -} -export declare class ReadyForQueryMessage { - readonly length: number; - readonly status: string; - readonly name: MessageName; - constructor(length: number, status: string); -} -export declare class CommandCompleteMessage { - readonly length: number; - readonly text: string; - readonly name: MessageName; - constructor(length: number, text: string); -} -export declare class DataRowMessage { - length: number; - fields: any[]; - readonly fieldCount: number; - readonly name: MessageName; - constructor(length: number, fields: any[]); -} -export declare class NoticeMessage implements BackendMessage, NoticeOrError { - readonly length: number; - readonly message: string | undefined; - constructor(length: number, message: string | undefined); - readonly name = "notice"; - severity: string | undefined; - code: string | undefined; - detail: string | undefined; - hint: string | undefined; - position: string | undefined; - internalPosition: string | undefined; - internalQuery: string | undefined; - where: string | undefined; - schema: string | undefined; - table: string | undefined; - column: string | undefined; - dataType: string | undefined; - constraint: string | undefined; - file: string | undefined; - line: string | undefined; - routine: string | undefined; -} -export {}; diff --git a/reverse_engineering/node_modules/pg-protocol/dist/messages.js b/reverse_engineering/node_modules/pg-protocol/dist/messages.js deleted file mode 100644 index b9f2c44..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/messages.js +++ /dev/null @@ -1,160 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NoticeMessage = exports.DataRowMessage = exports.CommandCompleteMessage = exports.ReadyForQueryMessage = exports.NotificationResponseMessage = exports.BackendKeyDataMessage = exports.AuthenticationMD5Password = exports.ParameterStatusMessage = exports.ParameterDescriptionMessage = exports.RowDescriptionMessage = exports.Field = exports.CopyResponse = exports.CopyDataMessage = exports.DatabaseError = exports.copyDone = exports.emptyQuery = exports.replicationStart = exports.portalSuspended = exports.noData = exports.closeComplete = exports.bindComplete = exports.parseComplete = void 0; -exports.parseComplete = { - name: 'parseComplete', - length: 5, -}; -exports.bindComplete = { - name: 'bindComplete', - length: 5, -}; -exports.closeComplete = { - name: 'closeComplete', - length: 5, -}; -exports.noData = { - name: 'noData', - length: 5, -}; -exports.portalSuspended = { - name: 'portalSuspended', - length: 5, -}; -exports.replicationStart = { - name: 'replicationStart', - length: 4, -}; -exports.emptyQuery = { - name: 'emptyQuery', - length: 4, -}; -exports.copyDone = { - name: 'copyDone', - length: 4, -}; -class DatabaseError extends Error { - constructor(message, length, name) { - super(message); - this.length = length; - this.name = name; - } -} -exports.DatabaseError = DatabaseError; -class CopyDataMessage { - constructor(length, chunk) { - this.length = length; - this.chunk = chunk; - this.name = 'copyData'; - } -} -exports.CopyDataMessage = CopyDataMessage; -class CopyResponse { - constructor(length, name, binary, columnCount) { - this.length = length; - this.name = name; - this.binary = binary; - this.columnTypes = new Array(columnCount); - } -} -exports.CopyResponse = CopyResponse; -class Field { - constructor(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, format) { - this.name = name; - this.tableID = tableID; - this.columnID = columnID; - this.dataTypeID = dataTypeID; - this.dataTypeSize = dataTypeSize; - this.dataTypeModifier = dataTypeModifier; - this.format = format; - } -} -exports.Field = Field; -class RowDescriptionMessage { - constructor(length, fieldCount) { - this.length = length; - this.fieldCount = fieldCount; - this.name = 'rowDescription'; - this.fields = new Array(this.fieldCount); - } -} -exports.RowDescriptionMessage = RowDescriptionMessage; -class ParameterDescriptionMessage { - constructor(length, parameterCount) { - this.length = length; - this.parameterCount = parameterCount; - this.name = 'parameterDescription'; - this.dataTypeIDs = new Array(this.parameterCount); - } -} -exports.ParameterDescriptionMessage = ParameterDescriptionMessage; -class ParameterStatusMessage { - constructor(length, parameterName, parameterValue) { - this.length = length; - this.parameterName = parameterName; - this.parameterValue = parameterValue; - this.name = 'parameterStatus'; - } -} -exports.ParameterStatusMessage = ParameterStatusMessage; -class AuthenticationMD5Password { - constructor(length, salt) { - this.length = length; - this.salt = salt; - this.name = 'authenticationMD5Password'; - } -} -exports.AuthenticationMD5Password = AuthenticationMD5Password; -class BackendKeyDataMessage { - constructor(length, processID, secretKey) { - this.length = length; - this.processID = processID; - this.secretKey = secretKey; - this.name = 'backendKeyData'; - } -} -exports.BackendKeyDataMessage = BackendKeyDataMessage; -class NotificationResponseMessage { - constructor(length, processId, channel, payload) { - this.length = length; - this.processId = processId; - this.channel = channel; - this.payload = payload; - this.name = 'notification'; - } -} -exports.NotificationResponseMessage = NotificationResponseMessage; -class ReadyForQueryMessage { - constructor(length, status) { - this.length = length; - this.status = status; - this.name = 'readyForQuery'; - } -} -exports.ReadyForQueryMessage = ReadyForQueryMessage; -class CommandCompleteMessage { - constructor(length, text) { - this.length = length; - this.text = text; - this.name = 'commandComplete'; - } -} -exports.CommandCompleteMessage = CommandCompleteMessage; -class DataRowMessage { - constructor(length, fields) { - this.length = length; - this.fields = fields; - this.name = 'dataRow'; - this.fieldCount = fields.length; - } -} -exports.DataRowMessage = DataRowMessage; -class NoticeMessage { - constructor(length, message) { - this.length = length; - this.message = message; - this.name = 'notice'; - } -} -exports.NoticeMessage = NoticeMessage; -//# sourceMappingURL=messages.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/messages.js.map b/reverse_engineering/node_modules/pg-protocol/dist/messages.js.map deleted file mode 100644 index 091e5c3..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/messages.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"messages.js","sourceRoot":"","sources":["../src/messages.ts"],"names":[],"mappings":";;;AAoCa,QAAA,aAAa,GAAmB;IAC3C,IAAI,EAAE,eAAe;IACrB,MAAM,EAAE,CAAC;CACV,CAAA;AAEY,QAAA,YAAY,GAAmB;IAC1C,IAAI,EAAE,cAAc;IACpB,MAAM,EAAE,CAAC;CACV,CAAA;AAEY,QAAA,aAAa,GAAmB;IAC3C,IAAI,EAAE,eAAe;IACrB,MAAM,EAAE,CAAC;CACV,CAAA;AAEY,QAAA,MAAM,GAAmB;IACpC,IAAI,EAAE,QAAQ;IACd,MAAM,EAAE,CAAC;CACV,CAAA;AAEY,QAAA,eAAe,GAAmB;IAC7C,IAAI,EAAE,iBAAiB;IACvB,MAAM,EAAE,CAAC;CACV,CAAA;AAEY,QAAA,gBAAgB,GAAmB;IAC9C,IAAI,EAAE,kBAAkB;IACxB,MAAM,EAAE,CAAC;CACV,CAAA;AAEY,QAAA,UAAU,GAAmB;IACxC,IAAI,EAAE,YAAY;IAClB,MAAM,EAAE,CAAC;CACV,CAAA;AAEY,QAAA,QAAQ,GAAmB;IACtC,IAAI,EAAE,UAAU;IAChB,MAAM,EAAE,CAAC;CACV,CAAA;AAsBD,MAAa,aAAc,SAAQ,KAAK;IAiBtC,YAAY,OAAe,EAAkB,MAAc,EAAkB,IAAiB;QAC5F,KAAK,CAAC,OAAO,CAAC,CAAA;QAD6B,WAAM,GAAN,MAAM,CAAQ;QAAkB,SAAI,GAAJ,IAAI,CAAa;IAE9F,CAAC;CACF;AApBD,sCAoBC;AAED,MAAa,eAAe;IAE1B,YAA4B,MAAc,EAAkB,KAAa;QAA7C,WAAM,GAAN,MAAM,CAAQ;QAAkB,UAAK,GAAL,KAAK,CAAQ;QADzD,SAAI,GAAG,UAAU,CAAA;IAC2C,CAAC;CAC9E;AAHD,0CAGC;AAED,MAAa,YAAY;IAEvB,YACkB,MAAc,EACd,IAAiB,EACjB,MAAe,EAC/B,WAAmB;QAHH,WAAM,GAAN,MAAM,CAAQ;QACd,SAAI,GAAJ,IAAI,CAAa;QACjB,WAAM,GAAN,MAAM,CAAS;QAG/B,IAAI,CAAC,WAAW,GAAG,IAAI,KAAK,CAAC,WAAW,CAAC,CAAA;IAC3C,CAAC;CACF;AAVD,oCAUC;AAED,MAAa,KAAK;IAChB,YACkB,IAAY,EACZ,OAAe,EACf,QAAgB,EAChB,UAAkB,EAClB,YAAoB,EACpB,gBAAwB,EACxB,MAAY;QANZ,SAAI,GAAJ,IAAI,CAAQ;QACZ,YAAO,GAAP,OAAO,CAAQ;QACf,aAAQ,GAAR,QAAQ,CAAQ;QAChB,eAAU,GAAV,UAAU,CAAQ;QAClB,iBAAY,GAAZ,YAAY,CAAQ;QACpB,qBAAgB,GAAhB,gBAAgB,CAAQ;QACxB,WAAM,GAAN,MAAM,CAAM;IAC3B,CAAC;CACL;AAVD,sBAUC;AAED,MAAa,qBAAqB;IAGhC,YAA4B,MAAc,EAAkB,UAAkB;QAAlD,WAAM,GAAN,MAAM,CAAQ;QAAkB,eAAU,GAAV,UAAU,CAAQ;QAF9D,SAAI,GAAgB,gBAAgB,CAAA;QAGlD,IAAI,CAAC,MAAM,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;IAC1C,CAAC;CACF;AAND,sDAMC;AAED,MAAa,2BAA2B;IAGtC,YAA4B,MAAc,EAAkB,cAAsB;QAAtD,WAAM,GAAN,MAAM,CAAQ;QAAkB,mBAAc,GAAd,cAAc,CAAQ;QAFlE,SAAI,GAAgB,sBAAsB,CAAA;QAGxD,IAAI,CAAC,WAAW,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,CAAA;IACnD,CAAC;CACF;AAND,kEAMC;AAED,MAAa,sBAAsB;IAEjC,YACkB,MAAc,EACd,aAAqB,EACrB,cAAsB;QAFtB,WAAM,GAAN,MAAM,CAAQ;QACd,kBAAa,GAAb,aAAa,CAAQ;QACrB,mBAAc,GAAd,cAAc,CAAQ;QAJxB,SAAI,GAAgB,iBAAiB,CAAA;IAKlD,CAAC;CACL;AAPD,wDAOC;AAED,MAAa,yBAAyB;IAEpC,YAA4B,MAAc,EAAkB,IAAY;QAA5C,WAAM,GAAN,MAAM,CAAQ;QAAkB,SAAI,GAAJ,IAAI,CAAQ;QADxD,SAAI,GAAgB,2BAA2B,CAAA;IACY,CAAC;CAC7E;AAHD,8DAGC;AAED,MAAa,qBAAqB;IAEhC,YAA4B,MAAc,EAAkB,SAAiB,EAAkB,SAAiB;QAApF,WAAM,GAAN,MAAM,CAAQ;QAAkB,cAAS,GAAT,SAAS,CAAQ;QAAkB,cAAS,GAAT,SAAS,CAAQ;QADhG,SAAI,GAAgB,gBAAgB,CAAA;IAC+D,CAAC;CACrH;AAHD,sDAGC;AAED,MAAa,2BAA2B;IAEtC,YACkB,MAAc,EACd,SAAiB,EACjB,OAAe,EACf,OAAe;QAHf,WAAM,GAAN,MAAM,CAAQ;QACd,cAAS,GAAT,SAAS,CAAQ;QACjB,YAAO,GAAP,OAAO,CAAQ;QACf,YAAO,GAAP,OAAO,CAAQ;QALjB,SAAI,GAAgB,cAAc,CAAA;IAM/C,CAAC;CACL;AARD,kEAQC;AAED,MAAa,oBAAoB;IAE/B,YAA4B,MAAc,EAAkB,MAAc;QAA9C,WAAM,GAAN,MAAM,CAAQ;QAAkB,WAAM,GAAN,MAAM,CAAQ;QAD1D,SAAI,GAAgB,eAAe,CAAA;IAC0B,CAAC;CAC/E;AAHD,oDAGC;AAED,MAAa,sBAAsB;IAEjC,YAA4B,MAAc,EAAkB,IAAY;QAA5C,WAAM,GAAN,MAAM,CAAQ;QAAkB,SAAI,GAAJ,IAAI,CAAQ;QADxD,SAAI,GAAgB,iBAAiB,CAAA;IACsB,CAAC;CAC7E;AAHD,wDAGC;AAED,MAAa,cAAc;IAGzB,YAAmB,MAAc,EAAS,MAAa;QAApC,WAAM,GAAN,MAAM,CAAQ;QAAS,WAAM,GAAN,MAAM,CAAO;QADvC,SAAI,GAAgB,SAAS,CAAA;QAE3C,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,CAAA;IACjC,CAAC;CACF;AAND,wCAMC;AAED,MAAa,aAAa;IACxB,YAA4B,MAAc,EAAkB,OAA2B;QAA3D,WAAM,GAAN,MAAM,CAAQ;QAAkB,YAAO,GAAP,OAAO,CAAoB;QACvE,SAAI,GAAG,QAAQ,CAAA;IAD2D,CAAC;CAkB5F;AAnBD,sCAmBC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/outbound-serializer.test.d.ts b/reverse_engineering/node_modules/pg-protocol/dist/outbound-serializer.test.d.ts deleted file mode 100644 index cb0ff5c..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/outbound-serializer.test.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/reverse_engineering/node_modules/pg-protocol/dist/outbound-serializer.test.js b/reverse_engineering/node_modules/pg-protocol/dist/outbound-serializer.test.js deleted file mode 100644 index 18d1eab..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/outbound-serializer.test.js +++ /dev/null @@ -1,248 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const assert_1 = __importDefault(require("assert")); -const serializer_1 = require("./serializer"); -const buffer_list_1 = __importDefault(require("./testing/buffer-list")); -describe('serializer', () => { - it('builds startup message', function () { - const actual = serializer_1.serialize.startup({ - user: 'brian', - database: 'bang', - }); - assert_1.default.deepEqual(actual, new buffer_list_1.default() - .addInt16(3) - .addInt16(0) - .addCString('user') - .addCString('brian') - .addCString('database') - .addCString('bang') - .addCString('client_encoding') - .addCString('UTF8') - .addCString('') - .join(true)); - }); - it('builds password message', function () { - const actual = serializer_1.serialize.password('!'); - assert_1.default.deepEqual(actual, new buffer_list_1.default().addCString('!').join(true, 'p')); - }); - it('builds request ssl message', function () { - const actual = serializer_1.serialize.requestSsl(); - const expected = new buffer_list_1.default().addInt32(80877103).join(true); - assert_1.default.deepEqual(actual, expected); - }); - it('builds SASLInitialResponseMessage message', function () { - const actual = serializer_1.serialize.sendSASLInitialResponseMessage('mech', 'data'); - assert_1.default.deepEqual(actual, new buffer_list_1.default().addCString('mech').addInt32(4).addString('data').join(true, 'p')); - }); - it('builds SCRAMClientFinalMessage message', function () { - const actual = serializer_1.serialize.sendSCRAMClientFinalMessage('data'); - assert_1.default.deepEqual(actual, new buffer_list_1.default().addString('data').join(true, 'p')); - }); - it('builds query message', function () { - var txt = 'select * from boom'; - const actual = serializer_1.serialize.query(txt); - assert_1.default.deepEqual(actual, new buffer_list_1.default().addCString(txt).join(true, 'Q')); - }); - describe('parse message', () => { - it('builds parse message', function () { - const actual = serializer_1.serialize.parse({ text: '!' }); - var expected = new buffer_list_1.default().addCString('').addCString('!').addInt16(0).join(true, 'P'); - assert_1.default.deepEqual(actual, expected); - }); - it('builds parse message with named query', function () { - const actual = serializer_1.serialize.parse({ - name: 'boom', - text: 'select * from boom', - types: [], - }); - var expected = new buffer_list_1.default().addCString('boom').addCString('select * from boom').addInt16(0).join(true, 'P'); - assert_1.default.deepEqual(actual, expected); - }); - it('with multiple parameters', function () { - const actual = serializer_1.serialize.parse({ - name: 'force', - text: 'select * from bang where name = $1', - types: [1, 2, 3, 4], - }); - var expected = new buffer_list_1.default() - .addCString('force') - .addCString('select * from bang where name = $1') - .addInt16(4) - .addInt32(1) - .addInt32(2) - .addInt32(3) - .addInt32(4) - .join(true, 'P'); - assert_1.default.deepEqual(actual, expected); - }); - }); - describe('bind messages', function () { - it('with no values', function () { - const actual = serializer_1.serialize.bind(); - var expectedBuffer = new buffer_list_1.default() - .addCString('') - .addCString('') - .addInt16(0) - .addInt16(0) - .addInt16(0) - .join(true, 'B'); - assert_1.default.deepEqual(actual, expectedBuffer); - }); - it('with named statement, portal, and values', function () { - const actual = serializer_1.serialize.bind({ - portal: 'bang', - statement: 'woo', - values: ['1', 'hi', null, 'zing'], - }); - var expectedBuffer = new buffer_list_1.default() - .addCString('bang') // portal name - .addCString('woo') // statement name - .addInt16(4) - .addInt16(0) - .addInt16(0) - .addInt16(0) - .addInt16(0) - .addInt16(4) - .addInt32(1) - .add(Buffer.from('1')) - .addInt32(2) - .add(Buffer.from('hi')) - .addInt32(-1) - .addInt32(4) - .add(Buffer.from('zing')) - .addInt16(0) - .join(true, 'B'); - assert_1.default.deepEqual(actual, expectedBuffer); - }); - }); - it('with custom valueMapper', function () { - const actual = serializer_1.serialize.bind({ - portal: 'bang', - statement: 'woo', - values: ['1', 'hi', null, 'zing'], - valueMapper: () => null, - }); - var expectedBuffer = new buffer_list_1.default() - .addCString('bang') // portal name - .addCString('woo') // statement name - .addInt16(4) - .addInt16(0) - .addInt16(0) - .addInt16(0) - .addInt16(0) - .addInt16(4) - .addInt32(-1) - .addInt32(-1) - .addInt32(-1) - .addInt32(-1) - .addInt16(0) - .join(true, 'B'); - assert_1.default.deepEqual(actual, expectedBuffer); - }); - it('with named statement, portal, and buffer value', function () { - const actual = serializer_1.serialize.bind({ - portal: 'bang', - statement: 'woo', - values: ['1', 'hi', null, Buffer.from('zing', 'utf8')], - }); - var expectedBuffer = new buffer_list_1.default() - .addCString('bang') // portal name - .addCString('woo') // statement name - .addInt16(4) // value count - .addInt16(0) // string - .addInt16(0) // string - .addInt16(0) // string - .addInt16(1) // binary - .addInt16(4) - .addInt32(1) - .add(Buffer.from('1')) - .addInt32(2) - .add(Buffer.from('hi')) - .addInt32(-1) - .addInt32(4) - .add(Buffer.from('zing', 'utf-8')) - .addInt16(0) - .join(true, 'B'); - assert_1.default.deepEqual(actual, expectedBuffer); - }); - describe('builds execute message', function () { - it('for unamed portal with no row limit', function () { - const actual = serializer_1.serialize.execute(); - var expectedBuffer = new buffer_list_1.default().addCString('').addInt32(0).join(true, 'E'); - assert_1.default.deepEqual(actual, expectedBuffer); - }); - it('for named portal with row limit', function () { - const actual = serializer_1.serialize.execute({ - portal: 'my favorite portal', - rows: 100, - }); - var expectedBuffer = new buffer_list_1.default().addCString('my favorite portal').addInt32(100).join(true, 'E'); - assert_1.default.deepEqual(actual, expectedBuffer); - }); - }); - it('builds flush command', function () { - const actual = serializer_1.serialize.flush(); - var expected = new buffer_list_1.default().join(true, 'H'); - assert_1.default.deepEqual(actual, expected); - }); - it('builds sync command', function () { - const actual = serializer_1.serialize.sync(); - var expected = new buffer_list_1.default().join(true, 'S'); - assert_1.default.deepEqual(actual, expected); - }); - it('builds end command', function () { - const actual = serializer_1.serialize.end(); - var expected = Buffer.from([0x58, 0, 0, 0, 4]); - assert_1.default.deepEqual(actual, expected); - }); - describe('builds describe command', function () { - it('describe statement', function () { - const actual = serializer_1.serialize.describe({ type: 'S', name: 'bang' }); - var expected = new buffer_list_1.default().addChar('S').addCString('bang').join(true, 'D'); - assert_1.default.deepEqual(actual, expected); - }); - it('describe unnamed portal', function () { - const actual = serializer_1.serialize.describe({ type: 'P' }); - var expected = new buffer_list_1.default().addChar('P').addCString('').join(true, 'D'); - assert_1.default.deepEqual(actual, expected); - }); - }); - describe('builds close command', function () { - it('describe statement', function () { - const actual = serializer_1.serialize.close({ type: 'S', name: 'bang' }); - var expected = new buffer_list_1.default().addChar('S').addCString('bang').join(true, 'C'); - assert_1.default.deepEqual(actual, expected); - }); - it('describe unnamed portal', function () { - const actual = serializer_1.serialize.close({ type: 'P' }); - var expected = new buffer_list_1.default().addChar('P').addCString('').join(true, 'C'); - assert_1.default.deepEqual(actual, expected); - }); - }); - describe('copy messages', function () { - it('builds copyFromChunk', () => { - const actual = serializer_1.serialize.copyData(Buffer.from([1, 2, 3])); - const expected = new buffer_list_1.default().add(Buffer.from([1, 2, 3])).join(true, 'd'); - assert_1.default.deepEqual(actual, expected); - }); - it('builds copy fail', () => { - const actual = serializer_1.serialize.copyFail('err!'); - const expected = new buffer_list_1.default().addCString('err!').join(true, 'f'); - assert_1.default.deepEqual(actual, expected); - }); - it('builds copy done', () => { - const actual = serializer_1.serialize.copyDone(); - const expected = new buffer_list_1.default().join(true, 'c'); - assert_1.default.deepEqual(actual, expected); - }); - }); - it('builds cancel message', () => { - const actual = serializer_1.serialize.cancel(3, 4); - const expected = new buffer_list_1.default().addInt16(1234).addInt16(5678).addInt32(3).addInt32(4).join(true); - assert_1.default.deepEqual(actual, expected); - }); -}); -//# sourceMappingURL=outbound-serializer.test.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/outbound-serializer.test.js.map b/reverse_engineering/node_modules/pg-protocol/dist/outbound-serializer.test.js.map deleted file mode 100644 index 3dcb1c8..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/outbound-serializer.test.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"outbound-serializer.test.js","sourceRoot":"","sources":["../src/outbound-serializer.test.ts"],"names":[],"mappings":";;;;;AAAA,oDAA2B;AAC3B,6CAAwC;AACxC,wEAA8C;AAE9C,QAAQ,CAAC,YAAY,EAAE,GAAG,EAAE;IAC1B,EAAE,CAAC,wBAAwB,EAAE;QAC3B,MAAM,MAAM,GAAG,sBAAS,CAAC,OAAO,CAAC;YAC/B,IAAI,EAAE,OAAO;YACb,QAAQ,EAAE,MAAM;SACjB,CAAC,CAAA;QACF,gBAAM,CAAC,SAAS,CACd,MAAM,EACN,IAAI,qBAAU,EAAE;aACb,QAAQ,CAAC,CAAC,CAAC;aACX,QAAQ,CAAC,CAAC,CAAC;aACX,UAAU,CAAC,MAAM,CAAC;aAClB,UAAU,CAAC,OAAO,CAAC;aACnB,UAAU,CAAC,UAAU,CAAC;aACtB,UAAU,CAAC,MAAM,CAAC;aAClB,UAAU,CAAC,iBAAiB,CAAC;aAC7B,UAAU,CAAC,MAAM,CAAC;aAClB,UAAU,CAAC,EAAE,CAAC;aACd,IAAI,CAAC,IAAI,CAAC,CACd,CAAA;IACH,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,yBAAyB,EAAE;QAC5B,MAAM,MAAM,GAAG,sBAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;QACtC,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,qBAAU,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;IAC5E,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,4BAA4B,EAAE;QAC/B,MAAM,MAAM,GAAG,sBAAS,CAAC,UAAU,EAAE,CAAA;QACrC,MAAM,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAC/D,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IACpC,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,2CAA2C,EAAE;QAC9C,MAAM,MAAM,GAAG,sBAAS,CAAC,8BAA8B,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QACvE,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,qBAAU,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;IAC7G,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,wCAAwC,EAAE;QAC3C,MAAM,MAAM,GAAG,sBAAS,CAAC,2BAA2B,CAAC,MAAM,CAAC,CAAA;QAC5D,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,qBAAU,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;IAC9E,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,sBAAsB,EAAE;QACzB,IAAI,GAAG,GAAG,oBAAoB,CAAA;QAC9B,MAAM,MAAM,GAAG,sBAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;QACnC,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,qBAAU,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;IAC5E,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,eAAe,EAAE,GAAG,EAAE;QAC7B,EAAE,CAAC,sBAAsB,EAAE;YACzB,MAAM,MAAM,GAAG,sBAAS,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAA;YAC7C,IAAI,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAC1F,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,uCAAuC,EAAE;YAC1C,MAAM,MAAM,GAAG,sBAAS,CAAC,KAAK,CAAC;gBAC7B,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,oBAAoB;gBAC1B,KAAK,EAAE,EAAE;aACV,CAAC,CAAA;YACF,IAAI,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,UAAU,CAAC,oBAAoB,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAC/G,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,0BAA0B,EAAE;YAC7B,MAAM,MAAM,GAAG,sBAAS,CAAC,KAAK,CAAC;gBAC7B,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,oCAAoC;gBAC1C,KAAK,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;aACpB,CAAC,CAAA;YACF,IAAI,QAAQ,GAAG,IAAI,qBAAU,EAAE;iBAC5B,UAAU,CAAC,OAAO,CAAC;iBACnB,UAAU,CAAC,oCAAoC,CAAC;iBAChD,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAClB,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,eAAe,EAAE;QACxB,EAAE,CAAC,gBAAgB,EAAE;YACnB,MAAM,MAAM,GAAG,sBAAS,CAAC,IAAI,EAAE,CAAA;YAE/B,IAAI,cAAc,GAAG,IAAI,qBAAU,EAAE;iBAClC,UAAU,CAAC,EAAE,CAAC;iBACd,UAAU,CAAC,EAAE,CAAC;iBACd,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAClB,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,cAAc,CAAC,CAAA;QAC1C,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,0CAA0C,EAAE;YAC7C,MAAM,MAAM,GAAG,sBAAS,CAAC,IAAI,CAAC;gBAC5B,MAAM,EAAE,MAAM;gBACd,SAAS,EAAE,KAAK;gBAChB,MAAM,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC;aAClC,CAAC,CAAA;YACF,IAAI,cAAc,GAAG,IAAI,qBAAU,EAAE;iBAClC,UAAU,CAAC,MAAM,CAAC,CAAC,cAAc;iBACjC,UAAU,CAAC,KAAK,CAAC,CAAC,iBAAiB;iBACnC,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,QAAQ,CAAC,CAAC,CAAC;iBACX,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;iBACrB,QAAQ,CAAC,CAAC,CAAC;iBACX,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;iBACtB,QAAQ,CAAC,CAAC,CAAC,CAAC;iBACZ,QAAQ,CAAC,CAAC,CAAC;iBACX,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;iBACxB,QAAQ,CAAC,CAAC,CAAC;iBACX,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAClB,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,cAAc,CAAC,CAAA;QAC1C,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,yBAAyB,EAAE;QAC5B,MAAM,MAAM,GAAG,sBAAS,CAAC,IAAI,CAAC;YAC5B,MAAM,EAAE,MAAM;YACd,SAAS,EAAE,KAAK;YAChB,MAAM,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC;YACjC,WAAW,EAAE,GAAG,EAAE,CAAC,IAAI;SACxB,CAAC,CAAA;QACF,IAAI,cAAc,GAAG,IAAI,qBAAU,EAAE;aAClC,UAAU,CAAC,MAAM,CAAC,CAAC,cAAc;aACjC,UAAU,CAAC,KAAK,CAAC,CAAC,iBAAiB;aACnC,QAAQ,CAAC,CAAC,CAAC;aACX,QAAQ,CAAC,CAAC,CAAC;aACX,QAAQ,CAAC,CAAC,CAAC;aACX,QAAQ,CAAC,CAAC,CAAC;aACX,QAAQ,CAAC,CAAC,CAAC;aACX,QAAQ,CAAC,CAAC,CAAC;aACX,QAAQ,CAAC,CAAC,CAAC,CAAC;aACZ,QAAQ,CAAC,CAAC,CAAC,CAAC;aACZ,QAAQ,CAAC,CAAC,CAAC,CAAC;aACZ,QAAQ,CAAC,CAAC,CAAC,CAAC;aACZ,QAAQ,CAAC,CAAC,CAAC;aACX,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;QAClB,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,cAAc,CAAC,CAAA;IAC1C,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,gDAAgD,EAAE;QACnD,MAAM,MAAM,GAAG,sBAAS,CAAC,IAAI,CAAC;YAC5B,MAAM,EAAE,MAAM;YACd,SAAS,EAAE,KAAK;YAChB,MAAM,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;SACvD,CAAC,CAAA;QACF,IAAI,cAAc,GAAG,IAAI,qBAAU,EAAE;aAClC,UAAU,CAAC,MAAM,CAAC,CAAC,cAAc;aACjC,UAAU,CAAC,KAAK,CAAC,CAAC,iBAAiB;aACnC,QAAQ,CAAC,CAAC,CAAC,CAAC,cAAc;aAC1B,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS;aACrB,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS;aACrB,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS;aACrB,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS;aACrB,QAAQ,CAAC,CAAC,CAAC;aACX,QAAQ,CAAC,CAAC,CAAC;aACX,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;aACrB,QAAQ,CAAC,CAAC,CAAC;aACX,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;aACtB,QAAQ,CAAC,CAAC,CAAC,CAAC;aACZ,QAAQ,CAAC,CAAC,CAAC;aACX,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;aACjC,QAAQ,CAAC,CAAC,CAAC;aACX,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;QAClB,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,cAAc,CAAC,CAAA;IAC1C,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,wBAAwB,EAAE;QACjC,EAAE,CAAC,qCAAqC,EAAE;YACxC,MAAM,MAAM,GAAG,sBAAS,CAAC,OAAO,EAAE,CAAA;YAClC,IAAI,cAAc,GAAG,IAAI,qBAAU,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAChF,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,cAAc,CAAC,CAAA;QAC1C,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,iCAAiC,EAAE;YACpC,MAAM,MAAM,GAAG,sBAAS,CAAC,OAAO,CAAC;gBAC/B,MAAM,EAAE,oBAAoB;gBAC5B,IAAI,EAAE,GAAG;aACV,CAAC,CAAA;YACF,IAAI,cAAc,GAAG,IAAI,qBAAU,EAAE,CAAC,UAAU,CAAC,oBAAoB,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YACpG,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,cAAc,CAAC,CAAA;QAC1C,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,sBAAsB,EAAE;QACzB,MAAM,MAAM,GAAG,sBAAS,CAAC,KAAK,EAAE,CAAA;QAChC,IAAI,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;QAC/C,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IACpC,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,qBAAqB,EAAE;QACxB,MAAM,MAAM,GAAG,sBAAS,CAAC,IAAI,EAAE,CAAA;QAC/B,IAAI,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;QAC/C,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IACpC,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,oBAAoB,EAAE;QACvB,MAAM,MAAM,GAAG,sBAAS,CAAC,GAAG,EAAE,CAAA;QAC9B,IAAI,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;QAC9C,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IACpC,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,yBAAyB,EAAE;QAClC,EAAE,CAAC,oBAAoB,EAAE;YACvB,MAAM,MAAM,GAAG,sBAAS,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;YAC9D,IAAI,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAC/E,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,yBAAyB,EAAE;YAC5B,MAAM,MAAM,GAAG,sBAAS,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAA;YAChD,IAAI,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAC3E,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,sBAAsB,EAAE;QAC/B,EAAE,CAAC,oBAAoB,EAAE;YACvB,MAAM,MAAM,GAAG,sBAAS,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAA;YAC3D,IAAI,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAC/E,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,yBAAyB,EAAE;YAC5B,MAAM,MAAM,GAAG,sBAAS,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAA;YAC7C,IAAI,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAC3E,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,eAAe,EAAE;QACxB,EAAE,CAAC,sBAAsB,EAAE,GAAG,EAAE;YAC9B,MAAM,MAAM,GAAG,sBAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;YACzD,MAAM,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAC7E,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,kBAAkB,EAAE,GAAG,EAAE;YAC1B,MAAM,MAAM,GAAG,sBAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA;YACzC,MAAM,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YACpE,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,kBAAkB,EAAE,GAAG,EAAE;YAC1B,MAAM,MAAM,GAAG,sBAAS,CAAC,QAAQ,EAAE,CAAA;YACnC,MAAM,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YACjD,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;QACpC,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,uBAAuB,EAAE,GAAG,EAAE;QAC/B,MAAM,MAAM,GAAG,sBAAS,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;QACrC,MAAM,QAAQ,GAAG,IAAI,qBAAU,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAClG,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IACpC,CAAC,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/parser.d.ts b/reverse_engineering/node_modules/pg-protocol/dist/parser.d.ts deleted file mode 100644 index 030d1ef..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/parser.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -/// -import { TransformOptions } from 'stream'; -import { Mode, BackendMessage } from './messages'; -export declare type Packet = { - code: number; - packet: Buffer; -}; -declare type StreamOptions = TransformOptions & { - mode: Mode; -}; -export declare type MessageCallback = (msg: BackendMessage) => void; -export declare class Parser { - private buffer; - private bufferLength; - private bufferOffset; - private reader; - private mode; - constructor(opts?: StreamOptions); - parse(buffer: Buffer, callback: MessageCallback): void; - private mergeBuffer; - private handlePacket; - private parseReadyForQueryMessage; - private parseCommandCompleteMessage; - private parseCopyData; - private parseCopyInMessage; - private parseCopyOutMessage; - private parseCopyMessage; - private parseNotificationMessage; - private parseRowDescriptionMessage; - private parseField; - private parseParameterDescriptionMessage; - private parseDataRowMessage; - private parseParameterStatusMessage; - private parseBackendKeyData; - parseAuthenticationResponse(offset: number, length: number, bytes: Buffer): any; - private parseErrorMessage; -} -export {}; diff --git a/reverse_engineering/node_modules/pg-protocol/dist/parser.js b/reverse_engineering/node_modules/pg-protocol/dist/parser.js deleted file mode 100644 index d03b637..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/parser.js +++ /dev/null @@ -1,308 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Parser = void 0; -const messages_1 = require("./messages"); -const buffer_reader_1 = require("./buffer-reader"); -const assert_1 = __importDefault(require("assert")); -// every message is prefixed with a single bye -const CODE_LENGTH = 1; -// every message has an int32 length which includes itself but does -// NOT include the code in the length -const LEN_LENGTH = 4; -const HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH; -const emptyBuffer = Buffer.allocUnsafe(0); -class Parser { - constructor(opts) { - this.buffer = emptyBuffer; - this.bufferLength = 0; - this.bufferOffset = 0; - this.reader = new buffer_reader_1.BufferReader(); - if ((opts === null || opts === void 0 ? void 0 : opts.mode) === 'binary') { - throw new Error('Binary mode not supported yet'); - } - this.mode = (opts === null || opts === void 0 ? void 0 : opts.mode) || 'text'; - } - parse(buffer, callback) { - this.mergeBuffer(buffer); - const bufferFullLength = this.bufferOffset + this.bufferLength; - let offset = this.bufferOffset; - while (offset + HEADER_LENGTH <= bufferFullLength) { - // code is 1 byte long - it identifies the message type - const code = this.buffer[offset]; - // length is 1 Uint32BE - it is the length of the message EXCLUDING the code - const length = this.buffer.readUInt32BE(offset + CODE_LENGTH); - const fullMessageLength = CODE_LENGTH + length; - if (fullMessageLength + offset <= bufferFullLength) { - const message = this.handlePacket(offset + HEADER_LENGTH, code, length, this.buffer); - callback(message); - offset += fullMessageLength; - } - else { - break; - } - } - if (offset === bufferFullLength) { - // No more use for the buffer - this.buffer = emptyBuffer; - this.bufferLength = 0; - this.bufferOffset = 0; - } - else { - // Adjust the cursors of remainingBuffer - this.bufferLength = bufferFullLength - offset; - this.bufferOffset = offset; - } - } - mergeBuffer(buffer) { - if (this.bufferLength > 0) { - const newLength = this.bufferLength + buffer.byteLength; - const newFullLength = newLength + this.bufferOffset; - if (newFullLength > this.buffer.byteLength) { - // We can't concat the new buffer with the remaining one - let newBuffer; - if (newLength <= this.buffer.byteLength && this.bufferOffset >= this.bufferLength) { - // We can move the relevant part to the beginning of the buffer instead of allocating a new buffer - newBuffer = this.buffer; - } - else { - // Allocate a new larger buffer - let newBufferLength = this.buffer.byteLength * 2; - while (newLength >= newBufferLength) { - newBufferLength *= 2; - } - newBuffer = Buffer.allocUnsafe(newBufferLength); - } - // Move the remaining buffer to the new one - this.buffer.copy(newBuffer, 0, this.bufferOffset, this.bufferOffset + this.bufferLength); - this.buffer = newBuffer; - this.bufferOffset = 0; - } - // Concat the new buffer with the remaining one - buffer.copy(this.buffer, this.bufferOffset + this.bufferLength); - this.bufferLength = newLength; - } - else { - this.buffer = buffer; - this.bufferOffset = 0; - this.bufferLength = buffer.byteLength; - } - } - handlePacket(offset, code, length, bytes) { - switch (code) { - case 50 /* BindComplete */: - return messages_1.bindComplete; - case 49 /* ParseComplete */: - return messages_1.parseComplete; - case 51 /* CloseComplete */: - return messages_1.closeComplete; - case 110 /* NoData */: - return messages_1.noData; - case 115 /* PortalSuspended */: - return messages_1.portalSuspended; - case 99 /* CopyDone */: - return messages_1.copyDone; - case 87 /* ReplicationStart */: - return messages_1.replicationStart; - case 73 /* EmptyQuery */: - return messages_1.emptyQuery; - case 68 /* DataRow */: - return this.parseDataRowMessage(offset, length, bytes); - case 67 /* CommandComplete */: - return this.parseCommandCompleteMessage(offset, length, bytes); - case 90 /* ReadyForQuery */: - return this.parseReadyForQueryMessage(offset, length, bytes); - case 65 /* NotificationResponse */: - return this.parseNotificationMessage(offset, length, bytes); - case 82 /* AuthenticationResponse */: - return this.parseAuthenticationResponse(offset, length, bytes); - case 83 /* ParameterStatus */: - return this.parseParameterStatusMessage(offset, length, bytes); - case 75 /* BackendKeyData */: - return this.parseBackendKeyData(offset, length, bytes); - case 69 /* ErrorMessage */: - return this.parseErrorMessage(offset, length, bytes, 'error'); - case 78 /* NoticeMessage */: - return this.parseErrorMessage(offset, length, bytes, 'notice'); - case 84 /* RowDescriptionMessage */: - return this.parseRowDescriptionMessage(offset, length, bytes); - case 116 /* ParameterDescriptionMessage */: - return this.parseParameterDescriptionMessage(offset, length, bytes); - case 71 /* CopyIn */: - return this.parseCopyInMessage(offset, length, bytes); - case 72 /* CopyOut */: - return this.parseCopyOutMessage(offset, length, bytes); - case 100 /* CopyData */: - return this.parseCopyData(offset, length, bytes); - default: - assert_1.default.fail(`unknown message code: ${code.toString(16)}`); - } - } - parseReadyForQueryMessage(offset, length, bytes) { - this.reader.setBuffer(offset, bytes); - const status = this.reader.string(1); - return new messages_1.ReadyForQueryMessage(length, status); - } - parseCommandCompleteMessage(offset, length, bytes) { - this.reader.setBuffer(offset, bytes); - const text = this.reader.cstring(); - return new messages_1.CommandCompleteMessage(length, text); - } - parseCopyData(offset, length, bytes) { - const chunk = bytes.slice(offset, offset + (length - 4)); - return new messages_1.CopyDataMessage(length, chunk); - } - parseCopyInMessage(offset, length, bytes) { - return this.parseCopyMessage(offset, length, bytes, 'copyInResponse'); - } - parseCopyOutMessage(offset, length, bytes) { - return this.parseCopyMessage(offset, length, bytes, 'copyOutResponse'); - } - parseCopyMessage(offset, length, bytes, messageName) { - this.reader.setBuffer(offset, bytes); - const isBinary = this.reader.byte() !== 0; - const columnCount = this.reader.int16(); - const message = new messages_1.CopyResponse(length, messageName, isBinary, columnCount); - for (let i = 0; i < columnCount; i++) { - message.columnTypes[i] = this.reader.int16(); - } - return message; - } - parseNotificationMessage(offset, length, bytes) { - this.reader.setBuffer(offset, bytes); - const processId = this.reader.int32(); - const channel = this.reader.cstring(); - const payload = this.reader.cstring(); - return new messages_1.NotificationResponseMessage(length, processId, channel, payload); - } - parseRowDescriptionMessage(offset, length, bytes) { - this.reader.setBuffer(offset, bytes); - const fieldCount = this.reader.int16(); - const message = new messages_1.RowDescriptionMessage(length, fieldCount); - for (let i = 0; i < fieldCount; i++) { - message.fields[i] = this.parseField(); - } - return message; - } - parseField() { - const name = this.reader.cstring(); - const tableID = this.reader.int32(); - const columnID = this.reader.int16(); - const dataTypeID = this.reader.int32(); - const dataTypeSize = this.reader.int16(); - const dataTypeModifier = this.reader.int32(); - const mode = this.reader.int16() === 0 ? 'text' : 'binary'; - return new messages_1.Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode); - } - parseParameterDescriptionMessage(offset, length, bytes) { - this.reader.setBuffer(offset, bytes); - const parameterCount = this.reader.int16(); - const message = new messages_1.ParameterDescriptionMessage(length, parameterCount); - for (let i = 0; i < parameterCount; i++) { - message.dataTypeIDs[i] = this.reader.int32(); - } - return message; - } - parseDataRowMessage(offset, length, bytes) { - this.reader.setBuffer(offset, bytes); - const fieldCount = this.reader.int16(); - const fields = new Array(fieldCount); - for (let i = 0; i < fieldCount; i++) { - const len = this.reader.int32(); - // a -1 for length means the value of the field is null - fields[i] = len === -1 ? null : this.reader.string(len); - } - return new messages_1.DataRowMessage(length, fields); - } - parseParameterStatusMessage(offset, length, bytes) { - this.reader.setBuffer(offset, bytes); - const name = this.reader.cstring(); - const value = this.reader.cstring(); - return new messages_1.ParameterStatusMessage(length, name, value); - } - parseBackendKeyData(offset, length, bytes) { - this.reader.setBuffer(offset, bytes); - const processID = this.reader.int32(); - const secretKey = this.reader.int32(); - return new messages_1.BackendKeyDataMessage(length, processID, secretKey); - } - parseAuthenticationResponse(offset, length, bytes) { - this.reader.setBuffer(offset, bytes); - const code = this.reader.int32(); - // TODO(bmc): maybe better types here - const message = { - name: 'authenticationOk', - length, - }; - switch (code) { - case 0: // AuthenticationOk - break; - case 3: // AuthenticationCleartextPassword - if (message.length === 8) { - message.name = 'authenticationCleartextPassword'; - } - break; - case 5: // AuthenticationMD5Password - if (message.length === 12) { - message.name = 'authenticationMD5Password'; - const salt = this.reader.bytes(4); - return new messages_1.AuthenticationMD5Password(length, salt); - } - break; - case 10: // AuthenticationSASL - message.name = 'authenticationSASL'; - message.mechanisms = []; - let mechanism; - do { - mechanism = this.reader.cstring(); - if (mechanism) { - message.mechanisms.push(mechanism); - } - } while (mechanism); - break; - case 11: // AuthenticationSASLContinue - message.name = 'authenticationSASLContinue'; - message.data = this.reader.string(length - 8); - break; - case 12: // AuthenticationSASLFinal - message.name = 'authenticationSASLFinal'; - message.data = this.reader.string(length - 8); - break; - default: - throw new Error('Unknown authenticationOk message type ' + code); - } - return message; - } - parseErrorMessage(offset, length, bytes, name) { - this.reader.setBuffer(offset, bytes); - const fields = {}; - let fieldType = this.reader.string(1); - while (fieldType !== '\0') { - fields[fieldType] = this.reader.cstring(); - fieldType = this.reader.string(1); - } - const messageValue = fields.M; - const message = name === 'notice' ? new messages_1.NoticeMessage(length, messageValue) : new messages_1.DatabaseError(messageValue, length, name); - message.severity = fields.S; - message.code = fields.C; - message.detail = fields.D; - message.hint = fields.H; - message.position = fields.P; - message.internalPosition = fields.p; - message.internalQuery = fields.q; - message.where = fields.W; - message.schema = fields.s; - message.table = fields.t; - message.column = fields.c; - message.dataType = fields.d; - message.constraint = fields.n; - message.file = fields.F; - message.line = fields.L; - message.routine = fields.R; - return message; - } -} -exports.Parser = Parser; -//# sourceMappingURL=parser.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/parser.js.map b/reverse_engineering/node_modules/pg-protocol/dist/parser.js.map deleted file mode 100644 index 3eb27ad..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/parser.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"parser.js","sourceRoot":"","sources":["../src/parser.ts"],"names":[],"mappings":";;;;;;AACA,yCA0BmB;AACnB,mDAA8C;AAC9C,oDAA2B;AAE3B,8CAA8C;AAC9C,MAAM,WAAW,GAAG,CAAC,CAAA;AACrB,mEAAmE;AACnE,qCAAqC;AACrC,MAAM,UAAU,GAAG,CAAC,CAAA;AAEpB,MAAM,aAAa,GAAG,WAAW,GAAG,UAAU,CAAA;AAO9C,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAA;AAiCzC,MAAa,MAAM;IAOjB,YAAY,IAAoB;QANxB,WAAM,GAAW,WAAW,CAAA;QAC5B,iBAAY,GAAW,CAAC,CAAA;QACxB,iBAAY,GAAW,CAAC,CAAA;QACxB,WAAM,GAAG,IAAI,4BAAY,EAAE,CAAA;QAIjC,IAAI,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,IAAI,MAAK,QAAQ,EAAE;YAC3B,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAA;SACjD;QACD,IAAI,CAAC,IAAI,GAAG,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,IAAI,KAAI,MAAM,CAAA;IAClC,CAAC;IAEM,KAAK,CAAC,MAAc,EAAE,QAAyB;QACpD,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAA;QACxB,MAAM,gBAAgB,GAAG,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,CAAA;QAC9D,IAAI,MAAM,GAAG,IAAI,CAAC,YAAY,CAAA;QAC9B,OAAO,MAAM,GAAG,aAAa,IAAI,gBAAgB,EAAE;YACjD,uDAAuD;YACvD,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;YAChC,4EAA4E;YAC5E,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,MAAM,GAAG,WAAW,CAAC,CAAA;YAC7D,MAAM,iBAAiB,GAAG,WAAW,GAAG,MAAM,CAAA;YAC9C,IAAI,iBAAiB,GAAG,MAAM,IAAI,gBAAgB,EAAE;gBAClD,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,GAAG,aAAa,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;gBACpF,QAAQ,CAAC,OAAO,CAAC,CAAA;gBACjB,MAAM,IAAI,iBAAiB,CAAA;aAC5B;iBAAM;gBACL,MAAK;aACN;SACF;QACD,IAAI,MAAM,KAAK,gBAAgB,EAAE;YAC/B,6BAA6B;YAC7B,IAAI,CAAC,MAAM,GAAG,WAAW,CAAA;YACzB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAA;YACrB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAA;SACtB;aAAM;YACL,wCAAwC;YACxC,IAAI,CAAC,YAAY,GAAG,gBAAgB,GAAG,MAAM,CAAA;YAC7C,IAAI,CAAC,YAAY,GAAG,MAAM,CAAA;SAC3B;IACH,CAAC;IAEO,WAAW,CAAC,MAAc;QAChC,IAAI,IAAI,CAAC,YAAY,GAAG,CAAC,EAAE;YACzB,MAAM,SAAS,GAAG,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC,UAAU,CAAA;YACvD,MAAM,aAAa,GAAG,SAAS,GAAG,IAAI,CAAC,YAAY,CAAA;YACnD,IAAI,aAAa,GAAG,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE;gBAC1C,wDAAwD;gBACxD,IAAI,SAAiB,CAAA;gBACrB,IAAI,SAAS,IAAI,IAAI,CAAC,MAAM,CAAC,UAAU,IAAI,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,YAAY,EAAE;oBACjF,kGAAkG;oBAClG,SAAS,GAAG,IAAI,CAAC,MAAM,CAAA;iBACxB;qBAAM;oBACL,+BAA+B;oBAC/B,IAAI,eAAe,GAAG,IAAI,CAAC,MAAM,CAAC,UAAU,GAAG,CAAC,CAAA;oBAChD,OAAO,SAAS,IAAI,eAAe,EAAE;wBACnC,eAAe,IAAI,CAAC,CAAA;qBACrB;oBACD,SAAS,GAAG,MAAM,CAAC,WAAW,CAAC,eAAe,CAAC,CAAA;iBAChD;gBACD,2CAA2C;gBAC3C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,EAAE,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC,CAAA;gBACxF,IAAI,CAAC,MAAM,GAAG,SAAS,CAAA;gBACvB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAA;aACtB;YACD,+CAA+C;YAC/C,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC,CAAA;YAC/D,IAAI,CAAC,YAAY,GAAG,SAAS,CAAA;SAC9B;aAAM;YACL,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;YACpB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAA;YACrB,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC,UAAU,CAAA;SACtC;IACH,CAAC;IAEO,YAAY,CAAC,MAAc,EAAE,IAAY,EAAE,MAAc,EAAE,KAAa;QAC9E,QAAQ,IAAI,EAAE;YACZ;gBACE,OAAO,uBAAY,CAAA;YACrB;gBACE,OAAO,wBAAa,CAAA;YACtB;gBACE,OAAO,wBAAa,CAAA;YACtB;gBACE,OAAO,iBAAM,CAAA;YACf;gBACE,OAAO,0BAAe,CAAA;YACxB;gBACE,OAAO,mBAAQ,CAAA;YACjB;gBACE,OAAO,2BAAgB,CAAA;YACzB;gBACE,OAAO,qBAAU,CAAA;YACnB;gBACE,OAAO,IAAI,CAAC,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YACxD;gBACE,OAAO,IAAI,CAAC,2BAA2B,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YAChE;gBACE,OAAO,IAAI,CAAC,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YAC9D;gBACE,OAAO,IAAI,CAAC,wBAAwB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YAC7D;gBACE,OAAO,IAAI,CAAC,2BAA2B,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YAChE;gBACE,OAAO,IAAI,CAAC,2BAA2B,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YAChE;gBACE,OAAO,IAAI,CAAC,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YACxD;gBACE,OAAO,IAAI,CAAC,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,CAAA;YAC/D;gBACE,OAAO,IAAI,CAAC,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAA;YAChE;gBACE,OAAO,IAAI,CAAC,0BAA0B,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YAC/D;gBACE,OAAO,IAAI,CAAC,gCAAgC,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YACrE;gBACE,OAAO,IAAI,CAAC,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YACvD;gBACE,OAAO,IAAI,CAAC,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YACxD;gBACE,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;YAClD;gBACE,gBAAM,CAAC,IAAI,CAAC,yBAAyB,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC,CAAA;SAC5D;IACH,CAAC;IAEO,yBAAyB,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QAC7E,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACpC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;QACpC,OAAO,IAAI,+BAAoB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACjD,CAAC;IAEO,2BAA2B,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QAC/E,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACpC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAA;QAClC,OAAO,IAAI,iCAAsB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;IACjD,CAAC;IAEO,aAAa,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QACjE,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAA;QACxD,OAAO,IAAI,0BAAe,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;IAC3C,CAAC;IAEO,kBAAkB,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QACtE,OAAO,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB,CAAC,CAAA;IACvE,CAAC;IAEO,mBAAmB,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QACvE,OAAO,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,iBAAiB,CAAC,CAAA;IACxE,CAAC;IAEO,gBAAgB,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa,EAAE,WAAwB;QAC9F,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACpC,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACzC,MAAM,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QACvC,MAAM,OAAO,GAAG,IAAI,uBAAY,CAAC,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAA;QAC5E,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE,EAAE;YACpC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;SAC7C;QACD,OAAO,OAAO,CAAA;IAChB,CAAC;IAEO,wBAAwB,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QAC5E,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACpC,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QACrC,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAA;QACrC,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAA;QACrC,OAAO,IAAI,sCAA2B,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;IAC7E,CAAC;IAEO,0BAA0B,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QAC9E,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACpC,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QACtC,MAAM,OAAO,GAAG,IAAI,gCAAqB,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;QAC7D,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,EAAE,CAAC,EAAE,EAAE;YACnC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,UAAU,EAAE,CAAA;SACtC;QACD,OAAO,OAAO,CAAA;IAChB,CAAC;IAEO,UAAU;QAChB,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAA;QAClC,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QACnC,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QACpC,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QACtC,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QACxC,MAAM,gBAAgB,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QAC5C,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAA;QAC1D,OAAO,IAAI,gBAAK,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,YAAY,EAAE,gBAAgB,EAAE,IAAI,CAAC,CAAA;IAC7F,CAAC;IAEO,gCAAgC,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QACpF,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACpC,MAAM,cAAc,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QAC1C,MAAM,OAAO,GAAG,IAAI,sCAA2B,CAAC,MAAM,EAAE,cAAc,CAAC,CAAA;QACvE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE,EAAE;YACvC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;SAC7C;QACD,OAAO,OAAO,CAAA;IAChB,CAAC;IAEO,mBAAmB,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QACvE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACpC,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QACtC,MAAM,MAAM,GAAU,IAAI,KAAK,CAAC,UAAU,CAAC,CAAA;QAC3C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,EAAE,CAAC,EAAE,EAAE;YACnC,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;YAC/B,uDAAuD;YACvD,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;SACxD;QACD,OAAO,IAAI,yBAAc,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC3C,CAAC;IAEO,2BAA2B,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QAC/E,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACpC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAA;QAClC,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAA;QACnC,OAAO,IAAI,iCAAsB,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;IACxD,CAAC;IAEO,mBAAmB,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QACvE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACpC,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QACrC,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QACrC,OAAO,IAAI,gCAAqB,CAAC,MAAM,EAAE,SAAS,EAAE,SAAS,CAAC,CAAA;IAChE,CAAC;IAEM,2BAA2B,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa;QAC9E,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACpC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;QAChC,qCAAqC;QACrC,MAAM,OAAO,GAAyB;YACpC,IAAI,EAAE,kBAAkB;YACxB,MAAM;SACP,CAAA;QAED,QAAQ,IAAI,EAAE;YACZ,KAAK,CAAC,EAAE,mBAAmB;gBACzB,MAAK;YACP,KAAK,CAAC,EAAE,kCAAkC;gBACxC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;oBACxB,OAAO,CAAC,IAAI,GAAG,iCAAiC,CAAA;iBACjD;gBACD,MAAK;YACP,KAAK,CAAC,EAAE,4BAA4B;gBAClC,IAAI,OAAO,CAAC,MAAM,KAAK,EAAE,EAAE;oBACzB,OAAO,CAAC,IAAI,GAAG,2BAA2B,CAAA;oBAC1C,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;oBACjC,OAAO,IAAI,oCAAyB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;iBACnD;gBACD,MAAK;YACP,KAAK,EAAE,EAAE,qBAAqB;gBAC5B,OAAO,CAAC,IAAI,GAAG,oBAAoB,CAAA;gBACnC,OAAO,CAAC,UAAU,GAAG,EAAE,CAAA;gBACvB,IAAI,SAAiB,CAAA;gBACrB,GAAG;oBACD,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAA;oBAEjC,IAAI,SAAS,EAAE;wBACb,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;qBACnC;iBACF,QAAQ,SAAS,EAAC;gBACnB,MAAK;YACP,KAAK,EAAE,EAAE,6BAA6B;gBACpC,OAAO,CAAC,IAAI,GAAG,4BAA4B,CAAA;gBAC3C,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;gBAC7C,MAAK;YACP,KAAK,EAAE,EAAE,0BAA0B;gBACjC,OAAO,CAAC,IAAI,GAAG,yBAAyB,CAAA;gBACxC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;gBAC7C,MAAK;YACP;gBACE,MAAM,IAAI,KAAK,CAAC,wCAAwC,GAAG,IAAI,CAAC,CAAA;SACnE;QACD,OAAO,OAAO,CAAA;IAChB,CAAC;IAEO,iBAAiB,CAAC,MAAc,EAAE,MAAc,EAAE,KAAa,EAAE,IAAiB;QACxF,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACpC,MAAM,MAAM,GAA2B,EAAE,CAAA;QACzC,IAAI,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;QACrC,OAAO,SAAS,KAAK,IAAI,EAAE;YACzB,MAAM,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAA;YACzC,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;SAClC;QAED,MAAM,YAAY,GAAG,MAAM,CAAC,CAAC,CAAA;QAE7B,MAAM,OAAO,GACX,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,wBAAa,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,wBAAa,CAAC,YAAY,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;QAE7G,OAAO,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAC,CAAA;QAC3B,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC,CAAA;QACvB,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAA;QACzB,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC,CAAA;QACvB,OAAO,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAC,CAAA;QAC3B,OAAO,CAAC,gBAAgB,GAAG,MAAM,CAAC,CAAC,CAAA;QACnC,OAAO,CAAC,aAAa,GAAG,MAAM,CAAC,CAAC,CAAA;QAChC,OAAO,CAAC,KAAK,GAAG,MAAM,CAAC,CAAC,CAAA;QACxB,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAA;QACzB,OAAO,CAAC,KAAK,GAAG,MAAM,CAAC,CAAC,CAAA;QACxB,OAAO,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAA;QACzB,OAAO,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAC,CAAA;QAC3B,OAAO,CAAC,UAAU,GAAG,MAAM,CAAC,CAAC,CAAA;QAC7B,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC,CAAA;QACvB,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC,CAAA;QACvB,OAAO,CAAC,OAAO,GAAG,MAAM,CAAC,CAAC,CAAA;QAC1B,OAAO,OAAO,CAAA;IAChB,CAAC;CACF;AAvTD,wBAuTC"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/serializer.d.ts b/reverse_engineering/node_modules/pg-protocol/dist/serializer.d.ts deleted file mode 100644 index e0f0a00..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/serializer.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -/// -declare type ParseOpts = { - name?: string; - types?: number[]; - text: string; -}; -declare type ValueMapper = (param: any, index: number) => any; -declare type BindOpts = { - portal?: string; - binary?: boolean; - statement?: string; - values?: any[]; - valueMapper?: ValueMapper; -}; -declare type ExecOpts = { - portal?: string; - rows?: number; -}; -declare type PortalOpts = { - type: 'S' | 'P'; - name?: string; -}; -declare const serialize: { - startup: (opts: Record) => Buffer; - password: (password: string) => Buffer; - requestSsl: () => Buffer; - sendSASLInitialResponseMessage: (mechanism: string, initialResponse: string) => Buffer; - sendSCRAMClientFinalMessage: (additionalData: string) => Buffer; - query: (text: string) => Buffer; - parse: (query: ParseOpts) => Buffer; - bind: (config?: BindOpts) => Buffer; - execute: (config?: ExecOpts | undefined) => Buffer; - describe: (msg: PortalOpts) => Buffer; - close: (msg: PortalOpts) => Buffer; - flush: () => Buffer; - sync: () => Buffer; - end: () => Buffer; - copyData: (chunk: Buffer) => Buffer; - copyDone: () => Buffer; - copyFail: (message: string) => Buffer; - cancel: (processID: number, secretKey: number) => Buffer; -}; -export { serialize }; diff --git a/reverse_engineering/node_modules/pg-protocol/dist/serializer.js b/reverse_engineering/node_modules/pg-protocol/dist/serializer.js deleted file mode 100644 index 9aa0aed..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/serializer.js +++ /dev/null @@ -1,189 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.serialize = void 0; -const buffer_writer_1 = require("./buffer-writer"); -const writer = new buffer_writer_1.Writer(); -const startup = (opts) => { - // protocol version - writer.addInt16(3).addInt16(0); - for (const key of Object.keys(opts)) { - writer.addCString(key).addCString(opts[key]); - } - writer.addCString('client_encoding').addCString('UTF8'); - var bodyBuffer = writer.addCString('').flush(); - // this message is sent without a code - var length = bodyBuffer.length + 4; - return new buffer_writer_1.Writer().addInt32(length).add(bodyBuffer).flush(); -}; -const requestSsl = () => { - const response = Buffer.allocUnsafe(8); - response.writeInt32BE(8, 0); - response.writeInt32BE(80877103, 4); - return response; -}; -const password = (password) => { - return writer.addCString(password).flush(112 /* startup */); -}; -const sendSASLInitialResponseMessage = function (mechanism, initialResponse) { - // 0x70 = 'p' - writer.addCString(mechanism).addInt32(Buffer.byteLength(initialResponse)).addString(initialResponse); - return writer.flush(112 /* startup */); -}; -const sendSCRAMClientFinalMessage = function (additionalData) { - return writer.addString(additionalData).flush(112 /* startup */); -}; -const query = (text) => { - return writer.addCString(text).flush(81 /* query */); -}; -const emptyArray = []; -const parse = (query) => { - // expect something like this: - // { name: 'queryName', - // text: 'select * from blah', - // types: ['int8', 'bool'] } - // normalize missing query names to allow for null - const name = query.name || ''; - if (name.length > 63) { - /* eslint-disable no-console */ - console.error('Warning! Postgres only supports 63 characters for query names.'); - console.error('You supplied %s (%s)', name, name.length); - console.error('This can cause conflicts and silent errors executing queries'); - /* eslint-enable no-console */ - } - const types = query.types || emptyArray; - var len = types.length; - var buffer = writer - .addCString(name) // name of query - .addCString(query.text) // actual query text - .addInt16(len); - for (var i = 0; i < len; i++) { - buffer.addInt32(types[i]); - } - return writer.flush(80 /* parse */); -}; -const paramWriter = new buffer_writer_1.Writer(); -const writeValues = function (values, valueMapper) { - for (let i = 0; i < values.length; i++) { - const mappedVal = valueMapper ? valueMapper(values[i], i) : values[i]; - if (mappedVal == null) { - // add the param type (string) to the writer - writer.addInt16(0 /* STRING */); - // write -1 to the param writer to indicate null - paramWriter.addInt32(-1); - } - else if (mappedVal instanceof Buffer) { - // add the param type (binary) to the writer - writer.addInt16(1 /* BINARY */); - // add the buffer to the param writer - paramWriter.addInt32(mappedVal.length); - paramWriter.add(mappedVal); - } - else { - // add the param type (string) to the writer - writer.addInt16(0 /* STRING */); - paramWriter.addInt32(Buffer.byteLength(mappedVal)); - paramWriter.addString(mappedVal); - } - } -}; -const bind = (config = {}) => { - // normalize config - const portal = config.portal || ''; - const statement = config.statement || ''; - const binary = config.binary || false; - const values = config.values || emptyArray; - const len = values.length; - writer.addCString(portal).addCString(statement); - writer.addInt16(len); - writeValues(values, config.valueMapper); - writer.addInt16(len); - writer.add(paramWriter.flush()); - // format code - writer.addInt16(binary ? 1 /* BINARY */ : 0 /* STRING */); - return writer.flush(66 /* bind */); -}; -const emptyExecute = Buffer.from([69 /* execute */, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00]); -const execute = (config) => { - // this is the happy path for most queries - if (!config || (!config.portal && !config.rows)) { - return emptyExecute; - } - const portal = config.portal || ''; - const rows = config.rows || 0; - const portalLength = Buffer.byteLength(portal); - const len = 4 + portalLength + 1 + 4; - // one extra bit for code - const buff = Buffer.allocUnsafe(1 + len); - buff[0] = 69 /* execute */; - buff.writeInt32BE(len, 1); - buff.write(portal, 5, 'utf-8'); - buff[portalLength + 5] = 0; // null terminate portal cString - buff.writeUInt32BE(rows, buff.length - 4); - return buff; -}; -const cancel = (processID, secretKey) => { - const buffer = Buffer.allocUnsafe(16); - buffer.writeInt32BE(16, 0); - buffer.writeInt16BE(1234, 4); - buffer.writeInt16BE(5678, 6); - buffer.writeInt32BE(processID, 8); - buffer.writeInt32BE(secretKey, 12); - return buffer; -}; -const cstringMessage = (code, string) => { - const stringLen = Buffer.byteLength(string); - const len = 4 + stringLen + 1; - // one extra bit for code - const buffer = Buffer.allocUnsafe(1 + len); - buffer[0] = code; - buffer.writeInt32BE(len, 1); - buffer.write(string, 5, 'utf-8'); - buffer[len] = 0; // null terminate cString - return buffer; -}; -const emptyDescribePortal = writer.addCString('P').flush(68 /* describe */); -const emptyDescribeStatement = writer.addCString('S').flush(68 /* describe */); -const describe = (msg) => { - return msg.name - ? cstringMessage(68 /* describe */, `${msg.type}${msg.name || ''}`) - : msg.type === 'P' - ? emptyDescribePortal - : emptyDescribeStatement; -}; -const close = (msg) => { - const text = `${msg.type}${msg.name || ''}`; - return cstringMessage(67 /* close */, text); -}; -const copyData = (chunk) => { - return writer.add(chunk).flush(100 /* copyFromChunk */); -}; -const copyFail = (message) => { - return cstringMessage(102 /* copyFail */, message); -}; -const codeOnlyBuffer = (code) => Buffer.from([code, 0x00, 0x00, 0x00, 0x04]); -const flushBuffer = codeOnlyBuffer(72 /* flush */); -const syncBuffer = codeOnlyBuffer(83 /* sync */); -const endBuffer = codeOnlyBuffer(88 /* end */); -const copyDoneBuffer = codeOnlyBuffer(99 /* copyDone */); -const serialize = { - startup, - password, - requestSsl, - sendSASLInitialResponseMessage, - sendSCRAMClientFinalMessage, - query, - parse, - bind, - execute, - describe, - close, - flush: () => flushBuffer, - sync: () => syncBuffer, - end: () => endBuffer, - copyData, - copyDone: () => copyDoneBuffer, - copyFail, - cancel, -}; -exports.serialize = serialize; -//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/dist/serializer.js.map b/reverse_engineering/node_modules/pg-protocol/dist/serializer.js.map deleted file mode 100644 index 75d7119..0000000 --- a/reverse_engineering/node_modules/pg-protocol/dist/serializer.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"serializer.js","sourceRoot":"","sources":["../src/serializer.ts"],"names":[],"mappings":";;;AAAA,mDAAwC;AAkBxC,MAAM,MAAM,GAAG,IAAI,sBAAM,EAAE,CAAA;AAE3B,MAAM,OAAO,GAAG,CAAC,IAA4B,EAAU,EAAE;IACvD,mBAAmB;IACnB,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;IAC9B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QACnC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;KAC7C;IAED,MAAM,CAAC,UAAU,CAAC,iBAAiB,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAA;IAEvD,IAAI,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,CAAA;IAC9C,sCAAsC;IAEtC,IAAI,MAAM,GAAG,UAAU,CAAC,MAAM,GAAG,CAAC,CAAA;IAElC,OAAO,IAAI,sBAAM,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,KAAK,EAAE,CAAA;AAC9D,CAAC,CAAA;AAED,MAAM,UAAU,GAAG,GAAW,EAAE;IAC9B,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAA;IACtC,QAAQ,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;IAC3B,QAAQ,CAAC,YAAY,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAA;IAClC,OAAO,QAAQ,CAAA;AACjB,CAAC,CAAA;AAED,MAAM,QAAQ,GAAG,CAAC,QAAgB,EAAU,EAAE;IAC5C,OAAO,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,KAAK,mBAAc,CAAA;AACxD,CAAC,CAAA;AAED,MAAM,8BAA8B,GAAG,UAAU,SAAiB,EAAE,eAAuB;IACzF,aAAa;IACb,MAAM,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,eAAe,CAAC,CAAC,CAAC,SAAS,CAAC,eAAe,CAAC,CAAA;IAEpG,OAAO,MAAM,CAAC,KAAK,mBAAc,CAAA;AACnC,CAAC,CAAA;AAED,MAAM,2BAA2B,GAAG,UAAU,cAAsB;IAClE,OAAO,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC,KAAK,mBAAc,CAAA;AAC7D,CAAC,CAAA;AAED,MAAM,KAAK,GAAG,CAAC,IAAY,EAAU,EAAE;IACrC,OAAO,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,KAAK,gBAAY,CAAA;AAClD,CAAC,CAAA;AAQD,MAAM,UAAU,GAAU,EAAE,CAAA;AAE5B,MAAM,KAAK,GAAG,CAAC,KAAgB,EAAU,EAAE;IACzC,8BAA8B;IAC9B,uBAAuB;IACvB,gCAAgC;IAChC,8BAA8B;IAE9B,kDAAkD;IAClD,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,IAAI,EAAE,CAAA;IAC7B,IAAI,IAAI,CAAC,MAAM,GAAG,EAAE,EAAE;QACpB,+BAA+B;QAC/B,OAAO,CAAC,KAAK,CAAC,gEAAgE,CAAC,CAAA;QAC/E,OAAO,CAAC,KAAK,CAAC,sBAAsB,EAAE,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;QACxD,OAAO,CAAC,KAAK,CAAC,8DAA8D,CAAC,CAAA;QAC7E,8BAA8B;KAC/B;IAED,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,IAAI,UAAU,CAAA;IAEvC,IAAI,GAAG,GAAG,KAAK,CAAC,MAAM,CAAA;IAEtB,IAAI,MAAM,GAAG,MAAM;SAChB,UAAU,CAAC,IAAI,CAAC,CAAC,gBAAgB;SACjC,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,oBAAoB;SAC3C,QAAQ,CAAC,GAAG,CAAC,CAAA;IAEhB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;QAC5B,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;KAC1B;IAED,OAAO,MAAM,CAAC,KAAK,gBAAY,CAAA;AACjC,CAAC,CAAA;AAaD,MAAM,WAAW,GAAG,IAAI,sBAAM,EAAE,CAAA;AAQhC,MAAM,WAAW,GAAG,UAAU,MAAa,EAAE,WAAyB;IACpE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACtC,MAAM,SAAS,GAAG,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;QACrE,IAAI,SAAS,IAAI,IAAI,EAAE;YACrB,4CAA4C;YAC5C,MAAM,CAAC,QAAQ,gBAAkB,CAAA;YACjC,gDAAgD;YAChD,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAA;SACzB;aAAM,IAAI,SAAS,YAAY,MAAM,EAAE;YACtC,4CAA4C;YAC5C,MAAM,CAAC,QAAQ,gBAAkB,CAAA;YACjC,qCAAqC;YACrC,WAAW,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC,CAAA;YACtC,WAAW,CAAC,GAAG,CAAC,SAAS,CAAC,CAAA;SAC3B;aAAM;YACL,4CAA4C;YAC5C,MAAM,CAAC,QAAQ,gBAAkB,CAAA;YACjC,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAA;YAClD,WAAW,CAAC,SAAS,CAAC,SAAS,CAAC,CAAA;SACjC;KACF;AACH,CAAC,CAAA;AAED,MAAM,IAAI,GAAG,CAAC,SAAmB,EAAE,EAAU,EAAE;IAC7C,mBAAmB;IACnB,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,IAAI,EAAE,CAAA;IAClC,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,IAAI,EAAE,CAAA;IACxC,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,IAAI,KAAK,CAAA;IACrC,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,IAAI,UAAU,CAAA;IAC1C,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAA;IAEzB,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,CAAA;IAC/C,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;IAEpB,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,WAAW,CAAC,CAAA;IAEvC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;IACpB,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC,CAAA;IAE/B,cAAc;IACd,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,gBAAkB,CAAC,eAAiB,CAAC,CAAA;IAC7D,OAAO,MAAM,CAAC,KAAK,eAAW,CAAA;AAChC,CAAC,CAAA;AAOD,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,mBAAe,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;AAEtG,MAAM,OAAO,GAAG,CAAC,MAAiB,EAAU,EAAE;IAC5C,0CAA0C;IAC1C,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;QAC/C,OAAO,YAAY,CAAA;KACpB;IAED,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,IAAI,EAAE,CAAA;IAClC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,IAAI,CAAC,CAAA;IAE7B,MAAM,YAAY,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAA;IAC9C,MAAM,GAAG,GAAG,CAAC,GAAG,YAAY,GAAG,CAAC,GAAG,CAAC,CAAA;IACpC,yBAAyB;IACzB,MAAM,IAAI,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,GAAG,GAAG,CAAC,CAAA;IACxC,IAAI,CAAC,CAAC,CAAC,mBAAe,CAAA;IACtB,IAAI,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC,CAAC,CAAA;IACzB,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,OAAO,CAAC,CAAA;IAC9B,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,GAAG,CAAC,CAAA,CAAC,gCAAgC;IAC3D,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;IACzC,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,MAAM,GAAG,CAAC,SAAiB,EAAE,SAAiB,EAAU,EAAE;IAC9D,MAAM,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAA;IACrC,MAAM,CAAC,YAAY,CAAC,EAAE,EAAE,CAAC,CAAC,CAAA;IAC1B,MAAM,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;IAC5B,MAAM,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;IAC5B,MAAM,CAAC,YAAY,CAAC,SAAS,EAAE,CAAC,CAAC,CAAA;IACjC,MAAM,CAAC,YAAY,CAAC,SAAS,EAAE,EAAE,CAAC,CAAA;IAClC,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AAOD,MAAM,cAAc,GAAG,CAAC,IAAU,EAAE,MAAc,EAAU,EAAE;IAC5D,MAAM,SAAS,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAA;IAC3C,MAAM,GAAG,GAAG,CAAC,GAAG,SAAS,GAAG,CAAC,CAAA;IAC7B,yBAAyB;IACzB,MAAM,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,GAAG,GAAG,CAAC,CAAA;IAC1C,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,CAAA;IAChB,MAAM,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC,CAAC,CAAA;IAC3B,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,OAAO,CAAC,CAAA;IAChC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA,CAAC,yBAAyB;IACzC,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AAED,MAAM,mBAAmB,GAAG,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,KAAK,mBAAe,CAAA;AACvE,MAAM,sBAAsB,GAAG,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,KAAK,mBAAe,CAAA;AAE1E,MAAM,QAAQ,GAAG,CAAC,GAAe,EAAU,EAAE;IAC3C,OAAO,GAAG,CAAC,IAAI;QACb,CAAC,CAAC,cAAc,oBAAgB,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,CAAC;QAC/D,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,GAAG;YAClB,CAAC,CAAC,mBAAmB;YACrB,CAAC,CAAC,sBAAsB,CAAA;AAC5B,CAAC,CAAA;AAED,MAAM,KAAK,GAAG,CAAC,GAAe,EAAU,EAAE;IACxC,MAAM,IAAI,GAAG,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,IAAI,EAAE,EAAE,CAAA;IAC3C,OAAO,cAAc,iBAAa,IAAI,CAAC,CAAA;AACzC,CAAC,CAAA;AAED,MAAM,QAAQ,GAAG,CAAC,KAAa,EAAU,EAAE;IACzC,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,yBAAoB,CAAA;AACpD,CAAC,CAAA;AAED,MAAM,QAAQ,GAAG,CAAC,OAAe,EAAU,EAAE;IAC3C,OAAO,cAAc,qBAAgB,OAAO,CAAC,CAAA;AAC/C,CAAC,CAAA;AAED,MAAM,cAAc,GAAG,CAAC,IAAU,EAAU,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;AAE1F,MAAM,WAAW,GAAG,cAAc,gBAAY,CAAA;AAC9C,MAAM,UAAU,GAAG,cAAc,eAAW,CAAA;AAC5C,MAAM,SAAS,GAAG,cAAc,cAAU,CAAA;AAC1C,MAAM,cAAc,GAAG,cAAc,mBAAe,CAAA;AAEpD,MAAM,SAAS,GAAG;IAChB,OAAO;IACP,QAAQ;IACR,UAAU;IACV,8BAA8B;IAC9B,2BAA2B;IAC3B,KAAK;IACL,KAAK;IACL,IAAI;IACJ,OAAO;IACP,QAAQ;IACR,KAAK;IACL,KAAK,EAAE,GAAG,EAAE,CAAC,WAAW;IACxB,IAAI,EAAE,GAAG,EAAE,CAAC,UAAU;IACtB,GAAG,EAAE,GAAG,EAAE,CAAC,SAAS;IACpB,QAAQ;IACR,QAAQ,EAAE,GAAG,EAAE,CAAC,cAAc;IAC9B,QAAQ;IACR,MAAM;CACP,CAAA;AAEQ,8BAAS"} \ No newline at end of file diff --git a/reverse_engineering/node_modules/pg-protocol/package.json b/reverse_engineering/node_modules/pg-protocol/package.json deleted file mode 100644 index 9e92fd0..0000000 --- a/reverse_engineering/node_modules/pg-protocol/package.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "_from": "pg-protocol@^1.5.0", - "_id": "pg-protocol@1.5.0", - "_inBundle": false, - "_integrity": "sha512-muRttij7H8TqRNu/DxrAJQITO4Ac7RmX3Klyr/9mJEOBeIpgnF8f9jAfRz5d3XwQZl5qBjF9gLsUtMPJE0vezQ==", - "_location": "/pg-protocol", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "pg-protocol@^1.5.0", - "name": "pg-protocol", - "escapedName": "pg-protocol", - "rawSpec": "^1.5.0", - "saveSpec": null, - "fetchSpec": "^1.5.0" - }, - "_requiredBy": [ - "/pg" - ], - "_resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.5.0.tgz", - "_shasum": "b5dd452257314565e2d54ab3c132adc46565a6a0", - "_spec": "pg-protocol@^1.5.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg", - "bugs": { - "url": "https://github.com/brianc/node-postgres/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "The postgres client/server binary protocol, implemented in TypeScript", - "devDependencies": { - "@types/chai": "^4.2.7", - "@types/mocha": "^5.2.7", - "@types/node": "^12.12.21", - "chai": "^4.2.0", - "chunky": "^0.0.0", - "mocha": "^7.1.2", - "ts-node": "^8.5.4", - "typescript": "^4.0.3" - }, - "files": [ - "/dist/*{js,ts,map}", - "/src" - ], - "gitHead": "d45947938263bec30a1e3252452f04177b785f66", - "homepage": "https://github.com/brianc/node-postgres#readme", - "license": "MIT", - "main": "dist/index.js", - "name": "pg-protocol", - "repository": { - "type": "git", - "url": "git://github.com/brianc/node-postgres.git", - "directory": "packages/pg-protocol" - }, - "scripts": { - "build": "tsc", - "build:watch": "tsc --watch", - "prepublish": "yarn build", - "pretest": "yarn build", - "test": "mocha dist/**/*.test.js" - }, - "types": "dist/index.d.ts", - "version": "1.5.0" -} diff --git a/reverse_engineering/node_modules/pg-protocol/src/b.ts b/reverse_engineering/node_modules/pg-protocol/src/b.ts deleted file mode 100644 index 028b763..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/b.ts +++ /dev/null @@ -1,28 +0,0 @@ -// file for microbenchmarking - -import { Writer } from './buffer-writer' -import { serialize } from './index' -import { BufferReader } from './buffer-reader' - -const LOOPS = 1000 -let count = 0 -let start = Date.now() -const writer = new Writer() - -const reader = new BufferReader() -const buffer = Buffer.from([33, 33, 33, 33, 33, 33, 33, 0]) - -const run = () => { - if (count > LOOPS) { - console.log(Date.now() - start) - return - } - count++ - for (let i = 0; i < LOOPS; i++) { - reader.setBuffer(0, buffer) - reader.cstring() - } - setImmediate(run) -} - -run() diff --git a/reverse_engineering/node_modules/pg-protocol/src/buffer-reader.ts b/reverse_engineering/node_modules/pg-protocol/src/buffer-reader.ts deleted file mode 100644 index 2305e13..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/buffer-reader.ts +++ /dev/null @@ -1,53 +0,0 @@ -const emptyBuffer = Buffer.allocUnsafe(0) - -export class BufferReader { - private buffer: Buffer = emptyBuffer - - // TODO(bmc): support non-utf8 encoding? - private encoding: string = 'utf-8' - - constructor(private offset: number = 0) {} - - public setBuffer(offset: number, buffer: Buffer): void { - this.offset = offset - this.buffer = buffer - } - - public int16(): number { - const result = this.buffer.readInt16BE(this.offset) - this.offset += 2 - return result - } - - public byte(): number { - const result = this.buffer[this.offset] - this.offset++ - return result - } - - public int32(): number { - const result = this.buffer.readInt32BE(this.offset) - this.offset += 4 - return result - } - - public string(length: number): string { - const result = this.buffer.toString(this.encoding, this.offset, this.offset + length) - this.offset += length - return result - } - - public cstring(): string { - const start = this.offset - let end = start - while (this.buffer[end++] !== 0) {} - this.offset = end - return this.buffer.toString(this.encoding, start, end - 1) - } - - public bytes(length: number): Buffer { - const result = this.buffer.slice(this.offset, this.offset + length) - this.offset += length - return result - } -} diff --git a/reverse_engineering/node_modules/pg-protocol/src/buffer-writer.ts b/reverse_engineering/node_modules/pg-protocol/src/buffer-writer.ts deleted file mode 100644 index 756cdc9..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/buffer-writer.ts +++ /dev/null @@ -1,85 +0,0 @@ -//binary data writer tuned for encoding binary specific to the postgres binary protocol - -export class Writer { - private buffer: Buffer - private offset: number = 5 - private headerPosition: number = 0 - constructor(private size = 256) { - this.buffer = Buffer.allocUnsafe(size) - } - - private ensure(size: number): void { - var remaining = this.buffer.length - this.offset - if (remaining < size) { - var oldBuffer = this.buffer - // exponential growth factor of around ~ 1.5 - // https://stackoverflow.com/questions/2269063/buffer-growth-strategy - var newSize = oldBuffer.length + (oldBuffer.length >> 1) + size - this.buffer = Buffer.allocUnsafe(newSize) - oldBuffer.copy(this.buffer) - } - } - - public addInt32(num: number): Writer { - this.ensure(4) - this.buffer[this.offset++] = (num >>> 24) & 0xff - this.buffer[this.offset++] = (num >>> 16) & 0xff - this.buffer[this.offset++] = (num >>> 8) & 0xff - this.buffer[this.offset++] = (num >>> 0) & 0xff - return this - } - - public addInt16(num: number): Writer { - this.ensure(2) - this.buffer[this.offset++] = (num >>> 8) & 0xff - this.buffer[this.offset++] = (num >>> 0) & 0xff - return this - } - - public addCString(string: string): Writer { - if (!string) { - this.ensure(1) - } else { - var len = Buffer.byteLength(string) - this.ensure(len + 1) // +1 for null terminator - this.buffer.write(string, this.offset, 'utf-8') - this.offset += len - } - - this.buffer[this.offset++] = 0 // null terminator - return this - } - - public addString(string: string = ''): Writer { - var len = Buffer.byteLength(string) - this.ensure(len) - this.buffer.write(string, this.offset) - this.offset += len - return this - } - - public add(otherBuffer: Buffer): Writer { - this.ensure(otherBuffer.length) - otherBuffer.copy(this.buffer, this.offset) - this.offset += otherBuffer.length - return this - } - - private join(code?: number): Buffer { - if (code) { - this.buffer[this.headerPosition] = code - //length is everything in this packet minus the code - const length = this.offset - (this.headerPosition + 1) - this.buffer.writeInt32BE(length, this.headerPosition + 1) - } - return this.buffer.slice(code ? 0 : 5, this.offset) - } - - public flush(code?: number): Buffer { - var result = this.join(code) - this.offset = 5 - this.headerPosition = 0 - this.buffer = Buffer.allocUnsafe(this.size) - return result - } -} diff --git a/reverse_engineering/node_modules/pg-protocol/src/inbound-parser.test.ts b/reverse_engineering/node_modules/pg-protocol/src/inbound-parser.test.ts deleted file mode 100644 index 364bd8d..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/inbound-parser.test.ts +++ /dev/null @@ -1,557 +0,0 @@ -import buffers from './testing/test-buffers' -import BufferList from './testing/buffer-list' -import { parse } from '.' -import assert from 'assert' -import { PassThrough } from 'stream' -import { BackendMessage } from './messages' - -var authOkBuffer = buffers.authenticationOk() -var paramStatusBuffer = buffers.parameterStatus('client_encoding', 'UTF8') -var readyForQueryBuffer = buffers.readyForQuery() -var backendKeyDataBuffer = buffers.backendKeyData(1, 2) -var commandCompleteBuffer = buffers.commandComplete('SELECT 3') -var parseCompleteBuffer = buffers.parseComplete() -var bindCompleteBuffer = buffers.bindComplete() -var portalSuspendedBuffer = buffers.portalSuspended() - -var addRow = function (bufferList: BufferList, name: string, offset: number) { - return bufferList - .addCString(name) // field name - .addInt32(offset++) // table id - .addInt16(offset++) // attribute of column number - .addInt32(offset++) // objectId of field's data type - .addInt16(offset++) // datatype size - .addInt32(offset++) // type modifier - .addInt16(0) // format code, 0 => text -} - -var row1 = { - name: 'id', - tableID: 1, - attributeNumber: 2, - dataTypeID: 3, - dataTypeSize: 4, - typeModifier: 5, - formatCode: 0, -} -var oneRowDescBuff = buffers.rowDescription([row1]) -row1.name = 'bang' - -var twoRowBuf = buffers.rowDescription([ - row1, - { - name: 'whoah', - tableID: 10, - attributeNumber: 11, - dataTypeID: 12, - dataTypeSize: 13, - typeModifier: 14, - formatCode: 0, - }, -]) - -var emptyRowFieldBuf = new BufferList().addInt16(0).join(true, 'D') - -var emptyRowFieldBuf = buffers.dataRow([]) - -var oneFieldBuf = new BufferList() - .addInt16(1) // number of fields - .addInt32(5) // length of bytes of fields - .addCString('test') - .join(true, 'D') - -var oneFieldBuf = buffers.dataRow(['test']) - -var expectedAuthenticationOkayMessage = { - name: 'authenticationOk', - length: 8, -} - -var expectedParameterStatusMessage = { - name: 'parameterStatus', - parameterName: 'client_encoding', - parameterValue: 'UTF8', - length: 25, -} - -var expectedBackendKeyDataMessage = { - name: 'backendKeyData', - processID: 1, - secretKey: 2, -} - -var expectedReadyForQueryMessage = { - name: 'readyForQuery', - length: 5, - status: 'I', -} - -var expectedCommandCompleteMessage = { - name: 'commandComplete', - length: 13, - text: 'SELECT 3', -} -var emptyRowDescriptionBuffer = new BufferList() - .addInt16(0) // number of fields - .join(true, 'T') - -var expectedEmptyRowDescriptionMessage = { - name: 'rowDescription', - length: 6, - fieldCount: 0, - fields: [], -} -var expectedOneRowMessage = { - name: 'rowDescription', - length: 27, - fieldCount: 1, - fields: [ - { - name: 'id', - tableID: 1, - columnID: 2, - dataTypeID: 3, - dataTypeSize: 4, - dataTypeModifier: 5, - format: 'text', - }, - ], -} - -var expectedTwoRowMessage = { - name: 'rowDescription', - length: 53, - fieldCount: 2, - fields: [ - { - name: 'bang', - tableID: 1, - columnID: 2, - dataTypeID: 3, - dataTypeSize: 4, - dataTypeModifier: 5, - format: 'text', - }, - { - name: 'whoah', - tableID: 10, - columnID: 11, - dataTypeID: 12, - dataTypeSize: 13, - dataTypeModifier: 14, - format: 'text', - }, - ], -} - -var emptyParameterDescriptionBuffer = new BufferList() - .addInt16(0) // number of parameters - .join(true, 't') - -var oneParameterDescBuf = buffers.parameterDescription([1111]) - -var twoParameterDescBuf = buffers.parameterDescription([2222, 3333]) - -var expectedEmptyParameterDescriptionMessage = { - name: 'parameterDescription', - length: 6, - parameterCount: 0, - dataTypeIDs: [], -} - -var expectedOneParameterMessage = { - name: 'parameterDescription', - length: 10, - parameterCount: 1, - dataTypeIDs: [1111], -} - -var expectedTwoParameterMessage = { - name: 'parameterDescription', - length: 14, - parameterCount: 2, - dataTypeIDs: [2222, 3333], -} - -var testForMessage = function (buffer: Buffer, expectedMessage: any) { - it('recieves and parses ' + expectedMessage.name, async () => { - const messages = await parseBuffers([buffer]) - const [lastMessage] = messages - - for (const key in expectedMessage) { - assert.deepEqual((lastMessage as any)[key], expectedMessage[key]) - } - }) -} - -var plainPasswordBuffer = buffers.authenticationCleartextPassword() -var md5PasswordBuffer = buffers.authenticationMD5Password() -var SASLBuffer = buffers.authenticationSASL() -var SASLContinueBuffer = buffers.authenticationSASLContinue() -var SASLFinalBuffer = buffers.authenticationSASLFinal() - -var expectedPlainPasswordMessage = { - name: 'authenticationCleartextPassword', -} - -var expectedMD5PasswordMessage = { - name: 'authenticationMD5Password', - salt: Buffer.from([1, 2, 3, 4]), -} - -var expectedSASLMessage = { - name: 'authenticationSASL', - mechanisms: ['SCRAM-SHA-256'], -} - -var expectedSASLContinueMessage = { - name: 'authenticationSASLContinue', - data: 'data', -} - -var expectedSASLFinalMessage = { - name: 'authenticationSASLFinal', - data: 'data', -} - -var notificationResponseBuffer = buffers.notification(4, 'hi', 'boom') -var expectedNotificationResponseMessage = { - name: 'notification', - processId: 4, - channel: 'hi', - payload: 'boom', -} - -const parseBuffers = async (buffers: Buffer[]): Promise => { - const stream = new PassThrough() - for (const buffer of buffers) { - stream.write(buffer) - } - stream.end() - const msgs: BackendMessage[] = [] - await parse(stream, (msg) => msgs.push(msg)) - return msgs -} - -describe('PgPacketStream', function () { - testForMessage(authOkBuffer, expectedAuthenticationOkayMessage) - testForMessage(plainPasswordBuffer, expectedPlainPasswordMessage) - testForMessage(md5PasswordBuffer, expectedMD5PasswordMessage) - testForMessage(SASLBuffer, expectedSASLMessage) - testForMessage(SASLContinueBuffer, expectedSASLContinueMessage) - - // this exercises a found bug in the parser: - // https://github.com/brianc/node-postgres/pull/2210#issuecomment-627626084 - // and adds a test which is deterministic, rather than relying on network packet chunking - const extendedSASLContinueBuffer = Buffer.concat([SASLContinueBuffer, Buffer.from([1, 2, 3, 4])]) - testForMessage(extendedSASLContinueBuffer, expectedSASLContinueMessage) - - testForMessage(SASLFinalBuffer, expectedSASLFinalMessage) - - // this exercises a found bug in the parser: - // https://github.com/brianc/node-postgres/pull/2210#issuecomment-627626084 - // and adds a test which is deterministic, rather than relying on network packet chunking - const extendedSASLFinalBuffer = Buffer.concat([SASLFinalBuffer, Buffer.from([1, 2, 4, 5])]) - testForMessage(extendedSASLFinalBuffer, expectedSASLFinalMessage) - - testForMessage(paramStatusBuffer, expectedParameterStatusMessage) - testForMessage(backendKeyDataBuffer, expectedBackendKeyDataMessage) - testForMessage(readyForQueryBuffer, expectedReadyForQueryMessage) - testForMessage(commandCompleteBuffer, expectedCommandCompleteMessage) - testForMessage(notificationResponseBuffer, expectedNotificationResponseMessage) - testForMessage(buffers.emptyQuery(), { - name: 'emptyQuery', - length: 4, - }) - - testForMessage(Buffer.from([0x6e, 0, 0, 0, 4]), { - name: 'noData', - }) - - describe('rowDescription messages', function () { - testForMessage(emptyRowDescriptionBuffer, expectedEmptyRowDescriptionMessage) - testForMessage(oneRowDescBuff, expectedOneRowMessage) - testForMessage(twoRowBuf, expectedTwoRowMessage) - }) - - describe('parameterDescription messages', function () { - testForMessage(emptyParameterDescriptionBuffer, expectedEmptyParameterDescriptionMessage) - testForMessage(oneParameterDescBuf, expectedOneParameterMessage) - testForMessage(twoParameterDescBuf, expectedTwoParameterMessage) - }) - - describe('parsing rows', function () { - describe('parsing empty row', function () { - testForMessage(emptyRowFieldBuf, { - name: 'dataRow', - fieldCount: 0, - }) - }) - - describe('parsing data row with fields', function () { - testForMessage(oneFieldBuf, { - name: 'dataRow', - fieldCount: 1, - fields: ['test'], - }) - }) - }) - - describe('notice message', function () { - // this uses the same logic as error message - var buff = buffers.notice([{ type: 'C', value: 'code' }]) - testForMessage(buff, { - name: 'notice', - code: 'code', - }) - }) - - testForMessage(buffers.error([]), { - name: 'error', - }) - - describe('with all the fields', function () { - var buffer = buffers.error([ - { - type: 'S', - value: 'ERROR', - }, - { - type: 'C', - value: 'code', - }, - { - type: 'M', - value: 'message', - }, - { - type: 'D', - value: 'details', - }, - { - type: 'H', - value: 'hint', - }, - { - type: 'P', - value: '100', - }, - { - type: 'p', - value: '101', - }, - { - type: 'q', - value: 'query', - }, - { - type: 'W', - value: 'where', - }, - { - type: 'F', - value: 'file', - }, - { - type: 'L', - value: 'line', - }, - { - type: 'R', - value: 'routine', - }, - { - type: 'Z', // ignored - value: 'alsdkf', - }, - ]) - - testForMessage(buffer, { - name: 'error', - severity: 'ERROR', - code: 'code', - message: 'message', - detail: 'details', - hint: 'hint', - position: '100', - internalPosition: '101', - internalQuery: 'query', - where: 'where', - file: 'file', - line: 'line', - routine: 'routine', - }) - }) - - testForMessage(parseCompleteBuffer, { - name: 'parseComplete', - }) - - testForMessage(bindCompleteBuffer, { - name: 'bindComplete', - }) - - testForMessage(bindCompleteBuffer, { - name: 'bindComplete', - }) - - testForMessage(buffers.closeComplete(), { - name: 'closeComplete', - }) - - describe('parses portal suspended message', function () { - testForMessage(portalSuspendedBuffer, { - name: 'portalSuspended', - }) - }) - - describe('parses replication start message', function () { - testForMessage(Buffer.from([0x57, 0x00, 0x00, 0x00, 0x04]), { - name: 'replicationStart', - length: 4, - }) - }) - - describe('copy', () => { - testForMessage(buffers.copyIn(0), { - name: 'copyInResponse', - length: 7, - binary: false, - columnTypes: [], - }) - - testForMessage(buffers.copyIn(2), { - name: 'copyInResponse', - length: 11, - binary: false, - columnTypes: [0, 1], - }) - - testForMessage(buffers.copyOut(0), { - name: 'copyOutResponse', - length: 7, - binary: false, - columnTypes: [], - }) - - testForMessage(buffers.copyOut(3), { - name: 'copyOutResponse', - length: 13, - binary: false, - columnTypes: [0, 1, 2], - }) - - testForMessage(buffers.copyDone(), { - name: 'copyDone', - length: 4, - }) - - testForMessage(buffers.copyData(Buffer.from([5, 6, 7])), { - name: 'copyData', - length: 7, - chunk: Buffer.from([5, 6, 7]), - }) - }) - - // since the data message on a stream can randomly divide the incomming - // tcp packets anywhere, we need to make sure we can parse every single - // split on a tcp message - describe('split buffer, single message parsing', function () { - var fullBuffer = buffers.dataRow([null, 'bang', 'zug zug', null, '!']) - - it('parses when full buffer comes in', async function () { - const messages = await parseBuffers([fullBuffer]) - const message = messages[0] as any - assert.equal(message.fields.length, 5) - assert.equal(message.fields[0], null) - assert.equal(message.fields[1], 'bang') - assert.equal(message.fields[2], 'zug zug') - assert.equal(message.fields[3], null) - assert.equal(message.fields[4], '!') - }) - - var testMessageRecievedAfterSpiltAt = async function (split: number) { - var firstBuffer = Buffer.alloc(fullBuffer.length - split) - var secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length) - fullBuffer.copy(firstBuffer, 0, 0) - fullBuffer.copy(secondBuffer, 0, firstBuffer.length) - const messages = await parseBuffers([fullBuffer]) - const message = messages[0] as any - assert.equal(message.fields.length, 5) - assert.equal(message.fields[0], null) - assert.equal(message.fields[1], 'bang') - assert.equal(message.fields[2], 'zug zug') - assert.equal(message.fields[3], null) - assert.equal(message.fields[4], '!') - } - - it('parses when split in the middle', function () { - testMessageRecievedAfterSpiltAt(6) - }) - - it('parses when split at end', function () { - testMessageRecievedAfterSpiltAt(2) - }) - - it('parses when split at beginning', function () { - testMessageRecievedAfterSpiltAt(fullBuffer.length - 2) - testMessageRecievedAfterSpiltAt(fullBuffer.length - 1) - testMessageRecievedAfterSpiltAt(fullBuffer.length - 5) - }) - }) - - describe('split buffer, multiple message parsing', function () { - var dataRowBuffer = buffers.dataRow(['!']) - var readyForQueryBuffer = buffers.readyForQuery() - var fullBuffer = Buffer.alloc(dataRowBuffer.length + readyForQueryBuffer.length) - dataRowBuffer.copy(fullBuffer, 0, 0) - readyForQueryBuffer.copy(fullBuffer, dataRowBuffer.length, 0) - - var verifyMessages = function (messages: any[]) { - assert.strictEqual(messages.length, 2) - assert.deepEqual(messages[0], { - name: 'dataRow', - fieldCount: 1, - length: 11, - fields: ['!'], - }) - assert.equal(messages[0].fields[0], '!') - assert.deepEqual(messages[1], { - name: 'readyForQuery', - length: 5, - status: 'I', - }) - } - // sanity check - it('recieves both messages when packet is not split', async function () { - const messages = await parseBuffers([fullBuffer]) - verifyMessages(messages) - }) - - var splitAndVerifyTwoMessages = async function (split: number) { - var firstBuffer = Buffer.alloc(fullBuffer.length - split) - var secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length) - fullBuffer.copy(firstBuffer, 0, 0) - fullBuffer.copy(secondBuffer, 0, firstBuffer.length) - const messages = await parseBuffers([firstBuffer, secondBuffer]) - verifyMessages(messages) - } - - describe('recieves both messages when packet is split', function () { - it('in the middle', function () { - return splitAndVerifyTwoMessages(11) - }) - it('at the front', function () { - return Promise.all([ - splitAndVerifyTwoMessages(fullBuffer.length - 1), - splitAndVerifyTwoMessages(fullBuffer.length - 4), - splitAndVerifyTwoMessages(fullBuffer.length - 6), - ]) - }) - - it('at the end', function () { - return Promise.all([splitAndVerifyTwoMessages(8), splitAndVerifyTwoMessages(1)]) - }) - }) - }) -}) diff --git a/reverse_engineering/node_modules/pg-protocol/src/index.ts b/reverse_engineering/node_modules/pg-protocol/src/index.ts deleted file mode 100644 index 00491ff..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { BackendMessage, DatabaseError } from './messages' -import { serialize } from './serializer' -import { Parser, MessageCallback } from './parser' - -export function parse(stream: NodeJS.ReadableStream, callback: MessageCallback): Promise { - const parser = new Parser() - stream.on('data', (buffer: Buffer) => parser.parse(buffer, callback)) - return new Promise((resolve) => stream.on('end', () => resolve())) -} - -export { serialize, DatabaseError } diff --git a/reverse_engineering/node_modules/pg-protocol/src/messages.ts b/reverse_engineering/node_modules/pg-protocol/src/messages.ts deleted file mode 100644 index 7eab845..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/messages.ts +++ /dev/null @@ -1,230 +0,0 @@ -export type Mode = 'text' | 'binary' - -export type MessageName = - | 'parseComplete' - | 'bindComplete' - | 'closeComplete' - | 'noData' - | 'portalSuspended' - | 'replicationStart' - | 'emptyQuery' - | 'copyDone' - | 'copyData' - | 'rowDescription' - | 'parameterDescription' - | 'parameterStatus' - | 'backendKeyData' - | 'notification' - | 'readyForQuery' - | 'commandComplete' - | 'dataRow' - | 'copyInResponse' - | 'copyOutResponse' - | 'authenticationOk' - | 'authenticationMD5Password' - | 'authenticationCleartextPassword' - | 'authenticationSASL' - | 'authenticationSASLContinue' - | 'authenticationSASLFinal' - | 'error' - | 'notice' - -export interface BackendMessage { - name: MessageName - length: number -} - -export const parseComplete: BackendMessage = { - name: 'parseComplete', - length: 5, -} - -export const bindComplete: BackendMessage = { - name: 'bindComplete', - length: 5, -} - -export const closeComplete: BackendMessage = { - name: 'closeComplete', - length: 5, -} - -export const noData: BackendMessage = { - name: 'noData', - length: 5, -} - -export const portalSuspended: BackendMessage = { - name: 'portalSuspended', - length: 5, -} - -export const replicationStart: BackendMessage = { - name: 'replicationStart', - length: 4, -} - -export const emptyQuery: BackendMessage = { - name: 'emptyQuery', - length: 4, -} - -export const copyDone: BackendMessage = { - name: 'copyDone', - length: 4, -} - -interface NoticeOrError { - message: string | undefined - severity: string | undefined - code: string | undefined - detail: string | undefined - hint: string | undefined - position: string | undefined - internalPosition: string | undefined - internalQuery: string | undefined - where: string | undefined - schema: string | undefined - table: string | undefined - column: string | undefined - dataType: string | undefined - constraint: string | undefined - file: string | undefined - line: string | undefined - routine: string | undefined -} - -export class DatabaseError extends Error implements NoticeOrError { - public severity: string | undefined - public code: string | undefined - public detail: string | undefined - public hint: string | undefined - public position: string | undefined - public internalPosition: string | undefined - public internalQuery: string | undefined - public where: string | undefined - public schema: string | undefined - public table: string | undefined - public column: string | undefined - public dataType: string | undefined - public constraint: string | undefined - public file: string | undefined - public line: string | undefined - public routine: string | undefined - constructor(message: string, public readonly length: number, public readonly name: MessageName) { - super(message) - } -} - -export class CopyDataMessage { - public readonly name = 'copyData' - constructor(public readonly length: number, public readonly chunk: Buffer) {} -} - -export class CopyResponse { - public readonly columnTypes: number[] - constructor( - public readonly length: number, - public readonly name: MessageName, - public readonly binary: boolean, - columnCount: number - ) { - this.columnTypes = new Array(columnCount) - } -} - -export class Field { - constructor( - public readonly name: string, - public readonly tableID: number, - public readonly columnID: number, - public readonly dataTypeID: number, - public readonly dataTypeSize: number, - public readonly dataTypeModifier: number, - public readonly format: Mode - ) {} -} - -export class RowDescriptionMessage { - public readonly name: MessageName = 'rowDescription' - public readonly fields: Field[] - constructor(public readonly length: number, public readonly fieldCount: number) { - this.fields = new Array(this.fieldCount) - } -} - -export class ParameterDescriptionMessage { - public readonly name: MessageName = 'parameterDescription' - public readonly dataTypeIDs: number[] - constructor(public readonly length: number, public readonly parameterCount: number) { - this.dataTypeIDs = new Array(this.parameterCount) - } -} - -export class ParameterStatusMessage { - public readonly name: MessageName = 'parameterStatus' - constructor( - public readonly length: number, - public readonly parameterName: string, - public readonly parameterValue: string - ) {} -} - -export class AuthenticationMD5Password implements BackendMessage { - public readonly name: MessageName = 'authenticationMD5Password' - constructor(public readonly length: number, public readonly salt: Buffer) {} -} - -export class BackendKeyDataMessage { - public readonly name: MessageName = 'backendKeyData' - constructor(public readonly length: number, public readonly processID: number, public readonly secretKey: number) {} -} - -export class NotificationResponseMessage { - public readonly name: MessageName = 'notification' - constructor( - public readonly length: number, - public readonly processId: number, - public readonly channel: string, - public readonly payload: string - ) {} -} - -export class ReadyForQueryMessage { - public readonly name: MessageName = 'readyForQuery' - constructor(public readonly length: number, public readonly status: string) {} -} - -export class CommandCompleteMessage { - public readonly name: MessageName = 'commandComplete' - constructor(public readonly length: number, public readonly text: string) {} -} - -export class DataRowMessage { - public readonly fieldCount: number - public readonly name: MessageName = 'dataRow' - constructor(public length: number, public fields: any[]) { - this.fieldCount = fields.length - } -} - -export class NoticeMessage implements BackendMessage, NoticeOrError { - constructor(public readonly length: number, public readonly message: string | undefined) {} - public readonly name = 'notice' - public severity: string | undefined - public code: string | undefined - public detail: string | undefined - public hint: string | undefined - public position: string | undefined - public internalPosition: string | undefined - public internalQuery: string | undefined - public where: string | undefined - public schema: string | undefined - public table: string | undefined - public column: string | undefined - public dataType: string | undefined - public constraint: string | undefined - public file: string | undefined - public line: string | undefined - public routine: string | undefined -} diff --git a/reverse_engineering/node_modules/pg-protocol/src/outbound-serializer.test.ts b/reverse_engineering/node_modules/pg-protocol/src/outbound-serializer.test.ts deleted file mode 100644 index f6669be..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/outbound-serializer.test.ts +++ /dev/null @@ -1,272 +0,0 @@ -import assert from 'assert' -import { serialize } from './serializer' -import BufferList from './testing/buffer-list' - -describe('serializer', () => { - it('builds startup message', function () { - const actual = serialize.startup({ - user: 'brian', - database: 'bang', - }) - assert.deepEqual( - actual, - new BufferList() - .addInt16(3) - .addInt16(0) - .addCString('user') - .addCString('brian') - .addCString('database') - .addCString('bang') - .addCString('client_encoding') - .addCString('UTF8') - .addCString('') - .join(true) - ) - }) - - it('builds password message', function () { - const actual = serialize.password('!') - assert.deepEqual(actual, new BufferList().addCString('!').join(true, 'p')) - }) - - it('builds request ssl message', function () { - const actual = serialize.requestSsl() - const expected = new BufferList().addInt32(80877103).join(true) - assert.deepEqual(actual, expected) - }) - - it('builds SASLInitialResponseMessage message', function () { - const actual = serialize.sendSASLInitialResponseMessage('mech', 'data') - assert.deepEqual(actual, new BufferList().addCString('mech').addInt32(4).addString('data').join(true, 'p')) - }) - - it('builds SCRAMClientFinalMessage message', function () { - const actual = serialize.sendSCRAMClientFinalMessage('data') - assert.deepEqual(actual, new BufferList().addString('data').join(true, 'p')) - }) - - it('builds query message', function () { - var txt = 'select * from boom' - const actual = serialize.query(txt) - assert.deepEqual(actual, new BufferList().addCString(txt).join(true, 'Q')) - }) - - describe('parse message', () => { - it('builds parse message', function () { - const actual = serialize.parse({ text: '!' }) - var expected = new BufferList().addCString('').addCString('!').addInt16(0).join(true, 'P') - assert.deepEqual(actual, expected) - }) - - it('builds parse message with named query', function () { - const actual = serialize.parse({ - name: 'boom', - text: 'select * from boom', - types: [], - }) - var expected = new BufferList().addCString('boom').addCString('select * from boom').addInt16(0).join(true, 'P') - assert.deepEqual(actual, expected) - }) - - it('with multiple parameters', function () { - const actual = serialize.parse({ - name: 'force', - text: 'select * from bang where name = $1', - types: [1, 2, 3, 4], - }) - var expected = new BufferList() - .addCString('force') - .addCString('select * from bang where name = $1') - .addInt16(4) - .addInt32(1) - .addInt32(2) - .addInt32(3) - .addInt32(4) - .join(true, 'P') - assert.deepEqual(actual, expected) - }) - }) - - describe('bind messages', function () { - it('with no values', function () { - const actual = serialize.bind() - - var expectedBuffer = new BufferList() - .addCString('') - .addCString('') - .addInt16(0) - .addInt16(0) - .addInt16(0) - .join(true, 'B') - assert.deepEqual(actual, expectedBuffer) - }) - - it('with named statement, portal, and values', function () { - const actual = serialize.bind({ - portal: 'bang', - statement: 'woo', - values: ['1', 'hi', null, 'zing'], - }) - var expectedBuffer = new BufferList() - .addCString('bang') // portal name - .addCString('woo') // statement name - .addInt16(4) - .addInt16(0) - .addInt16(0) - .addInt16(0) - .addInt16(0) - .addInt16(4) - .addInt32(1) - .add(Buffer.from('1')) - .addInt32(2) - .add(Buffer.from('hi')) - .addInt32(-1) - .addInt32(4) - .add(Buffer.from('zing')) - .addInt16(0) - .join(true, 'B') - assert.deepEqual(actual, expectedBuffer) - }) - }) - - it('with custom valueMapper', function () { - const actual = serialize.bind({ - portal: 'bang', - statement: 'woo', - values: ['1', 'hi', null, 'zing'], - valueMapper: () => null, - }) - var expectedBuffer = new BufferList() - .addCString('bang') // portal name - .addCString('woo') // statement name - .addInt16(4) - .addInt16(0) - .addInt16(0) - .addInt16(0) - .addInt16(0) - .addInt16(4) - .addInt32(-1) - .addInt32(-1) - .addInt32(-1) - .addInt32(-1) - .addInt16(0) - .join(true, 'B') - assert.deepEqual(actual, expectedBuffer) - }) - - it('with named statement, portal, and buffer value', function () { - const actual = serialize.bind({ - portal: 'bang', - statement: 'woo', - values: ['1', 'hi', null, Buffer.from('zing', 'utf8')], - }) - var expectedBuffer = new BufferList() - .addCString('bang') // portal name - .addCString('woo') // statement name - .addInt16(4) // value count - .addInt16(0) // string - .addInt16(0) // string - .addInt16(0) // string - .addInt16(1) // binary - .addInt16(4) - .addInt32(1) - .add(Buffer.from('1')) - .addInt32(2) - .add(Buffer.from('hi')) - .addInt32(-1) - .addInt32(4) - .add(Buffer.from('zing', 'utf-8')) - .addInt16(0) - .join(true, 'B') - assert.deepEqual(actual, expectedBuffer) - }) - - describe('builds execute message', function () { - it('for unamed portal with no row limit', function () { - const actual = serialize.execute() - var expectedBuffer = new BufferList().addCString('').addInt32(0).join(true, 'E') - assert.deepEqual(actual, expectedBuffer) - }) - - it('for named portal with row limit', function () { - const actual = serialize.execute({ - portal: 'my favorite portal', - rows: 100, - }) - var expectedBuffer = new BufferList().addCString('my favorite portal').addInt32(100).join(true, 'E') - assert.deepEqual(actual, expectedBuffer) - }) - }) - - it('builds flush command', function () { - const actual = serialize.flush() - var expected = new BufferList().join(true, 'H') - assert.deepEqual(actual, expected) - }) - - it('builds sync command', function () { - const actual = serialize.sync() - var expected = new BufferList().join(true, 'S') - assert.deepEqual(actual, expected) - }) - - it('builds end command', function () { - const actual = serialize.end() - var expected = Buffer.from([0x58, 0, 0, 0, 4]) - assert.deepEqual(actual, expected) - }) - - describe('builds describe command', function () { - it('describe statement', function () { - const actual = serialize.describe({ type: 'S', name: 'bang' }) - var expected = new BufferList().addChar('S').addCString('bang').join(true, 'D') - assert.deepEqual(actual, expected) - }) - - it('describe unnamed portal', function () { - const actual = serialize.describe({ type: 'P' }) - var expected = new BufferList().addChar('P').addCString('').join(true, 'D') - assert.deepEqual(actual, expected) - }) - }) - - describe('builds close command', function () { - it('describe statement', function () { - const actual = serialize.close({ type: 'S', name: 'bang' }) - var expected = new BufferList().addChar('S').addCString('bang').join(true, 'C') - assert.deepEqual(actual, expected) - }) - - it('describe unnamed portal', function () { - const actual = serialize.close({ type: 'P' }) - var expected = new BufferList().addChar('P').addCString('').join(true, 'C') - assert.deepEqual(actual, expected) - }) - }) - - describe('copy messages', function () { - it('builds copyFromChunk', () => { - const actual = serialize.copyData(Buffer.from([1, 2, 3])) - const expected = new BufferList().add(Buffer.from([1, 2, 3])).join(true, 'd') - assert.deepEqual(actual, expected) - }) - - it('builds copy fail', () => { - const actual = serialize.copyFail('err!') - const expected = new BufferList().addCString('err!').join(true, 'f') - assert.deepEqual(actual, expected) - }) - - it('builds copy done', () => { - const actual = serialize.copyDone() - const expected = new BufferList().join(true, 'c') - assert.deepEqual(actual, expected) - }) - }) - - it('builds cancel message', () => { - const actual = serialize.cancel(3, 4) - const expected = new BufferList().addInt16(1234).addInt16(5678).addInt32(3).addInt32(4).join(true) - assert.deepEqual(actual, expected) - }) -}) diff --git a/reverse_engineering/node_modules/pg-protocol/src/parser.ts b/reverse_engineering/node_modules/pg-protocol/src/parser.ts deleted file mode 100644 index f900193..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/parser.ts +++ /dev/null @@ -1,389 +0,0 @@ -import { TransformOptions } from 'stream' -import { - Mode, - bindComplete, - parseComplete, - closeComplete, - noData, - portalSuspended, - copyDone, - replicationStart, - emptyQuery, - ReadyForQueryMessage, - CommandCompleteMessage, - CopyDataMessage, - CopyResponse, - NotificationResponseMessage, - RowDescriptionMessage, - ParameterDescriptionMessage, - Field, - DataRowMessage, - ParameterStatusMessage, - BackendKeyDataMessage, - DatabaseError, - BackendMessage, - MessageName, - AuthenticationMD5Password, - NoticeMessage, -} from './messages' -import { BufferReader } from './buffer-reader' -import assert from 'assert' - -// every message is prefixed with a single bye -const CODE_LENGTH = 1 -// every message has an int32 length which includes itself but does -// NOT include the code in the length -const LEN_LENGTH = 4 - -const HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH - -export type Packet = { - code: number - packet: Buffer -} - -const emptyBuffer = Buffer.allocUnsafe(0) - -type StreamOptions = TransformOptions & { - mode: Mode -} - -const enum MessageCodes { - DataRow = 0x44, // D - ParseComplete = 0x31, // 1 - BindComplete = 0x32, // 2 - CloseComplete = 0x33, // 3 - CommandComplete = 0x43, // C - ReadyForQuery = 0x5a, // Z - NoData = 0x6e, // n - NotificationResponse = 0x41, // A - AuthenticationResponse = 0x52, // R - ParameterStatus = 0x53, // S - BackendKeyData = 0x4b, // K - ErrorMessage = 0x45, // E - NoticeMessage = 0x4e, // N - RowDescriptionMessage = 0x54, // T - ParameterDescriptionMessage = 0x74, // t - PortalSuspended = 0x73, // s - ReplicationStart = 0x57, // W - EmptyQuery = 0x49, // I - CopyIn = 0x47, // G - CopyOut = 0x48, // H - CopyDone = 0x63, // c - CopyData = 0x64, // d -} - -export type MessageCallback = (msg: BackendMessage) => void - -export class Parser { - private buffer: Buffer = emptyBuffer - private bufferLength: number = 0 - private bufferOffset: number = 0 - private reader = new BufferReader() - private mode: Mode - - constructor(opts?: StreamOptions) { - if (opts?.mode === 'binary') { - throw new Error('Binary mode not supported yet') - } - this.mode = opts?.mode || 'text' - } - - public parse(buffer: Buffer, callback: MessageCallback) { - this.mergeBuffer(buffer) - const bufferFullLength = this.bufferOffset + this.bufferLength - let offset = this.bufferOffset - while (offset + HEADER_LENGTH <= bufferFullLength) { - // code is 1 byte long - it identifies the message type - const code = this.buffer[offset] - // length is 1 Uint32BE - it is the length of the message EXCLUDING the code - const length = this.buffer.readUInt32BE(offset + CODE_LENGTH) - const fullMessageLength = CODE_LENGTH + length - if (fullMessageLength + offset <= bufferFullLength) { - const message = this.handlePacket(offset + HEADER_LENGTH, code, length, this.buffer) - callback(message) - offset += fullMessageLength - } else { - break - } - } - if (offset === bufferFullLength) { - // No more use for the buffer - this.buffer = emptyBuffer - this.bufferLength = 0 - this.bufferOffset = 0 - } else { - // Adjust the cursors of remainingBuffer - this.bufferLength = bufferFullLength - offset - this.bufferOffset = offset - } - } - - private mergeBuffer(buffer: Buffer): void { - if (this.bufferLength > 0) { - const newLength = this.bufferLength + buffer.byteLength - const newFullLength = newLength + this.bufferOffset - if (newFullLength > this.buffer.byteLength) { - // We can't concat the new buffer with the remaining one - let newBuffer: Buffer - if (newLength <= this.buffer.byteLength && this.bufferOffset >= this.bufferLength) { - // We can move the relevant part to the beginning of the buffer instead of allocating a new buffer - newBuffer = this.buffer - } else { - // Allocate a new larger buffer - let newBufferLength = this.buffer.byteLength * 2 - while (newLength >= newBufferLength) { - newBufferLength *= 2 - } - newBuffer = Buffer.allocUnsafe(newBufferLength) - } - // Move the remaining buffer to the new one - this.buffer.copy(newBuffer, 0, this.bufferOffset, this.bufferOffset + this.bufferLength) - this.buffer = newBuffer - this.bufferOffset = 0 - } - // Concat the new buffer with the remaining one - buffer.copy(this.buffer, this.bufferOffset + this.bufferLength) - this.bufferLength = newLength - } else { - this.buffer = buffer - this.bufferOffset = 0 - this.bufferLength = buffer.byteLength - } - } - - private handlePacket(offset: number, code: number, length: number, bytes: Buffer): BackendMessage { - switch (code) { - case MessageCodes.BindComplete: - return bindComplete - case MessageCodes.ParseComplete: - return parseComplete - case MessageCodes.CloseComplete: - return closeComplete - case MessageCodes.NoData: - return noData - case MessageCodes.PortalSuspended: - return portalSuspended - case MessageCodes.CopyDone: - return copyDone - case MessageCodes.ReplicationStart: - return replicationStart - case MessageCodes.EmptyQuery: - return emptyQuery - case MessageCodes.DataRow: - return this.parseDataRowMessage(offset, length, bytes) - case MessageCodes.CommandComplete: - return this.parseCommandCompleteMessage(offset, length, bytes) - case MessageCodes.ReadyForQuery: - return this.parseReadyForQueryMessage(offset, length, bytes) - case MessageCodes.NotificationResponse: - return this.parseNotificationMessage(offset, length, bytes) - case MessageCodes.AuthenticationResponse: - return this.parseAuthenticationResponse(offset, length, bytes) - case MessageCodes.ParameterStatus: - return this.parseParameterStatusMessage(offset, length, bytes) - case MessageCodes.BackendKeyData: - return this.parseBackendKeyData(offset, length, bytes) - case MessageCodes.ErrorMessage: - return this.parseErrorMessage(offset, length, bytes, 'error') - case MessageCodes.NoticeMessage: - return this.parseErrorMessage(offset, length, bytes, 'notice') - case MessageCodes.RowDescriptionMessage: - return this.parseRowDescriptionMessage(offset, length, bytes) - case MessageCodes.ParameterDescriptionMessage: - return this.parseParameterDescriptionMessage(offset, length, bytes) - case MessageCodes.CopyIn: - return this.parseCopyInMessage(offset, length, bytes) - case MessageCodes.CopyOut: - return this.parseCopyOutMessage(offset, length, bytes) - case MessageCodes.CopyData: - return this.parseCopyData(offset, length, bytes) - default: - assert.fail(`unknown message code: ${code.toString(16)}`) - } - } - - private parseReadyForQueryMessage(offset: number, length: number, bytes: Buffer) { - this.reader.setBuffer(offset, bytes) - const status = this.reader.string(1) - return new ReadyForQueryMessage(length, status) - } - - private parseCommandCompleteMessage(offset: number, length: number, bytes: Buffer) { - this.reader.setBuffer(offset, bytes) - const text = this.reader.cstring() - return new CommandCompleteMessage(length, text) - } - - private parseCopyData(offset: number, length: number, bytes: Buffer) { - const chunk = bytes.slice(offset, offset + (length - 4)) - return new CopyDataMessage(length, chunk) - } - - private parseCopyInMessage(offset: number, length: number, bytes: Buffer) { - return this.parseCopyMessage(offset, length, bytes, 'copyInResponse') - } - - private parseCopyOutMessage(offset: number, length: number, bytes: Buffer) { - return this.parseCopyMessage(offset, length, bytes, 'copyOutResponse') - } - - private parseCopyMessage(offset: number, length: number, bytes: Buffer, messageName: MessageName) { - this.reader.setBuffer(offset, bytes) - const isBinary = this.reader.byte() !== 0 - const columnCount = this.reader.int16() - const message = new CopyResponse(length, messageName, isBinary, columnCount) - for (let i = 0; i < columnCount; i++) { - message.columnTypes[i] = this.reader.int16() - } - return message - } - - private parseNotificationMessage(offset: number, length: number, bytes: Buffer) { - this.reader.setBuffer(offset, bytes) - const processId = this.reader.int32() - const channel = this.reader.cstring() - const payload = this.reader.cstring() - return new NotificationResponseMessage(length, processId, channel, payload) - } - - private parseRowDescriptionMessage(offset: number, length: number, bytes: Buffer) { - this.reader.setBuffer(offset, bytes) - const fieldCount = this.reader.int16() - const message = new RowDescriptionMessage(length, fieldCount) - for (let i = 0; i < fieldCount; i++) { - message.fields[i] = this.parseField() - } - return message - } - - private parseField(): Field { - const name = this.reader.cstring() - const tableID = this.reader.int32() - const columnID = this.reader.int16() - const dataTypeID = this.reader.int32() - const dataTypeSize = this.reader.int16() - const dataTypeModifier = this.reader.int32() - const mode = this.reader.int16() === 0 ? 'text' : 'binary' - return new Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode) - } - - private parseParameterDescriptionMessage(offset: number, length: number, bytes: Buffer) { - this.reader.setBuffer(offset, bytes) - const parameterCount = this.reader.int16() - const message = new ParameterDescriptionMessage(length, parameterCount) - for (let i = 0; i < parameterCount; i++) { - message.dataTypeIDs[i] = this.reader.int32() - } - return message - } - - private parseDataRowMessage(offset: number, length: number, bytes: Buffer) { - this.reader.setBuffer(offset, bytes) - const fieldCount = this.reader.int16() - const fields: any[] = new Array(fieldCount) - for (let i = 0; i < fieldCount; i++) { - const len = this.reader.int32() - // a -1 for length means the value of the field is null - fields[i] = len === -1 ? null : this.reader.string(len) - } - return new DataRowMessage(length, fields) - } - - private parseParameterStatusMessage(offset: number, length: number, bytes: Buffer) { - this.reader.setBuffer(offset, bytes) - const name = this.reader.cstring() - const value = this.reader.cstring() - return new ParameterStatusMessage(length, name, value) - } - - private parseBackendKeyData(offset: number, length: number, bytes: Buffer) { - this.reader.setBuffer(offset, bytes) - const processID = this.reader.int32() - const secretKey = this.reader.int32() - return new BackendKeyDataMessage(length, processID, secretKey) - } - - public parseAuthenticationResponse(offset: number, length: number, bytes: Buffer) { - this.reader.setBuffer(offset, bytes) - const code = this.reader.int32() - // TODO(bmc): maybe better types here - const message: BackendMessage & any = { - name: 'authenticationOk', - length, - } - - switch (code) { - case 0: // AuthenticationOk - break - case 3: // AuthenticationCleartextPassword - if (message.length === 8) { - message.name = 'authenticationCleartextPassword' - } - break - case 5: // AuthenticationMD5Password - if (message.length === 12) { - message.name = 'authenticationMD5Password' - const salt = this.reader.bytes(4) - return new AuthenticationMD5Password(length, salt) - } - break - case 10: // AuthenticationSASL - message.name = 'authenticationSASL' - message.mechanisms = [] - let mechanism: string - do { - mechanism = this.reader.cstring() - - if (mechanism) { - message.mechanisms.push(mechanism) - } - } while (mechanism) - break - case 11: // AuthenticationSASLContinue - message.name = 'authenticationSASLContinue' - message.data = this.reader.string(length - 8) - break - case 12: // AuthenticationSASLFinal - message.name = 'authenticationSASLFinal' - message.data = this.reader.string(length - 8) - break - default: - throw new Error('Unknown authenticationOk message type ' + code) - } - return message - } - - private parseErrorMessage(offset: number, length: number, bytes: Buffer, name: MessageName) { - this.reader.setBuffer(offset, bytes) - const fields: Record = {} - let fieldType = this.reader.string(1) - while (fieldType !== '\0') { - fields[fieldType] = this.reader.cstring() - fieldType = this.reader.string(1) - } - - const messageValue = fields.M - - const message = - name === 'notice' ? new NoticeMessage(length, messageValue) : new DatabaseError(messageValue, length, name) - - message.severity = fields.S - message.code = fields.C - message.detail = fields.D - message.hint = fields.H - message.position = fields.P - message.internalPosition = fields.p - message.internalQuery = fields.q - message.where = fields.W - message.schema = fields.s - message.table = fields.t - message.column = fields.c - message.dataType = fields.d - message.constraint = fields.n - message.file = fields.F - message.line = fields.L - message.routine = fields.R - return message - } -} diff --git a/reverse_engineering/node_modules/pg-protocol/src/serializer.ts b/reverse_engineering/node_modules/pg-protocol/src/serializer.ts deleted file mode 100644 index 07e2fe4..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/serializer.ts +++ /dev/null @@ -1,274 +0,0 @@ -import { Writer } from './buffer-writer' - -const enum code { - startup = 0x70, - query = 0x51, - parse = 0x50, - bind = 0x42, - execute = 0x45, - flush = 0x48, - sync = 0x53, - end = 0x58, - close = 0x43, - describe = 0x44, - copyFromChunk = 0x64, - copyDone = 0x63, - copyFail = 0x66, -} - -const writer = new Writer() - -const startup = (opts: Record): Buffer => { - // protocol version - writer.addInt16(3).addInt16(0) - for (const key of Object.keys(opts)) { - writer.addCString(key).addCString(opts[key]) - } - - writer.addCString('client_encoding').addCString('UTF8') - - var bodyBuffer = writer.addCString('').flush() - // this message is sent without a code - - var length = bodyBuffer.length + 4 - - return new Writer().addInt32(length).add(bodyBuffer).flush() -} - -const requestSsl = (): Buffer => { - const response = Buffer.allocUnsafe(8) - response.writeInt32BE(8, 0) - response.writeInt32BE(80877103, 4) - return response -} - -const password = (password: string): Buffer => { - return writer.addCString(password).flush(code.startup) -} - -const sendSASLInitialResponseMessage = function (mechanism: string, initialResponse: string): Buffer { - // 0x70 = 'p' - writer.addCString(mechanism).addInt32(Buffer.byteLength(initialResponse)).addString(initialResponse) - - return writer.flush(code.startup) -} - -const sendSCRAMClientFinalMessage = function (additionalData: string): Buffer { - return writer.addString(additionalData).flush(code.startup) -} - -const query = (text: string): Buffer => { - return writer.addCString(text).flush(code.query) -} - -type ParseOpts = { - name?: string - types?: number[] - text: string -} - -const emptyArray: any[] = [] - -const parse = (query: ParseOpts): Buffer => { - // expect something like this: - // { name: 'queryName', - // text: 'select * from blah', - // types: ['int8', 'bool'] } - - // normalize missing query names to allow for null - const name = query.name || '' - if (name.length > 63) { - /* eslint-disable no-console */ - console.error('Warning! Postgres only supports 63 characters for query names.') - console.error('You supplied %s (%s)', name, name.length) - console.error('This can cause conflicts and silent errors executing queries') - /* eslint-enable no-console */ - } - - const types = query.types || emptyArray - - var len = types.length - - var buffer = writer - .addCString(name) // name of query - .addCString(query.text) // actual query text - .addInt16(len) - - for (var i = 0; i < len; i++) { - buffer.addInt32(types[i]) - } - - return writer.flush(code.parse) -} - -type ValueMapper = (param: any, index: number) => any - -type BindOpts = { - portal?: string - binary?: boolean - statement?: string - values?: any[] - // optional map from JS value to postgres value per parameter - valueMapper?: ValueMapper -} - -const paramWriter = new Writer() - -// make this a const enum so typescript will inline the value -const enum ParamType { - STRING = 0, - BINARY = 1, -} - -const writeValues = function (values: any[], valueMapper?: ValueMapper): void { - for (let i = 0; i < values.length; i++) { - const mappedVal = valueMapper ? valueMapper(values[i], i) : values[i] - if (mappedVal == null) { - // add the param type (string) to the writer - writer.addInt16(ParamType.STRING) - // write -1 to the param writer to indicate null - paramWriter.addInt32(-1) - } else if (mappedVal instanceof Buffer) { - // add the param type (binary) to the writer - writer.addInt16(ParamType.BINARY) - // add the buffer to the param writer - paramWriter.addInt32(mappedVal.length) - paramWriter.add(mappedVal) - } else { - // add the param type (string) to the writer - writer.addInt16(ParamType.STRING) - paramWriter.addInt32(Buffer.byteLength(mappedVal)) - paramWriter.addString(mappedVal) - } - } -} - -const bind = (config: BindOpts = {}): Buffer => { - // normalize config - const portal = config.portal || '' - const statement = config.statement || '' - const binary = config.binary || false - const values = config.values || emptyArray - const len = values.length - - writer.addCString(portal).addCString(statement) - writer.addInt16(len) - - writeValues(values, config.valueMapper) - - writer.addInt16(len) - writer.add(paramWriter.flush()) - - // format code - writer.addInt16(binary ? ParamType.BINARY : ParamType.STRING) - return writer.flush(code.bind) -} - -type ExecOpts = { - portal?: string - rows?: number -} - -const emptyExecute = Buffer.from([code.execute, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00]) - -const execute = (config?: ExecOpts): Buffer => { - // this is the happy path for most queries - if (!config || (!config.portal && !config.rows)) { - return emptyExecute - } - - const portal = config.portal || '' - const rows = config.rows || 0 - - const portalLength = Buffer.byteLength(portal) - const len = 4 + portalLength + 1 + 4 - // one extra bit for code - const buff = Buffer.allocUnsafe(1 + len) - buff[0] = code.execute - buff.writeInt32BE(len, 1) - buff.write(portal, 5, 'utf-8') - buff[portalLength + 5] = 0 // null terminate portal cString - buff.writeUInt32BE(rows, buff.length - 4) - return buff -} - -const cancel = (processID: number, secretKey: number): Buffer => { - const buffer = Buffer.allocUnsafe(16) - buffer.writeInt32BE(16, 0) - buffer.writeInt16BE(1234, 4) - buffer.writeInt16BE(5678, 6) - buffer.writeInt32BE(processID, 8) - buffer.writeInt32BE(secretKey, 12) - return buffer -} - -type PortalOpts = { - type: 'S' | 'P' - name?: string -} - -const cstringMessage = (code: code, string: string): Buffer => { - const stringLen = Buffer.byteLength(string) - const len = 4 + stringLen + 1 - // one extra bit for code - const buffer = Buffer.allocUnsafe(1 + len) - buffer[0] = code - buffer.writeInt32BE(len, 1) - buffer.write(string, 5, 'utf-8') - buffer[len] = 0 // null terminate cString - return buffer -} - -const emptyDescribePortal = writer.addCString('P').flush(code.describe) -const emptyDescribeStatement = writer.addCString('S').flush(code.describe) - -const describe = (msg: PortalOpts): Buffer => { - return msg.name - ? cstringMessage(code.describe, `${msg.type}${msg.name || ''}`) - : msg.type === 'P' - ? emptyDescribePortal - : emptyDescribeStatement -} - -const close = (msg: PortalOpts): Buffer => { - const text = `${msg.type}${msg.name || ''}` - return cstringMessage(code.close, text) -} - -const copyData = (chunk: Buffer): Buffer => { - return writer.add(chunk).flush(code.copyFromChunk) -} - -const copyFail = (message: string): Buffer => { - return cstringMessage(code.copyFail, message) -} - -const codeOnlyBuffer = (code: code): Buffer => Buffer.from([code, 0x00, 0x00, 0x00, 0x04]) - -const flushBuffer = codeOnlyBuffer(code.flush) -const syncBuffer = codeOnlyBuffer(code.sync) -const endBuffer = codeOnlyBuffer(code.end) -const copyDoneBuffer = codeOnlyBuffer(code.copyDone) - -const serialize = { - startup, - password, - requestSsl, - sendSASLInitialResponseMessage, - sendSCRAMClientFinalMessage, - query, - parse, - bind, - execute, - describe, - close, - flush: () => flushBuffer, - sync: () => syncBuffer, - end: () => endBuffer, - copyData, - copyDone: () => copyDoneBuffer, - copyFail, - cancel, -} - -export { serialize } diff --git a/reverse_engineering/node_modules/pg-protocol/src/testing/buffer-list.ts b/reverse_engineering/node_modules/pg-protocol/src/testing/buffer-list.ts deleted file mode 100644 index 15ac785..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/testing/buffer-list.ts +++ /dev/null @@ -1,75 +0,0 @@ -export default class BufferList { - constructor(public buffers: Buffer[] = []) {} - - public add(buffer: Buffer, front?: boolean) { - this.buffers[front ? 'unshift' : 'push'](buffer) - return this - } - - public addInt16(val: number, front?: boolean) { - return this.add(Buffer.from([val >>> 8, val >>> 0]), front) - } - - public getByteLength(initial?: number) { - return this.buffers.reduce(function (previous, current) { - return previous + current.length - }, initial || 0) - } - - public addInt32(val: number, first?: boolean) { - return this.add( - Buffer.from([(val >>> 24) & 0xff, (val >>> 16) & 0xff, (val >>> 8) & 0xff, (val >>> 0) & 0xff]), - first - ) - } - - public addCString(val: string, front?: boolean) { - var len = Buffer.byteLength(val) - var buffer = Buffer.alloc(len + 1) - buffer.write(val) - buffer[len] = 0 - return this.add(buffer, front) - } - - public addString(val: string, front?: boolean) { - var len = Buffer.byteLength(val) - var buffer = Buffer.alloc(len) - buffer.write(val) - return this.add(buffer, front) - } - - public addChar(char: string, first?: boolean) { - return this.add(Buffer.from(char, 'utf8'), first) - } - - public addByte(byte: number) { - return this.add(Buffer.from([byte])) - } - - public join(appendLength?: boolean, char?: string): Buffer { - var length = this.getByteLength() - if (appendLength) { - this.addInt32(length + 4, true) - return this.join(false, char) - } - if (char) { - this.addChar(char, true) - length++ - } - var result = Buffer.alloc(length) - var index = 0 - this.buffers.forEach(function (buffer) { - buffer.copy(result, index, 0) - index += buffer.length - }) - return result - } - - public static concat(): Buffer { - var total = new BufferList() - for (var i = 0; i < arguments.length; i++) { - total.add(arguments[i]) - } - return total.join() - } -} diff --git a/reverse_engineering/node_modules/pg-protocol/src/testing/test-buffers.ts b/reverse_engineering/node_modules/pg-protocol/src/testing/test-buffers.ts deleted file mode 100644 index e0a04a7..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/testing/test-buffers.ts +++ /dev/null @@ -1,166 +0,0 @@ -// http://developer.postgresql.org/pgdocs/postgres/protocol-message-formats.html -import BufferList from './buffer-list' - -const buffers = { - readyForQuery: function () { - return new BufferList().add(Buffer.from('I')).join(true, 'Z') - }, - - authenticationOk: function () { - return new BufferList().addInt32(0).join(true, 'R') - }, - - authenticationCleartextPassword: function () { - return new BufferList().addInt32(3).join(true, 'R') - }, - - authenticationMD5Password: function () { - return new BufferList() - .addInt32(5) - .add(Buffer.from([1, 2, 3, 4])) - .join(true, 'R') - }, - - authenticationSASL: function () { - return new BufferList().addInt32(10).addCString('SCRAM-SHA-256').addCString('').join(true, 'R') - }, - - authenticationSASLContinue: function () { - return new BufferList().addInt32(11).addString('data').join(true, 'R') - }, - - authenticationSASLFinal: function () { - return new BufferList().addInt32(12).addString('data').join(true, 'R') - }, - - parameterStatus: function (name: string, value: string) { - return new BufferList().addCString(name).addCString(value).join(true, 'S') - }, - - backendKeyData: function (processID: number, secretKey: number) { - return new BufferList().addInt32(processID).addInt32(secretKey).join(true, 'K') - }, - - commandComplete: function (string: string) { - return new BufferList().addCString(string).join(true, 'C') - }, - - rowDescription: function (fields: any[]) { - fields = fields || [] - var buf = new BufferList() - buf.addInt16(fields.length) - fields.forEach(function (field) { - buf - .addCString(field.name) - .addInt32(field.tableID || 0) - .addInt16(field.attributeNumber || 0) - .addInt32(field.dataTypeID || 0) - .addInt16(field.dataTypeSize || 0) - .addInt32(field.typeModifier || 0) - .addInt16(field.formatCode || 0) - }) - return buf.join(true, 'T') - }, - - parameterDescription: function (dataTypeIDs: number[]) { - dataTypeIDs = dataTypeIDs || [] - var buf = new BufferList() - buf.addInt16(dataTypeIDs.length) - dataTypeIDs.forEach(function (dataTypeID) { - buf.addInt32(dataTypeID) - }) - return buf.join(true, 't') - }, - - dataRow: function (columns: any[]) { - columns = columns || [] - var buf = new BufferList() - buf.addInt16(columns.length) - columns.forEach(function (col) { - if (col == null) { - buf.addInt32(-1) - } else { - var strBuf = Buffer.from(col, 'utf8') - buf.addInt32(strBuf.length) - buf.add(strBuf) - } - }) - return buf.join(true, 'D') - }, - - error: function (fields: any) { - return buffers.errorOrNotice(fields).join(true, 'E') - }, - - notice: function (fields: any) { - return buffers.errorOrNotice(fields).join(true, 'N') - }, - - errorOrNotice: function (fields: any) { - fields = fields || [] - var buf = new BufferList() - fields.forEach(function (field: any) { - buf.addChar(field.type) - buf.addCString(field.value) - }) - return buf.add(Buffer.from([0])) // terminator - }, - - parseComplete: function () { - return new BufferList().join(true, '1') - }, - - bindComplete: function () { - return new BufferList().join(true, '2') - }, - - notification: function (id: number, channel: string, payload: string) { - return new BufferList().addInt32(id).addCString(channel).addCString(payload).join(true, 'A') - }, - - emptyQuery: function () { - return new BufferList().join(true, 'I') - }, - - portalSuspended: function () { - return new BufferList().join(true, 's') - }, - - closeComplete: function () { - return new BufferList().join(true, '3') - }, - - copyIn: function (cols: number) { - const list = new BufferList() - // text mode - .addByte(0) - // column count - .addInt16(cols) - for (let i = 0; i < cols; i++) { - list.addInt16(i) - } - return list.join(true, 'G') - }, - - copyOut: function (cols: number) { - const list = new BufferList() - // text mode - .addByte(0) - // column count - .addInt16(cols) - for (let i = 0; i < cols; i++) { - list.addInt16(i) - } - return list.join(true, 'H') - }, - - copyData: function (bytes: Buffer) { - return new BufferList().add(bytes).join(true, 'd') - }, - - copyDone: function () { - return new BufferList().join(true, 'c') - }, -} - -export default buffers diff --git a/reverse_engineering/node_modules/pg-protocol/src/types/chunky.d.ts b/reverse_engineering/node_modules/pg-protocol/src/types/chunky.d.ts deleted file mode 100644 index 7389bda..0000000 --- a/reverse_engineering/node_modules/pg-protocol/src/types/chunky.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module 'chunky' diff --git a/reverse_engineering/node_modules/pg-types/.travis.yml b/reverse_engineering/node_modules/pg-types/.travis.yml deleted file mode 100644 index dd6b033..0000000 --- a/reverse_engineering/node_modules/pg-types/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: node_js -node_js: - - '4' - - 'lts/*' - - 'node' -env: - - PGUSER=postgres diff --git a/reverse_engineering/node_modules/pg-types/Makefile b/reverse_engineering/node_modules/pg-types/Makefile deleted file mode 100644 index d7ec83d..0000000 --- a/reverse_engineering/node_modules/pg-types/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -.PHONY: publish-patch test - -test: - npm test - -patch: test - npm version patch -m "Bump version" - git push origin master --tags - npm publish - -minor: test - npm version minor -m "Bump version" - git push origin master --tags - npm publish diff --git a/reverse_engineering/node_modules/pg-types/README.md b/reverse_engineering/node_modules/pg-types/README.md deleted file mode 100644 index 54a3f2c..0000000 --- a/reverse_engineering/node_modules/pg-types/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# pg-types - -This is the code that turns all the raw text from postgres into JavaScript types for [node-postgres](https://github.com/brianc/node-postgres.git) - -## use - -This module is consumed and exported from the root `pg` object of node-postgres. To access it, do the following: - -```js -var types = require('pg').types -``` - -Generally what you'll want to do is override how a specific data-type is parsed and turned into a JavaScript type. By default the PostgreSQL backend server returns everything as strings. Every data type corresponds to a unique `OID` within the server, and these `OIDs` are sent back with the query response. So, you need to match a particluar `OID` to a function you'd like to use to take the raw text input and produce a valid JavaScript object as a result. `null` values are never parsed. - -Let's do something I commonly like to do on projects: return 64-bit integers `(int8)` as JavaScript integers. Because JavaScript doesn't have support for 64-bit integers node-postgres cannot confidently parse `int8` data type results as numbers because if you have a _huge_ number it will overflow and the result you'd get back from node-postgres would not be the result in the datbase. That would be a __very bad thing__ so node-postgres just returns `int8` results as strings and leaves the parsing up to you. Let's say that you know you don't and wont ever have numbers greater than `int4` in your database, but you're tired of recieving results from the `COUNT(*)` function as strings (because that function returns `int8`). You would do this: - -```js -var types = require('pg').types -types.setTypeParser(20, function(val) { - return parseInt(val) -}) -``` - -__boom__: now you get numbers instead of strings. - -Just as another example -- not saying this is a good idea -- let's say you want to return all dates from your database as [moment](http://momentjs.com/docs/) objects. Okay, do this: - -```js -var types = require('pg').types -var moment = require('moment') -var parseFn = function(val) { - return val === null ? null : moment(val) -} -types.setTypeParser(types.builtins.TIMESTAMPTZ, parseFn) -types.setTypeParser(types.builtins.TIMESTAMP, parseFn) -``` -_note: I've never done that with my dates, and I'm not 100% sure moment can parse all the date strings returned from postgres. It's just an example!_ - -If you're thinking "gee, this seems pretty handy, but how can I get a list of all the OIDs in the database and what they correspond to?!?!?!" worry not: - -```bash -$ psql -c "select typname, oid, typarray from pg_type order by oid" -``` - -If you want to find out the OID of a specific type: - -```bash -$ psql -c "select typname, oid, typarray from pg_type where typname = 'daterange' order by oid" -``` - -:smile: - -## license - -The MIT License (MIT) - -Copyright (c) 2014 Brian M. Carlson - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/pg-types/index.d.ts b/reverse_engineering/node_modules/pg-types/index.d.ts deleted file mode 100644 index 4bebcbe..0000000 --- a/reverse_engineering/node_modules/pg-types/index.d.ts +++ /dev/null @@ -1,137 +0,0 @@ -export enum TypeId { - BOOL = 16, - BYTEA = 17, - CHAR = 18, - INT8 = 20, - INT2 = 21, - INT4 = 23, - REGPROC = 24, - TEXT = 25, - OID = 26, - TID = 27, - XID = 28, - CID = 29, - JSON = 114, - XML = 142, - PG_NODE_TREE = 194, - SMGR = 210, - PATH = 602, - POLYGON = 604, - CIDR = 650, - FLOAT4 = 700, - FLOAT8 = 701, - ABSTIME = 702, - RELTIME = 703, - TINTERVAL = 704, - CIRCLE = 718, - MACADDR8 = 774, - MONEY = 790, - MACADDR = 829, - INET = 869, - ACLITEM = 1033, - BPCHAR = 1042, - VARCHAR = 1043, - DATE = 1082, - TIME = 1083, - TIMESTAMP = 1114, - TIMESTAMPTZ = 1184, - INTERVAL = 1186, - TIMETZ = 1266, - BIT = 1560, - VARBIT = 1562, - NUMERIC = 1700, - REFCURSOR = 1790, - REGPROCEDURE = 2202, - REGOPER = 2203, - REGOPERATOR = 2204, - REGCLASS = 2205, - REGTYPE = 2206, - UUID = 2950, - TXID_SNAPSHOT = 2970, - PG_LSN = 3220, - PG_NDISTINCT = 3361, - PG_DEPENDENCIES = 3402, - TSVECTOR = 3614, - TSQUERY = 3615, - GTSVECTOR = 3642, - REGCONFIG = 3734, - REGDICTIONARY = 3769, - JSONB = 3802, - REGNAMESPACE = 4089, - REGROLE = 4096 -} - -export type builtinsTypes = - 'BOOL' | - 'BYTEA' | - 'CHAR' | - 'INT8' | - 'INT2' | - 'INT4' | - 'REGPROC' | - 'TEXT' | - 'OID' | - 'TID' | - 'XID' | - 'CID' | - 'JSON' | - 'XML' | - 'PG_NODE_TREE' | - 'SMGR' | - 'PATH' | - 'POLYGON' | - 'CIDR' | - 'FLOAT4' | - 'FLOAT8' | - 'ABSTIME' | - 'RELTIME' | - 'TINTERVAL' | - 'CIRCLE' | - 'MACADDR8' | - 'MONEY' | - 'MACADDR' | - 'INET' | - 'ACLITEM' | - 'BPCHAR' | - 'VARCHAR' | - 'DATE' | - 'TIME' | - 'TIMESTAMP' | - 'TIMESTAMPTZ' | - 'INTERVAL' | - 'TIMETZ' | - 'BIT' | - 'VARBIT' | - 'NUMERIC' | - 'REFCURSOR' | - 'REGPROCEDURE' | - 'REGOPER' | - 'REGOPERATOR' | - 'REGCLASS' | - 'REGTYPE' | - 'UUID' | - 'TXID_SNAPSHOT' | - 'PG_LSN' | - 'PG_NDISTINCT' | - 'PG_DEPENDENCIES' | - 'TSVECTOR' | - 'TSQUERY' | - 'GTSVECTOR' | - 'REGCONFIG' | - 'REGDICTIONARY' | - 'JSONB' | - 'REGNAMESPACE' | - 'REGROLE'; - -export type TypesBuiltins = {[key in builtinsTypes]: TypeId}; - -export type TypeFormat = 'text' | 'binary'; - -export const builtins: TypesBuiltins; - -export function setTypeParser (id: TypeId, parseFn: ((value: string) => any)): void; -export function setTypeParser (id: TypeId, format: TypeFormat, parseFn: (value: string) => any): void; - -export const getTypeParser: (id: TypeId, format?: TypeFormat) => any - -export const arrayParser: (source: string, transform: (entry: any) => any) => any[]; diff --git a/reverse_engineering/node_modules/pg-types/index.js b/reverse_engineering/node_modules/pg-types/index.js deleted file mode 100644 index 952d8c2..0000000 --- a/reverse_engineering/node_modules/pg-types/index.js +++ /dev/null @@ -1,47 +0,0 @@ -var textParsers = require('./lib/textParsers'); -var binaryParsers = require('./lib/binaryParsers'); -var arrayParser = require('./lib/arrayParser'); -var builtinTypes = require('./lib/builtins'); - -exports.getTypeParser = getTypeParser; -exports.setTypeParser = setTypeParser; -exports.arrayParser = arrayParser; -exports.builtins = builtinTypes; - -var typeParsers = { - text: {}, - binary: {} -}; - -//the empty parse function -function noParse (val) { - return String(val); -}; - -//returns a function used to convert a specific type (specified by -//oid) into a result javascript type -//note: the oid can be obtained via the following sql query: -//SELECT oid FROM pg_type WHERE typname = 'TYPE_NAME_HERE'; -function getTypeParser (oid, format) { - format = format || 'text'; - if (!typeParsers[format]) { - return noParse; - } - return typeParsers[format][oid] || noParse; -}; - -function setTypeParser (oid, format, parseFn) { - if(typeof format == 'function') { - parseFn = format; - format = 'text'; - } - typeParsers[format][oid] = parseFn; -}; - -textParsers.init(function(oid, converter) { - typeParsers.text[oid] = converter; -}); - -binaryParsers.init(function(oid, converter) { - typeParsers.binary[oid] = converter; -}); diff --git a/reverse_engineering/node_modules/pg-types/index.test-d.ts b/reverse_engineering/node_modules/pg-types/index.test-d.ts deleted file mode 100644 index d530e6e..0000000 --- a/reverse_engineering/node_modules/pg-types/index.test-d.ts +++ /dev/null @@ -1,21 +0,0 @@ -import * as types from '.'; -import { expectType } from 'tsd'; - -// builtins -expectType(types.builtins); - -// getTypeParser -const noParse = types.getTypeParser(types.builtins.NUMERIC, 'text'); -const numericParser = types.getTypeParser(types.builtins.NUMERIC, 'binary'); -expectType(noParse('noParse')); -expectType(numericParser([200, 1, 0, 15])); - -// getArrayParser -const value = types.arrayParser('{1,2,3}', (num) => parseInt(num)); -expectType(value); - -//setTypeParser -types.setTypeParser(types.builtins.INT8, parseInt); -types.setTypeParser(types.builtins.FLOAT8, parseFloat); -types.setTypeParser(types.builtins.FLOAT8, 'binary', (data) => data[0]); -types.setTypeParser(types.builtins.FLOAT8, 'text', parseFloat); diff --git a/reverse_engineering/node_modules/pg-types/lib/arrayParser.js b/reverse_engineering/node_modules/pg-types/lib/arrayParser.js deleted file mode 100644 index 81ccffb..0000000 --- a/reverse_engineering/node_modules/pg-types/lib/arrayParser.js +++ /dev/null @@ -1,11 +0,0 @@ -var array = require('postgres-array'); - -module.exports = { - create: function (source, transform) { - return { - parse: function() { - return array.parse(source, transform); - } - }; - } -}; diff --git a/reverse_engineering/node_modules/pg-types/lib/binaryParsers.js b/reverse_engineering/node_modules/pg-types/lib/binaryParsers.js deleted file mode 100644 index e12c2f4..0000000 --- a/reverse_engineering/node_modules/pg-types/lib/binaryParsers.js +++ /dev/null @@ -1,257 +0,0 @@ -var parseInt64 = require('pg-int8'); - -var parseBits = function(data, bits, offset, invert, callback) { - offset = offset || 0; - invert = invert || false; - callback = callback || function(lastValue, newValue, bits) { return (lastValue * Math.pow(2, bits)) + newValue; }; - var offsetBytes = offset >> 3; - - var inv = function(value) { - if (invert) { - return ~value & 0xff; - } - - return value; - }; - - // read first (maybe partial) byte - var mask = 0xff; - var firstBits = 8 - (offset % 8); - if (bits < firstBits) { - mask = (0xff << (8 - bits)) & 0xff; - firstBits = bits; - } - - if (offset) { - mask = mask >> (offset % 8); - } - - var result = 0; - if ((offset % 8) + bits >= 8) { - result = callback(0, inv(data[offsetBytes]) & mask, firstBits); - } - - // read bytes - var bytes = (bits + offset) >> 3; - for (var i = offsetBytes + 1; i < bytes; i++) { - result = callback(result, inv(data[i]), 8); - } - - // bits to read, that are not a complete byte - var lastBits = (bits + offset) % 8; - if (lastBits > 0) { - result = callback(result, inv(data[bytes]) >> (8 - lastBits), lastBits); - } - - return result; -}; - -var parseFloatFromBits = function(data, precisionBits, exponentBits) { - var bias = Math.pow(2, exponentBits - 1) - 1; - var sign = parseBits(data, 1); - var exponent = parseBits(data, exponentBits, 1); - - if (exponent === 0) { - return 0; - } - - // parse mantissa - var precisionBitsCounter = 1; - var parsePrecisionBits = function(lastValue, newValue, bits) { - if (lastValue === 0) { - lastValue = 1; - } - - for (var i = 1; i <= bits; i++) { - precisionBitsCounter /= 2; - if ((newValue & (0x1 << (bits - i))) > 0) { - lastValue += precisionBitsCounter; - } - } - - return lastValue; - }; - - var mantissa = parseBits(data, precisionBits, exponentBits + 1, false, parsePrecisionBits); - - // special cases - if (exponent == (Math.pow(2, exponentBits + 1) - 1)) { - if (mantissa === 0) { - return (sign === 0) ? Infinity : -Infinity; - } - - return NaN; - } - - // normale number - return ((sign === 0) ? 1 : -1) * Math.pow(2, exponent - bias) * mantissa; -}; - -var parseInt16 = function(value) { - if (parseBits(value, 1) == 1) { - return -1 * (parseBits(value, 15, 1, true) + 1); - } - - return parseBits(value, 15, 1); -}; - -var parseInt32 = function(value) { - if (parseBits(value, 1) == 1) { - return -1 * (parseBits(value, 31, 1, true) + 1); - } - - return parseBits(value, 31, 1); -}; - -var parseFloat32 = function(value) { - return parseFloatFromBits(value, 23, 8); -}; - -var parseFloat64 = function(value) { - return parseFloatFromBits(value, 52, 11); -}; - -var parseNumeric = function(value) { - var sign = parseBits(value, 16, 32); - if (sign == 0xc000) { - return NaN; - } - - var weight = Math.pow(10000, parseBits(value, 16, 16)); - var result = 0; - - var digits = []; - var ndigits = parseBits(value, 16); - for (var i = 0; i < ndigits; i++) { - result += parseBits(value, 16, 64 + (16 * i)) * weight; - weight /= 10000; - } - - var scale = Math.pow(10, parseBits(value, 16, 48)); - return ((sign === 0) ? 1 : -1) * Math.round(result * scale) / scale; -}; - -var parseDate = function(isUTC, value) { - var sign = parseBits(value, 1); - var rawValue = parseBits(value, 63, 1); - - // discard usecs and shift from 2000 to 1970 - var result = new Date((((sign === 0) ? 1 : -1) * rawValue / 1000) + 946684800000); - - if (!isUTC) { - result.setTime(result.getTime() + result.getTimezoneOffset() * 60000); - } - - // add microseconds to the date - result.usec = rawValue % 1000; - result.getMicroSeconds = function() { - return this.usec; - }; - result.setMicroSeconds = function(value) { - this.usec = value; - }; - result.getUTCMicroSeconds = function() { - return this.usec; - }; - - return result; -}; - -var parseArray = function(value) { - var dim = parseBits(value, 32); - - var flags = parseBits(value, 32, 32); - var elementType = parseBits(value, 32, 64); - - var offset = 96; - var dims = []; - for (var i = 0; i < dim; i++) { - // parse dimension - dims[i] = parseBits(value, 32, offset); - offset += 32; - - // ignore lower bounds - offset += 32; - } - - var parseElement = function(elementType) { - // parse content length - var length = parseBits(value, 32, offset); - offset += 32; - - // parse null values - if (length == 0xffffffff) { - return null; - } - - var result; - if ((elementType == 0x17) || (elementType == 0x14)) { - // int/bigint - result = parseBits(value, length * 8, offset); - offset += length * 8; - return result; - } - else if (elementType == 0x19) { - // string - result = value.toString(this.encoding, offset >> 3, (offset += (length << 3)) >> 3); - return result; - } - else { - console.log("ERROR: ElementType not implemented: " + elementType); - } - }; - - var parse = function(dimension, elementType) { - var array = []; - var i; - - if (dimension.length > 1) { - var count = dimension.shift(); - for (i = 0; i < count; i++) { - array[i] = parse(dimension, elementType); - } - dimension.unshift(count); - } - else { - for (i = 0; i < dimension[0]; i++) { - array[i] = parseElement(elementType); - } - } - - return array; - }; - - return parse(dims, elementType); -}; - -var parseText = function(value) { - return value.toString('utf8'); -}; - -var parseBool = function(value) { - if(value === null) return null; - return (parseBits(value, 8) > 0); -}; - -var init = function(register) { - register(20, parseInt64); - register(21, parseInt16); - register(23, parseInt32); - register(26, parseInt32); - register(1700, parseNumeric); - register(700, parseFloat32); - register(701, parseFloat64); - register(16, parseBool); - register(1114, parseDate.bind(null, false)); - register(1184, parseDate.bind(null, true)); - register(1000, parseArray); - register(1007, parseArray); - register(1016, parseArray); - register(1008, parseArray); - register(1009, parseArray); - register(25, parseText); -}; - -module.exports = { - init: init -}; diff --git a/reverse_engineering/node_modules/pg-types/lib/builtins.js b/reverse_engineering/node_modules/pg-types/lib/builtins.js deleted file mode 100644 index f0c134a..0000000 --- a/reverse_engineering/node_modules/pg-types/lib/builtins.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Following query was used to generate this file: - - SELECT json_object_agg(UPPER(PT.typname), PT.oid::int4 ORDER BY pt.oid) - FROM pg_type PT - WHERE typnamespace = (SELECT pgn.oid FROM pg_namespace pgn WHERE nspname = 'pg_catalog') -- Take only builting Postgres types with stable OID (extension types are not guaranted to be stable) - AND typtype = 'b' -- Only basic types - AND typelem = 0 -- Ignore aliases - AND typisdefined -- Ignore undefined types - */ - -module.exports = { - BOOL: 16, - BYTEA: 17, - CHAR: 18, - INT8: 20, - INT2: 21, - INT4: 23, - REGPROC: 24, - TEXT: 25, - OID: 26, - TID: 27, - XID: 28, - CID: 29, - JSON: 114, - XML: 142, - PG_NODE_TREE: 194, - SMGR: 210, - PATH: 602, - POLYGON: 604, - CIDR: 650, - FLOAT4: 700, - FLOAT8: 701, - ABSTIME: 702, - RELTIME: 703, - TINTERVAL: 704, - CIRCLE: 718, - MACADDR8: 774, - MONEY: 790, - MACADDR: 829, - INET: 869, - ACLITEM: 1033, - BPCHAR: 1042, - VARCHAR: 1043, - DATE: 1082, - TIME: 1083, - TIMESTAMP: 1114, - TIMESTAMPTZ: 1184, - INTERVAL: 1186, - TIMETZ: 1266, - BIT: 1560, - VARBIT: 1562, - NUMERIC: 1700, - REFCURSOR: 1790, - REGPROCEDURE: 2202, - REGOPER: 2203, - REGOPERATOR: 2204, - REGCLASS: 2205, - REGTYPE: 2206, - UUID: 2950, - TXID_SNAPSHOT: 2970, - PG_LSN: 3220, - PG_NDISTINCT: 3361, - PG_DEPENDENCIES: 3402, - TSVECTOR: 3614, - TSQUERY: 3615, - GTSVECTOR: 3642, - REGCONFIG: 3734, - REGDICTIONARY: 3769, - JSONB: 3802, - REGNAMESPACE: 4089, - REGROLE: 4096 -}; diff --git a/reverse_engineering/node_modules/pg-types/lib/textParsers.js b/reverse_engineering/node_modules/pg-types/lib/textParsers.js deleted file mode 100644 index b1218bf..0000000 --- a/reverse_engineering/node_modules/pg-types/lib/textParsers.js +++ /dev/null @@ -1,215 +0,0 @@ -var array = require('postgres-array') -var arrayParser = require('./arrayParser'); -var parseDate = require('postgres-date'); -var parseInterval = require('postgres-interval'); -var parseByteA = require('postgres-bytea'); - -function allowNull (fn) { - return function nullAllowed (value) { - if (value === null) return value - return fn(value) - } -} - -function parseBool (value) { - if (value === null) return value - return value === 'TRUE' || - value === 't' || - value === 'true' || - value === 'y' || - value === 'yes' || - value === 'on' || - value === '1'; -} - -function parseBoolArray (value) { - if (!value) return null - return array.parse(value, parseBool) -} - -function parseBaseTenInt (string) { - return parseInt(string, 10) -} - -function parseIntegerArray (value) { - if (!value) return null - return array.parse(value, allowNull(parseBaseTenInt)) -} - -function parseBigIntegerArray (value) { - if (!value) return null - return array.parse(value, allowNull(function (entry) { - return parseBigInteger(entry).trim() - })) -} - -var parsePointArray = function(value) { - if(!value) { return null; } - var p = arrayParser.create(value, function(entry) { - if(entry !== null) { - entry = parsePoint(entry); - } - return entry; - }); - - return p.parse(); -}; - -var parseFloatArray = function(value) { - if(!value) { return null; } - var p = arrayParser.create(value, function(entry) { - if(entry !== null) { - entry = parseFloat(entry); - } - return entry; - }); - - return p.parse(); -}; - -var parseStringArray = function(value) { - if(!value) { return null; } - - var p = arrayParser.create(value); - return p.parse(); -}; - -var parseDateArray = function(value) { - if (!value) { return null; } - - var p = arrayParser.create(value, function(entry) { - if (entry !== null) { - entry = parseDate(entry); - } - return entry; - }); - - return p.parse(); -}; - -var parseIntervalArray = function(value) { - if (!value) { return null; } - - var p = arrayParser.create(value, function(entry) { - if (entry !== null) { - entry = parseInterval(entry); - } - return entry; - }); - - return p.parse(); -}; - -var parseByteAArray = function(value) { - if (!value) { return null; } - - return array.parse(value, allowNull(parseByteA)); -}; - -var parseInteger = function(value) { - return parseInt(value, 10); -}; - -var parseBigInteger = function(value) { - var valStr = String(value); - if (/^\d+$/.test(valStr)) { return valStr; } - return value; -}; - -var parseJsonArray = function(value) { - if (!value) { return null; } - - return array.parse(value, allowNull(JSON.parse)); -}; - -var parsePoint = function(value) { - if (value[0] !== '(') { return null; } - - value = value.substring( 1, value.length - 1 ).split(','); - - return { - x: parseFloat(value[0]) - , y: parseFloat(value[1]) - }; -}; - -var parseCircle = function(value) { - if (value[0] !== '<' && value[1] !== '(') { return null; } - - var point = '('; - var radius = ''; - var pointParsed = false; - for (var i = 2; i < value.length - 1; i++){ - if (!pointParsed) { - point += value[i]; - } - - if (value[i] === ')') { - pointParsed = true; - continue; - } else if (!pointParsed) { - continue; - } - - if (value[i] === ','){ - continue; - } - - radius += value[i]; - } - var result = parsePoint(point); - result.radius = parseFloat(radius); - - return result; -}; - -var init = function(register) { - register(20, parseBigInteger); // int8 - register(21, parseInteger); // int2 - register(23, parseInteger); // int4 - register(26, parseInteger); // oid - register(700, parseFloat); // float4/real - register(701, parseFloat); // float8/double - register(16, parseBool); - register(1082, parseDate); // date - register(1114, parseDate); // timestamp without timezone - register(1184, parseDate); // timestamp - register(600, parsePoint); // point - register(651, parseStringArray); // cidr[] - register(718, parseCircle); // circle - register(1000, parseBoolArray); - register(1001, parseByteAArray); - register(1005, parseIntegerArray); // _int2 - register(1007, parseIntegerArray); // _int4 - register(1028, parseIntegerArray); // oid[] - register(1016, parseBigIntegerArray); // _int8 - register(1017, parsePointArray); // point[] - register(1021, parseFloatArray); // _float4 - register(1022, parseFloatArray); // _float8 - register(1231, parseFloatArray); // _numeric - register(1014, parseStringArray); //char - register(1015, parseStringArray); //varchar - register(1008, parseStringArray); - register(1009, parseStringArray); - register(1040, parseStringArray); // macaddr[] - register(1041, parseStringArray); // inet[] - register(1115, parseDateArray); // timestamp without time zone[] - register(1182, parseDateArray); // _date - register(1185, parseDateArray); // timestamp with time zone[] - register(1186, parseInterval); - register(1187, parseIntervalArray); - register(17, parseByteA); - register(114, JSON.parse.bind(JSON)); // json - register(3802, JSON.parse.bind(JSON)); // jsonb - register(199, parseJsonArray); // json[] - register(3807, parseJsonArray); // jsonb[] - register(3907, parseStringArray); // numrange[] - register(2951, parseStringArray); // uuid[] - register(791, parseStringArray); // money[] - register(1183, parseStringArray); // time[] - register(1270, parseStringArray); // timetz[] -}; - -module.exports = { - init: init -}; diff --git a/reverse_engineering/node_modules/pg-types/package.json b/reverse_engineering/node_modules/pg-types/package.json deleted file mode 100644 index 938ae5f..0000000 --- a/reverse_engineering/node_modules/pg-types/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "pg-types@^2.1.0", - "_id": "pg-types@2.2.0", - "_inBundle": false, - "_integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", - "_location": "/pg-types", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "pg-types@^2.1.0", - "name": "pg-types", - "escapedName": "pg-types", - "rawSpec": "^2.1.0", - "saveSpec": null, - "fetchSpec": "^2.1.0" - }, - "_requiredBy": [ - "/pg" - ], - "_resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", - "_shasum": "2d0250d636454f7cfa3b6ae0382fdfa8063254a3", - "_spec": "pg-types@^2.1.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg", - "author": { - "name": "Brian M. Carlson" - }, - "bugs": { - "url": "https://github.com/brianc/node-pg-types/issues" - }, - "bundleDependencies": false, - "dependencies": { - "pg-int8": "1.0.1", - "postgres-array": "~2.0.0", - "postgres-bytea": "~1.0.0", - "postgres-date": "~1.0.4", - "postgres-interval": "^1.1.0" - }, - "deprecated": false, - "description": "Query result type converters for node-postgres", - "devDependencies": { - "if-node-version": "^1.1.1", - "pff": "^1.0.0", - "tap-spec": "^4.0.0", - "tape": "^4.0.0", - "tsd": "^0.7.4" - }, - "engines": { - "node": ">=4" - }, - "homepage": "https://github.com/brianc/node-pg-types", - "keywords": [ - "postgres", - "PostgreSQL", - "pg" - ], - "license": "MIT", - "main": "index.js", - "name": "pg-types", - "repository": { - "type": "git", - "url": "git://github.com/brianc/node-pg-types.git" - }, - "scripts": { - "test": "tape test/*.js | tap-spec && npm run test-ts", - "test-ts": "if-node-version '>= 8' tsd" - }, - "version": "2.2.0" -} diff --git a/reverse_engineering/node_modules/pg-types/test/index.js b/reverse_engineering/node_modules/pg-types/test/index.js deleted file mode 100644 index b7d05cd..0000000 --- a/reverse_engineering/node_modules/pg-types/test/index.js +++ /dev/null @@ -1,24 +0,0 @@ - -var test = require('tape') -var printf = require('pff') -var getTypeParser = require('../').getTypeParser -var types = require('./types') - -test('types', function (t) { - Object.keys(types).forEach(function (typeName) { - var type = types[typeName] - t.test(typeName, function (t) { - var parser = getTypeParser(type.id, type.format) - type.tests.forEach(function (tests) { - var input = tests[0] - var expected = tests[1] - var result = parser(input) - if (typeof expected === 'function') { - return expected(t, result) - } - t.equal(result, expected) - }) - t.end() - }) - }) -}) diff --git a/reverse_engineering/node_modules/pg-types/test/types.js b/reverse_engineering/node_modules/pg-types/test/types.js deleted file mode 100644 index af708a5..0000000 --- a/reverse_engineering/node_modules/pg-types/test/types.js +++ /dev/null @@ -1,597 +0,0 @@ -'use strict' - -exports['string/varchar'] = { - format: 'text', - id: 1043, - tests: [ - ['bang', 'bang'] - ] -} - -exports['integer/int4'] = { - format: 'text', - id: 23, - tests: [ - ['2147483647', 2147483647] - ] -} - -exports['smallint/int2'] = { - format: 'text', - id: 21, - tests: [ - ['32767', 32767] - ] -} - -exports['bigint/int8'] = { - format: 'text', - id: 20, - tests: [ - ['9223372036854775807', '9223372036854775807'] - ] -} - -exports.oid = { - format: 'text', - id: 26, - tests: [ - ['103', 103] - ] -} - -var bignum = '31415926535897932384626433832795028841971693993751058.16180339887498948482045868343656381177203091798057628' -exports.numeric = { - format: 'text', - id: 1700, - tests: [ - [bignum, bignum] - ] -} - -exports['real/float4'] = { - format: 'text', - id: 700, - tests: [ - ['123.456', 123.456] - ] -} - -exports['double precision / float 8'] = { - format: 'text', - id: 701, - tests: [ - ['12345678.12345678', 12345678.12345678] - ] -} - -exports.boolean = { - format: 'text', - id: 16, - tests: [ - ['TRUE', true], - ['t', true], - ['true', true], - ['y', true], - ['yes', true], - ['on', true], - ['1', true], - ['f', false], - [null, null] - ] -} - -exports.timestamptz = { - format: 'text', - id: 1184, - tests: [ - [ - '2010-10-31 14:54:13.74-05:30', - dateEquals(2010, 9, 31, 20, 24, 13, 740) - ], - [ - '2011-01-23 22:05:00.68-06', - dateEquals(2011, 0, 24, 4, 5, 0, 680) - ], - [ - '2010-10-30 14:11:12.730838Z', - dateEquals(2010, 9, 30, 14, 11, 12, 730) - ], - [ - '2010-10-30 13:10:01+05', - dateEquals(2010, 9, 30, 8, 10, 1, 0) - ] - ] -} - -exports.timestamp = { - format: 'text', - id: 1114, - tests: [ - [ - '2010-10-31 00:00:00', - function (t, value) { - t.equal( - value.toUTCString(), - new Date(2010, 9, 31, 0, 0, 0, 0, 0).toUTCString() - ) - t.equal( - value.toString(), - new Date(2010, 9, 31, 0, 0, 0, 0, 0, 0).toString() - ) - } - ] - ] -} - -exports.date = { - format: 'text', - id: 1082, - tests: [ - ['2010-10-31', function (t, value) { - var now = new Date(2010, 9, 31) - dateEquals( - 2010, - now.getUTCMonth(), - now.getUTCDate(), - now.getUTCHours(), 0, 0, 0)(t, value) - t.equal(value.getHours(), now.getHours()) - }] - ] -} - -exports.inet = { - format: 'text', - id: 869, - tests: [ - ['8.8.8.8', '8.8.8.8'], - ['2001:4860:4860::8888', '2001:4860:4860::8888'], - ['127.0.0.1', '127.0.0.1'], - ['fd00:1::40e', 'fd00:1::40e'], - ['1.2.3.4', '1.2.3.4'] - ] -} - -exports.cidr = { - format: 'text', - id: 650, - tests: [ - ['172.16.0.0/12', '172.16.0.0/12'], - ['fe80::/10', 'fe80::/10'], - ['fc00::/7', 'fc00::/7'], - ['192.168.0.0/24', '192.168.0.0/24'], - ['10.0.0.0/8', '10.0.0.0/8'] - ] -} - -exports.macaddr = { - format: 'text', - id: 829, - tests: [ - ['08:00:2b:01:02:03', '08:00:2b:01:02:03'], - ['16:10:9f:0d:66:00', '16:10:9f:0d:66:00'] - ] -} - -exports.numrange = { - format: 'text', - id: 3906, - tests: [ - ['[,]', '[,]'], - ['(,)', '(,)'], - ['(,]', '(,]'], - ['[1,)', '[1,)'], - ['[,1]', '[,1]'], - ['(1,2)', '(1,2)'], - ['(1,20.5]', '(1,20.5]'] - ] -} - -exports.interval = { - format: 'text', - id: 1186, - tests: [ - ['01:02:03', function (t, value) { - t.equal(value.toPostgres(), '3 seconds 2 minutes 1 hours') - t.deepEqual(value, {hours: 1, minutes: 2, seconds: 3}) - }], - ['01:02:03.456', function (t, value) { - t.deepEqual(value, {hours: 1, minutes:2, seconds: 3, milliseconds: 456}) - }], - ['1 year -32 days', function (t, value) { - t.equal(value.toPostgres(), '-32 days 1 years') - t.deepEqual(value, {years: 1, days: -32}) - }], - ['1 day -00:00:03', function (t, value) { - t.equal(value.toPostgres(), '-3 seconds 1 days') - t.deepEqual(value, {days: 1, seconds: -3}) - }] - ] -} - -exports.bytea = { - format: 'text', - id: 17, - tests: [ - ['foo\\000\\200\\\\\\377', function (t, value) { - var buffer = new Buffer([102, 111, 111, 0, 128, 92, 255]) - t.ok(buffer.equals(value)) - }], - ['', function (t, value) { - var buffer = new Buffer(0) - t.ok(buffer.equals(value)) - }] - ] -} - -exports['array/boolean'] = { - format: 'text', - id: 1000, - tests: [ - ['{true,false}', function (t, value) { - t.deepEqual(value, [true, false]) - }] - ] -} - -exports['array/char'] = { - format: 'text', - id: 1014, - tests: [ - ['{foo,bar}', function (t, value) { - t.deepEqual(value, ['foo', 'bar']) - }] - ] -} - -exports['array/varchar'] = { - format: 'text', - id: 1015, - tests: [ - ['{foo,bar}', function (t, value) { - t.deepEqual(value, ['foo', 'bar']) - }] - ] -} - -exports['array/text'] = { - format: 'text', - id: 1008, - tests: [ - ['{foo}', function (t, value) { - t.deepEqual(value, ['foo']) - }] - ] -} - -exports['array/bytea'] = { - format: 'text', - id: 1001, - tests: [ - ['{"\\\\x00000000"}', function (t, value) { - var buffer = new Buffer('00000000', 'hex') - t.ok(Array.isArray(value)) - t.equal(value.length, 1) - t.ok(buffer.equals(value[0])) - }], - ['{NULL,"\\\\x4e554c4c"}', function (t, value) { - var buffer = new Buffer('4e554c4c', 'hex') - t.ok(Array.isArray(value)) - t.equal(value.length, 2) - t.equal(value[0], null) - t.ok(buffer.equals(value[1])) - }], - ] -} - -exports['array/numeric'] = { - format: 'text', - id: 1231, - tests: [ - ['{1.2,3.4}', function (t, value) { - t.deepEqual(value, [1.2, 3.4]) - }] - ] -} - -exports['array/int2'] = { - format: 'text', - id: 1005, - tests: [ - ['{-32768, -32767, 32766, 32767}', function (t, value) { - t.deepEqual(value, [-32768, -32767, 32766, 32767]) - }] - ] -} - -exports['array/int4'] = { - format: 'text', - id: 1005, - tests: [ - ['{-2147483648, -2147483647, 2147483646, 2147483647}', function (t, value) { - t.deepEqual(value, [-2147483648, -2147483647, 2147483646, 2147483647]) - }] - ] -} - -exports['array/int8'] = { - format: 'text', - id: 1016, - tests: [ - [ - '{-9223372036854775808, -9223372036854775807, 9223372036854775806, 9223372036854775807}', - function (t, value) { - t.deepEqual(value, [ - '-9223372036854775808', - '-9223372036854775807', - '9223372036854775806', - '9223372036854775807' - ]) - } - ] - ] -} - -exports['array/json'] = { - format: 'text', - id: 199, - tests: [ - [ - '{{1,2},{[3],"[4,5]"},{null,NULL}}', - function (t, value) { - t.deepEqual(value, [ - [1, 2], - [[3], [4, 5]], - [null, null], - ]) - } - ] - ] -} - -exports['array/jsonb'] = { - format: 'text', - id: 3807, - tests: exports['array/json'].tests -} - -exports['array/point'] = { - format: 'text', - id: 1017, - tests: [ - ['{"(25.1,50.5)","(10.1,40)"}', function (t, value) { - t.deepEqual(value, [{x: 25.1, y: 50.5}, {x: 10.1, y: 40}]) - }] - ] -} - -exports['array/oid'] = { - format: 'text', - id: 1028, - tests: [ - ['{25864,25860}', function (t, value) { - t.deepEqual(value, [25864, 25860]) - }] - ] -} - -exports['array/float4'] = { - format: 'text', - id: 1021, - tests: [ - ['{1.2, 3.4}', function (t, value) { - t.deepEqual(value, [1.2, 3.4]) - }] - ] -} - -exports['array/float8'] = { - format: 'text', - id: 1022, - tests: [ - ['{-12345678.1234567, 12345678.12345678}', function (t, value) { - t.deepEqual(value, [-12345678.1234567, 12345678.12345678]) - }] - ] -} - -exports['array/date'] = { - format: 'text', - id: 1182, - tests: [ - ['{2014-01-01,2015-12-31}', function (t, value) { - var expecteds = [new Date(2014, 0, 1), new Date(2015, 11, 31)] - t.equal(value.length, 2) - value.forEach(function (date, index) { - var expected = expecteds[index] - dateEquals( - expected.getUTCFullYear(), - expected.getUTCMonth(), - expected.getUTCDate(), - expected.getUTCHours(), 0, 0, 0)(t, date) - }) - }] - ] -} - -exports['array/interval'] = { - format: 'text', - id: 1187, - tests: [ - ['{01:02:03,1 day -00:00:03}', function (t, value) { - var expecteds = [{hours: 1, minutes: 2, seconds: 3}, - {days: 1, seconds: -3}] - t.equal(value.length, 2) - t.deepEqual(value, expecteds); - }] - ] -} - -exports['array/inet'] = { - format: 'text', - id: 1041, - tests: [ - ['{8.8.8.8}', function (t, value) { - t.deepEqual(value, ['8.8.8.8']); - }], - ['{2001:4860:4860::8888}', function (t, value) { - t.deepEqual(value, ['2001:4860:4860::8888']); - }], - ['{127.0.0.1,fd00:1::40e,1.2.3.4}', function (t, value) { - t.deepEqual(value, ['127.0.0.1', 'fd00:1::40e', '1.2.3.4']); - }] - ] -} - -exports['array/cidr'] = { - format: 'text', - id: 651, - tests: [ - ['{172.16.0.0/12}', function (t, value) { - t.deepEqual(value, ['172.16.0.0/12']); - }], - ['{fe80::/10}', function (t, value) { - t.deepEqual(value, ['fe80::/10']); - }], - ['{10.0.0.0/8,fc00::/7,192.168.0.0/24}', function (t, value) { - t.deepEqual(value, ['10.0.0.0/8', 'fc00::/7', '192.168.0.0/24']); - }] - ] -} - -exports['array/macaddr'] = { - format: 'text', - id: 1040, - tests: [ - ['{08:00:2b:01:02:03,16:10:9f:0d:66:00}', function (t, value) { - t.deepEqual(value, ['08:00:2b:01:02:03', '16:10:9f:0d:66:00']); - }] - ] -} - -exports['array/numrange'] = { - format: 'text', - id: 3907, - tests: [ - ['{"[1,2]","(4.5,8)","[10,40)","(-21.2,60.3]"}', function (t, value) { - t.deepEqual(value, ['[1,2]', '(4.5,8)', '[10,40)', '(-21.2,60.3]']); - }], - ['{"[,20]","[3,]","[,]","(,35)","(1,)","(,)"}', function (t, value) { - t.deepEqual(value, ['[,20]', '[3,]', '[,]', '(,35)', '(1,)', '(,)']); - }], - ['{"[,20)","[3,)","[,)","[,35)","[1,)","[,)"}', function (t, value) { - t.deepEqual(value, ['[,20)', '[3,)', '[,)', '[,35)', '[1,)', '[,)']); - }] - ] -} - -exports['binary-string/varchar'] = { - format: 'binary', - id: 1043, - tests: [ - ['bang', 'bang'] - ] -} - -exports['binary-integer/int4'] = { - format: 'binary', - id: 23, - tests: [ - [[0, 0, 0, 100], 100] - ] -} - -exports['binary-smallint/int2'] = { - format: 'binary', - id: 21, - tests: [ - [[0, 101], 101] - ] -} - -exports['binary-bigint/int8'] = { - format: 'binary', - id: 20, - tests: [ - [new Buffer([0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), '9223372036854775807'] - ] -} - -exports['binary-oid'] = { - format: 'binary', - id: 26, - tests: [ - [[0, 0, 0, 103], 103] - ] -} - -exports['binary-numeric'] = { - format: 'binary', - id: 1700, - tests: [ - [ - [0, 2, 0, 0, 0, 0, 0, hex('0x64'), 0, 12, hex('0xd'), hex('0x48'), 0, 0, 0, 0], - 12.34 - ] - ] -} - -exports['binary-real/float4'] = { - format: 'binary', - id: 700, - tests: [ - [['0x41', '0x48', '0x00', '0x00'].map(hex), 12.5] - ] -} - -exports['binary-boolean'] = { - format: 'binary', - id: 16, - tests: [ - [[1], true], - [[0], false], - [null, null] - ] -} - -exports['binary-string'] = { - format: 'binary', - id: 25, - tests: [ - [ - new Buffer(['0x73', '0x6c', '0x61', '0x64', '0x64', '0x61'].map(hex)), - 'sladda' - ] - ] -} - -exports.point = { - format: 'text', - id: 600, - tests: [ - ['(25.1,50.5)', function (t, value) { - t.deepEqual(value, {x: 25.1, y: 50.5}) - }] - ] -} - -exports.circle = { - format: 'text', - id: 718, - tests: [ - ['<(25,10),5>', function (t, value) { - t.deepEqual(value, {x: 25, y: 10, radius: 5}) - }] - ] -} - -function hex (string) { - return parseInt(string, 16) -} - -function dateEquals () { - var timestamp = Date.UTC.apply(Date, arguments) - return function (t, value) { - t.equal(value.toUTCString(), new Date(timestamp).toUTCString()) - } -} diff --git a/reverse_engineering/node_modules/pg/LICENSE b/reverse_engineering/node_modules/pg/LICENSE deleted file mode 100644 index 5c14056..0000000 --- a/reverse_engineering/node_modules/pg/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2010 - 2021 Brian Carlson - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/reverse_engineering/node_modules/pg/README.md b/reverse_engineering/node_modules/pg/README.md deleted file mode 100644 index e5fcf02..0000000 --- a/reverse_engineering/node_modules/pg/README.md +++ /dev/null @@ -1,101 +0,0 @@ -# node-postgres - -[![Build Status](https://secure.travis-ci.org/brianc/node-postgres.svg?branch=master)](http://travis-ci.org/brianc/node-postgres) -[![Dependency Status](https://david-dm.org/brianc/node-postgres.svg?path=packages/pg)](https://david-dm.org/brianc/node-postgres?path=packages/pg) -NPM version -NPM downloads - -Non-blocking PostgreSQL client for Node.js. Pure JavaScript and optional native libpq bindings. - -## Install - -```sh -$ npm install pg -``` - ---- - -## :star: [Documentation](https://node-postgres.com) :star: - -### Features - -- Pure JavaScript client and native libpq bindings share _the same API_ -- Connection pooling -- Extensible JS ↔ PostgreSQL data-type coercion -- Supported PostgreSQL features - - Parameterized queries - - Named statements with query plan caching - - Async notifications with `LISTEN/NOTIFY` - - Bulk import & export with `COPY TO/COPY FROM` - -### Extras - -node-postgres is by design pretty light on abstractions. These are some handy modules we've been using over the years to complete the picture. -The entire list can be found on our [wiki](https://github.com/brianc/node-postgres/wiki/Extras). - -## Support - -node-postgres is free software. If you encounter a bug with the library please open an issue on the [GitHub repo](https://github.com/brianc/node-postgres). If you have questions unanswered by the documentation please open an issue pointing out how the documentation was unclear & I will do my best to make it better! - -When you open an issue please provide: - -- version of Node -- version of Postgres -- smallest possible snippet of code to reproduce the problem - -You can also follow me [@briancarlson](https://twitter.com/briancarlson) if that's your thing. I try to always announce noteworthy changes & developments with node-postgres on Twitter. - -## Sponsorship :two_hearts: - -node-postgres's continued development has been made possible in part by generous finanical support from [the community](https://github.com/brianc/node-postgres/blob/master/SPONSORS.md) and these featured sponsors: - -

- - - - - - - - -
- -If you or your company are benefiting from node-postgres and would like to help keep the project financially sustainable [please consider supporting](https://github.com/sponsors/brianc) its development. - -## Contributing - -**:heart: contributions!** - -I will **happily** accept your pull request if it: - -- **has tests** -- looks reasonable -- does not break backwards compatibility - -If your change involves breaking backwards compatibility please please point that out in the pull request & we can discuss & plan when and how to release it and what type of documentation or communicate it will require. - -## Troubleshooting and FAQ - -The causes and solutions to common errors can be found among the [Frequently Asked Questions (FAQ)](https://github.com/brianc/node-postgres/wiki/FAQ) - -## License - -Copyright (c) 2010-2020 Brian Carlson (brian.m.carlson@gmail.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/pg/lib/client.js b/reverse_engineering/node_modules/pg/lib/client.js deleted file mode 100644 index 589aa9f..0000000 --- a/reverse_engineering/node_modules/pg/lib/client.js +++ /dev/null @@ -1,621 +0,0 @@ -'use strict' - -var EventEmitter = require('events').EventEmitter -var util = require('util') -var utils = require('./utils') -var sasl = require('./sasl') -var pgPass = require('pgpass') -var TypeOverrides = require('./type-overrides') - -var ConnectionParameters = require('./connection-parameters') -var Query = require('./query') -var defaults = require('./defaults') -var Connection = require('./connection') - -class Client extends EventEmitter { - constructor(config) { - super() - - this.connectionParameters = new ConnectionParameters(config) - this.user = this.connectionParameters.user - this.database = this.connectionParameters.database - this.port = this.connectionParameters.port - this.host = this.connectionParameters.host - - // "hiding" the password so it doesn't show up in stack traces - // or if the client is console.logged - Object.defineProperty(this, 'password', { - configurable: true, - enumerable: false, - writable: true, - value: this.connectionParameters.password, - }) - - this.replication = this.connectionParameters.replication - - var c = config || {} - - this._Promise = c.Promise || global.Promise - this._types = new TypeOverrides(c.types) - this._ending = false - this._connecting = false - this._connected = false - this._connectionError = false - this._queryable = true - - this.connection = - c.connection || - new Connection({ - stream: c.stream, - ssl: this.connectionParameters.ssl, - keepAlive: c.keepAlive || false, - keepAliveInitialDelayMillis: c.keepAliveInitialDelayMillis || 0, - encoding: this.connectionParameters.client_encoding || 'utf8', - }) - this.queryQueue = [] - this.binary = c.binary || defaults.binary - this.processID = null - this.secretKey = null - this.ssl = this.connectionParameters.ssl || false - // As with Password, make SSL->Key (the private key) non-enumerable. - // It won't show up in stack traces - // or if the client is console.logged - if (this.ssl && this.ssl.key) { - Object.defineProperty(this.ssl, 'key', { - enumerable: false, - }) - } - - this._connectionTimeoutMillis = c.connectionTimeoutMillis || 0 - } - - _errorAllQueries(err) { - const enqueueError = (query) => { - process.nextTick(() => { - query.handleError(err, this.connection) - }) - } - - if (this.activeQuery) { - enqueueError(this.activeQuery) - this.activeQuery = null - } - - this.queryQueue.forEach(enqueueError) - this.queryQueue.length = 0 - } - - _connect(callback) { - var self = this - var con = this.connection - this._connectionCallback = callback - - if (this._connecting || this._connected) { - const err = new Error('Client has already been connected. You cannot reuse a client.') - process.nextTick(() => { - callback(err) - }) - return - } - this._connecting = true - - this.connectionTimeoutHandle - if (this._connectionTimeoutMillis > 0) { - this.connectionTimeoutHandle = setTimeout(() => { - con._ending = true - con.stream.destroy(new Error('timeout expired')) - }, this._connectionTimeoutMillis) - } - - if (this.host && this.host.indexOf('/') === 0) { - con.connect(this.host + '/.s.PGSQL.' + this.port) - } else { - con.connect(this.port, this.host) - } - - // once connection is established send startup message - con.on('connect', function () { - if (self.ssl) { - con.requestSsl() - } else { - con.startup(self.getStartupConf()) - } - }) - - con.on('sslconnect', function () { - con.startup(self.getStartupConf()) - }) - - this._attachListeners(con) - - con.once('end', () => { - const error = this._ending ? new Error('Connection terminated') : new Error('Connection terminated unexpectedly') - - clearTimeout(this.connectionTimeoutHandle) - this._errorAllQueries(error) - - if (!this._ending) { - // if the connection is ended without us calling .end() - // on this client then we have an unexpected disconnection - // treat this as an error unless we've already emitted an error - // during connection. - if (this._connecting && !this._connectionError) { - if (this._connectionCallback) { - this._connectionCallback(error) - } else { - this._handleErrorEvent(error) - } - } else if (!this._connectionError) { - this._handleErrorEvent(error) - } - } - - process.nextTick(() => { - this.emit('end') - }) - }) - } - - connect(callback) { - if (callback) { - this._connect(callback) - return - } - - return new this._Promise((resolve, reject) => { - this._connect((error) => { - if (error) { - reject(error) - } else { - resolve() - } - }) - }) - } - - _attachListeners(con) { - // password request handling - con.on('authenticationCleartextPassword', this._handleAuthCleartextPassword.bind(this)) - // password request handling - con.on('authenticationMD5Password', this._handleAuthMD5Password.bind(this)) - // password request handling (SASL) - con.on('authenticationSASL', this._handleAuthSASL.bind(this)) - con.on('authenticationSASLContinue', this._handleAuthSASLContinue.bind(this)) - con.on('authenticationSASLFinal', this._handleAuthSASLFinal.bind(this)) - con.on('backendKeyData', this._handleBackendKeyData.bind(this)) - con.on('error', this._handleErrorEvent.bind(this)) - con.on('errorMessage', this._handleErrorMessage.bind(this)) - con.on('readyForQuery', this._handleReadyForQuery.bind(this)) - con.on('notice', this._handleNotice.bind(this)) - con.on('rowDescription', this._handleRowDescription.bind(this)) - con.on('dataRow', this._handleDataRow.bind(this)) - con.on('portalSuspended', this._handlePortalSuspended.bind(this)) - con.on('emptyQuery', this._handleEmptyQuery.bind(this)) - con.on('commandComplete', this._handleCommandComplete.bind(this)) - con.on('parseComplete', this._handleParseComplete.bind(this)) - con.on('copyInResponse', this._handleCopyInResponse.bind(this)) - con.on('copyData', this._handleCopyData.bind(this)) - con.on('notification', this._handleNotification.bind(this)) - } - - // TODO(bmc): deprecate pgpass "built in" integration since this.password can be a function - // it can be supplied by the user if required - this is a breaking change! - _checkPgPass(cb) { - const con = this.connection - if (typeof this.password === 'function') { - this._Promise - .resolve() - .then(() => this.password()) - .then((pass) => { - if (pass !== undefined) { - if (typeof pass !== 'string') { - con.emit('error', new TypeError('Password must be a string')) - return - } - this.connectionParameters.password = this.password = pass - } else { - this.connectionParameters.password = this.password = null - } - cb() - }) - .catch((err) => { - con.emit('error', err) - }) - } else if (this.password !== null) { - cb() - } else { - pgPass(this.connectionParameters, (pass) => { - if (undefined !== pass) { - this.connectionParameters.password = this.password = pass - } - cb() - }) - } - } - - _handleAuthCleartextPassword(msg) { - this._checkPgPass(() => { - this.connection.password(this.password) - }) - } - - _handleAuthMD5Password(msg) { - this._checkPgPass(() => { - const hashedPassword = utils.postgresMd5PasswordHash(this.user, this.password, msg.salt) - this.connection.password(hashedPassword) - }) - } - - _handleAuthSASL(msg) { - this._checkPgPass(() => { - this.saslSession = sasl.startSession(msg.mechanisms) - this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism, this.saslSession.response) - }) - } - - _handleAuthSASLContinue(msg) { - sasl.continueSession(this.saslSession, this.password, msg.data) - this.connection.sendSCRAMClientFinalMessage(this.saslSession.response) - } - - _handleAuthSASLFinal(msg) { - sasl.finalizeSession(this.saslSession, msg.data) - this.saslSession = null - } - - _handleBackendKeyData(msg) { - this.processID = msg.processID - this.secretKey = msg.secretKey - } - - _handleReadyForQuery(msg) { - if (this._connecting) { - this._connecting = false - this._connected = true - clearTimeout(this.connectionTimeoutHandle) - - // process possible callback argument to Client#connect - if (this._connectionCallback) { - this._connectionCallback(null, this) - // remove callback for proper error handling - // after the connect event - this._connectionCallback = null - } - this.emit('connect') - } - const { activeQuery } = this - this.activeQuery = null - this.readyForQuery = true - if (activeQuery) { - activeQuery.handleReadyForQuery(this.connection) - } - this._pulseQueryQueue() - } - - // if we receieve an error event or error message - // during the connection process we handle it here - _handleErrorWhileConnecting(err) { - if (this._connectionError) { - // TODO(bmc): this is swallowing errors - we shouldn't do this - return - } - this._connectionError = true - clearTimeout(this.connectionTimeoutHandle) - if (this._connectionCallback) { - return this._connectionCallback(err) - } - this.emit('error', err) - } - - // if we're connected and we receive an error event from the connection - // this means the socket is dead - do a hard abort of all queries and emit - // the socket error on the client as well - _handleErrorEvent(err) { - if (this._connecting) { - return this._handleErrorWhileConnecting(err) - } - this._queryable = false - this._errorAllQueries(err) - this.emit('error', err) - } - - // handle error messages from the postgres backend - _handleErrorMessage(msg) { - if (this._connecting) { - return this._handleErrorWhileConnecting(msg) - } - const activeQuery = this.activeQuery - - if (!activeQuery) { - this._handleErrorEvent(msg) - return - } - - this.activeQuery = null - activeQuery.handleError(msg, this.connection) - } - - _handleRowDescription(msg) { - // delegate rowDescription to active query - this.activeQuery.handleRowDescription(msg) - } - - _handleDataRow(msg) { - // delegate dataRow to active query - this.activeQuery.handleDataRow(msg) - } - - _handlePortalSuspended(msg) { - // delegate portalSuspended to active query - this.activeQuery.handlePortalSuspended(this.connection) - } - - _handleEmptyQuery(msg) { - // delegate emptyQuery to active query - this.activeQuery.handleEmptyQuery(this.connection) - } - - _handleCommandComplete(msg) { - // delegate commandComplete to active query - this.activeQuery.handleCommandComplete(msg, this.connection) - } - - _handleParseComplete(msg) { - // if a prepared statement has a name and properly parses - // we track that its already been executed so we don't parse - // it again on the same client - if (this.activeQuery.name) { - this.connection.parsedStatements[this.activeQuery.name] = this.activeQuery.text - } - } - - _handleCopyInResponse(msg) { - this.activeQuery.handleCopyInResponse(this.connection) - } - - _handleCopyData(msg) { - this.activeQuery.handleCopyData(msg, this.connection) - } - - _handleNotification(msg) { - this.emit('notification', msg) - } - - _handleNotice(msg) { - this.emit('notice', msg) - } - - getStartupConf() { - var params = this.connectionParameters - - var data = { - user: params.user, - database: params.database, - } - - var appName = params.application_name || params.fallback_application_name - if (appName) { - data.application_name = appName - } - if (params.replication) { - data.replication = '' + params.replication - } - if (params.statement_timeout) { - data.statement_timeout = String(parseInt(params.statement_timeout, 10)) - } - if (params.idle_in_transaction_session_timeout) { - data.idle_in_transaction_session_timeout = String(parseInt(params.idle_in_transaction_session_timeout, 10)) - } - if (params.options) { - data.options = params.options - } - - return data - } - - cancel(client, query) { - if (client.activeQuery === query) { - var con = this.connection - - if (this.host && this.host.indexOf('/') === 0) { - con.connect(this.host + '/.s.PGSQL.' + this.port) - } else { - con.connect(this.port, this.host) - } - - // once connection is established send cancel message - con.on('connect', function () { - con.cancel(client.processID, client.secretKey) - }) - } else if (client.queryQueue.indexOf(query) !== -1) { - client.queryQueue.splice(client.queryQueue.indexOf(query), 1) - } - } - - setTypeParser(oid, format, parseFn) { - return this._types.setTypeParser(oid, format, parseFn) - } - - getTypeParser(oid, format) { - return this._types.getTypeParser(oid, format) - } - - // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c - escapeIdentifier(str) { - return '"' + str.replace(/"/g, '""') + '"' - } - - // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c - escapeLiteral(str) { - var hasBackslash = false - var escaped = "'" - - for (var i = 0; i < str.length; i++) { - var c = str[i] - if (c === "'") { - escaped += c + c - } else if (c === '\\') { - escaped += c + c - hasBackslash = true - } else { - escaped += c - } - } - - escaped += "'" - - if (hasBackslash === true) { - escaped = ' E' + escaped - } - - return escaped - } - - _pulseQueryQueue() { - if (this.readyForQuery === true) { - this.activeQuery = this.queryQueue.shift() - if (this.activeQuery) { - this.readyForQuery = false - this.hasExecuted = true - - const queryError = this.activeQuery.submit(this.connection) - if (queryError) { - process.nextTick(() => { - this.activeQuery.handleError(queryError, this.connection) - this.readyForQuery = true - this._pulseQueryQueue() - }) - } - } else if (this.hasExecuted) { - this.activeQuery = null - this.emit('drain') - } - } - } - - query(config, values, callback) { - // can take in strings, config object or query object - var query - var result - var readTimeout - var readTimeoutTimer - var queryCallback - - if (config === null || config === undefined) { - throw new TypeError('Client was passed a null or undefined query') - } else if (typeof config.submit === 'function') { - readTimeout = config.query_timeout || this.connectionParameters.query_timeout - result = query = config - if (typeof values === 'function') { - query.callback = query.callback || values - } - } else { - readTimeout = this.connectionParameters.query_timeout - query = new Query(config, values, callback) - if (!query.callback) { - result = new this._Promise((resolve, reject) => { - query.callback = (err, res) => (err ? reject(err) : resolve(res)) - }) - } - } - - if (readTimeout) { - queryCallback = query.callback - - readTimeoutTimer = setTimeout(() => { - var error = new Error('Query read timeout') - - process.nextTick(() => { - query.handleError(error, this.connection) - }) - - queryCallback(error) - - // we already returned an error, - // just do nothing if query completes - query.callback = () => {} - - // Remove from queue - var index = this.queryQueue.indexOf(query) - if (index > -1) { - this.queryQueue.splice(index, 1) - } - - this._pulseQueryQueue() - }, readTimeout) - - query.callback = (err, res) => { - clearTimeout(readTimeoutTimer) - queryCallback(err, res) - } - } - - if (this.binary && !query.binary) { - query.binary = true - } - - if (query._result && !query._result._types) { - query._result._types = this._types - } - - if (!this._queryable) { - process.nextTick(() => { - query.handleError(new Error('Client has encountered a connection error and is not queryable'), this.connection) - }) - return result - } - - if (this._ending) { - process.nextTick(() => { - query.handleError(new Error('Client was closed and is not queryable'), this.connection) - }) - return result - } - - this.queryQueue.push(query) - this._pulseQueryQueue() - return result - } - - ref() { - this.connection.ref() - } - - unref() { - this.connection.unref() - } - - end(cb) { - this._ending = true - - // if we have never connected, then end is a noop, callback immediately - if (!this.connection._connecting) { - if (cb) { - cb() - } else { - return this._Promise.resolve() - } - } - - if (this.activeQuery || !this._queryable) { - // if we have an active query we need to force a disconnect - // on the socket - otherwise a hung query could block end forever - this.connection.stream.destroy() - } else { - this.connection.end() - } - - if (cb) { - this.connection.once('end', cb) - } else { - return new this._Promise((resolve) => { - this.connection.once('end', resolve) - }) - } - } -} - -// expose a Query constructor -Client.Query = Query - -module.exports = Client diff --git a/reverse_engineering/node_modules/pg/lib/connection-parameters.js b/reverse_engineering/node_modules/pg/lib/connection-parameters.js deleted file mode 100644 index 165e6d5..0000000 --- a/reverse_engineering/node_modules/pg/lib/connection-parameters.js +++ /dev/null @@ -1,166 +0,0 @@ -'use strict' - -var dns = require('dns') - -var defaults = require('./defaults') - -var parse = require('pg-connection-string').parse // parses a connection string - -var val = function (key, config, envVar) { - if (envVar === undefined) { - envVar = process.env['PG' + key.toUpperCase()] - } else if (envVar === false) { - // do nothing ... use false - } else { - envVar = process.env[envVar] - } - - return config[key] || envVar || defaults[key] -} - -var readSSLConfigFromEnvironment = function () { - switch (process.env.PGSSLMODE) { - case 'disable': - return false - case 'prefer': - case 'require': - case 'verify-ca': - case 'verify-full': - return true - case 'no-verify': - return { rejectUnauthorized: false } - } - return defaults.ssl -} - -// Convert arg to a string, surround in single quotes, and escape single quotes and backslashes -var quoteParamValue = function (value) { - return "'" + ('' + value).replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'" -} - -var add = function (params, config, paramName) { - var value = config[paramName] - if (value !== undefined && value !== null) { - params.push(paramName + '=' + quoteParamValue(value)) - } -} - -class ConnectionParameters { - constructor(config) { - // if a string is passed, it is a raw connection string so we parse it into a config - config = typeof config === 'string' ? parse(config) : config || {} - - // if the config has a connectionString defined, parse IT into the config we use - // this will override other default values with what is stored in connectionString - if (config.connectionString) { - config = Object.assign({}, config, parse(config.connectionString)) - } - - this.user = val('user', config) - this.database = val('database', config) - - if (this.database === undefined) { - this.database = this.user - } - - this.port = parseInt(val('port', config), 10) - this.host = val('host', config) - - // "hiding" the password so it doesn't show up in stack traces - // or if the client is console.logged - Object.defineProperty(this, 'password', { - configurable: true, - enumerable: false, - writable: true, - value: val('password', config), - }) - - this.binary = val('binary', config) - this.options = val('options', config) - - this.ssl = typeof config.ssl === 'undefined' ? readSSLConfigFromEnvironment() : config.ssl - - if (typeof this.ssl === 'string') { - if (this.ssl === 'true') { - this.ssl = true - } - } - // support passing in ssl=no-verify via connection string - if (this.ssl === 'no-verify') { - this.ssl = { rejectUnauthorized: false } - } - if (this.ssl && this.ssl.key) { - Object.defineProperty(this.ssl, 'key', { - enumerable: false, - }) - } - - this.client_encoding = val('client_encoding', config) - this.replication = val('replication', config) - // a domain socket begins with '/' - this.isDomainSocket = !(this.host || '').indexOf('/') - - this.application_name = val('application_name', config, 'PGAPPNAME') - this.fallback_application_name = val('fallback_application_name', config, false) - this.statement_timeout = val('statement_timeout', config, false) - this.idle_in_transaction_session_timeout = val('idle_in_transaction_session_timeout', config, false) - this.query_timeout = val('query_timeout', config, false) - - if (config.connectionTimeoutMillis === undefined) { - this.connect_timeout = process.env.PGCONNECT_TIMEOUT || 0 - } else { - this.connect_timeout = Math.floor(config.connectionTimeoutMillis / 1000) - } - - if (config.keepAlive === false) { - this.keepalives = 0 - } else if (config.keepAlive === true) { - this.keepalives = 1 - } - - if (typeof config.keepAliveInitialDelayMillis === 'number') { - this.keepalives_idle = Math.floor(config.keepAliveInitialDelayMillis / 1000) - } - } - - getLibpqConnectionString(cb) { - var params = [] - add(params, this, 'user') - add(params, this, 'password') - add(params, this, 'port') - add(params, this, 'application_name') - add(params, this, 'fallback_application_name') - add(params, this, 'connect_timeout') - add(params, this, 'options') - - var ssl = typeof this.ssl === 'object' ? this.ssl : this.ssl ? { sslmode: this.ssl } : {} - add(params, ssl, 'sslmode') - add(params, ssl, 'sslca') - add(params, ssl, 'sslkey') - add(params, ssl, 'sslcert') - add(params, ssl, 'sslrootcert') - - if (this.database) { - params.push('dbname=' + quoteParamValue(this.database)) - } - if (this.replication) { - params.push('replication=' + quoteParamValue(this.replication)) - } - if (this.host) { - params.push('host=' + quoteParamValue(this.host)) - } - if (this.isDomainSocket) { - return cb(null, params.join(' ')) - } - if (this.client_encoding) { - params.push('client_encoding=' + quoteParamValue(this.client_encoding)) - } - dns.lookup(this.host, function (err, address) { - if (err) return cb(err, null) - params.push('hostaddr=' + quoteParamValue(address)) - return cb(null, params.join(' ')) - }) - } -} - -module.exports = ConnectionParameters diff --git a/reverse_engineering/node_modules/pg/lib/connection.js b/reverse_engineering/node_modules/pg/lib/connection.js deleted file mode 100644 index ebb2f09..0000000 --- a/reverse_engineering/node_modules/pg/lib/connection.js +++ /dev/null @@ -1,221 +0,0 @@ -'use strict' - -var net = require('net') -var EventEmitter = require('events').EventEmitter - -const { parse, serialize } = require('pg-protocol') - -const flushBuffer = serialize.flush() -const syncBuffer = serialize.sync() -const endBuffer = serialize.end() - -// TODO(bmc) support binary mode at some point -class Connection extends EventEmitter { - constructor(config) { - super() - config = config || {} - this.stream = config.stream || new net.Socket() - this._keepAlive = config.keepAlive - this._keepAliveInitialDelayMillis = config.keepAliveInitialDelayMillis - this.lastBuffer = false - this.parsedStatements = {} - this.ssl = config.ssl || false - this._ending = false - this._emitMessage = false - var self = this - this.on('newListener', function (eventName) { - if (eventName === 'message') { - self._emitMessage = true - } - }) - } - - connect(port, host) { - var self = this - - this._connecting = true - this.stream.setNoDelay(true) - this.stream.connect(port, host) - - this.stream.once('connect', function () { - if (self._keepAlive) { - self.stream.setKeepAlive(true, self._keepAliveInitialDelayMillis) - } - self.emit('connect') - }) - - const reportStreamError = function (error) { - // errors about disconnections should be ignored during disconnect - if (self._ending && (error.code === 'ECONNRESET' || error.code === 'EPIPE')) { - return - } - self.emit('error', error) - } - this.stream.on('error', reportStreamError) - - this.stream.on('close', function () { - self.emit('end') - }) - - if (!this.ssl) { - return this.attachListeners(this.stream) - } - - this.stream.once('data', function (buffer) { - var responseCode = buffer.toString('utf8') - switch (responseCode) { - case 'S': // Server supports SSL connections, continue with a secure connection - break - case 'N': // Server does not support SSL connections - self.stream.end() - return self.emit('error', new Error('The server does not support SSL connections')) - default: - // Any other response byte, including 'E' (ErrorResponse) indicating a server error - self.stream.end() - return self.emit('error', new Error('There was an error establishing an SSL connection')) - } - var tls = require('tls') - const options = { - socket: self.stream, - } - - if (self.ssl !== true) { - Object.assign(options, self.ssl) - - if ('key' in self.ssl) { - options.key = self.ssl.key - } - } - - if (net.isIP(host) === 0) { - options.servername = host - } - try { - self.stream = tls.connect(options) - } catch (err) { - return self.emit('error', err) - } - self.attachListeners(self.stream) - self.stream.on('error', reportStreamError) - - self.emit('sslconnect') - }) - } - - attachListeners(stream) { - stream.on('end', () => { - this.emit('end') - }) - parse(stream, (msg) => { - var eventName = msg.name === 'error' ? 'errorMessage' : msg.name - if (this._emitMessage) { - this.emit('message', msg) - } - this.emit(eventName, msg) - }) - } - - requestSsl() { - this.stream.write(serialize.requestSsl()) - } - - startup(config) { - this.stream.write(serialize.startup(config)) - } - - cancel(processID, secretKey) { - this._send(serialize.cancel(processID, secretKey)) - } - - password(password) { - this._send(serialize.password(password)) - } - - sendSASLInitialResponseMessage(mechanism, initialResponse) { - this._send(serialize.sendSASLInitialResponseMessage(mechanism, initialResponse)) - } - - sendSCRAMClientFinalMessage(additionalData) { - this._send(serialize.sendSCRAMClientFinalMessage(additionalData)) - } - - _send(buffer) { - if (!this.stream.writable) { - return false - } - return this.stream.write(buffer) - } - - query(text) { - this._send(serialize.query(text)) - } - - // send parse message - parse(query) { - this._send(serialize.parse(query)) - } - - // send bind message - bind(config) { - this._send(serialize.bind(config)) - } - - // send execute message - execute(config) { - this._send(serialize.execute(config)) - } - - flush() { - if (this.stream.writable) { - this.stream.write(flushBuffer) - } - } - - sync() { - this._ending = true - this._send(flushBuffer) - this._send(syncBuffer) - } - - ref() { - this.stream.ref() - } - - unref() { - this.stream.unref() - } - - end() { - // 0x58 = 'X' - this._ending = true - if (!this._connecting || !this.stream.writable) { - this.stream.end() - return - } - return this.stream.write(endBuffer, () => { - this.stream.end() - }) - } - - close(msg) { - this._send(serialize.close(msg)) - } - - describe(msg) { - this._send(serialize.describe(msg)) - } - - sendCopyFromChunk(chunk) { - this._send(serialize.copyData(chunk)) - } - - endCopyFrom() { - this._send(serialize.copyDone()) - } - - sendCopyFail(msg) { - this._send(serialize.copyFail(msg)) - } -} - -module.exports = Connection diff --git a/reverse_engineering/node_modules/pg/lib/defaults.js b/reverse_engineering/node_modules/pg/lib/defaults.js deleted file mode 100644 index 9384e01..0000000 --- a/reverse_engineering/node_modules/pg/lib/defaults.js +++ /dev/null @@ -1,80 +0,0 @@ -'use strict' - -module.exports = { - // database host. defaults to localhost - host: 'localhost', - - // database user's name - user: process.platform === 'win32' ? process.env.USERNAME : process.env.USER, - - // name of database to connect - database: undefined, - - // database user's password - password: null, - - // a Postgres connection string to be used instead of setting individual connection items - // NOTE: Setting this value will cause it to override any other value (such as database or user) defined - // in the defaults object. - connectionString: undefined, - - // database port - port: 5432, - - // number of rows to return at a time from a prepared statement's - // portal. 0 will return all rows at once - rows: 0, - - // binary result mode - binary: false, - - // Connection pool options - see https://github.com/brianc/node-pg-pool - - // number of connections to use in connection pool - // 0 will disable connection pooling - max: 10, - - // max milliseconds a client can go unused before it is removed - // from the pool and destroyed - idleTimeoutMillis: 30000, - - client_encoding: '', - - ssl: false, - - application_name: undefined, - - fallback_application_name: undefined, - - options: undefined, - - parseInputDatesAsUTC: false, - - // max milliseconds any query using this connection will execute for before timing out in error. - // false=unlimited - statement_timeout: false, - - // Terminate any session with an open transaction that has been idle for longer than the specified duration in milliseconds - // false=unlimited - idle_in_transaction_session_timeout: false, - - // max milliseconds to wait for query to complete (client side) - query_timeout: false, - - connect_timeout: 0, - - keepalives: 1, - - keepalives_idle: 0, -} - -var pgTypes = require('pg-types') -// save default parsers -var parseBigInteger = pgTypes.getTypeParser(20, 'text') -var parseBigIntegerArray = pgTypes.getTypeParser(1016, 'text') - -// parse int8 so you can get your count values as actual numbers -module.exports.__defineSetter__('parseInt8', function (val) { - pgTypes.setTypeParser(20, 'text', val ? pgTypes.getTypeParser(23, 'text') : parseBigInteger) - pgTypes.setTypeParser(1016, 'text', val ? pgTypes.getTypeParser(1007, 'text') : parseBigIntegerArray) -}) diff --git a/reverse_engineering/node_modules/pg/lib/index.js b/reverse_engineering/node_modules/pg/lib/index.js deleted file mode 100644 index 7f02aba..0000000 --- a/reverse_engineering/node_modules/pg/lib/index.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict' - -var Client = require('./client') -var defaults = require('./defaults') -var Connection = require('./connection') -var Pool = require('pg-pool') -const { DatabaseError } = require('pg-protocol') - -const poolFactory = (Client) => { - return class BoundPool extends Pool { - constructor(options) { - super(options, Client) - } - } -} - -var PG = function (clientConstructor) { - this.defaults = defaults - this.Client = clientConstructor - this.Query = this.Client.Query - this.Pool = poolFactory(this.Client) - this._pools = [] - this.Connection = Connection - this.types = require('pg-types') - this.DatabaseError = DatabaseError -} - -if (typeof process.env.NODE_PG_FORCE_NATIVE !== 'undefined') { - module.exports = new PG(require('./native')) -} else { - module.exports = new PG(Client) - - // lazy require native module...the native module may not have installed - Object.defineProperty(module.exports, 'native', { - configurable: true, - enumerable: false, - get() { - var native = null - try { - native = new PG(require('./native')) - } catch (err) { - if (err.code !== 'MODULE_NOT_FOUND') { - throw err - } - } - - // overwrite module.exports.native so that getter is never called again - Object.defineProperty(module.exports, 'native', { - value: native, - }) - - return native - }, - }) -} diff --git a/reverse_engineering/node_modules/pg/lib/native/client.js b/reverse_engineering/node_modules/pg/lib/native/client.js deleted file mode 100644 index d1faeb3..0000000 --- a/reverse_engineering/node_modules/pg/lib/native/client.js +++ /dev/null @@ -1,297 +0,0 @@ -'use strict' - -// eslint-disable-next-line -var Native = require('pg-native') -var TypeOverrides = require('../type-overrides') -var pkg = require('../../package.json') -var EventEmitter = require('events').EventEmitter -var util = require('util') -var ConnectionParameters = require('../connection-parameters') - -var NativeQuery = require('./query') - -var Client = (module.exports = function (config) { - EventEmitter.call(this) - config = config || {} - - this._Promise = config.Promise || global.Promise - this._types = new TypeOverrides(config.types) - - this.native = new Native({ - types: this._types, - }) - - this._queryQueue = [] - this._ending = false - this._connecting = false - this._connected = false - this._queryable = true - - // keep these on the object for legacy reasons - // for the time being. TODO: deprecate all this jazz - var cp = (this.connectionParameters = new ConnectionParameters(config)) - this.user = cp.user - - // "hiding" the password so it doesn't show up in stack traces - // or if the client is console.logged - Object.defineProperty(this, 'password', { - configurable: true, - enumerable: false, - writable: true, - value: cp.password, - }) - this.database = cp.database - this.host = cp.host - this.port = cp.port - - // a hash to hold named queries - this.namedQueries = {} -}) - -Client.Query = NativeQuery - -util.inherits(Client, EventEmitter) - -Client.prototype._errorAllQueries = function (err) { - const enqueueError = (query) => { - process.nextTick(() => { - query.native = this.native - query.handleError(err) - }) - } - - if (this._hasActiveQuery()) { - enqueueError(this._activeQuery) - this._activeQuery = null - } - - this._queryQueue.forEach(enqueueError) - this._queryQueue.length = 0 -} - -// connect to the backend -// pass an optional callback to be called once connected -// or with an error if there was a connection error -Client.prototype._connect = function (cb) { - var self = this - - if (this._connecting) { - process.nextTick(() => cb(new Error('Client has already been connected. You cannot reuse a client.'))) - return - } - - this._connecting = true - - this.connectionParameters.getLibpqConnectionString(function (err, conString) { - if (err) return cb(err) - self.native.connect(conString, function (err) { - if (err) { - self.native.end() - return cb(err) - } - - // set internal states to connected - self._connected = true - - // handle connection errors from the native layer - self.native.on('error', function (err) { - self._queryable = false - self._errorAllQueries(err) - self.emit('error', err) - }) - - self.native.on('notification', function (msg) { - self.emit('notification', { - channel: msg.relname, - payload: msg.extra, - }) - }) - - // signal we are connected now - self.emit('connect') - self._pulseQueryQueue(true) - - cb() - }) - }) -} - -Client.prototype.connect = function (callback) { - if (callback) { - this._connect(callback) - return - } - - return new this._Promise((resolve, reject) => { - this._connect((error) => { - if (error) { - reject(error) - } else { - resolve() - } - }) - }) -} - -// send a query to the server -// this method is highly overloaded to take -// 1) string query, optional array of parameters, optional function callback -// 2) object query with { -// string query -// optional array values, -// optional function callback instead of as a separate parameter -// optional string name to name & cache the query plan -// optional string rowMode = 'array' for an array of results -// } -Client.prototype.query = function (config, values, callback) { - var query - var result - var readTimeout - var readTimeoutTimer - var queryCallback - - if (config === null || config === undefined) { - throw new TypeError('Client was passed a null or undefined query') - } else if (typeof config.submit === 'function') { - readTimeout = config.query_timeout || this.connectionParameters.query_timeout - result = query = config - // accept query(new Query(...), (err, res) => { }) style - if (typeof values === 'function') { - config.callback = values - } - } else { - readTimeout = this.connectionParameters.query_timeout - query = new NativeQuery(config, values, callback) - if (!query.callback) { - let resolveOut, rejectOut - result = new this._Promise((resolve, reject) => { - resolveOut = resolve - rejectOut = reject - }) - query.callback = (err, res) => (err ? rejectOut(err) : resolveOut(res)) - } - } - - if (readTimeout) { - queryCallback = query.callback - - readTimeoutTimer = setTimeout(() => { - var error = new Error('Query read timeout') - - process.nextTick(() => { - query.handleError(error, this.connection) - }) - - queryCallback(error) - - // we already returned an error, - // just do nothing if query completes - query.callback = () => {} - - // Remove from queue - var index = this._queryQueue.indexOf(query) - if (index > -1) { - this._queryQueue.splice(index, 1) - } - - this._pulseQueryQueue() - }, readTimeout) - - query.callback = (err, res) => { - clearTimeout(readTimeoutTimer) - queryCallback(err, res) - } - } - - if (!this._queryable) { - query.native = this.native - process.nextTick(() => { - query.handleError(new Error('Client has encountered a connection error and is not queryable')) - }) - return result - } - - if (this._ending) { - query.native = this.native - process.nextTick(() => { - query.handleError(new Error('Client was closed and is not queryable')) - }) - return result - } - - this._queryQueue.push(query) - this._pulseQueryQueue() - return result -} - -// disconnect from the backend server -Client.prototype.end = function (cb) { - var self = this - - this._ending = true - - if (!this._connected) { - this.once('connect', this.end.bind(this, cb)) - } - var result - if (!cb) { - result = new this._Promise(function (resolve, reject) { - cb = (err) => (err ? reject(err) : resolve()) - }) - } - this.native.end(function () { - self._errorAllQueries(new Error('Connection terminated')) - - process.nextTick(() => { - self.emit('end') - if (cb) cb() - }) - }) - return result -} - -Client.prototype._hasActiveQuery = function () { - return this._activeQuery && this._activeQuery.state !== 'error' && this._activeQuery.state !== 'end' -} - -Client.prototype._pulseQueryQueue = function (initialConnection) { - if (!this._connected) { - return - } - if (this._hasActiveQuery()) { - return - } - var query = this._queryQueue.shift() - if (!query) { - if (!initialConnection) { - this.emit('drain') - } - return - } - this._activeQuery = query - query.submit(this) - var self = this - query.once('_done', function () { - self._pulseQueryQueue() - }) -} - -// attempt to cancel an in-progress query -Client.prototype.cancel = function (query) { - if (this._activeQuery === query) { - this.native.cancel(function () {}) - } else if (this._queryQueue.indexOf(query) !== -1) { - this._queryQueue.splice(this._queryQueue.indexOf(query), 1) - } -} - -Client.prototype.ref = function () {} -Client.prototype.unref = function () {} - -Client.prototype.setTypeParser = function (oid, format, parseFn) { - return this._types.setTypeParser(oid, format, parseFn) -} - -Client.prototype.getTypeParser = function (oid, format) { - return this._types.getTypeParser(oid, format) -} diff --git a/reverse_engineering/node_modules/pg/lib/native/index.js b/reverse_engineering/node_modules/pg/lib/native/index.js deleted file mode 100644 index eead422..0000000 --- a/reverse_engineering/node_modules/pg/lib/native/index.js +++ /dev/null @@ -1,2 +0,0 @@ -'use strict' -module.exports = require('./client') diff --git a/reverse_engineering/node_modules/pg/lib/native/query.js b/reverse_engineering/node_modules/pg/lib/native/query.js deleted file mode 100644 index d06db43..0000000 --- a/reverse_engineering/node_modules/pg/lib/native/query.js +++ /dev/null @@ -1,165 +0,0 @@ -'use strict' - -var EventEmitter = require('events').EventEmitter -var util = require('util') -var utils = require('../utils') - -var NativeQuery = (module.exports = function (config, values, callback) { - EventEmitter.call(this) - config = utils.normalizeQueryConfig(config, values, callback) - this.text = config.text - this.values = config.values - this.name = config.name - this.callback = config.callback - this.state = 'new' - this._arrayMode = config.rowMode === 'array' - - // if the 'row' event is listened for - // then emit them as they come in - // without setting singleRowMode to true - // this has almost no meaning because libpq - // reads all rows into memory befor returning any - this._emitRowEvents = false - this.on( - 'newListener', - function (event) { - if (event === 'row') this._emitRowEvents = true - }.bind(this) - ) -}) - -util.inherits(NativeQuery, EventEmitter) - -var errorFieldMap = { - /* eslint-disable quote-props */ - sqlState: 'code', - statementPosition: 'position', - messagePrimary: 'message', - context: 'where', - schemaName: 'schema', - tableName: 'table', - columnName: 'column', - dataTypeName: 'dataType', - constraintName: 'constraint', - sourceFile: 'file', - sourceLine: 'line', - sourceFunction: 'routine', -} - -NativeQuery.prototype.handleError = function (err) { - // copy pq error fields into the error object - var fields = this.native.pq.resultErrorFields() - if (fields) { - for (var key in fields) { - var normalizedFieldName = errorFieldMap[key] || key - err[normalizedFieldName] = fields[key] - } - } - if (this.callback) { - this.callback(err) - } else { - this.emit('error', err) - } - this.state = 'error' -} - -NativeQuery.prototype.then = function (onSuccess, onFailure) { - return this._getPromise().then(onSuccess, onFailure) -} - -NativeQuery.prototype.catch = function (callback) { - return this._getPromise().catch(callback) -} - -NativeQuery.prototype._getPromise = function () { - if (this._promise) return this._promise - this._promise = new Promise( - function (resolve, reject) { - this._once('end', resolve) - this._once('error', reject) - }.bind(this) - ) - return this._promise -} - -NativeQuery.prototype.submit = function (client) { - this.state = 'running' - var self = this - this.native = client.native - client.native.arrayMode = this._arrayMode - - var after = function (err, rows, results) { - client.native.arrayMode = false - setImmediate(function () { - self.emit('_done') - }) - - // handle possible query error - if (err) { - return self.handleError(err) - } - - // emit row events for each row in the result - if (self._emitRowEvents) { - if (results.length > 1) { - rows.forEach((rowOfRows, i) => { - rowOfRows.forEach((row) => { - self.emit('row', row, results[i]) - }) - }) - } else { - rows.forEach(function (row) { - self.emit('row', row, results) - }) - } - } - - // handle successful result - self.state = 'end' - self.emit('end', results) - if (self.callback) { - self.callback(null, results) - } - } - - if (process.domain) { - after = process.domain.bind(after) - } - - // named query - if (this.name) { - if (this.name.length > 63) { - /* eslint-disable no-console */ - console.error('Warning! Postgres only supports 63 characters for query names.') - console.error('You supplied %s (%s)', this.name, this.name.length) - console.error('This can cause conflicts and silent errors executing queries') - /* eslint-enable no-console */ - } - var values = (this.values || []).map(utils.prepareValue) - - // check if the client has already executed this named query - // if so...just execute it again - skip the planning phase - if (client.namedQueries[this.name]) { - if (this.text && client.namedQueries[this.name] !== this.text) { - const err = new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`) - return after(err) - } - return client.native.execute(this.name, values, after) - } - // plan the named query the first time, then execute it - return client.native.prepare(this.name, this.text, values.length, function (err) { - if (err) return after(err) - client.namedQueries[self.name] = self.text - return self.native.execute(self.name, values, after) - }) - } else if (this.values) { - if (!Array.isArray(this.values)) { - const err = new Error('Query values must be an array') - return after(err) - } - var vals = this.values.map(utils.prepareValue) - client.native.query(this.text, vals, after) - } else { - client.native.query(this.text, after) - } -} diff --git a/reverse_engineering/node_modules/pg/lib/query.js b/reverse_engineering/node_modules/pg/lib/query.js deleted file mode 100644 index c0dfedd..0000000 --- a/reverse_engineering/node_modules/pg/lib/query.js +++ /dev/null @@ -1,234 +0,0 @@ -'use strict' - -const { EventEmitter } = require('events') - -const Result = require('./result') -const utils = require('./utils') - -class Query extends EventEmitter { - constructor(config, values, callback) { - super() - - config = utils.normalizeQueryConfig(config, values, callback) - - this.text = config.text - this.values = config.values - this.rows = config.rows - this.types = config.types - this.name = config.name - this.binary = config.binary - // use unique portal name each time - this.portal = config.portal || '' - this.callback = config.callback - this._rowMode = config.rowMode - if (process.domain && config.callback) { - this.callback = process.domain.bind(config.callback) - } - this._result = new Result(this._rowMode, this.types) - - // potential for multiple results - this._results = this._result - this.isPreparedStatement = false - this._canceledDueToError = false - this._promise = null - } - - requiresPreparation() { - // named queries must always be prepared - if (this.name) { - return true - } - // always prepare if there are max number of rows expected per - // portal execution - if (this.rows) { - return true - } - // don't prepare empty text queries - if (!this.text) { - return false - } - // prepare if there are values - if (!this.values) { - return false - } - return this.values.length > 0 - } - - _checkForMultirow() { - // if we already have a result with a command property - // then we've already executed one query in a multi-statement simple query - // turn our results into an array of results - if (this._result.command) { - if (!Array.isArray(this._results)) { - this._results = [this._result] - } - this._result = new Result(this._rowMode, this.types) - this._results.push(this._result) - } - } - - // associates row metadata from the supplied - // message with this query object - // metadata used when parsing row results - handleRowDescription(msg) { - this._checkForMultirow() - this._result.addFields(msg.fields) - this._accumulateRows = this.callback || !this.listeners('row').length - } - - handleDataRow(msg) { - let row - - if (this._canceledDueToError) { - return - } - - try { - row = this._result.parseRow(msg.fields) - } catch (err) { - this._canceledDueToError = err - return - } - - this.emit('row', row, this._result) - if (this._accumulateRows) { - this._result.addRow(row) - } - } - - handleCommandComplete(msg, connection) { - this._checkForMultirow() - this._result.addCommandComplete(msg) - // need to sync after each command complete of a prepared statement - // if we were using a row count which results in multiple calls to _getRows - if (this.rows) { - connection.sync() - } - } - - // if a named prepared statement is created with empty query text - // the backend will send an emptyQuery message but *not* a command complete message - // since we pipeline sync immediately after execute we don't need to do anything here - // unless we have rows specified, in which case we did not pipeline the intial sync call - handleEmptyQuery(connection) { - if (this.rows) { - connection.sync() - } - } - - handleError(err, connection) { - // need to sync after error during a prepared statement - if (this._canceledDueToError) { - err = this._canceledDueToError - this._canceledDueToError = false - } - // if callback supplied do not emit error event as uncaught error - // events will bubble up to node process - if (this.callback) { - return this.callback(err) - } - this.emit('error', err) - } - - handleReadyForQuery(con) { - if (this._canceledDueToError) { - return this.handleError(this._canceledDueToError, con) - } - if (this.callback) { - this.callback(null, this._results) - } - this.emit('end', this._results) - } - - submit(connection) { - if (typeof this.text !== 'string' && typeof this.name !== 'string') { - return new Error('A query must have either text or a name. Supplying neither is unsupported.') - } - const previous = connection.parsedStatements[this.name] - if (this.text && previous && this.text !== previous) { - return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`) - } - if (this.values && !Array.isArray(this.values)) { - return new Error('Query values must be an array') - } - if (this.requiresPreparation()) { - this.prepare(connection) - } else { - connection.query(this.text) - } - return null - } - - hasBeenParsed(connection) { - return this.name && connection.parsedStatements[this.name] - } - - handlePortalSuspended(connection) { - this._getRows(connection, this.rows) - } - - _getRows(connection, rows) { - connection.execute({ - portal: this.portal, - rows: rows, - }) - // if we're not reading pages of rows send the sync command - // to indicate the pipeline is finished - if (!rows) { - connection.sync() - } else { - // otherwise flush the call out to read more rows - connection.flush() - } - } - - // http://developer.postgresql.org/pgdocs/postgres/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY - prepare(connection) { - // prepared statements need sync to be called after each command - // complete or when an error is encountered - this.isPreparedStatement = true - - // TODO refactor this poor encapsulation - if (!this.hasBeenParsed(connection)) { - connection.parse({ - text: this.text, - name: this.name, - types: this.types, - }) - } - - // because we're mapping user supplied values to - // postgres wire protocol compatible values it could - // throw an exception, so try/catch this section - try { - connection.bind({ - portal: this.portal, - statement: this.name, - values: this.values, - binary: this.binary, - valueMapper: utils.prepareValue, - }) - } catch (err) { - this.handleError(err, connection) - return - } - - connection.describe({ - type: 'P', - name: this.portal || '', - }) - - this._getRows(connection, this.rows) - } - - handleCopyInResponse(connection) { - connection.sendCopyFail('No source stream defined') - } - - // eslint-disable-next-line no-unused-vars - handleCopyData(msg, connection) { - // noop - } -} - -module.exports = Query diff --git a/reverse_engineering/node_modules/pg/lib/result.js b/reverse_engineering/node_modules/pg/lib/result.js deleted file mode 100644 index 3506097..0000000 --- a/reverse_engineering/node_modules/pg/lib/result.js +++ /dev/null @@ -1,100 +0,0 @@ -'use strict' - -var types = require('pg-types') - -var matchRegexp = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/ - -// result object returned from query -// in the 'end' event and also -// passed as second argument to provided callback -class Result { - constructor(rowMode, types) { - this.command = null - this.rowCount = null - this.oid = null - this.rows = [] - this.fields = [] - this._parsers = undefined - this._types = types - this.RowCtor = null - this.rowAsArray = rowMode === 'array' - if (this.rowAsArray) { - this.parseRow = this._parseRowAsArray - } - } - - // adds a command complete message - addCommandComplete(msg) { - var match - if (msg.text) { - // pure javascript - match = matchRegexp.exec(msg.text) - } else { - // native bindings - match = matchRegexp.exec(msg.command) - } - if (match) { - this.command = match[1] - if (match[3]) { - // COMMMAND OID ROWS - this.oid = parseInt(match[2], 10) - this.rowCount = parseInt(match[3], 10) - } else if (match[2]) { - // COMMAND ROWS - this.rowCount = parseInt(match[2], 10) - } - } - } - - _parseRowAsArray(rowData) { - var row = new Array(rowData.length) - for (var i = 0, len = rowData.length; i < len; i++) { - var rawValue = rowData[i] - if (rawValue !== null) { - row[i] = this._parsers[i](rawValue) - } else { - row[i] = null - } - } - return row - } - - parseRow(rowData) { - var row = {} - for (var i = 0, len = rowData.length; i < len; i++) { - var rawValue = rowData[i] - var field = this.fields[i].name - if (rawValue !== null) { - row[field] = this._parsers[i](rawValue) - } else { - row[field] = null - } - } - return row - } - - addRow(row) { - this.rows.push(row) - } - - addFields(fieldDescriptions) { - // clears field definitions - // multiple query statements in 1 action can result in multiple sets - // of rowDescriptions...eg: 'select NOW(); select 1::int;' - // you need to reset the fields - this.fields = fieldDescriptions - if (this.fields.length) { - this._parsers = new Array(fieldDescriptions.length) - } - for (var i = 0; i < fieldDescriptions.length; i++) { - var desc = fieldDescriptions[i] - if (this._types) { - this._parsers[i] = this._types.getTypeParser(desc.dataTypeID, desc.format || 'text') - } else { - this._parsers[i] = types.getTypeParser(desc.dataTypeID, desc.format || 'text') - } - } - } -} - -module.exports = Result diff --git a/reverse_engineering/node_modules/pg/lib/sasl.js b/reverse_engineering/node_modules/pg/lib/sasl.js deleted file mode 100644 index c618047..0000000 --- a/reverse_engineering/node_modules/pg/lib/sasl.js +++ /dev/null @@ -1,209 +0,0 @@ -'use strict' -const crypto = require('crypto') - -function startSession(mechanisms) { - if (mechanisms.indexOf('SCRAM-SHA-256') === -1) { - throw new Error('SASL: Only mechanism SCRAM-SHA-256 is currently supported') - } - - const clientNonce = crypto.randomBytes(18).toString('base64') - - return { - mechanism: 'SCRAM-SHA-256', - clientNonce, - response: 'n,,n=*,r=' + clientNonce, - message: 'SASLInitialResponse', - } -} - -function continueSession(session, password, serverData) { - if (session.message !== 'SASLInitialResponse') { - throw new Error('SASL: Last message was not SASLInitialResponse') - } - if (typeof password !== 'string') { - throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string') - } - if (typeof serverData !== 'string') { - throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string') - } - - const sv = parseServerFirstMessage(serverData) - - if (!sv.nonce.startsWith(session.clientNonce)) { - throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce') - } else if (sv.nonce.length === session.clientNonce.length) { - throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short') - } - - var saltBytes = Buffer.from(sv.salt, 'base64') - - var saltedPassword = Hi(password, saltBytes, sv.iteration) - - var clientKey = hmacSha256(saltedPassword, 'Client Key') - var storedKey = sha256(clientKey) - - var clientFirstMessageBare = 'n=*,r=' + session.clientNonce - var serverFirstMessage = 'r=' + sv.nonce + ',s=' + sv.salt + ',i=' + sv.iteration - - var clientFinalMessageWithoutProof = 'c=biws,r=' + sv.nonce - - var authMessage = clientFirstMessageBare + ',' + serverFirstMessage + ',' + clientFinalMessageWithoutProof - - var clientSignature = hmacSha256(storedKey, authMessage) - var clientProofBytes = xorBuffers(clientKey, clientSignature) - var clientProof = clientProofBytes.toString('base64') - - var serverKey = hmacSha256(saltedPassword, 'Server Key') - var serverSignatureBytes = hmacSha256(serverKey, authMessage) - - session.message = 'SASLResponse' - session.serverSignature = serverSignatureBytes.toString('base64') - session.response = clientFinalMessageWithoutProof + ',p=' + clientProof -} - -function finalizeSession(session, serverData) { - if (session.message !== 'SASLResponse') { - throw new Error('SASL: Last message was not SASLResponse') - } - if (typeof serverData !== 'string') { - throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string') - } - - const { serverSignature } = parseServerFinalMessage(serverData) - - if (serverSignature !== session.serverSignature) { - throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match') - } -} - -/** - * printable = %x21-2B / %x2D-7E - * ;; Printable ASCII except ",". - * ;; Note that any "printable" is also - * ;; a valid "value". - */ -function isPrintableChars(text) { - if (typeof text !== 'string') { - throw new TypeError('SASL: text must be a string') - } - return text - .split('') - .map((_, i) => text.charCodeAt(i)) - .every((c) => (c >= 0x21 && c <= 0x2b) || (c >= 0x2d && c <= 0x7e)) -} - -/** - * base64-char = ALPHA / DIGIT / "/" / "+" - * - * base64-4 = 4base64-char - * - * base64-3 = 3base64-char "=" - * - * base64-2 = 2base64-char "==" - * - * base64 = *base64-4 [base64-3 / base64-2] - */ -function isBase64(text) { - return /^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(text) -} - -function parseAttributePairs(text) { - if (typeof text !== 'string') { - throw new TypeError('SASL: attribute pairs text must be a string') - } - - return new Map( - text.split(',').map((attrValue) => { - if (!/^.=/.test(attrValue)) { - throw new Error('SASL: Invalid attribute pair entry') - } - const name = attrValue[0] - const value = attrValue.substring(2) - return [name, value] - }) - ) -} - -function parseServerFirstMessage(data) { - const attrPairs = parseAttributePairs(data) - - const nonce = attrPairs.get('r') - if (!nonce) { - throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing') - } else if (!isPrintableChars(nonce)) { - throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters') - } - const salt = attrPairs.get('s') - if (!salt) { - throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing') - } else if (!isBase64(salt)) { - throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64') - } - const iterationText = attrPairs.get('i') - if (!iterationText) { - throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing') - } else if (!/^[1-9][0-9]*$/.test(iterationText)) { - throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count') - } - const iteration = parseInt(iterationText, 10) - - return { - nonce, - salt, - iteration, - } -} - -function parseServerFinalMessage(serverData) { - const attrPairs = parseAttributePairs(serverData) - const serverSignature = attrPairs.get('v') - if (!serverSignature) { - throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing') - } else if (!isBase64(serverSignature)) { - throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64') - } - return { - serverSignature, - } -} - -function xorBuffers(a, b) { - if (!Buffer.isBuffer(a)) { - throw new TypeError('first argument must be a Buffer') - } - if (!Buffer.isBuffer(b)) { - throw new TypeError('second argument must be a Buffer') - } - if (a.length !== b.length) { - throw new Error('Buffer lengths must match') - } - if (a.length === 0) { - throw new Error('Buffers cannot be empty') - } - return Buffer.from(a.map((_, i) => a[i] ^ b[i])) -} - -function sha256(text) { - return crypto.createHash('sha256').update(text).digest() -} - -function hmacSha256(key, msg) { - return crypto.createHmac('sha256', key).update(msg).digest() -} - -function Hi(password, saltBytes, iterations) { - var ui1 = hmacSha256(password, Buffer.concat([saltBytes, Buffer.from([0, 0, 0, 1])])) - var ui = ui1 - for (var i = 0; i < iterations - 1; i++) { - ui1 = hmacSha256(password, ui1) - ui = xorBuffers(ui, ui1) - } - - return ui -} - -module.exports = { - startSession, - continueSession, - finalizeSession, -} diff --git a/reverse_engineering/node_modules/pg/lib/type-overrides.js b/reverse_engineering/node_modules/pg/lib/type-overrides.js deleted file mode 100644 index 6669348..0000000 --- a/reverse_engineering/node_modules/pg/lib/type-overrides.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict' - -var types = require('pg-types') - -function TypeOverrides(userTypes) { - this._types = userTypes || types - this.text = {} - this.binary = {} -} - -TypeOverrides.prototype.getOverrides = function (format) { - switch (format) { - case 'text': - return this.text - case 'binary': - return this.binary - default: - return {} - } -} - -TypeOverrides.prototype.setTypeParser = function (oid, format, parseFn) { - if (typeof format === 'function') { - parseFn = format - format = 'text' - } - this.getOverrides(format)[oid] = parseFn -} - -TypeOverrides.prototype.getTypeParser = function (oid, format) { - format = format || 'text' - return this.getOverrides(format)[oid] || this._types.getTypeParser(oid, format) -} - -module.exports = TypeOverrides diff --git a/reverse_engineering/node_modules/pg/lib/utils.js b/reverse_engineering/node_modules/pg/lib/utils.js deleted file mode 100644 index d63fe68..0000000 --- a/reverse_engineering/node_modules/pg/lib/utils.js +++ /dev/null @@ -1,187 +0,0 @@ -'use strict' - -const crypto = require('crypto') - -const defaults = require('./defaults') - -function escapeElement(elementRepresentation) { - var escaped = elementRepresentation.replace(/\\/g, '\\\\').replace(/"/g, '\\"') - - return '"' + escaped + '"' -} - -// convert a JS array to a postgres array literal -// uses comma separator so won't work for types like box that use -// a different array separator. -function arrayString(val) { - var result = '{' - for (var i = 0; i < val.length; i++) { - if (i > 0) { - result = result + ',' - } - if (val[i] === null || typeof val[i] === 'undefined') { - result = result + 'NULL' - } else if (Array.isArray(val[i])) { - result = result + arrayString(val[i]) - } else if (val[i] instanceof Buffer) { - result += '\\\\x' + val[i].toString('hex') - } else { - result += escapeElement(prepareValue(val[i])) - } - } - result = result + '}' - return result -} - -// converts values from javascript types -// to their 'raw' counterparts for use as a postgres parameter -// note: you can override this function to provide your own conversion mechanism -// for complex types, etc... -var prepareValue = function (val, seen) { - // null and undefined are both null for postgres - if (val == null) { - return null - } - if (val instanceof Buffer) { - return val - } - if (ArrayBuffer.isView(val)) { - var buf = Buffer.from(val.buffer, val.byteOffset, val.byteLength) - if (buf.length === val.byteLength) { - return buf - } - return buf.slice(val.byteOffset, val.byteOffset + val.byteLength) // Node.js v4 does not support those Buffer.from params - } - if (val instanceof Date) { - if (defaults.parseInputDatesAsUTC) { - return dateToStringUTC(val) - } else { - return dateToString(val) - } - } - if (Array.isArray(val)) { - return arrayString(val) - } - if (typeof val === 'object') { - return prepareObject(val, seen) - } - return val.toString() -} - -function prepareObject(val, seen) { - if (val && typeof val.toPostgres === 'function') { - seen = seen || [] - if (seen.indexOf(val) !== -1) { - throw new Error('circular reference detected while preparing "' + val + '" for query') - } - seen.push(val) - - return prepareValue(val.toPostgres(prepareValue), seen) - } - return JSON.stringify(val) -} - -function pad(number, digits) { - number = '' + number - while (number.length < digits) { - number = '0' + number - } - return number -} - -function dateToString(date) { - var offset = -date.getTimezoneOffset() - - var year = date.getFullYear() - var isBCYear = year < 1 - if (isBCYear) year = Math.abs(year) + 1 // negative years are 1 off their BC representation - - var ret = - pad(year, 4) + - '-' + - pad(date.getMonth() + 1, 2) + - '-' + - pad(date.getDate(), 2) + - 'T' + - pad(date.getHours(), 2) + - ':' + - pad(date.getMinutes(), 2) + - ':' + - pad(date.getSeconds(), 2) + - '.' + - pad(date.getMilliseconds(), 3) - - if (offset < 0) { - ret += '-' - offset *= -1 - } else { - ret += '+' - } - - ret += pad(Math.floor(offset / 60), 2) + ':' + pad(offset % 60, 2) - if (isBCYear) ret += ' BC' - return ret -} - -function dateToStringUTC(date) { - var year = date.getUTCFullYear() - var isBCYear = year < 1 - if (isBCYear) year = Math.abs(year) + 1 // negative years are 1 off their BC representation - - var ret = - pad(year, 4) + - '-' + - pad(date.getUTCMonth() + 1, 2) + - '-' + - pad(date.getUTCDate(), 2) + - 'T' + - pad(date.getUTCHours(), 2) + - ':' + - pad(date.getUTCMinutes(), 2) + - ':' + - pad(date.getUTCSeconds(), 2) + - '.' + - pad(date.getUTCMilliseconds(), 3) - - ret += '+00:00' - if (isBCYear) ret += ' BC' - return ret -} - -function normalizeQueryConfig(config, values, callback) { - // can take in strings or config objects - config = typeof config === 'string' ? { text: config } : config - if (values) { - if (typeof values === 'function') { - config.callback = values - } else { - config.values = values - } - } - if (callback) { - config.callback = callback - } - return config -} - -const md5 = function (string) { - return crypto.createHash('md5').update(string, 'utf-8').digest('hex') -} - -// See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html -const postgresMd5PasswordHash = function (user, password, salt) { - var inner = md5(password + user) - var outer = md5(Buffer.concat([Buffer.from(inner), salt])) - return 'md5' + outer -} - -module.exports = { - prepareValue: function prepareValueWrapper(value) { - // this ensures that extra arguments do not get passed into prepareValue - // by accident, eg: from calling values.map(utils.prepareValue) - return prepareValue(value) - }, - normalizeQueryConfig, - postgresMd5PasswordHash, - md5, -} diff --git a/reverse_engineering/node_modules/pg/package.json b/reverse_engineering/node_modules/pg/package.json deleted file mode 100644 index 634e494..0000000 --- a/reverse_engineering/node_modules/pg/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "_from": "pg@^8.7.1", - "_id": "pg@8.7.1", - "_inBundle": false, - "_integrity": "sha512-7bdYcv7V6U3KAtWjpQJJBww0UEsWuh4yQ/EjNf2HeO/NnvKjpvhEIe/A/TleP6wtmSKnUnghs5A9jUoK6iDdkA==", - "_location": "/pg", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "pg@^8.7.1", - "name": "pg", - "escapedName": "pg", - "rawSpec": "^8.7.1", - "saveSpec": null, - "fetchSpec": "^8.7.1" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmjs.org/pg/-/pg-8.7.1.tgz", - "_shasum": "9ea9d1ec225980c36f94e181d009ab9f4ce4c471", - "_spec": "pg@^8.7.1", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering", - "author": { - "name": "Brian Carlson", - "email": "brian.m.carlson@gmail.com" - }, - "bugs": { - "url": "https://github.com/brianc/node-postgres/issues" - }, - "bundleDependencies": false, - "dependencies": { - "buffer-writer": "2.0.0", - "packet-reader": "1.0.0", - "pg-connection-string": "^2.5.0", - "pg-pool": "^3.4.1", - "pg-protocol": "^1.5.0", - "pg-types": "^2.1.0", - "pgpass": "1.x" - }, - "deprecated": false, - "description": "PostgreSQL client - pure javascript & libpq with the same API", - "devDependencies": { - "async": "0.9.0", - "bluebird": "3.5.2", - "co": "4.6.0", - "pg-copy-streams": "0.3.0" - }, - "engines": { - "node": ">= 8.0.0" - }, - "files": [ - "lib", - "SPONSORS.md" - ], - "gitHead": "92b4d37926c276d343bfe56447ff6f526af757cf", - "homepage": "https://github.com/brianc/node-postgres", - "keywords": [ - "database", - "libpq", - "pg", - "postgre", - "postgres", - "postgresql", - "rdbms" - ], - "license": "MIT", - "main": "./lib", - "name": "pg", - "peerDependencies": { - "pg-native": ">=2.0.0" - }, - "peerDependenciesMeta": { - "pg-native": { - "optional": true - } - }, - "repository": { - "type": "git", - "url": "git://github.com/brianc/node-postgres.git", - "directory": "packages/pg" - }, - "scripts": { - "test": "make test-all" - }, - "version": "8.7.1" -} diff --git a/reverse_engineering/node_modules/pgpass/README.md b/reverse_engineering/node_modules/pgpass/README.md deleted file mode 100644 index bbc5193..0000000 --- a/reverse_engineering/node_modules/pgpass/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# pgpass - -[![Build Status](https://github.com/hoegaarden/pgpass/workflows/CI/badge.svg?branch=master)](https://github.com/hoegaarden/pgpass/actions?query=workflow%3ACI+branch%3Amaster) - -## Install - -```sh -npm install pgpass -``` - -## Usage -```js -var pgPass = require('pgpass'); - -var connInfo = { - 'host' : 'pgserver' , - 'user' : 'the_user_name' , -}; - -pgPass(connInfo, function(pass){ - conn_info.password = pass; - // connect to postgresql server -}); -``` - -## Description - -This module tries to read the `~/.pgpass` file (or the equivalent for windows systems). If the environment variable `PGPASSFILE` is set, this file is used instead. If everything goes right, the password from said file is passed to the callback; if the password cannot be read `undefined` is passed to the callback. - -Cases where `undefined` is returned: - -- the environment variable `PGPASSWORD` is set -- the file cannot be read (wrong permissions, no such file, ...) -- for non windows systems: the file is write-/readable by the group or by other users -- there is no matching line for the given connection info - -There should be no need to use this module directly; it is already included in `node-postgres`. - -## Configuration - -The module reads the environment variable `PGPASS_NO_DEESCAPE` to decide if the the read tokens from the password file should be de-escaped or not. Default is to do de-escaping. For further information on this see [this commit](https://github.com/postgres/postgres/commit/8d15e3ec4fcb735875a8a70a09ec0c62153c3329). - - -## Tests - -There are tests in `./test/`; including linting and coverage testing. Running `npm test` runs: - -- `jshint` -- `mocha` tests -- `jscoverage` and `mocha -R html-cov` - -You can see the coverage report in `coverage.html`. - - -## Development, Patches, Bugs, ... - -If you find Bugs or have improvements, please feel free to open a issue on GitHub. If you provide a pull request, I'm more than happy to merge them, just make sure to add tests for your changes. - -## Links - -- https://github.com/hoegaarden/node-pgpass -- http://www.postgresql.org/docs/current/static/libpq-pgpass.html -- https://wiki.postgresql.org/wiki/Pgpass -- https://github.com/postgres/postgres/blob/master/src/interfaces/libpq/fe-connect.c - -## License - -Copyright (c) 2013-2016 Hannes Hörl - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/pgpass/lib/helper.js b/reverse_engineering/node_modules/pgpass/lib/helper.js deleted file mode 100644 index f988460..0000000 --- a/reverse_engineering/node_modules/pgpass/lib/helper.js +++ /dev/null @@ -1,233 +0,0 @@ -'use strict'; - -var path = require('path') - , Stream = require('stream').Stream - , split = require('split2') - , util = require('util') - , defaultPort = 5432 - , isWin = (process.platform === 'win32') - , warnStream = process.stderr -; - - -var S_IRWXG = 56 // 00070(8) - , S_IRWXO = 7 // 00007(8) - , S_IFMT = 61440 // 00170000(8) - , S_IFREG = 32768 // 0100000(8) -; -function isRegFile(mode) { - return ((mode & S_IFMT) == S_IFREG); -} - -var fieldNames = [ 'host', 'port', 'database', 'user', 'password' ]; -var nrOfFields = fieldNames.length; -var passKey = fieldNames[ nrOfFields -1 ]; - - -function warn() { - var isWritable = ( - warnStream instanceof Stream && - true === warnStream.writable - ); - - if (isWritable) { - var args = Array.prototype.slice.call(arguments).concat("\n"); - warnStream.write( util.format.apply(util, args) ); - } -} - - -Object.defineProperty(module.exports, 'isWin', { - get : function() { - return isWin; - } , - set : function(val) { - isWin = val; - } -}); - - -module.exports.warnTo = function(stream) { - var old = warnStream; - warnStream = stream; - return old; -}; - -module.exports.getFileName = function(rawEnv){ - var env = rawEnv || process.env; - var file = env.PGPASSFILE || ( - isWin ? - path.join( env.APPDATA || './' , 'postgresql', 'pgpass.conf' ) : - path.join( env.HOME || './', '.pgpass' ) - ); - return file; -}; - -module.exports.usePgPass = function(stats, fname) { - if (Object.prototype.hasOwnProperty.call(process.env, 'PGPASSWORD')) { - return false; - } - - if (isWin) { - return true; - } - - fname = fname || ''; - - if (! isRegFile(stats.mode)) { - warn('WARNING: password file "%s" is not a plain file', fname); - return false; - } - - if (stats.mode & (S_IRWXG | S_IRWXO)) { - /* If password file is insecure, alert the user and ignore it. */ - warn('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less', fname); - return false; - } - - return true; -}; - - -var matcher = module.exports.match = function(connInfo, entry) { - return fieldNames.slice(0, -1).reduce(function(prev, field, idx){ - if (idx == 1) { - // the port - if ( Number( connInfo[field] || defaultPort ) === Number( entry[field] ) ) { - return prev && true; - } - } - return prev && ( - entry[field] === '*' || - entry[field] === connInfo[field] - ); - }, true); -}; - - -module.exports.getPassword = function(connInfo, stream, cb) { - var pass; - var lineStream = stream.pipe(split()); - - function onLine(line) { - var entry = parseLine(line); - if (entry && isValidEntry(entry) && matcher(connInfo, entry)) { - pass = entry[passKey]; - lineStream.end(); // -> calls onEnd(), but pass is set now - } - } - - var onEnd = function() { - stream.destroy(); - cb(pass); - }; - - var onErr = function(err) { - stream.destroy(); - warn('WARNING: error on reading file: %s', err); - cb(undefined); - }; - - stream.on('error', onErr); - lineStream - .on('data', onLine) - .on('end', onEnd) - .on('error', onErr) - ; - -}; - - -var parseLine = module.exports.parseLine = function(line) { - if (line.length < 11 || line.match(/^\s+#/)) { - return null; - } - - var curChar = ''; - var prevChar = ''; - var fieldIdx = 0; - var startIdx = 0; - var endIdx = 0; - var obj = {}; - var isLastField = false; - var addToObj = function(idx, i0, i1) { - var field = line.substring(i0, i1); - - if (! Object.hasOwnProperty.call(process.env, 'PGPASS_NO_DEESCAPE')) { - field = field.replace(/\\([:\\])/g, '$1'); - } - - obj[ fieldNames[idx] ] = field; - }; - - for (var i = 0 ; i < line.length-1 ; i += 1) { - curChar = line.charAt(i+1); - prevChar = line.charAt(i); - - isLastField = (fieldIdx == nrOfFields-1); - - if (isLastField) { - addToObj(fieldIdx, startIdx); - break; - } - - if (i >= 0 && curChar == ':' && prevChar !== '\\') { - addToObj(fieldIdx, startIdx, i+1); - - startIdx = i+2; - fieldIdx += 1; - } - } - - obj = ( Object.keys(obj).length === nrOfFields ) ? obj : null; - - return obj; -}; - - -var isValidEntry = module.exports.isValidEntry = function(entry){ - var rules = { - // host - 0 : function(x){ - return x.length > 0; - } , - // port - 1 : function(x){ - if (x === '*') { - return true; - } - x = Number(x); - return ( - isFinite(x) && - x > 0 && - x < 9007199254740992 && - Math.floor(x) === x - ); - } , - // database - 2 : function(x){ - return x.length > 0; - } , - // username - 3 : function(x){ - return x.length > 0; - } , - // password - 4 : function(x){ - return x.length > 0; - } - }; - - for (var idx = 0 ; idx < fieldNames.length ; idx += 1) { - var rule = rules[idx]; - var value = entry[ fieldNames[idx] ] || ''; - - var res = rule(value); - if (!res) { - return false; - } - } - - return true; -}; - diff --git a/reverse_engineering/node_modules/pgpass/lib/index.js b/reverse_engineering/node_modules/pgpass/lib/index.js deleted file mode 100644 index ecfcf30..0000000 --- a/reverse_engineering/node_modules/pgpass/lib/index.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var path = require('path') - , fs = require('fs') - , helper = require('./helper.js') -; - - -module.exports = function(connInfo, cb) { - var file = helper.getFileName(); - - fs.stat(file, function(err, stat){ - if (err || !helper.usePgPass(stat, file)) { - return cb(undefined); - } - - var st = fs.createReadStream(file); - - helper.getPassword(connInfo, st, cb); - }); -}; - -module.exports.warnTo = helper.warnTo; diff --git a/reverse_engineering/node_modules/pgpass/package.json b/reverse_engineering/node_modules/pgpass/package.json deleted file mode 100644 index d83c75d..0000000 --- a/reverse_engineering/node_modules/pgpass/package.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "_from": "pgpass@1.x", - "_id": "pgpass@1.0.4", - "_inBundle": false, - "_integrity": "sha512-YmuA56alyBq7M59vxVBfPJrGSozru8QAdoNlWuW3cz8l+UX3cWge0vTvjKhsSHSJpo3Bom8/Mm6hf0TR5GY0+w==", - "_location": "/pgpass", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "pgpass@1.x", - "name": "pgpass", - "escapedName": "pgpass", - "rawSpec": "1.x", - "saveSpec": null, - "fetchSpec": "1.x" - }, - "_requiredBy": [ - "/pg" - ], - "_resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.4.tgz", - "_shasum": "85eb93a83800b20f8057a2b029bf05abaf94ea9c", - "_spec": "pgpass@1.x", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg", - "author": { - "name": "Hannes Hörl", - "email": "hannes.hoerl+pgpass@snowreporter.com" - }, - "bugs": { - "url": "https://github.com/hoegaarden/pgpass/issues" - }, - "bundleDependencies": false, - "dependencies": { - "split2": "^3.1.1" - }, - "deprecated": false, - "description": "Module for reading .pgpass", - "devDependencies": { - "jshint": "^2.12.0", - "mocha": "^8.2.0", - "nyc": "^15.1.0", - "pg": "^8.4.1", - "pg-escape": "^0.2.0", - "pg-native": "3.0.0", - "resumer": "0.0.0", - "tmp": "^0.2.1", - "which": "^2.0.2" - }, - "homepage": "https://github.com/hoegaarden/pgpass#readme", - "keywords": [ - "postgres", - "pg", - "pgpass", - "password", - "postgresql" - ], - "license": "MIT", - "main": "lib/index", - "name": "pgpass", - "repository": { - "type": "git", - "url": "git+https://github.com/hoegaarden/pgpass.git" - }, - "scripts": { - "_covered_test": "nyc --reporter html --reporter text \"$npm_execpath\" run _test", - "_hint": "jshint --exclude node_modules --verbose lib test", - "_test": "mocha --recursive -R list", - "pretest": "chmod 600 ./test/_pgpass", - "test": "\"$npm_execpath\" run _hint && \"$npm_execpath\" run _covered_test" - }, - "version": "1.0.4" -} diff --git a/reverse_engineering/node_modules/postgres-array/index.d.ts b/reverse_engineering/node_modules/postgres-array/index.d.ts deleted file mode 100644 index 88665bd..0000000 --- a/reverse_engineering/node_modules/postgres-array/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ - -export function parse(source: string): string[]; -export function parse(source: string, transform: (value: string) => T): T[]; - diff --git a/reverse_engineering/node_modules/postgres-array/index.js b/reverse_engineering/node_modules/postgres-array/index.js deleted file mode 100644 index 18bfd16..0000000 --- a/reverse_engineering/node_modules/postgres-array/index.js +++ /dev/null @@ -1,97 +0,0 @@ -'use strict' - -exports.parse = function (source, transform) { - return new ArrayParser(source, transform).parse() -} - -class ArrayParser { - constructor (source, transform) { - this.source = source - this.transform = transform || identity - this.position = 0 - this.entries = [] - this.recorded = [] - this.dimension = 0 - } - - isEof () { - return this.position >= this.source.length - } - - nextCharacter () { - var character = this.source[this.position++] - if (character === '\\') { - return { - value: this.source[this.position++], - escaped: true - } - } - return { - value: character, - escaped: false - } - } - - record (character) { - this.recorded.push(character) - } - - newEntry (includeEmpty) { - var entry - if (this.recorded.length > 0 || includeEmpty) { - entry = this.recorded.join('') - if (entry === 'NULL' && !includeEmpty) { - entry = null - } - if (entry !== null) entry = this.transform(entry) - this.entries.push(entry) - this.recorded = [] - } - } - - consumeDimensions () { - if (this.source[0] === '[') { - while (!this.isEof()) { - var char = this.nextCharacter() - if (char.value === '=') break - } - } - } - - parse (nested) { - var character, parser, quote - this.consumeDimensions() - while (!this.isEof()) { - character = this.nextCharacter() - if (character.value === '{' && !quote) { - this.dimension++ - if (this.dimension > 1) { - parser = new ArrayParser(this.source.substr(this.position - 1), this.transform) - this.entries.push(parser.parse(true)) - this.position += parser.position - 2 - } - } else if (character.value === '}' && !quote) { - this.dimension-- - if (!this.dimension) { - this.newEntry() - if (nested) return this.entries - } - } else if (character.value === '"' && !character.escaped) { - if (quote) this.newEntry(true) - quote = !quote - } else if (character.value === ',' && !quote) { - this.newEntry() - } else { - this.record(character.value) - } - } - if (this.dimension !== 0) { - throw new Error('array dimension not balanced') - } - return this.entries - } -} - -function identity (value) { - return value -} diff --git a/reverse_engineering/node_modules/postgres-array/license b/reverse_engineering/node_modules/postgres-array/license deleted file mode 100644 index 25c6247..0000000 --- a/reverse_engineering/node_modules/postgres-array/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Ben Drucker (bendrucker.me) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/postgres-array/package.json b/reverse_engineering/node_modules/postgres-array/package.json deleted file mode 100644 index 77ba72e..0000000 --- a/reverse_engineering/node_modules/postgres-array/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "_from": "postgres-array@~2.0.0", - "_id": "postgres-array@2.0.0", - "_inBundle": false, - "_integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", - "_location": "/postgres-array", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "postgres-array@~2.0.0", - "name": "postgres-array", - "escapedName": "postgres-array", - "rawSpec": "~2.0.0", - "saveSpec": null, - "fetchSpec": "~2.0.0" - }, - "_requiredBy": [ - "/pg-types" - ], - "_resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", - "_shasum": "48f8fce054fbc69671999329b8834b772652d82e", - "_spec": "postgres-array@~2.0.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg-types", - "author": { - "name": "Ben Drucker", - "email": "bvdrucker@gmail.com", - "url": "bendrucker.me" - }, - "bugs": { - "url": "https://github.com/bendrucker/postgres-array/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Parse postgres array columns", - "devDependencies": { - "standard": "^12.0.1", - "tape": "^4.0.0" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js", - "index.d.ts", - "readme.md" - ], - "homepage": "https://github.com/bendrucker/postgres-array#readme", - "keywords": [ - "postgres", - "array", - "parser" - ], - "license": "MIT", - "main": "index.js", - "name": "postgres-array", - "repository": { - "type": "git", - "url": "git+https://github.com/bendrucker/postgres-array.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "types": "index.d.ts", - "version": "2.0.0" -} diff --git a/reverse_engineering/node_modules/postgres-array/readme.md b/reverse_engineering/node_modules/postgres-array/readme.md deleted file mode 100644 index b74b369..0000000 --- a/reverse_engineering/node_modules/postgres-array/readme.md +++ /dev/null @@ -1,43 +0,0 @@ -# postgres-array [![Build Status](https://travis-ci.org/bendrucker/postgres-array.svg?branch=master)](https://travis-ci.org/bendrucker/postgres-array) - -> Parse postgres array columns - - -## Install - -``` -$ npm install --save postgres-array -``` - - -## Usage - -```js -var postgresArray = require('postgres-array') - -postgresArray.parse('{1,2,3}', (value) => parseInt(value, 10)) -//=> [1, 2, 3] -``` - -## API - -#### `parse(input, [transform])` -> `array` - -##### input - -*Required* -Type: `string` - -A Postgres array string. - -##### transform - -Type: `function` -Default: `identity` - -A function that transforms non-null values inserted into the array. - - -## License - -MIT © [Ben Drucker](http://bendrucker.me) diff --git a/reverse_engineering/node_modules/postgres-bytea/index.js b/reverse_engineering/node_modules/postgres-bytea/index.js deleted file mode 100644 index d1107a0..0000000 --- a/reverse_engineering/node_modules/postgres-bytea/index.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict' - -module.exports = function parseBytea (input) { - if (/^\\x/.test(input)) { - // new 'hex' style response (pg >9.0) - return new Buffer(input.substr(2), 'hex') - } - var output = '' - var i = 0 - while (i < input.length) { - if (input[i] !== '\\') { - output += input[i] - ++i - } else { - if (/[0-7]{3}/.test(input.substr(i + 1, 3))) { - output += String.fromCharCode(parseInt(input.substr(i + 1, 3), 8)) - i += 4 - } else { - var backslashes = 1 - while (i + backslashes < input.length && input[i + backslashes] === '\\') { - backslashes++ - } - for (var k = 0; k < Math.floor(backslashes / 2); ++k) { - output += '\\' - } - i += Math.floor(backslashes / 2) * 2 - } - } - } - return new Buffer(output, 'binary') -} diff --git a/reverse_engineering/node_modules/postgres-bytea/license b/reverse_engineering/node_modules/postgres-bytea/license deleted file mode 100644 index 25c6247..0000000 --- a/reverse_engineering/node_modules/postgres-bytea/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Ben Drucker (bendrucker.me) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/postgres-bytea/package.json b/reverse_engineering/node_modules/postgres-bytea/package.json deleted file mode 100644 index e87b5eb..0000000 --- a/reverse_engineering/node_modules/postgres-bytea/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "_from": "postgres-bytea@~1.0.0", - "_id": "postgres-bytea@1.0.0", - "_inBundle": false, - "_integrity": "sha1-AntTPAqokOJtFy1Hz5zOzFIazTU=", - "_location": "/postgres-bytea", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "postgres-bytea@~1.0.0", - "name": "postgres-bytea", - "escapedName": "postgres-bytea", - "rawSpec": "~1.0.0", - "saveSpec": null, - "fetchSpec": "~1.0.0" - }, - "_requiredBy": [ - "/pg-types" - ], - "_resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.0.tgz", - "_shasum": "027b533c0aa890e26d172d47cf9ccecc521acd35", - "_spec": "postgres-bytea@~1.0.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg-types", - "author": { - "name": "Ben Drucker", - "email": "bvdrucker@gmail.com", - "url": "bendrucker.me" - }, - "bugs": { - "url": "https://github.com/bendrucker/postgres-bytea/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Postgres bytea parser", - "devDependencies": { - "standard": "^4.0.0", - "tape": "^4.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js", - "readme.md" - ], - "homepage": "https://github.com/bendrucker/postgres-bytea#readme", - "keywords": [ - "bytea", - "postgres", - "binary", - "parser" - ], - "license": "MIT", - "main": "index.js", - "name": "postgres-bytea", - "repository": { - "type": "git", - "url": "git+https://github.com/bendrucker/postgres-bytea.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "version": "1.0.0" -} diff --git a/reverse_engineering/node_modules/postgres-bytea/readme.md b/reverse_engineering/node_modules/postgres-bytea/readme.md deleted file mode 100644 index 4939c3b..0000000 --- a/reverse_engineering/node_modules/postgres-bytea/readme.md +++ /dev/null @@ -1,34 +0,0 @@ -# postgres-bytea [![Build Status](https://travis-ci.org/bendrucker/postgres-bytea.svg?branch=master)](https://travis-ci.org/bendrucker/postgres-bytea) - -> Postgres bytea parser - - -## Install - -``` -$ npm install --save postgres-bytea -``` - - -## Usage - -```js -var bytea = require('postgres-bytea'); -bytea('\\000\\100\\200') -//=> buffer -``` - -## API - -#### `bytea(input)` -> `buffer` - -##### input - -*Required* -Type: `string` - -A Postgres bytea binary string. - -## License - -MIT © [Ben Drucker](http://bendrucker.me) diff --git a/reverse_engineering/node_modules/postgres-date/index.js b/reverse_engineering/node_modules/postgres-date/index.js deleted file mode 100644 index 5dc73fb..0000000 --- a/reverse_engineering/node_modules/postgres-date/index.js +++ /dev/null @@ -1,116 +0,0 @@ -'use strict' - -var DATE_TIME = /(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/ -var DATE = /^(\d{1,})-(\d{2})-(\d{2})( BC)?$/ -var TIME_ZONE = /([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/ -var INFINITY = /^-?infinity$/ - -module.exports = function parseDate (isoDate) { - if (INFINITY.test(isoDate)) { - // Capitalize to Infinity before passing to Number - return Number(isoDate.replace('i', 'I')) - } - var matches = DATE_TIME.exec(isoDate) - - if (!matches) { - // Force YYYY-MM-DD dates to be parsed as local time - return getDate(isoDate) || null - } - - var isBC = !!matches[8] - var year = parseInt(matches[1], 10) - if (isBC) { - year = bcYearToNegativeYear(year) - } - - var month = parseInt(matches[2], 10) - 1 - var day = matches[3] - var hour = parseInt(matches[4], 10) - var minute = parseInt(matches[5], 10) - var second = parseInt(matches[6], 10) - - var ms = matches[7] - ms = ms ? 1000 * parseFloat(ms) : 0 - - var date - var offset = timeZoneOffset(isoDate) - if (offset != null) { - date = new Date(Date.UTC(year, month, day, hour, minute, second, ms)) - - // Account for years from 0 to 99 being interpreted as 1900-1999 - // by Date.UTC / the multi-argument form of the Date constructor - if (is0To99(year)) { - date.setUTCFullYear(year) - } - - if (offset !== 0) { - date.setTime(date.getTime() - offset) - } - } else { - date = new Date(year, month, day, hour, minute, second, ms) - - if (is0To99(year)) { - date.setFullYear(year) - } - } - - return date -} - -function getDate (isoDate) { - var matches = DATE.exec(isoDate) - if (!matches) { - return - } - - var year = parseInt(matches[1], 10) - var isBC = !!matches[4] - if (isBC) { - year = bcYearToNegativeYear(year) - } - - var month = parseInt(matches[2], 10) - 1 - var day = matches[3] - // YYYY-MM-DD will be parsed as local time - var date = new Date(year, month, day) - - if (is0To99(year)) { - date.setFullYear(year) - } - - return date -} - -// match timezones: -// Z (UTC) -// -05 -// +06:30 -function timeZoneOffset (isoDate) { - if (isoDate.endsWith('+00')) { - return 0 - } - - var zone = TIME_ZONE.exec(isoDate.split(' ')[1]) - if (!zone) return - var type = zone[1] - - if (type === 'Z') { - return 0 - } - var sign = type === '-' ? -1 : 1 - var offset = parseInt(zone[2], 10) * 3600 + - parseInt(zone[3] || 0, 10) * 60 + - parseInt(zone[4] || 0, 10) - - return offset * sign * 1000 -} - -function bcYearToNegativeYear (year) { - // Account for numerical difference between representations of BC years - // See: https://github.com/bendrucker/postgres-date/issues/5 - return -(year - 1) -} - -function is0To99 (num) { - return num >= 0 && num < 100 -} diff --git a/reverse_engineering/node_modules/postgres-date/license b/reverse_engineering/node_modules/postgres-date/license deleted file mode 100644 index 25c6247..0000000 --- a/reverse_engineering/node_modules/postgres-date/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Ben Drucker (bendrucker.me) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/postgres-date/package.json b/reverse_engineering/node_modules/postgres-date/package.json deleted file mode 100644 index 7cc2d88..0000000 --- a/reverse_engineering/node_modules/postgres-date/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "_from": "postgres-date@~1.0.4", - "_id": "postgres-date@1.0.7", - "_inBundle": false, - "_integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", - "_location": "/postgres-date", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "postgres-date@~1.0.4", - "name": "postgres-date", - "escapedName": "postgres-date", - "rawSpec": "~1.0.4", - "saveSpec": null, - "fetchSpec": "~1.0.4" - }, - "_requiredBy": [ - "/pg-types" - ], - "_resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", - "_shasum": "51bc086006005e5061c591cee727f2531bf641a8", - "_spec": "postgres-date@~1.0.4", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg-types", - "author": { - "name": "Ben Drucker", - "email": "bvdrucker@gmail.com", - "url": "bendrucker.me" - }, - "bugs": { - "url": "https://github.com/bendrucker/postgres-date/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Postgres date column parser", - "devDependencies": { - "standard": "^14.0.0", - "tape": "^5.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js", - "readme.md" - ], - "homepage": "https://github.com/bendrucker/postgres-date#readme", - "keywords": [ - "postgres", - "date", - "parser" - ], - "license": "MIT", - "main": "index.js", - "name": "postgres-date", - "repository": { - "type": "git", - "url": "git+https://github.com/bendrucker/postgres-date.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "version": "1.0.7" -} diff --git a/reverse_engineering/node_modules/postgres-date/readme.md b/reverse_engineering/node_modules/postgres-date/readme.md deleted file mode 100644 index 095431a..0000000 --- a/reverse_engineering/node_modules/postgres-date/readme.md +++ /dev/null @@ -1,49 +0,0 @@ -# postgres-date [![Build Status](https://travis-ci.org/bendrucker/postgres-date.svg?branch=master)](https://travis-ci.org/bendrucker/postgres-date) [![Greenkeeper badge](https://badges.greenkeeper.io/bendrucker/postgres-date.svg)](https://greenkeeper.io/) - -> Postgres date output parser - -This package parses [date/time outputs](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-OUTPUT) from Postgres into Javascript `Date` objects. Its goal is to match Postgres behavior and preserve data accuracy. - -If you find a case where a valid Postgres output results in incorrect parsing (including loss of precision), please [create a pull request](https://github.com/bendrucker/postgres-date/compare) and provide a failing test. - -**Supported Postgres Versions:** `>= 9.6` - -All prior versions of Postgres are likely compatible but not officially supported. - -## Install - -``` -$ npm install --save postgres-date -``` - - -## Usage - -```js -var parse = require('postgres-date') -parse('2011-01-23 22:15:51Z') -// => 2011-01-23T22:15:51.000Z -``` - -## API - -#### `parse(isoDate)` -> `date` - -##### isoDate - -*Required* -Type: `string` - -A date string from Postgres. - -## Releases - -The following semantic versioning increments will be used for changes: - -* **Major**: Removal of support for Node.js versions or Postgres versions (not expected) -* **Minor**: Unused, since Postgres returns dates in standard ISO 8601 format -* **Patch**: Any fix for parsing behavior - -## License - -MIT © [Ben Drucker](http://bendrucker.me) diff --git a/reverse_engineering/node_modules/postgres-interval/index.d.ts b/reverse_engineering/node_modules/postgres-interval/index.d.ts deleted file mode 100644 index f82b4c3..0000000 --- a/reverse_engineering/node_modules/postgres-interval/index.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -declare namespace PostgresInterval { - export interface IPostgresInterval { - years?: number; - months?: number; - days?: number; - hours?: number; - minutes?: number; - seconds?: number; - milliseconds?: number; - - toPostgres(): string; - - toISO(): string; - toISOString(): string; - } -} - -declare function PostgresInterval(raw: string): PostgresInterval.IPostgresInterval; - -export = PostgresInterval; diff --git a/reverse_engineering/node_modules/postgres-interval/index.js b/reverse_engineering/node_modules/postgres-interval/index.js deleted file mode 100644 index 8ecca80..0000000 --- a/reverse_engineering/node_modules/postgres-interval/index.js +++ /dev/null @@ -1,125 +0,0 @@ -'use strict' - -var extend = require('xtend/mutable') - -module.exports = PostgresInterval - -function PostgresInterval (raw) { - if (!(this instanceof PostgresInterval)) { - return new PostgresInterval(raw) - } - extend(this, parse(raw)) -} -var properties = ['seconds', 'minutes', 'hours', 'days', 'months', 'years'] -PostgresInterval.prototype.toPostgres = function () { - var filtered = properties.filter(this.hasOwnProperty, this) - - // In addition to `properties`, we need to account for fractions of seconds. - if (this.milliseconds && filtered.indexOf('seconds') < 0) { - filtered.push('seconds') - } - - if (filtered.length === 0) return '0' - return filtered - .map(function (property) { - var value = this[property] || 0 - - // Account for fractional part of seconds, - // remove trailing zeroes. - if (property === 'seconds' && this.milliseconds) { - value = (value + this.milliseconds / 1000).toFixed(6).replace(/\.?0+$/, '') - } - - return value + ' ' + property - }, this) - .join(' ') -} - -var propertiesISOEquivalent = { - years: 'Y', - months: 'M', - days: 'D', - hours: 'H', - minutes: 'M', - seconds: 'S' -} -var dateProperties = ['years', 'months', 'days'] -var timeProperties = ['hours', 'minutes', 'seconds'] -// according to ISO 8601 -PostgresInterval.prototype.toISOString = PostgresInterval.prototype.toISO = function () { - var datePart = dateProperties - .map(buildProperty, this) - .join('') - - var timePart = timeProperties - .map(buildProperty, this) - .join('') - - return 'P' + datePart + 'T' + timePart - - function buildProperty (property) { - var value = this[property] || 0 - - // Account for fractional part of seconds, - // remove trailing zeroes. - if (property === 'seconds' && this.milliseconds) { - value = (value + this.milliseconds / 1000).toFixed(6).replace(/0+$/, '') - } - - return value + propertiesISOEquivalent[property] - } -} - -var NUMBER = '([+-]?\\d+)' -var YEAR = NUMBER + '\\s+years?' -var MONTH = NUMBER + '\\s+mons?' -var DAY = NUMBER + '\\s+days?' -var TIME = '([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?' -var INTERVAL = new RegExp([YEAR, MONTH, DAY, TIME].map(function (regexString) { - return '(' + regexString + ')?' -}) - .join('\\s*')) - -// Positions of values in regex match -var positions = { - years: 2, - months: 4, - days: 6, - hours: 9, - minutes: 10, - seconds: 11, - milliseconds: 12 -} -// We can use negative time -var negatives = ['hours', 'minutes', 'seconds', 'milliseconds'] - -function parseMilliseconds (fraction) { - // add omitted zeroes - var microseconds = fraction + '000000'.slice(fraction.length) - return parseInt(microseconds, 10) / 1000 -} - -function parse (interval) { - if (!interval) return {} - var matches = INTERVAL.exec(interval) - var isNegative = matches[8] === '-' - return Object.keys(positions) - .reduce(function (parsed, property) { - var position = positions[property] - var value = matches[position] - // no empty string - if (!value) return parsed - // milliseconds are actually microseconds (up to 6 digits) - // with omitted trailing zeroes. - value = property === 'milliseconds' - ? parseMilliseconds(value) - : parseInt(value, 10) - // no zeros - if (!value) return parsed - if (isNegative && ~negatives.indexOf(property)) { - value *= -1 - } - parsed[property] = value - return parsed - }, {}) -} diff --git a/reverse_engineering/node_modules/postgres-interval/license b/reverse_engineering/node_modules/postgres-interval/license deleted file mode 100644 index 25c6247..0000000 --- a/reverse_engineering/node_modules/postgres-interval/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Ben Drucker (bendrucker.me) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/postgres-interval/package.json b/reverse_engineering/node_modules/postgres-interval/package.json deleted file mode 100644 index 8b23de1..0000000 --- a/reverse_engineering/node_modules/postgres-interval/package.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "_from": "postgres-interval@^1.1.0", - "_id": "postgres-interval@1.2.0", - "_inBundle": false, - "_integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", - "_location": "/postgres-interval", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "postgres-interval@^1.1.0", - "name": "postgres-interval", - "escapedName": "postgres-interval", - "rawSpec": "^1.1.0", - "saveSpec": null, - "fetchSpec": "^1.1.0" - }, - "_requiredBy": [ - "/pg-types" - ], - "_resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", - "_shasum": "b460c82cb1587507788819a06aa0fffdb3544695", - "_spec": "postgres-interval@^1.1.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pg-types", - "author": { - "name": "Ben Drucker", - "email": "bvdrucker@gmail.com", - "url": "bendrucker.me" - }, - "bugs": { - "url": "https://github.com/bendrucker/postgres-interval/issues" - }, - "bundleDependencies": false, - "dependencies": { - "xtend": "^4.0.0" - }, - "deprecated": false, - "description": "Parse Postgres interval columns", - "devDependencies": { - "standard": "^12.0.1", - "tape": "^4.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js", - "index.d.ts", - "readme.md" - ], - "homepage": "https://github.com/bendrucker/postgres-interval#readme", - "keywords": [ - "postgres", - "interval", - "parser" - ], - "license": "MIT", - "main": "index.js", - "name": "postgres-interval", - "repository": { - "type": "git", - "url": "git+https://github.com/bendrucker/postgres-interval.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "version": "1.2.0" -} diff --git a/reverse_engineering/node_modules/postgres-interval/readme.md b/reverse_engineering/node_modules/postgres-interval/readme.md deleted file mode 100644 index 53cda4a..0000000 --- a/reverse_engineering/node_modules/postgres-interval/readme.md +++ /dev/null @@ -1,48 +0,0 @@ -# postgres-interval [![Build Status](https://travis-ci.org/bendrucker/postgres-interval.svg?branch=master)](https://travis-ci.org/bendrucker/postgres-interval) [![Greenkeeper badge](https://badges.greenkeeper.io/bendrucker/postgres-interval.svg)](https://greenkeeper.io/) - -> Parse Postgres interval columns - - -## Install - -``` -$ npm install --save postgres-interval -``` - - -## Usage - -```js -var parse = require('postgres-interval') -var interval = parse('01:02:03') -//=> {hours: 1, minutes: 2, seconds: 3} -interval.toPostgres() -// 3 seconds 2 minutes 1 hours -interval.toISO() -// P0Y0M0DT1H2M3S -``` - -## API - -#### `parse(pgInterval)` -> `interval` - -##### pgInterval - -*Required* -Type: `string` - -A Postgres interval string. - -#### `interval.toPostgres()` -> `string` - -Returns an interval string. This allows the interval object to be passed into prepared statements. - -#### `interval.toISOString()` -> `string` - -Returns an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) compliant string. - -Also available as `interval.toISO()` for backwards compatibility. - -## License - -MIT © [Ben Drucker](http://bendrucker.me) diff --git a/reverse_engineering/node_modules/readable-stream/CONTRIBUTING.md b/reverse_engineering/node_modules/readable-stream/CONTRIBUTING.md deleted file mode 100644 index f478d58..0000000 --- a/reverse_engineering/node_modules/readable-stream/CONTRIBUTING.md +++ /dev/null @@ -1,38 +0,0 @@ -# Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -* (a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -* (b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -* (c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -* (d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. - -## Moderation Policy - -The [Node.js Moderation Policy] applies to this WG. - -## Code of Conduct - -The [Node.js Code of Conduct][] applies to this WG. - -[Node.js Code of Conduct]: -https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md -[Node.js Moderation Policy]: -https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/reverse_engineering/node_modules/readable-stream/GOVERNANCE.md b/reverse_engineering/node_modules/readable-stream/GOVERNANCE.md deleted file mode 100644 index 16ffb93..0000000 --- a/reverse_engineering/node_modules/readable-stream/GOVERNANCE.md +++ /dev/null @@ -1,136 +0,0 @@ -### Streams Working Group - -The Node.js Streams is jointly governed by a Working Group -(WG) -that is responsible for high-level guidance of the project. - -The WG has final authority over this project including: - -* Technical direction -* Project governance and process (including this policy) -* Contribution policy -* GitHub repository hosting -* Conduct guidelines -* Maintaining the list of additional Collaborators - -For the current list of WG members, see the project -[README.md](./README.md#current-project-team-members). - -### Collaborators - -The readable-stream GitHub repository is -maintained by the WG and additional Collaborators who are added by the -WG on an ongoing basis. - -Individuals making significant and valuable contributions are made -Collaborators and given commit-access to the project. These -individuals are identified by the WG and their addition as -Collaborators is discussed during the WG meeting. - -_Note:_ If you make a significant contribution and are not considered -for commit-access log an issue or contact a WG member directly and it -will be brought up in the next WG meeting. - -Modifications of the contents of the readable-stream repository are -made on -a collaborative basis. Anybody with a GitHub account may propose a -modification via pull request and it will be considered by the project -Collaborators. All pull requests must be reviewed and accepted by a -Collaborator with sufficient expertise who is able to take full -responsibility for the change. In the case of pull requests proposed -by an existing Collaborator, an additional Collaborator is required -for sign-off. Consensus should be sought if additional Collaborators -participate and there is disagreement around a particular -modification. See _Consensus Seeking Process_ below for further detail -on the consensus model used for governance. - -Collaborators may opt to elevate significant or controversial -modifications, or modifications that have not found consensus to the -WG for discussion by assigning the ***WG-agenda*** tag to a pull -request or issue. The WG should serve as the final arbiter where -required. - -For the current list of Collaborators, see the project -[README.md](./README.md#members). - -### WG Membership - -WG seats are not time-limited. There is no fixed size of the WG. -However, the expected target is between 6 and 12, to ensure adequate -coverage of important areas of expertise, balanced with the ability to -make decisions efficiently. - -There is no specific set of requirements or qualifications for WG -membership beyond these rules. - -The WG may add additional members to the WG by unanimous consensus. - -A WG member may be removed from the WG by voluntary resignation, or by -unanimous consensus of all other WG members. - -Changes to WG membership should be posted in the agenda, and may be -suggested as any other agenda item (see "WG Meetings" below). - -If an addition or removal is proposed during a meeting, and the full -WG is not in attendance to participate, then the addition or removal -is added to the agenda for the subsequent meeting. This is to ensure -that all members are given the opportunity to participate in all -membership decisions. If a WG member is unable to attend a meeting -where a planned membership decision is being made, then their consent -is assumed. - -No more than 1/3 of the WG members may be affiliated with the same -employer. If removal or resignation of a WG member, or a change of -employment by a WG member, creates a situation where more than 1/3 of -the WG membership shares an employer, then the situation must be -immediately remedied by the resignation or removal of one or more WG -members affiliated with the over-represented employer(s). - -### WG Meetings - -The WG meets occasionally on a Google Hangout On Air. A designated moderator -approved by the WG runs the meeting. Each meeting should be -published to YouTube. - -Items are added to the WG agenda that are considered contentious or -are modifications of governance, contribution policy, WG membership, -or release process. - -The intention of the agenda is not to approve or review all patches; -that should happen continuously on GitHub and be handled by the larger -group of Collaborators. - -Any community member or contributor can ask that something be added to -the next meeting's agenda by logging a GitHub Issue. Any Collaborator, -WG member or the moderator can add the item to the agenda by adding -the ***WG-agenda*** tag to the issue. - -Prior to each WG meeting the moderator will share the Agenda with -members of the WG. WG members can add any items they like to the -agenda at the beginning of each meeting. The moderator and the WG -cannot veto or remove items. - -The WG may invite persons or representatives from certain projects to -participate in a non-voting capacity. - -The moderator is responsible for summarizing the discussion of each -agenda item and sends it as a pull request after the meeting. - -### Consensus Seeking Process - -The WG follows a -[Consensus -Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) -decision-making model. - -When an agenda item has appeared to reach a consensus the moderator -will ask "Does anyone object?" as a final call for dissent from the -consensus. - -If an agenda item cannot reach a consensus a WG member can call for -either a closing vote or a vote to table the issue to the next -meeting. The call for a vote must be seconded by a majority of the WG -or else the discussion will continue. Simple majority wins. - -Note that changes to WG membership require a majority consensus. See -"WG Membership" above. diff --git a/reverse_engineering/node_modules/readable-stream/LICENSE b/reverse_engineering/node_modules/readable-stream/LICENSE deleted file mode 100644 index 2873b3b..0000000 --- a/reverse_engineering/node_modules/readable-stream/LICENSE +++ /dev/null @@ -1,47 +0,0 @@ -Node.js is licensed for use as follows: - -""" -Copyright Node.js contributors. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. -""" - -This license applies to parts of Node.js originating from the -https://github.com/joyent/node repository: - -""" -Copyright Joyent, Inc. and other Node contributors. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. -""" diff --git a/reverse_engineering/node_modules/readable-stream/README.md b/reverse_engineering/node_modules/readable-stream/README.md deleted file mode 100644 index 6f035ab..0000000 --- a/reverse_engineering/node_modules/readable-stream/README.md +++ /dev/null @@ -1,106 +0,0 @@ -# readable-stream - -***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) - - -[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) -[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) - - -[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) - -```bash -npm install --save readable-stream -``` - -This package is a mirror of the streams implementations in Node.js. - -Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.19.0/docs/api/stream.html). - -If you want to guarantee a stable streams base, regardless of what version of -Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). - -As of version 2.0.0 **readable-stream** uses semantic versioning. - -## Version 3.x.x - -v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: - -1. Error codes: https://github.com/nodejs/node/pull/13310, - https://github.com/nodejs/node/pull/13291, - https://github.com/nodejs/node/pull/16589, - https://github.com/nodejs/node/pull/15042, - https://github.com/nodejs/node/pull/15665, - https://github.com/nodejs/readable-stream/pull/344 -2. 'readable' have precedence over flowing - https://github.com/nodejs/node/pull/18994 -3. make virtual methods errors consistent - https://github.com/nodejs/node/pull/18813 -4. updated streams error handling - https://github.com/nodejs/node/pull/18438 -5. writable.end should return this. - https://github.com/nodejs/node/pull/18780 -6. readable continues to read when push('') - https://github.com/nodejs/node/pull/18211 -7. add custom inspect to BufferList - https://github.com/nodejs/node/pull/17907 -8. always defer 'readable' with nextTick - https://github.com/nodejs/node/pull/17979 - -## Version 2.x.x -v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. - -### Big Thanks - -Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] - -# Usage - -You can swap your `require('stream')` with `require('readable-stream')` -without any changes, if you are just using one of the main classes and -functions. - -```js -const { - Readable, - Writable, - Transform, - Duplex, - pipeline, - finished -} = require('readable-stream') -```` - -Note that `require('stream')` will return `Stream`, while -`require('readable-stream')` will return `Readable`. We discourage using -whatever is exported directly, but rather use one of the properties as -shown in the example above. - -# Streams Working Group - -`readable-stream` is maintained by the Streams Working Group, which -oversees the development and maintenance of the Streams API within -Node.js. The responsibilities of the Streams Working Group include: - -* Addressing stream issues on the Node.js issue tracker. -* Authoring and editing stream documentation within the Node.js project. -* Reviewing changes to stream subclasses within the Node.js project. -* Redirecting changes to streams from the Node.js project to this - project. -* Assisting in the implementation of stream providers within Node.js. -* Recommending versions of `readable-stream` to be included in Node.js. -* Messaging about the future of streams to give the community advance - notice of changes. - - -## Team Members - -* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> - - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 -* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> -* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> - - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E -* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> -* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> - -[sauce]: https://saucelabs.com diff --git a/reverse_engineering/node_modules/readable-stream/errors-browser.js b/reverse_engineering/node_modules/readable-stream/errors-browser.js deleted file mode 100644 index fb8e73e..0000000 --- a/reverse_engineering/node_modules/readable-stream/errors-browser.js +++ /dev/null @@ -1,127 +0,0 @@ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; diff --git a/reverse_engineering/node_modules/readable-stream/errors.js b/reverse_engineering/node_modules/readable-stream/errors.js deleted file mode 100644 index 8471526..0000000 --- a/reverse_engineering/node_modules/readable-stream/errors.js +++ /dev/null @@ -1,116 +0,0 @@ -'use strict'; - -const codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error - } - - function getMessage (arg1, arg2, arg3) { - if (typeof message === 'string') { - return message - } else { - return message(arg1, arg2, arg3) - } - } - - class NodeError extends Base { - constructor (arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); - } - } - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - - codes[code] = NodeError; -} - -// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + - expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; - } - } else { - return `of ${thing} ${String(expected)}`; - } -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"' -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - let msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = includes(name, '.') ? 'property' : 'argument'; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; - } - - msg += `. Received type ${typeof actual}`; - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented' -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - -module.exports.codes = codes; diff --git a/reverse_engineering/node_modules/readable-stream/experimentalWarning.js b/reverse_engineering/node_modules/readable-stream/experimentalWarning.js deleted file mode 100644 index 78e8414..0000000 --- a/reverse_engineering/node_modules/readable-stream/experimentalWarning.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict' - -var experimentalWarnings = new Set(); - -function emitExperimentalWarning(feature) { - if (experimentalWarnings.has(feature)) return; - var msg = feature + ' is an experimental feature. This feature could ' + - 'change at any time'; - experimentalWarnings.add(feature); - process.emitWarning(msg, 'ExperimentalWarning'); -} - -function noop() {} - -module.exports.emitExperimentalWarning = process.emitWarning - ? emitExperimentalWarning - : noop; diff --git a/reverse_engineering/node_modules/readable-stream/lib/_stream_duplex.js b/reverse_engineering/node_modules/readable-stream/lib/_stream_duplex.js deleted file mode 100644 index 6752519..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/_stream_duplex.js +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/_stream_passthrough.js b/reverse_engineering/node_modules/readable-stream/lib/_stream_passthrough.js deleted file mode 100644 index 32e7414..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/_stream_passthrough.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/_stream_readable.js b/reverse_engineering/node_modules/readable-stream/lib/_stream_readable.js deleted file mode 100644 index 192d451..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/_stream_readable.js +++ /dev/null @@ -1,1124 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/_stream_transform.js b/reverse_engineering/node_modules/readable-stream/lib/_stream_transform.js deleted file mode 100644 index 41a738c..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/_stream_transform.js +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/_stream_writable.js b/reverse_engineering/node_modules/readable-stream/lib/_stream_writable.js deleted file mode 100644 index a2634d7..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/_stream_writable.js +++ /dev/null @@ -1,697 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/async_iterator.js deleted file mode 100644 index 9fb615a..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/async_iterator.js +++ /dev/null @@ -1,207 +0,0 @@ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/buffer_list.js deleted file mode 100644 index cdea425..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/buffer_list.js +++ /dev/null @@ -1,210 +0,0 @@ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/destroy.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/destroy.js deleted file mode 100644 index 3268a16..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/destroy.js +++ /dev/null @@ -1,105 +0,0 @@ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/end-of-stream.js deleted file mode 100644 index 831f286..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/end-of-stream.js +++ /dev/null @@ -1,104 +0,0 @@ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/from-browser.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/from-browser.js deleted file mode 100644 index a4ce56f..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/from-browser.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/from.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/from.js deleted file mode 100644 index 6c41284..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/from.js +++ /dev/null @@ -1,64 +0,0 @@ -'use strict'; - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; - -function from(Readable, iterable, opts) { - var iterator; - - if (iterable && typeof iterable.next === 'function') { - iterator = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); - - var readable = new Readable(_objectSpread({ - objectMode: true - }, opts)); // Reading boolean to protect against _read - // being called before last iteration completion. - - var reading = false; - - readable._read = function () { - if (!reading) { - reading = true; - next(); - } - }; - - function next() { - return _next2.apply(this, arguments); - } - - function _next2() { - _next2 = _asyncToGenerator(function* () { - try { - var _ref = yield iterator.next(), - value = _ref.value, - done = _ref.done; - - if (done) { - readable.push(null); - } else if (readable.push((yield value))) { - next(); - } else { - reading = false; - } - } catch (err) { - readable.destroy(err); - } - }); - return _next2.apply(this, arguments); - } - - return readable; -} - -module.exports = from; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/pipeline.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/pipeline.js deleted file mode 100644 index 6589909..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/pipeline.js +++ /dev/null @@ -1,97 +0,0 @@ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/state.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/state.js deleted file mode 100644 index 19887eb..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/state.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; \ No newline at end of file diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream-browser.js deleted file mode 100644 index 9332a3f..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream-browser.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('events').EventEmitter; diff --git a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream.js b/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream.js deleted file mode 100644 index ce2ad5b..0000000 --- a/reverse_engineering/node_modules/readable-stream/lib/internal/streams/stream.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('stream'); diff --git a/reverse_engineering/node_modules/readable-stream/package.json b/reverse_engineering/node_modules/readable-stream/package.json deleted file mode 100644 index b27d51c..0000000 --- a/reverse_engineering/node_modules/readable-stream/package.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "_from": "readable-stream@^3.0.0", - "_id": "readable-stream@3.6.0", - "_inBundle": false, - "_integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "_location": "/readable-stream", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "readable-stream@^3.0.0", - "name": "readable-stream", - "escapedName": "readable-stream", - "rawSpec": "^3.0.0", - "saveSpec": null, - "fetchSpec": "^3.0.0" - }, - "_requiredBy": [ - "/split2" - ], - "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "_shasum": "337bbda3adc0706bd3e024426a286d4b4b2c9198", - "_spec": "readable-stream@^3.0.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/split2", - "browser": { - "util": false, - "worker_threads": false, - "./errors": "./errors-browser.js", - "./readable.js": "./readable-browser.js", - "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", - "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" - }, - "bugs": { - "url": "https://github.com/nodejs/readable-stream/issues" - }, - "bundleDependencies": false, - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "deprecated": false, - "description": "Streams3, a user-land copy of the stream library from Node.js", - "devDependencies": { - "@babel/cli": "^7.2.0", - "@babel/core": "^7.2.0", - "@babel/polyfill": "^7.0.0", - "@babel/preset-env": "^7.2.0", - "airtap": "0.0.9", - "assert": "^1.4.0", - "bl": "^2.0.0", - "deep-strict-equal": "^0.2.0", - "events.once": "^2.0.2", - "glob": "^7.1.2", - "gunzip-maybe": "^1.4.1", - "hyperquest": "^2.1.3", - "lolex": "^2.6.0", - "nyc": "^11.0.0", - "pump": "^3.0.0", - "rimraf": "^2.6.2", - "tap": "^12.0.0", - "tape": "^4.9.0", - "tar-fs": "^1.16.2", - "util-promisify": "^2.1.0" - }, - "engines": { - "node": ">= 6" - }, - "homepage": "https://github.com/nodejs/readable-stream#readme", - "keywords": [ - "readable", - "stream", - "pipe" - ], - "license": "MIT", - "main": "readable.js", - "name": "readable-stream", - "nyc": { - "include": [ - "lib/**.js" - ] - }, - "repository": { - "type": "git", - "url": "git://github.com/nodejs/readable-stream.git" - }, - "scripts": { - "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", - "cover": "nyc npm test", - "report": "nyc report --reporter=lcov", - "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", - "test-browser-local": "airtap --open --local -- test/browser.js", - "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", - "update-browser-errors": "babel -o errors-browser.js errors.js" - }, - "version": "3.6.0" -} diff --git a/reverse_engineering/node_modules/readable-stream/readable-browser.js b/reverse_engineering/node_modules/readable-stream/readable-browser.js deleted file mode 100644 index adbf60d..0000000 --- a/reverse_engineering/node_modules/readable-stream/readable-browser.js +++ /dev/null @@ -1,9 +0,0 @@ -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Stream = exports; -exports.Readable = exports; -exports.Writable = require('./lib/_stream_writable.js'); -exports.Duplex = require('./lib/_stream_duplex.js'); -exports.Transform = require('./lib/_stream_transform.js'); -exports.PassThrough = require('./lib/_stream_passthrough.js'); -exports.finished = require('./lib/internal/streams/end-of-stream.js'); -exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/reverse_engineering/node_modules/readable-stream/readable.js b/reverse_engineering/node_modules/readable-stream/readable.js deleted file mode 100644 index 9e0ca12..0000000 --- a/reverse_engineering/node_modules/readable-stream/readable.js +++ /dev/null @@ -1,16 +0,0 @@ -var Stream = require('stream'); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream.Readable; - Object.assign(module.exports, Stream); - module.exports.Stream = Stream; -} else { - exports = module.exports = require('./lib/_stream_readable.js'); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = require('./lib/_stream_writable.js'); - exports.Duplex = require('./lib/_stream_duplex.js'); - exports.Transform = require('./lib/_stream_transform.js'); - exports.PassThrough = require('./lib/_stream_passthrough.js'); - exports.finished = require('./lib/internal/streams/end-of-stream.js'); - exports.pipeline = require('./lib/internal/streams/pipeline.js'); -} diff --git a/reverse_engineering/node_modules/safe-buffer/LICENSE b/reverse_engineering/node_modules/safe-buffer/LICENSE deleted file mode 100644 index 0c068ce..0000000 --- a/reverse_engineering/node_modules/safe-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Feross Aboukhadijeh - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/safe-buffer/README.md b/reverse_engineering/node_modules/safe-buffer/README.md deleted file mode 100644 index e9a81af..0000000 --- a/reverse_engineering/node_modules/safe-buffer/README.md +++ /dev/null @@ -1,584 +0,0 @@ -# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] - -[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg -[travis-url]: https://travis-ci.org/feross/safe-buffer -[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg -[npm-url]: https://npmjs.org/package/safe-buffer -[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg -[downloads-url]: https://npmjs.org/package/safe-buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com - -#### Safer Node.js Buffer API - -**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, -`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** - -**Uses the built-in implementation when available.** - -## install - -``` -npm install safe-buffer -``` - -## usage - -The goal of this package is to provide a safe replacement for the node.js `Buffer`. - -It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to -the top of your node.js modules: - -```js -var Buffer = require('safe-buffer').Buffer - -// Existing buffer code will continue to work without issues: - -new Buffer('hey', 'utf8') -new Buffer([1, 2, 3], 'utf8') -new Buffer(obj) -new Buffer(16) // create an uninitialized buffer (potentially unsafe) - -// But you can use these new explicit APIs to make clear what you want: - -Buffer.from('hey', 'utf8') // convert from many types to a Buffer -Buffer.alloc(16) // create a zero-filled buffer (safe) -Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) -``` - -## api - -### Class Method: Buffer.from(array) - - -* `array` {Array} - -Allocates a new `Buffer` using an `array` of octets. - -```js -const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); - // creates a new Buffer containing ASCII bytes - // ['b','u','f','f','e','r'] -``` - -A `TypeError` will be thrown if `array` is not an `Array`. - -### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - - -* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or - a `new ArrayBuffer()` -* `byteOffset` {Number} Default: `0` -* `length` {Number} Default: `arrayBuffer.length - byteOffset` - -When passed a reference to the `.buffer` property of a `TypedArray` instance, -the newly created `Buffer` will share the same allocated memory as the -TypedArray. - -```js -const arr = new Uint16Array(2); -arr[0] = 5000; -arr[1] = 4000; - -const buf = Buffer.from(arr.buffer); // shares the memory with arr; - -console.log(buf); - // Prints: - -// changing the TypedArray changes the Buffer also -arr[1] = 6000; - -console.log(buf); - // Prints: -``` - -The optional `byteOffset` and `length` arguments specify a memory range within -the `arrayBuffer` that will be shared by the `Buffer`. - -```js -const ab = new ArrayBuffer(10); -const buf = Buffer.from(ab, 0, 2); -console.log(buf.length); - // Prints: 2 -``` - -A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. - -### Class Method: Buffer.from(buffer) - - -* `buffer` {Buffer} - -Copies the passed `buffer` data onto a new `Buffer` instance. - -```js -const buf1 = Buffer.from('buffer'); -const buf2 = Buffer.from(buf1); - -buf1[0] = 0x61; -console.log(buf1.toString()); - // 'auffer' -console.log(buf2.toString()); - // 'buffer' (copy is not changed) -``` - -A `TypeError` will be thrown if `buffer` is not a `Buffer`. - -### Class Method: Buffer.from(str[, encoding]) - - -* `str` {String} String to encode. -* `encoding` {String} Encoding to use, Default: `'utf8'` - -Creates a new `Buffer` containing the given JavaScript string `str`. If -provided, the `encoding` parameter identifies the character encoding. -If not provided, `encoding` defaults to `'utf8'`. - -```js -const buf1 = Buffer.from('this is a tést'); -console.log(buf1.toString()); - // prints: this is a tést -console.log(buf1.toString('ascii')); - // prints: this is a tC)st - -const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); -console.log(buf2.toString()); - // prints: this is a tést -``` - -A `TypeError` will be thrown if `str` is not a string. - -### Class Method: Buffer.alloc(size[, fill[, encoding]]) - - -* `size` {Number} -* `fill` {Value} Default: `undefined` -* `encoding` {String} Default: `utf8` - -Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the -`Buffer` will be *zero-filled*. - -```js -const buf = Buffer.alloc(5); -console.log(buf); - // -``` - -The `size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -If `fill` is specified, the allocated `Buffer` will be initialized by calling -`buf.fill(fill)`. See [`buf.fill()`][] for more information. - -```js -const buf = Buffer.alloc(5, 'a'); -console.log(buf); - // -``` - -If both `fill` and `encoding` are specified, the allocated `Buffer` will be -initialized by calling `buf.fill(fill, encoding)`. For example: - -```js -const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); -console.log(buf); - // -``` - -Calling `Buffer.alloc(size)` can be significantly slower than the alternative -`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance -contents will *never contain sensitive data*. - -A `TypeError` will be thrown if `size` is not a number. - -### Class Method: Buffer.allocUnsafe(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must -be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit -architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is -thrown. A zero-length Buffer will be created if a `size` less than or equal to -0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -```js -const buf = Buffer.allocUnsafe(5); -console.log(buf); - // - // (octets will be different, every time) -buf.fill(0); -console.log(buf); - // -``` - -A `TypeError` will be thrown if `size` is not a number. - -Note that the `Buffer` module pre-allocates an internal `Buffer` instance of -size `Buffer.poolSize` that is used as a pool for the fast allocation of new -`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated -`new Buffer(size)` constructor) only when `size` is less than or equal to -`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default -value of `Buffer.poolSize` is `8192` but can be modified. - -Use of this pre-allocated internal memory pool is a key difference between -calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. -Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer -pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal -Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The -difference is subtle but can be important when an application requires the -additional performance that `Buffer.allocUnsafe(size)` provides. - -### Class Method: Buffer.allocUnsafeSlow(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The -`size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, -allocations under 4KB are, by default, sliced from a single pre-allocated -`Buffer`. This allows applications to avoid the garbage collection overhead of -creating many individually allocated Buffers. This approach improves both -performance and memory usage by eliminating the need to track and cleanup as -many `Persistent` objects. - -However, in the case where a developer may need to retain a small chunk of -memory from a pool for an indeterminate amount of time, it may be appropriate -to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then -copy out the relevant bits. - -```js -// need to keep around a few small chunks of memory -const store = []; - -socket.on('readable', () => { - const data = socket.read(); - // allocate for retained data - const sb = Buffer.allocUnsafeSlow(10); - // copy the data into the new allocation - data.copy(sb, 0, 0, 10); - store.push(sb); -}); -``` - -Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* -a developer has observed undue memory retention in their applications. - -A `TypeError` will be thrown if `size` is not a number. - -### All the Rest - -The rest of the `Buffer` API is exactly the same as in node.js. -[See the docs](https://nodejs.org/api/buffer.html). - - -## Related links - -- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) -- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) - -## Why is `Buffer` unsafe? - -Today, the node.js `Buffer` constructor is overloaded to handle many different argument -types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), -`ArrayBuffer`, and also `Number`. - -The API is optimized for convenience: you can throw any type at it, and it will try to do -what you want. - -Because the Buffer constructor is so powerful, you often see code like this: - -```js -// Convert UTF-8 strings to hex -function toHex (str) { - return new Buffer(str).toString('hex') -} -``` - -***But what happens if `toHex` is called with a `Number` argument?*** - -### Remote Memory Disclosure - -If an attacker can make your program call the `Buffer` constructor with a `Number` -argument, then they can make it allocate uninitialized memory from the node.js process. -This could potentially disclose TLS private keys, user data, or database passwords. - -When the `Buffer` constructor is passed a `Number` argument, it returns an -**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like -this, you **MUST** overwrite the contents before returning it to the user. - -From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): - -> `new Buffer(size)` -> -> - `size` Number -> -> The underlying memory for `Buffer` instances created in this way is not initialized. -> **The contents of a newly created `Buffer` are unknown and could contain sensitive -> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. - -(Emphasis our own.) - -Whenever the programmer intended to create an uninitialized `Buffer` you often see code -like this: - -```js -var buf = new Buffer(16) - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### Would this ever be a problem in real code? - -Yes. It's surprisingly common to forget to check the type of your variables in a -dynamically-typed language like JavaScript. - -Usually the consequences of assuming the wrong type is that your program crashes with an -uncaught exception. But the failure mode for forgetting to check the type of arguments to -the `Buffer` constructor is more catastrophic. - -Here's an example of a vulnerable service that takes a JSON payload and converts it to -hex: - -```js -// Take a JSON payload {str: "some string"} and convert it to hex -var server = http.createServer(function (req, res) { - var data = '' - req.setEncoding('utf8') - req.on('data', function (chunk) { - data += chunk - }) - req.on('end', function () { - var body = JSON.parse(data) - res.end(new Buffer(body.str).toString('hex')) - }) -}) - -server.listen(8080) -``` - -In this example, an http client just has to send: - -```json -{ - "str": 1000 -} -``` - -and it will get back 1,000 bytes of uninitialized memory from the server. - -This is a very serious bug. It's similar in severity to the -[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process -memory by remote attackers. - - -### Which real-world packages were vulnerable? - -#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) - -[Mathias Buus](https://github.com/mafintosh) and I -([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, -[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow -anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get -them to reveal 20 bytes at a time of uninitialized memory from the node.js process. - -Here's -[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) -that fixed it. We released a new fixed version, created a -[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all -vulnerable versions on npm so users will get a warning to upgrade to a newer version. - -#### [`ws`](https://www.npmjs.com/package/ws) - -That got us wondering if there were other vulnerable packages. Sure enough, within a short -period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the -most popular WebSocket implementation in node.js. - -If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as -expected, then uninitialized server memory would be disclosed to the remote peer. - -These were the vulnerable methods: - -```js -socket.send(number) -socket.ping(number) -socket.pong(number) -``` - -Here's a vulnerable socket server with some echo functionality: - -```js -server.on('connection', function (socket) { - socket.on('message', function (message) { - message = JSON.parse(message) - if (message.type === 'echo') { - socket.send(message.data) // send back the user's message - } - }) -}) -``` - -`socket.send(number)` called on the server, will disclose server memory. - -Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue -was fixed, with a more detailed explanation. Props to -[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the -[Node Security Project disclosure](https://nodesecurity.io/advisories/67). - - -### What's the solution? - -It's important that node.js offers a fast way to get memory otherwise performance-critical -applications would needlessly get a lot slower. - -But we need a better way to *signal our intent* as programmers. **When we want -uninitialized memory, we should request it explicitly.** - -Sensitive functionality should not be packed into a developer-friendly API that loosely -accepts many different types. This type of API encourages the lazy practice of passing -variables in without checking the type very carefully. - -#### A new API: `Buffer.allocUnsafe(number)` - -The functionality of creating buffers with uninitialized memory should be part of another -API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that -frequently gets user input of all sorts of different types passed into it. - -```js -var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### How do we fix node.js core? - -We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as -`semver-major`) which defends against one case: - -```js -var str = 16 -new Buffer(str, 'utf8') -``` - -In this situation, it's implied that the programmer intended the first argument to be a -string, since they passed an encoding as a second argument. Today, node.js will allocate -uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not -what the programmer intended. - -But this is only a partial solution, since if the programmer does `new Buffer(variable)` -(without an `encoding` parameter) there's no way to know what they intended. If `variable` -is sometimes a number, then uninitialized memory will sometimes be returned. - -### What's the real long-term fix? - -We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when -we need uninitialized memory. But that would break 1000s of packages. - -~~We believe the best solution is to:~~ - -~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ - -~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ - -#### Update - -We now support adding three new APIs: - -- `Buffer.from(value)` - convert from any type to a buffer -- `Buffer.alloc(size)` - create a zero-filled buffer -- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size - -This solves the core problem that affected `ws` and `bittorrent-dht` which is -`Buffer(variable)` getting tricked into taking a number argument. - -This way, existing code continues working and the impact on the npm ecosystem will be -minimal. Over time, npm maintainers can migrate performance-critical code to use -`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. - - -### Conclusion - -We think there's a serious design issue with the `Buffer` API as it exists today. It -promotes insecure software by putting high-risk functionality into a convenient API -with friendly "developer ergonomics". - -This wasn't merely a theoretical exercise because we found the issue in some of the -most popular npm packages. - -Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of -`buffer`. - -```js -var Buffer = require('safe-buffer').Buffer -``` - -Eventually, we hope that node.js core can switch to this new, safer behavior. We believe -the impact on the ecosystem would be minimal since it's not a breaking change. -Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while -older, insecure packages would magically become safe from this attack vector. - - -## links - -- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) -- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) -- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) - - -## credit - -The original issues in `bittorrent-dht` -([disclosure](https://nodesecurity.io/advisories/68)) and -`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by -[Mathias Buus](https://github.com/mafintosh) and -[Feross Aboukhadijeh](http://feross.org/). - -Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues -and for his work running the [Node Security Project](https://nodesecurity.io/). - -Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and -auditing the code. - - -## license - -MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/reverse_engineering/node_modules/safe-buffer/index.d.ts b/reverse_engineering/node_modules/safe-buffer/index.d.ts deleted file mode 100644 index e9fed80..0000000 --- a/reverse_engineering/node_modules/safe-buffer/index.d.ts +++ /dev/null @@ -1,187 +0,0 @@ -declare module "safe-buffer" { - export class Buffer { - length: number - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - constructor (str: string, encoding?: string); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - constructor (size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - constructor (arrayBuffer: ArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - constructor (buffer: Buffer); - prototype: Buffer; - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - static from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - static from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - static from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - static isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - static isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - static byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - static concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - static compare(buf1: Buffer, buf2: Buffer): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafeSlow(size: number): Buffer; - } -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/safe-buffer/index.js b/reverse_engineering/node_modules/safe-buffer/index.js deleted file mode 100644 index f8d3ec9..0000000 --- a/reverse_engineering/node_modules/safe-buffer/index.js +++ /dev/null @@ -1,65 +0,0 @@ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} diff --git a/reverse_engineering/node_modules/safe-buffer/package.json b/reverse_engineering/node_modules/safe-buffer/package.json deleted file mode 100644 index 1d505e7..0000000 --- a/reverse_engineering/node_modules/safe-buffer/package.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "_from": "safe-buffer@~5.2.0", - "_id": "safe-buffer@5.2.1", - "_inBundle": false, - "_integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "_location": "/safe-buffer", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "safe-buffer@~5.2.0", - "name": "safe-buffer", - "escapedName": "safe-buffer", - "rawSpec": "~5.2.0", - "saveSpec": null, - "fetchSpec": "~5.2.0" - }, - "_requiredBy": [ - "/string_decoder" - ], - "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "_shasum": "1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6", - "_spec": "safe-buffer@~5.2.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/string_decoder", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "https://feross.org" - }, - "bugs": { - "url": "https://github.com/feross/safe-buffer/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Safer Node.js Buffer API", - "devDependencies": { - "standard": "*", - "tape": "^5.0.0" - }, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "homepage": "https://github.com/feross/safe-buffer", - "keywords": [ - "buffer", - "buffer allocate", - "node security", - "safe", - "safe-buffer", - "security", - "uninitialized" - ], - "license": "MIT", - "main": "index.js", - "name": "safe-buffer", - "repository": { - "type": "git", - "url": "git://github.com/feross/safe-buffer.git" - }, - "scripts": { - "test": "standard && tape test/*.js" - }, - "types": "index.d.ts", - "version": "5.2.1" -} diff --git a/reverse_engineering/node_modules/safer-buffer/LICENSE b/reverse_engineering/node_modules/safer-buffer/LICENSE deleted file mode 100644 index 4fe9e6f..0000000 --- a/reverse_engineering/node_modules/safer-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Nikita Skovoroda - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/reverse_engineering/node_modules/safer-buffer/Porting-Buffer.md b/reverse_engineering/node_modules/safer-buffer/Porting-Buffer.md deleted file mode 100644 index 68d86ba..0000000 --- a/reverse_engineering/node_modules/safer-buffer/Porting-Buffer.md +++ /dev/null @@ -1,268 +0,0 @@ -# Porting to the Buffer.from/Buffer.alloc API - - -## Overview - -- [Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x.](#variant-1) (*recommended*) -- [Variant 2: Use a polyfill](#variant-2) -- [Variant 3: manual detection, with safeguards](#variant-3) - -### Finding problematic bits of code using grep - -Just run `grep -nrE '[^a-zA-Z](Slow)?Buffer\s*\(' --exclude-dir node_modules`. - -It will find all the potentially unsafe places in your own code (with some considerably unlikely -exceptions). - -### Finding problematic bits of code using Node.js 8 - -If you’re using Node.js ≥ 8.0.0 (which is recommended), Node.js exposes multiple options that help with finding the relevant pieces of code: - -- `--trace-warnings` will make Node.js show a stack trace for this warning and other warnings that are printed by Node.js. -- `--trace-deprecation` does the same thing, but only for deprecation warnings. -- `--pending-deprecation` will show more types of deprecation warnings. In particular, it will show the `Buffer()` deprecation warning, even on Node.js 8. - -You can set these flags using an environment variable: - -```console -$ export NODE_OPTIONS='--trace-warnings --pending-deprecation' -$ cat example.js -'use strict'; -const foo = new Buffer('foo'); -$ node example.js -(node:7147) [DEP0005] DeprecationWarning: The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead. - at showFlaggedDeprecation (buffer.js:127:13) - at new Buffer (buffer.js:148:3) - at Object. (/path/to/example.js:2:13) - [... more stack trace lines ...] -``` - -### Finding problematic bits of code using linters - -Eslint rules [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) -or -[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) -also find calls to deprecated `Buffer()` API. Those rules are included in some pre-sets. - -There is a drawback, though, that it doesn't always -[work correctly](https://github.com/chalker/safer-buffer#why-not-safe-buffer) when `Buffer` is -overriden e.g. with a polyfill, so recommended is a combination of this and some other method -described above. - - -## Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x. - -This is the recommended solution nowadays that would imply only minimal overhead. - -The Node.js 5.x release line has been unsupported since July 2016, and the Node.js 4.x release line reaches its End of Life in April 2018 (→ [Schedule](https://github.com/nodejs/Release#release-schedule)). This means that these versions of Node.js will *not* receive any updates, even in case of security issues, so using these release lines should be avoided, if at all possible. - -What you would do in this case is to convert all `new Buffer()` or `Buffer()` calls to use `Buffer.alloc()` or `Buffer.from()`, in the following way: - -- For `new Buffer(number)`, replace it with `Buffer.alloc(number)`. -- For `new Buffer(string)` (or `new Buffer(string, encoding)`), replace it with `Buffer.from(string)` (or `Buffer.from(string, encoding)`). -- For all other combinations of arguments (these are much rarer), also replace `new Buffer(...arguments)` with `Buffer.from(...arguments)`. - -Note that `Buffer.alloc()` is also _faster_ on the current Node.js versions than -`new Buffer(size).fill(0)`, which is what you would otherwise need to ensure zero-filling. - -Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) -or -[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) -is recommended to avoid accidential unsafe Buffer API usage. - -There is also a [JSCodeshift codemod](https://github.com/joyeecheung/node-dep-codemod#dep005) -for automatically migrating Buffer constructors to `Buffer.alloc()` or `Buffer.from()`. -Note that it currently only works with cases where the arguments are literals or where the -constructor is invoked with two arguments. - -_If you currently support those older Node.js versions and dropping them would be a semver-major change -for you, or if you support older branches of your packages, consider using [Variant 2](#variant-2) -or [Variant 3](#variant-3) on older branches, so people using those older branches will also receive -the fix. That way, you will eradicate potential issues caused by unguarded Buffer API usage and -your users will not observe a runtime deprecation warning when running your code on Node.js 10._ - - -## Variant 2: Use a polyfill - -Utilize [safer-buffer](https://www.npmjs.com/package/safer-buffer) as a polyfill to support older -Node.js versions. - -You would take exacly the same steps as in [Variant 1](#variant-1), but with a polyfill -`const Buffer = require('safer-buffer').Buffer` in all files where you use the new `Buffer` api. - -Make sure that you do not use old `new Buffer` API — in any files where the line above is added, -using old `new Buffer()` API will _throw_. It will be easy to notice that in CI, though. - -Alternatively, you could use [buffer-from](https://www.npmjs.com/package/buffer-from) and/or -[buffer-alloc](https://www.npmjs.com/package/buffer-alloc) [ponyfills](https://ponyfill.com/) — -those are great, the only downsides being 4 deps in the tree and slightly more code changes to -migrate off them (as you would be using e.g. `Buffer.from` under a different name). If you need only -`Buffer.from` polyfilled — `buffer-from` alone which comes with no extra dependencies. - -_Alternatively, you could use [safe-buffer](https://www.npmjs.com/package/safe-buffer) — it also -provides a polyfill, but takes a different approach which has -[it's drawbacks](https://github.com/chalker/safer-buffer#why-not-safe-buffer). It will allow you -to also use the older `new Buffer()` API in your code, though — but that's arguably a benefit, as -it is problematic, can cause issues in your code, and will start emitting runtime deprecation -warnings starting with Node.js 10._ - -Note that in either case, it is important that you also remove all calls to the old Buffer -API manually — just throwing in `safe-buffer` doesn't fix the problem by itself, it just provides -a polyfill for the new API. I have seen people doing that mistake. - -Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) -or -[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) -is recommended. - -_Don't forget to drop the polyfill usage once you drop support for Node.js < 4.5.0._ - - -## Variant 3 — manual detection, with safeguards - -This is useful if you create Buffer instances in only a few places (e.g. one), or you have your own -wrapper around them. - -### Buffer(0) - -This special case for creating empty buffers can be safely replaced with `Buffer.concat([])`, which -returns the same result all the way down to Node.js 0.8.x. - -### Buffer(notNumber) - -Before: - -```js -var buf = new Buffer(notNumber, encoding); -``` - -After: - -```js -var buf; -if (Buffer.from && Buffer.from !== Uint8Array.from) { - buf = Buffer.from(notNumber, encoding); -} else { - if (typeof notNumber === 'number') - throw new Error('The "size" argument must be of type number.'); - buf = new Buffer(notNumber, encoding); -} -``` - -`encoding` is optional. - -Note that the `typeof notNumber` before `new Buffer` is required (for cases when `notNumber` argument is not -hard-coded) and _is not caused by the deprecation of Buffer constructor_ — it's exactly _why_ the -Buffer constructor is deprecated. Ecosystem packages lacking this type-check caused numereous -security issues — situations when unsanitized user input could end up in the `Buffer(arg)` create -problems ranging from DoS to leaking sensitive information to the attacker from the process memory. - -When `notNumber` argument is hardcoded (e.g. literal `"abc"` or `[0,1,2]`), the `typeof` check can -be omitted. - -Also note that using TypeScript does not fix this problem for you — when libs written in -`TypeScript` are used from JS, or when user input ends up there — it behaves exactly as pure JS, as -all type checks are translation-time only and are not present in the actual JS code which TS -compiles to. - -### Buffer(number) - -For Node.js 0.10.x (and below) support: - -```js -var buf; -if (Buffer.alloc) { - buf = Buffer.alloc(number); -} else { - buf = new Buffer(number); - buf.fill(0); -} -``` - -Otherwise (Node.js ≥ 0.12.x): - -```js -const buf = Buffer.alloc ? Buffer.alloc(number) : new Buffer(number).fill(0); -``` - -## Regarding Buffer.allocUnsafe - -Be extra cautious when using `Buffer.allocUnsafe`: - * Don't use it if you don't have a good reason to - * e.g. you probably won't ever see a performance difference for small buffers, in fact, those - might be even faster with `Buffer.alloc()`, - * if your code is not in the hot code path — you also probably won't notice a difference, - * keep in mind that zero-filling minimizes the potential risks. - * If you use it, make sure that you never return the buffer in a partially-filled state, - * if you are writing to it sequentially — always truncate it to the actuall written length - -Errors in handling buffers allocated with `Buffer.allocUnsafe` could result in various issues, -ranged from undefined behaviour of your code to sensitive data (user input, passwords, certs) -leaking to the remote attacker. - -_Note that the same applies to `new Buffer` usage without zero-filling, depending on the Node.js -version (and lacking type checks also adds DoS to the list of potential problems)._ - - -## FAQ - - -### What is wrong with the `Buffer` constructor? - -The `Buffer` constructor could be used to create a buffer in many different ways: - -- `new Buffer(42)` creates a `Buffer` of 42 bytes. Before Node.js 8, this buffer contained - *arbitrary memory* for performance reasons, which could include anything ranging from - program source code to passwords and encryption keys. -- `new Buffer('abc')` creates a `Buffer` that contains the UTF-8-encoded version of - the string `'abc'`. A second argument could specify another encoding: For example, - `new Buffer(string, 'base64')` could be used to convert a Base64 string into the original - sequence of bytes that it represents. -- There are several other combinations of arguments. - -This meant that, in code like `var buffer = new Buffer(foo);`, *it is not possible to tell -what exactly the contents of the generated buffer are* without knowing the type of `foo`. - -Sometimes, the value of `foo` comes from an external source. For example, this function -could be exposed as a service on a web server, converting a UTF-8 string into its Base64 form: - -``` -function stringToBase64(req, res) { - // The request body should have the format of `{ string: 'foobar' }` - const rawBytes = new Buffer(req.body.string) - const encoded = rawBytes.toString('base64') - res.end({ encoded: encoded }) -} -``` - -Note that this code does *not* validate the type of `req.body.string`: - -- `req.body.string` is expected to be a string. If this is the case, all goes well. -- `req.body.string` is controlled by the client that sends the request. -- If `req.body.string` is the *number* `50`, the `rawBytes` would be 50 bytes: - - Before Node.js 8, the content would be uninitialized - - After Node.js 8, the content would be `50` bytes with the value `0` - -Because of the missing type check, an attacker could intentionally send a number -as part of the request. Using this, they can either: - -- Read uninitialized memory. This **will** leak passwords, encryption keys and other - kinds of sensitive information. (Information leak) -- Force the program to allocate a large amount of memory. For example, when specifying - `500000000` as the input value, each request will allocate 500MB of memory. - This can be used to either exhaust the memory available of a program completely - and make it crash, or slow it down significantly. (Denial of Service) - -Both of these scenarios are considered serious security issues in a real-world -web server context. - -when using `Buffer.from(req.body.string)` instead, passing a number will always -throw an exception instead, giving a controlled behaviour that can always be -handled by the program. - - -### The `Buffer()` constructor has been deprecated for a while. Is this really an issue? - -Surveys of code in the `npm` ecosystem have shown that the `Buffer()` constructor is still -widely used. This includes new code, and overall usage of such code has actually been -*increasing*. diff --git a/reverse_engineering/node_modules/safer-buffer/Readme.md b/reverse_engineering/node_modules/safer-buffer/Readme.md deleted file mode 100644 index 14b0822..0000000 --- a/reverse_engineering/node_modules/safer-buffer/Readme.md +++ /dev/null @@ -1,156 +0,0 @@ -# safer-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![javascript style guide][standard-image]][standard-url] [![Security Responsible Disclosure][secuirty-image]][secuirty-url] - -[travis-image]: https://travis-ci.org/ChALkeR/safer-buffer.svg?branch=master -[travis-url]: https://travis-ci.org/ChALkeR/safer-buffer -[npm-image]: https://img.shields.io/npm/v/safer-buffer.svg -[npm-url]: https://npmjs.org/package/safer-buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com -[secuirty-image]: https://img.shields.io/badge/Security-Responsible%20Disclosure-green.svg -[secuirty-url]: https://github.com/nodejs/security-wg/blob/master/processes/responsible_disclosure_template.md - -Modern Buffer API polyfill without footguns, working on Node.js from 0.8 to current. - -## How to use? - -First, port all `Buffer()` and `new Buffer()` calls to `Buffer.alloc()` and `Buffer.from()` API. - -Then, to achieve compatibility with outdated Node.js versions (`<4.5.0` and 5.x `<5.9.0`), use -`const Buffer = require('safer-buffer').Buffer` in all files where you make calls to the new -Buffer API. _Use `var` instead of `const` if you need that for your Node.js version range support._ - -Also, see the -[porting Buffer](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) guide. - -## Do I need it? - -Hopefully, not — dropping support for outdated Node.js versions should be fine nowdays, and that -is the recommended path forward. You _do_ need to port to the `Buffer.alloc()` and `Buffer.from()` -though. - -See the [porting guide](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) -for a better description. - -## Why not [safe-buffer](https://npmjs.com/safe-buffer)? - -_In short: while `safe-buffer` serves as a polyfill for the new API, it allows old API usage and -itself contains footguns._ - -`safe-buffer` could be used safely to get the new API while still keeping support for older -Node.js versions (like this module), but while analyzing ecosystem usage of the old Buffer API -I found out that `safe-buffer` is itself causing problems in some cases. - -For example, consider the following snippet: - -```console -$ cat example.unsafe.js -console.log(Buffer(20)) -$ ./node-v6.13.0-linux-x64/bin/node example.unsafe.js - -$ standard example.unsafe.js -standard: Use JavaScript Standard Style (https://standardjs.com) - /home/chalker/repo/safer-buffer/example.unsafe.js:2:13: 'Buffer()' was deprecated since v6. Use 'Buffer.alloc()' or 'Buffer.from()' (use 'https://www.npmjs.com/package/safe-buffer' for '<4.5.0') instead. -``` - -This is allocates and writes to console an uninitialized chunk of memory. -[standard](https://www.npmjs.com/package/standard) linter (among others) catch that and warn people -to avoid using unsafe API. - -Let's now throw in `safe-buffer`! - -```console -$ cat example.safe-buffer.js -const Buffer = require('safe-buffer').Buffer -console.log(Buffer(20)) -$ standard example.safe-buffer.js -$ ./node-v6.13.0-linux-x64/bin/node example.safe-buffer.js - -``` - -See the problem? Adding in `safe-buffer` _magically removes the lint warning_, but the behavior -remains identiсal to what we had before, and when launched on Node.js 6.x LTS — this dumps out -chunks of uninitialized memory. -_And this code will still emit runtime warnings on Node.js 10.x and above._ - -That was done by design. I first considered changing `safe-buffer`, prohibiting old API usage or -emitting warnings on it, but that significantly diverges from `safe-buffer` design. After some -discussion, it was decided to move my approach into a separate package, and _this is that separate -package_. - -This footgun is not imaginary — I observed top-downloaded packages doing that kind of thing, -«fixing» the lint warning by blindly including `safe-buffer` without any actual changes. - -Also in some cases, even if the API _was_ migrated to use of safe Buffer API — a random pull request -can bring unsafe Buffer API usage back to the codebase by adding new calls — and that could go -unnoticed even if you have a linter prohibiting that (becase of the reason stated above), and even -pass CI. _I also observed that being done in popular packages._ - -Some examples: - * [webdriverio](https://github.com/webdriverio/webdriverio/commit/05cbd3167c12e4930f09ef7cf93b127ba4effae4#diff-124380949022817b90b622871837d56cR31) - (a module with 548 759 downloads/month), - * [websocket-stream](https://github.com/maxogden/websocket-stream/commit/c9312bd24d08271687d76da0fe3c83493871cf61) - (218 288 d/m, fix in [maxogden/websocket-stream#142](https://github.com/maxogden/websocket-stream/pull/142)), - * [node-serialport](https://github.com/node-serialport/node-serialport/commit/e8d9d2b16c664224920ce1c895199b1ce2def48c) - (113 138 d/m, fix in [node-serialport/node-serialport#1510](https://github.com/node-serialport/node-serialport/pull/1510)), - * [karma](https://github.com/karma-runner/karma/commit/3d94b8cf18c695104ca195334dc75ff054c74eec) - (3 973 193 d/m, fix in [karma-runner/karma#2947](https://github.com/karma-runner/karma/pull/2947)), - * [spdy-transport](https://github.com/spdy-http2/spdy-transport/commit/5375ac33f4a62a4f65bcfc2827447d42a5dbe8b1) - (5 970 727 d/m, fix in [spdy-http2/spdy-transport#53](https://github.com/spdy-http2/spdy-transport/pull/53)). - * And there are a lot more over the ecosystem. - -I filed a PR at -[mysticatea/eslint-plugin-node#110](https://github.com/mysticatea/eslint-plugin-node/pull/110) to -partially fix that (for cases when that lint rule is used), but it is a semver-major change for -linter rules and presets, so it would take significant time for that to reach actual setups. -_It also hasn't been released yet (2018-03-20)._ - -Also, `safer-buffer` discourages the usage of `.allocUnsafe()`, which is often done by a mistake. -It still supports it with an explicit concern barier, by placing it under -`require('safer-buffer/dangereous')`. - -## But isn't throwing bad? - -Not really. It's an error that could be noticed and fixed early, instead of causing havoc later like -unguarded `new Buffer()` calls that end up receiving user input can do. - -This package affects only the files where `var Buffer = require('safer-buffer').Buffer` was done, so -it is really simple to keep track of things and make sure that you don't mix old API usage with that. -Also, CI should hint anything that you might have missed. - -New commits, if tested, won't land new usage of unsafe Buffer API this way. -_Node.js 10.x also deals with that by printing a runtime depecation warning._ - -### Would it affect third-party modules? - -No, unless you explicitly do an awful thing like monkey-patching or overriding the built-in `Buffer`. -Don't do that. - -### But I don't want throwing… - -That is also fine! - -Also, it could be better in some cases when you don't comprehensive enough test coverage. - -In that case — just don't override `Buffer` and use -`var SaferBuffer = require('safer-buffer').Buffer` instead. - -That way, everything using `Buffer` natively would still work, but there would be two drawbacks: - -* `Buffer.from`/`Buffer.alloc` won't be polyfilled — use `SaferBuffer.from` and - `SaferBuffer.alloc` instead. -* You are still open to accidentally using the insecure deprecated API — use a linter to catch that. - -Note that using a linter to catch accidential `Buffer` constructor usage in this case is strongly -recommended. `Buffer` is not overriden in this usecase, so linters won't get confused. - -## «Without footguns»? - -Well, it is still possible to do _some_ things with `Buffer` API, e.g. accessing `.buffer` property -on older versions and duping things from there. You shouldn't do that in your code, probabably. - -The intention is to remove the most significant footguns that affect lots of packages in the -ecosystem, and to do it in the proper way. - -Also, this package doesn't protect against security issues affecting some Node.js versions, so for -usage in your own production code, it is still recommended to update to a Node.js version -[supported by upstream](https://github.com/nodejs/release#release-schedule). diff --git a/reverse_engineering/node_modules/safer-buffer/dangerous.js b/reverse_engineering/node_modules/safer-buffer/dangerous.js deleted file mode 100644 index ca41fdc..0000000 --- a/reverse_engineering/node_modules/safer-buffer/dangerous.js +++ /dev/null @@ -1,58 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ - -'use strict' - -var buffer = require('buffer') -var Buffer = buffer.Buffer -var safer = require('./safer.js') -var Safer = safer.Buffer - -var dangerous = {} - -var key - -for (key in safer) { - if (!safer.hasOwnProperty(key)) continue - dangerous[key] = safer[key] -} - -var Dangereous = dangerous.Buffer = {} - -// Copy Safer API -for (key in Safer) { - if (!Safer.hasOwnProperty(key)) continue - Dangereous[key] = Safer[key] -} - -// Copy those missing unsafe methods, if they are present -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (Dangereous.hasOwnProperty(key)) continue - Dangereous[key] = Buffer[key] -} - -if (!Dangereous.allocUnsafe) { - Dangereous.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - return Buffer(size) - } -} - -if (!Dangereous.allocUnsafeSlow) { - Dangereous.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - return buffer.SlowBuffer(size) - } -} - -module.exports = dangerous diff --git a/reverse_engineering/node_modules/safer-buffer/package.json b/reverse_engineering/node_modules/safer-buffer/package.json deleted file mode 100644 index aafd759..0000000 --- a/reverse_engineering/node_modules/safer-buffer/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "_from": "safer-buffer@~2.1.0", - "_id": "safer-buffer@2.1.2", - "_inBundle": false, - "_integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "_location": "/safer-buffer", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "safer-buffer@~2.1.0", - "name": "safer-buffer", - "escapedName": "safer-buffer", - "rawSpec": "~2.1.0", - "saveSpec": null, - "fetchSpec": "~2.1.0" - }, - "_requiredBy": [ - "/asn1" - ], - "_resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "_shasum": "44fa161b0187b9549dd84bb91802f9bd8385cd6a", - "_spec": "safer-buffer@~2.1.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/asn1", - "author": { - "name": "Nikita Skovoroda", - "email": "chalkerx@gmail.com", - "url": "https://github.com/ChALkeR" - }, - "bugs": { - "url": "https://github.com/ChALkeR/safer-buffer/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Modern Buffer API polyfill without footguns", - "devDependencies": { - "standard": "^11.0.1", - "tape": "^4.9.0" - }, - "files": [ - "Porting-Buffer.md", - "Readme.md", - "tests.js", - "dangerous.js", - "safer.js" - ], - "homepage": "https://github.com/ChALkeR/safer-buffer#readme", - "license": "MIT", - "main": "safer.js", - "name": "safer-buffer", - "repository": { - "type": "git", - "url": "git+https://github.com/ChALkeR/safer-buffer.git" - }, - "scripts": { - "browserify-test": "browserify --external tape tests.js > browserify-tests.js && tape browserify-tests.js", - "test": "standard && tape tests.js" - }, - "version": "2.1.2" -} diff --git a/reverse_engineering/node_modules/safer-buffer/safer.js b/reverse_engineering/node_modules/safer-buffer/safer.js deleted file mode 100644 index 37c7e1a..0000000 --- a/reverse_engineering/node_modules/safer-buffer/safer.js +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ - -'use strict' - -var buffer = require('buffer') -var Buffer = buffer.Buffer - -var safer = {} - -var key - -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} - -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} - -safer.Buffer.prototype = Buffer.prototype - -if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) - } - if (value && typeof value.length === 'undefined') { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) - } - return Buffer(value, encodingOrOffset, length) - } -} - -if (!Safer.alloc) { - Safer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - var buf = Buffer(size) - if (!fill || fill.length === 0) { - buf.fill(0) - } else if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - return buf - } -} - -if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding('buffer').kStringMaxLength - } catch (e) { - // we can't determine kStringMaxLength in environments where process.binding - // is unsupported, so let's not set it - } -} - -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } -} - -module.exports = safer diff --git a/reverse_engineering/node_modules/safer-buffer/tests.js b/reverse_engineering/node_modules/safer-buffer/tests.js deleted file mode 100644 index 7ed2777..0000000 --- a/reverse_engineering/node_modules/safer-buffer/tests.js +++ /dev/null @@ -1,406 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ - -'use strict' - -var test = require('tape') - -var buffer = require('buffer') - -var index = require('./') -var safer = require('./safer') -var dangerous = require('./dangerous') - -/* Inheritance tests */ - -test('Default is Safer', function (t) { - t.equal(index, safer) - t.notEqual(safer, dangerous) - t.notEqual(index, dangerous) - t.end() -}) - -test('Is not a function', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(typeof impl, 'object') - t.equal(typeof impl.Buffer, 'object') - }); - [buffer].forEach(function (impl) { - t.equal(typeof impl, 'object') - t.equal(typeof impl.Buffer, 'function') - }) - t.end() -}) - -test('Constructor throws', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.throws(function () { impl.Buffer() }) - t.throws(function () { impl.Buffer(0) }) - t.throws(function () { impl.Buffer('a') }) - t.throws(function () { impl.Buffer('a', 'utf-8') }) - t.throws(function () { return new impl.Buffer() }) - t.throws(function () { return new impl.Buffer(0) }) - t.throws(function () { return new impl.Buffer('a') }) - t.throws(function () { return new impl.Buffer('a', 'utf-8') }) - }) - t.end() -}) - -test('Safe methods exist', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(typeof impl.Buffer.alloc, 'function', 'alloc') - t.equal(typeof impl.Buffer.from, 'function', 'from') - }) - t.end() -}) - -test('Unsafe methods exist only in Dangerous', function (t) { - [index, safer].forEach(function (impl) { - t.equal(typeof impl.Buffer.allocUnsafe, 'undefined') - t.equal(typeof impl.Buffer.allocUnsafeSlow, 'undefined') - }); - [dangerous].forEach(function (impl) { - t.equal(typeof impl.Buffer.allocUnsafe, 'function') - t.equal(typeof impl.Buffer.allocUnsafeSlow, 'function') - }) - t.end() -}) - -test('Generic methods/properties are defined and equal', function (t) { - ['poolSize', 'isBuffer', 'concat', 'byteLength'].forEach(function (method) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], buffer.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -test('Built-in buffer static methods/properties are inherited', function (t) { - Object.keys(buffer).forEach(function (method) { - if (method === 'SlowBuffer' || method === 'Buffer') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl[method], buffer[method], method) - t.notEqual(typeof impl[method], 'undefined', method) - }) - }) - t.end() -}) - -test('Built-in Buffer static methods/properties are inherited', function (t) { - Object.keys(buffer.Buffer).forEach(function (method) { - if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], buffer.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -test('.prototype property of Buffer is inherited', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer.prototype, buffer.Buffer.prototype, 'prototype') - t.notEqual(typeof impl.Buffer.prototype, 'undefined', 'prototype') - }) - t.end() -}) - -test('All Safer methods are present in Dangerous', function (t) { - Object.keys(safer).forEach(function (method) { - if (method === 'Buffer') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl[method], safer[method], method) - if (method !== 'kStringMaxLength') { - t.notEqual(typeof impl[method], 'undefined', method) - } - }) - }) - Object.keys(safer.Buffer).forEach(function (method) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], safer.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -test('Safe methods from Dangerous methods are present in Safer', function (t) { - Object.keys(dangerous).forEach(function (method) { - if (method === 'Buffer') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl[method], dangerous[method], method) - if (method !== 'kStringMaxLength') { - t.notEqual(typeof impl[method], 'undefined', method) - } - }) - }) - Object.keys(dangerous.Buffer).forEach(function (method) { - if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer[method], dangerous.Buffer[method], method) - t.notEqual(typeof impl.Buffer[method], 'undefined', method) - }) - }) - t.end() -}) - -/* Behaviour tests */ - -test('Methods return Buffers', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 10))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 'a'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10, 'x'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(9, 'ab'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(''))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string', 'utf-8'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([0, 42, 3]))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(new Uint8Array([0, 42, 3])))) - t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([]))) - }); - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](0))) - t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](10))) - }) - t.end() -}) - -test('Constructor is buffer.Buffer', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer.alloc(0).constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(0, 10).constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(0, 'a').constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(10).constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(10, 'x').constructor, buffer.Buffer) - t.equal(impl.Buffer.alloc(9, 'ab').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('string').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('string', 'utf-8').constructor, buffer.Buffer) - t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').constructor, buffer.Buffer) - t.equal(impl.Buffer.from([0, 42, 3]).constructor, buffer.Buffer) - t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).constructor, buffer.Buffer) - t.equal(impl.Buffer.from([]).constructor, buffer.Buffer) - }); - [0, 10, 100].forEach(function (arg) { - t.equal(dangerous.Buffer.allocUnsafe(arg).constructor, buffer.Buffer) - t.equal(dangerous.Buffer.allocUnsafeSlow(arg).constructor, buffer.SlowBuffer(0).constructor) - }) - t.end() -}) - -test('Invalid calls throw', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.throws(function () { impl.Buffer.from(0) }) - t.throws(function () { impl.Buffer.from(10) }) - t.throws(function () { impl.Buffer.from(10, 'utf-8') }) - t.throws(function () { impl.Buffer.from('string', 'invalid encoding') }) - t.throws(function () { impl.Buffer.from(-10) }) - t.throws(function () { impl.Buffer.from(1e90) }) - t.throws(function () { impl.Buffer.from(Infinity) }) - t.throws(function () { impl.Buffer.from(-Infinity) }) - t.throws(function () { impl.Buffer.from(NaN) }) - t.throws(function () { impl.Buffer.from(null) }) - t.throws(function () { impl.Buffer.from(undefined) }) - t.throws(function () { impl.Buffer.from() }) - t.throws(function () { impl.Buffer.from({}) }) - t.throws(function () { impl.Buffer.alloc('') }) - t.throws(function () { impl.Buffer.alloc('string') }) - t.throws(function () { impl.Buffer.alloc('string', 'utf-8') }) - t.throws(function () { impl.Buffer.alloc('b25ldHdvdGhyZWU=', 'base64') }) - t.throws(function () { impl.Buffer.alloc(-10) }) - t.throws(function () { impl.Buffer.alloc(1e90) }) - t.throws(function () { impl.Buffer.alloc(2 * (1 << 30)) }) - t.throws(function () { impl.Buffer.alloc(Infinity) }) - t.throws(function () { impl.Buffer.alloc(-Infinity) }) - t.throws(function () { impl.Buffer.alloc(null) }) - t.throws(function () { impl.Buffer.alloc(undefined) }) - t.throws(function () { impl.Buffer.alloc() }) - t.throws(function () { impl.Buffer.alloc([]) }) - t.throws(function () { impl.Buffer.alloc([0, 42, 3]) }) - t.throws(function () { impl.Buffer.alloc({}) }) - }); - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - t.throws(function () { dangerous.Buffer[method]('') }) - t.throws(function () { dangerous.Buffer[method]('string') }) - t.throws(function () { dangerous.Buffer[method]('string', 'utf-8') }) - t.throws(function () { dangerous.Buffer[method](2 * (1 << 30)) }) - t.throws(function () { dangerous.Buffer[method](Infinity) }) - if (dangerous.Buffer[method] === buffer.Buffer.allocUnsafe) { - t.skip('Skipping, older impl of allocUnsafe coerced negative sizes to 0') - } else { - t.throws(function () { dangerous.Buffer[method](-10) }) - t.throws(function () { dangerous.Buffer[method](-1e90) }) - t.throws(function () { dangerous.Buffer[method](-Infinity) }) - } - t.throws(function () { dangerous.Buffer[method](null) }) - t.throws(function () { dangerous.Buffer[method](undefined) }) - t.throws(function () { dangerous.Buffer[method]() }) - t.throws(function () { dangerous.Buffer[method]([]) }) - t.throws(function () { dangerous.Buffer[method]([0, 42, 3]) }) - t.throws(function () { dangerous.Buffer[method]({}) }) - }) - t.end() -}) - -test('Buffers have appropriate lengths', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.equal(impl.Buffer.alloc(0).length, 0) - t.equal(impl.Buffer.alloc(10).length, 10) - t.equal(impl.Buffer.from('').length, 0) - t.equal(impl.Buffer.from('string').length, 6) - t.equal(impl.Buffer.from('string', 'utf-8').length, 6) - t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').length, 11) - t.equal(impl.Buffer.from([0, 42, 3]).length, 3) - t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).length, 3) - t.equal(impl.Buffer.from([]).length, 0) - }); - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - t.equal(dangerous.Buffer[method](0).length, 0) - t.equal(dangerous.Buffer[method](10).length, 10) - }) - t.end() -}) - -test('Buffers have appropriate lengths (2)', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true; - [ safer.Buffer.alloc, - dangerous.Buffer.allocUnsafe, - dangerous.Buffer.allocUnsafeSlow - ].forEach(function (method) { - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 1e5) - var buf = method(length) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - } - }) - t.ok(ok) - t.end() -}) - -test('.alloc(size) is zero-filled and has correct length', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var buf = index.Buffer.alloc(length) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - var j - for (j = 0; j < length; j++) { - if (buf[j] !== 0) ok = false - } - buf.fill(1) - for (j = 0; j < length; j++) { - if (buf[j] !== 1) ok = false - } - } - t.ok(ok) - t.end() -}) - -test('.allocUnsafe / .allocUnsafeSlow are fillable and have correct lengths', function (t) { - ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var buf = dangerous.Buffer[method](length) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - buf.fill(0, 0, length) - var j - for (j = 0; j < length; j++) { - if (buf[j] !== 0) ok = false - } - buf.fill(1, 0, length) - for (j = 0; j < length; j++) { - if (buf[j] !== 1) ok = false - } - } - t.ok(ok, method) - }) - t.end() -}) - -test('.alloc(size, fill) is `fill`-filled', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var fill = Math.round(Math.random() * 255) - var buf = index.Buffer.alloc(length, fill) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - for (var j = 0; j < length; j++) { - if (buf[j] !== fill) ok = false - } - } - t.ok(ok) - t.end() -}) - -test('.alloc(size, fill) is `fill`-filled', function (t) { - t.equal(index.Buffer.alloc, safer.Buffer.alloc) - t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) - var ok = true - for (var i = 0; i < 1e2; i++) { - var length = Math.round(Math.random() * 2e6) - var fill = Math.round(Math.random() * 255) - var buf = index.Buffer.alloc(length, fill) - if (!buffer.Buffer.isBuffer(buf)) ok = false - if (buf.length !== length) ok = false - for (var j = 0; j < length; j++) { - if (buf[j] !== fill) ok = false - } - } - t.ok(ok) - t.deepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 97)) - t.notDeepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 98)) - - var tmp = new buffer.Buffer(2) - tmp.fill('ok') - if (tmp[1] === tmp[0]) { - // Outdated Node.js - t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('ooooo')) - } else { - t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('okoko')) - } - t.notDeepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('kokok')) - - t.end() -}) - -test('safer.Buffer.from returns results same as Buffer constructor', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.deepEqual(impl.Buffer.from(''), new buffer.Buffer('')) - t.deepEqual(impl.Buffer.from('string'), new buffer.Buffer('string')) - t.deepEqual(impl.Buffer.from('string', 'utf-8'), new buffer.Buffer('string', 'utf-8')) - t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), new buffer.Buffer('b25ldHdvdGhyZWU=', 'base64')) - t.deepEqual(impl.Buffer.from([0, 42, 3]), new buffer.Buffer([0, 42, 3])) - t.deepEqual(impl.Buffer.from(new Uint8Array([0, 42, 3])), new buffer.Buffer(new Uint8Array([0, 42, 3]))) - t.deepEqual(impl.Buffer.from([]), new buffer.Buffer([])) - }) - t.end() -}) - -test('safer.Buffer.from returns consistent results', function (t) { - [index, safer, dangerous].forEach(function (impl) { - t.deepEqual(impl.Buffer.from(''), impl.Buffer.alloc(0)) - t.deepEqual(impl.Buffer.from([]), impl.Buffer.alloc(0)) - t.deepEqual(impl.Buffer.from(new Uint8Array([])), impl.Buffer.alloc(0)) - t.deepEqual(impl.Buffer.from('string', 'utf-8'), impl.Buffer.from('string')) - t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from([115, 116, 114, 105, 110, 103])) - t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from(impl.Buffer.from('string'))) - t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), impl.Buffer.from('onetwothree')) - t.notDeepEqual(impl.Buffer.from('b25ldHdvdGhyZWU='), impl.Buffer.from('onetwothree')) - }) - t.end() -}) diff --git a/reverse_engineering/node_modules/split2/LICENSE b/reverse_engineering/node_modules/split2/LICENSE deleted file mode 100644 index a91afe5..0000000 --- a/reverse_engineering/node_modules/split2/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2014-2018, Matteo Collina - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/split2/README.md b/reverse_engineering/node_modules/split2/README.md deleted file mode 100644 index 00db262..0000000 --- a/reverse_engineering/node_modules/split2/README.md +++ /dev/null @@ -1,97 +0,0 @@ -# Split2(matcher, mapper, options) - -![ci](https://github.com/mcollina/split2/workflows/ci/badge.svg) - -Break up a stream and reassemble it so that each line is a chunk. -`split2` is inspired by [@dominictarr](https://github.com/dominictarr) [`split`](https://github.com/dominictarr/split) module, -and it is totally API compatible with it. -However, it is based on Node.js core [`Transform`](https://nodejs.org/api/stream.html#stream_new_stream_transform_options) via [`readable-stream`](https://github.com/nodejs/readable-stream) - -`matcher` may be a `String`, or a `RegExp`. Example, read every line in a file ... - -``` js - fs.createReadStream(file) - .pipe(split2()) - .on('data', function (line) { - //each chunk now is a separate line! - }) - -``` - -`split` takes the same arguments as `string.split` except it defaults to '/\r?\n/', and the optional `limit` paremeter is ignored. -[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split) - -`split` takes an optional options object on it's third argument, which -is directly passed as a -[Transform](https://nodejs.org/api/stream.html#stream_new_stream_transform_options) -option. - -Additionally, the `.maxLength` and `.skipOverflow` options are implemented, which set limits on the internal -buffer size and the stream's behavior when the limit is exceeded. There is no limit unless `maxLength` is set. When -the internal buffer size exceeds `maxLength`, the stream emits an error by default. You may also set `skipOverflow` to -true to suppress the error and instead skip past any lines that cause the internal buffer to exceed `maxLength`. - -Calling `.destroy` will make the stream emit `close`. Use this to perform cleanup logic - -``` js -var splitFile = function(filename) { - var file = fs.createReadStream(filename) - - return file - .pipe(split2()) - .on('close', function() { - // destroy the file stream in case the split stream was destroyed - file.destroy() - }) -} - -var stream = splitFile('my-file.txt') - -stream.destroy() // will destroy the input file stream -``` - -# NDJ - Newline Delimited Json - -`split2` accepts a function which transforms each line. - -``` js -fs.createReadStream(file) - .pipe(split2(JSON.parse)) - .on('data', function (obj) { - //each chunk now is a js object - }) - .on("error", function(error) => { - //handling parsing errors - }) -``` - -However, in [@dominictarr](https://github.com/dominictarr) [`split`](https://github.com/dominictarr/split) the mapper -is wrapped in a try-catch, while here it is not: if your parsing logic can throw, wrap it yourself. Otherwise, you can also use the stream error handling when mapper function throw. - -# Benchmark - -```bash -$ node bench.js -benchSplit*10000: 1484.983ms -benchBinarySplit*10000: 1484.080ms -benchSplit*10000: 1407.334ms -benchBinarySplit*10000: 1500.281ms -``` - -Benchmark taken on Node 8.11.3, on a Macbook i5 2018. - -# License - -Copyright (c) 2014-2018, Matteo Collina - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/reverse_engineering/node_modules/split2/bench.js b/reverse_engineering/node_modules/split2/bench.js deleted file mode 100644 index 7a3f9d5..0000000 --- a/reverse_engineering/node_modules/split2/bench.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict' - -var split = require('./') -var bench = require('fastbench') -var binarySplit = require('binary-split') -var fs = require('fs') - -function benchSplit (cb) { - fs.createReadStream('package.json') - .pipe(split()) - .on('end', cb) - .resume() -} - -function benchBinarySplit (cb) { - fs.createReadStream('package.json') - .pipe(binarySplit()) - .on('end', cb) - .resume() -} - -var run = bench([ - benchSplit, - benchBinarySplit -], 10000) - -run(run) diff --git a/reverse_engineering/node_modules/split2/index.js b/reverse_engineering/node_modules/split2/index.js deleted file mode 100644 index fc2007b..0000000 --- a/reverse_engineering/node_modules/split2/index.js +++ /dev/null @@ -1,132 +0,0 @@ -/* -Copyright (c) 2014-2018, Matteo Collina - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -*/ - -'use strict' - -const { Transform } = require('readable-stream') -const { StringDecoder } = require('string_decoder') -const kLast = Symbol('last') -const kDecoder = Symbol('decoder') - -function transform (chunk, enc, cb) { - var list - if (this.overflow) { // Line buffer is full. Skip to start of next line. - var buf = this[kDecoder].write(chunk) - list = buf.split(this.matcher) - - if (list.length === 1) return cb() // Line ending not found. Discard entire chunk. - - // Line ending found. Discard trailing fragment of previous line and reset overflow state. - list.shift() - this.overflow = false - } else { - this[kLast] += this[kDecoder].write(chunk) - list = this[kLast].split(this.matcher) - } - - this[kLast] = list.pop() - - for (var i = 0; i < list.length; i++) { - try { - push(this, this.mapper(list[i])) - } catch (error) { - return cb(error) - } - } - - this.overflow = this[kLast].length > this.maxLength - if (this.overflow && !this.skipOverflow) return cb(new Error('maximum buffer reached')) - - cb() -} - -function flush (cb) { - // forward any gibberish left in there - this[kLast] += this[kDecoder].end() - - if (this[kLast]) { - try { - push(this, this.mapper(this[kLast])) - } catch (error) { - return cb(error) - } - } - - cb() -} - -function push (self, val) { - if (val !== undefined) { - self.push(val) - } -} - -function noop (incoming) { - return incoming -} - -function split (matcher, mapper, options) { - // Set defaults for any arguments not supplied. - matcher = matcher || /\r?\n/ - mapper = mapper || noop - options = options || {} - - // Test arguments explicitly. - switch (arguments.length) { - case 1: - // If mapper is only argument. - if (typeof matcher === 'function') { - mapper = matcher - matcher = /\r?\n/ - // If options is only argument. - } else if (typeof matcher === 'object' && !(matcher instanceof RegExp)) { - options = matcher - matcher = /\r?\n/ - } - break - - case 2: - // If mapper and options are arguments. - if (typeof matcher === 'function') { - options = mapper - mapper = matcher - matcher = /\r?\n/ - // If matcher and options are arguments. - } else if (typeof mapper === 'object') { - options = mapper - mapper = noop - } - } - - options = Object.assign({}, options) - options.transform = transform - options.flush = flush - options.readableObjectMode = true - - const stream = new Transform(options) - - stream[kLast] = '' - stream[kDecoder] = new StringDecoder('utf8') - stream.matcher = matcher - stream.mapper = mapper - stream.maxLength = options.maxLength - stream.skipOverflow = options.skipOverflow - stream.overflow = false - - return stream -} - -module.exports = split diff --git a/reverse_engineering/node_modules/split2/package.json b/reverse_engineering/node_modules/split2/package.json deleted file mode 100644 index 4ffa3c3..0000000 --- a/reverse_engineering/node_modules/split2/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "split2@^3.1.1", - "_id": "split2@3.2.2", - "_inBundle": false, - "_integrity": "sha512-9NThjpgZnifTkJpzTZ7Eue85S49QwpNhZTq6GRJwObb6jnLFNGB7Qm73V5HewTROPyxD0C29xqmaI68bQtV+hg==", - "_location": "/split2", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "split2@^3.1.1", - "name": "split2", - "escapedName": "split2", - "rawSpec": "^3.1.1", - "saveSpec": null, - "fetchSpec": "^3.1.1" - }, - "_requiredBy": [ - "/pgpass" - ], - "_resolved": "https://registry.npmjs.org/split2/-/split2-3.2.2.tgz", - "_shasum": "bf2cf2a37d838312c249c89206fd7a17dd12365f", - "_spec": "split2@^3.1.1", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/pgpass", - "author": { - "name": "Matteo Collina", - "email": "hello@matteocollina.com" - }, - "bugs": { - "url": "http://github.com/mcollina/split2/issues" - }, - "bundleDependencies": false, - "dependencies": { - "readable-stream": "^3.0.0" - }, - "deprecated": false, - "description": "split a Text Stream into a Line Stream, using Stream 3", - "devDependencies": { - "binary-split": "^1.0.3", - "callback-stream": "^1.1.0", - "fastbench": "^1.0.0", - "nyc": "^15.0.1", - "pre-commit": "^1.1.2", - "safe-buffer": "^5.1.1", - "standard": "^14.0.0", - "tape": "^5.0.0" - }, - "homepage": "https://github.com/mcollina/split2#readme", - "license": "ISC", - "main": "index.js", - "name": "split2", - "pre-commit": [ - "test" - ], - "repository": { - "type": "git", - "url": "git+https://github.com/mcollina/split2.git" - }, - "scripts": { - "coverage": "nyc --reporter=html --reporter=cobertura --reporter=text tape test/test.js", - "legacy": "tape test.js", - "lint": "standard --verbose", - "test": "npm run lint && npm run unit", - "test:report": "npm run lint && npm run unit:report", - "unit": "nyc --lines 100 --branches 100 --functions 100 --check-coverage --reporter=text tape test.js" - }, - "version": "3.2.2", - "website": "https://github.com/mcollina/split2" -} diff --git a/reverse_engineering/node_modules/split2/test.js b/reverse_engineering/node_modules/split2/test.js deleted file mode 100644 index e035787..0000000 --- a/reverse_engineering/node_modules/split2/test.js +++ /dev/null @@ -1,392 +0,0 @@ -'use strict' - -var test = require('tape') -var split = require('./') -var callback = require('callback-stream') -var Buffer = require('safe-buffer').Buffer -var strcb = callback.bind(null, { decodeStrings: false }) -var objcb = callback.bind(null, { objectMode: true }) - -test('split two lines on end', function (t) { - t.plan(2) - - var input = split() - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['hello', 'world']) - })) - - input.end('hello\nworld') -}) - -test('split two lines on two writes', function (t) { - t.plan(2) - - var input = split() - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['hello', 'world']) - })) - - input.write('hello') - input.write('\nworld') - input.end() -}) - -test('split four lines on three writes', function (t) { - t.plan(2) - - var input = split() - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['hello', 'world', 'bye', 'world']) - })) - - input.write('hello\nwor') - input.write('ld\nbye\nwo') - input.write('rld') - input.end() -}) - -test('accumulate multiple writes', function (t) { - t.plan(2) - - var input = split() - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['helloworld']) - })) - - input.write('hello') - input.write('world') - input.end() -}) - -test('split using a custom string matcher', function (t) { - t.plan(2) - - var input = split('~') - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['hello', 'world']) - })) - - input.end('hello~world') -}) - -test('split using a custom regexp matcher', function (t) { - t.plan(2) - - var input = split(/~/) - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['hello', 'world']) - })) - - input.end('hello~world') -}) - -test('support an option argument', function (t) { - t.plan(2) - - var input = split({ highWaterMark: 2 }) - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['hello', 'world']) - })) - - input.end('hello\nworld') -}) - -test('support a mapper function', function (t) { - t.plan(2) - - var a = { a: '42' } - var b = { b: '24' } - - var input = split(JSON.parse) - - input.pipe(objcb(function (err, list) { - t.error(err) - t.deepEqual(list, [a, b]) - })) - - input.write(JSON.stringify(a)) - input.write('\n') - input.end(JSON.stringify(b)) -}) - -test('split lines windows-style', function (t) { - t.plan(2) - - var input = split() - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['hello', 'world']) - })) - - input.end('hello\r\nworld') -}) - -test('splits a buffer', function (t) { - t.plan(2) - - var input = split() - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['hello', 'world']) - })) - - input.end(Buffer.from('hello\nworld')) -}) - -test('do not end on undefined', function (t) { - t.plan(2) - - var input = split(function (line) { }) - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, []) - })) - - input.end(Buffer.from('hello\nworld')) -}) - -test('has destroy method', function (t) { - t.plan(1) - - var input = split(function (line) { }) - - input.on('close', function () { - t.ok(true, 'close emitted') - t.end() - }) - - input.destroy() -}) - -test('support custom matcher and mapper', function (t) { - t.plan(4) - - var a = { a: '42' } - var b = { b: '24' } - var input = split('~', JSON.parse) - - t.equal(input.matcher, '~') - t.equal(typeof input.mapper, 'function') - - input.pipe(objcb(function (err, list) { - t.notOk(err, 'no errors') - t.deepEqual(list, [a, b]) - })) - - input.write(JSON.stringify(a)) - input.write('~') - input.end(JSON.stringify(b)) -}) - -test('support custom matcher and options', function (t) { - t.plan(6) - - var input = split('~', { highWaterMark: 1024 }) - - t.equal(input.matcher, '~') - t.equal(typeof input.mapper, 'function') - t.equal(input._readableState.highWaterMark, 1024) - t.equal(input._writableState.highWaterMark, 1024) - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['hello', 'world']) - })) - - input.end('hello~world') -}) - -test('support mapper and options', function (t) { - t.plan(6) - - var a = { a: '42' } - var b = { b: '24' } - var input = split(JSON.parse, { highWaterMark: 1024 }) - - t.ok(input.matcher instanceof RegExp, 'matcher is RegExp') - t.equal(typeof input.mapper, 'function') - t.equal(input._readableState.highWaterMark, 1024) - t.equal(input._writableState.highWaterMark, 1024) - - input.pipe(objcb(function (err, list) { - t.error(err) - t.deepEqual(list, [a, b]) - })) - - input.write(JSON.stringify(a)) - input.write('\n') - input.end(JSON.stringify(b)) -}) - -test('split utf8 chars', function (t) { - t.plan(2) - - var input = split() - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['烫烫烫', '锟斤拷']) - })) - - var buf = Buffer.from('烫烫烫\r\n锟斤拷', 'utf8') - for (var i = 0; i < buf.length; ++i) { - input.write(buf.slice(i, i + 1)) - } - input.end() -}) - -test('split utf8 chars 2by2', function (t) { - t.plan(2) - - var input = split() - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['烫烫烫', '烫烫烫']) - })) - - var str = '烫烫烫\r\n烫烫烫' - var buf = Buffer.from(str, 'utf8') - for (var i = 0; i < buf.length; i += 2) { - input.write(buf.slice(i, i + 2)) - } - input.end() -}) - -test('split lines when the \n comes at the end of a chunk', function (t) { - t.plan(2) - - var input = split() - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['hello', 'world']) - })) - - input.write('hello\n') - input.end('world') -}) - -test('truncated utf-8 char', function (t) { - t.plan(2) - - var input = split() - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['烫' + Buffer.from('e7', 'hex').toString()]) - })) - - var str = '烫烫' - var buf = Buffer.from(str, 'utf8') - - input.write(buf.slice(0, 3)) - input.end(buf.slice(3, 4)) -}) - -test('maximum buffer limit', function (t) { - t.plan(1) - - var input = split({ maxLength: 2 }) - - input.pipe(strcb(function (err, list) { - t.ok(err) - })) - - input.write('hey') -}) - -test('readable highWaterMark', function (t) { - var input = split() - t.equal(input._readableState.highWaterMark, 16) - t.end() -}) - -test('maxLength < chunk size', function (t) { - t.plan(2) - - var input = split({ maxLength: 2 }) - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['a', 'b']) - })) - - input.end('a\nb') -}) - -test('maximum buffer limit w/skip', function (t) { - t.plan(2) - - var input = split({ maxLength: 2, skipOverflow: true }) - - input.pipe(strcb(function (err, list) { - t.error(err) - t.deepEqual(list, ['a', 'b', 'c']) - })) - - input.write('a\n123') - input.write('456') - input.write('789\nb\nc') - input.end() -}) - -test("don't modify the options object", function (t) { - t.plan(2) - - var options = {} - var input = split(options) - - input.pipe(strcb(function (err, list) { - t.error(err) - t.same(options, {}) - })) - - input.end() -}) - -test('mapper throws flush', function (t) { - t.plan(1) - var error = new Error() - var input = split(function () { - throw error - }) - - input.on('error', (err, list) => { - t.same(err, error) - }) - input.end('hello') -}) - -test('mapper throws on transform', function (t) { - t.plan(2) - - var error = new Error() - var input = split(function (l) { - throw error - }) - - input.on('error', (err) => { - t.same(err, error) - }) - input.write('a') - input.write('\n') - input.end('b') -}) diff --git a/reverse_engineering/node_modules/ssh2/.eslintignore b/reverse_engineering/node_modules/ssh2/.eslintignore deleted file mode 100644 index 73ed104..0000000 --- a/reverse_engineering/node_modules/ssh2/.eslintignore +++ /dev/null @@ -1,4 +0,0 @@ -node_modules -lib/protocol/crypto/poly1305.js -.eslint-plugins -!.eslintrc.js diff --git a/reverse_engineering/node_modules/ssh2/.eslintrc.js b/reverse_engineering/node_modules/ssh2/.eslintrc.js deleted file mode 100644 index be9311d..0000000 --- a/reverse_engineering/node_modules/ssh2/.eslintrc.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = { - extends: '@mscdex/eslint-config', -}; diff --git a/reverse_engineering/node_modules/ssh2/.github/workflows/ci.yml b/reverse_engineering/node_modules/ssh2/.github/workflows/ci.yml deleted file mode 100644 index c6f610a..0000000 --- a/reverse_engineering/node_modules/ssh2/.github/workflows/ci.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: CI - -on: - pull_request: - push: - branches: [ master ] - -jobs: - tests-linux: - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - node-version: [10.16.0, 10.x, 12.x, 14.x, 16.x] - steps: - - uses: actions/checkout@v2 - - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v1 - with: - node-version: ${{ matrix.node-version }} - - name: Install module - run: npm install - - name: Run tests - run: npm test - tests-windows: - runs-on: windows-latest - strategy: - fail-fast: false - matrix: - node-version: [16.x] - steps: - - uses: actions/checkout@v2 - - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v1 - with: - node-version: ${{ matrix.node-version }} - - name: Install module - run: npm install - - name: Run tests - run: npm test diff --git a/reverse_engineering/node_modules/ssh2/.github/workflows/lint.yml b/reverse_engineering/node_modules/ssh2/.github/workflows/lint.yml deleted file mode 100644 index ec109fd..0000000 --- a/reverse_engineering/node_modules/ssh2/.github/workflows/lint.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: lint - -on: - pull_request: - push: - branches: [ master ] - -env: - NODE_VERSION: 14.x - -jobs: - lint-js: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Use Node.js ${{ env.NODE_VERSION }} - uses: actions/setup-node@v1 - with: - node-version: ${{ env.NODE_VERSION }} - - name: Install ESLint + ESLint configs/plugins - run: npm install --only=dev - - name: Lint files - run: npm run lint diff --git a/reverse_engineering/node_modules/ssh2/LICENSE b/reverse_engineering/node_modules/ssh2/LICENSE deleted file mode 100644 index 290762e..0000000 --- a/reverse_engineering/node_modules/ssh2/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright Brian White. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. \ No newline at end of file diff --git a/reverse_engineering/node_modules/ssh2/README.md b/reverse_engineering/node_modules/ssh2/README.md deleted file mode 100644 index e39ec73..0000000 --- a/reverse_engineering/node_modules/ssh2/README.md +++ /dev/null @@ -1,1473 +0,0 @@ -# Description - -SSH2 client and server modules written in pure JavaScript for [node.js](http://nodejs.org/). - -Development/testing is done against OpenSSH (8.7 currently). - -Changes (breaking or otherwise) in v1.0.0 can be found [here](https://github.com/mscdex/ssh2/issues/935). - -# Table of Contents - -* [Requirements](#requirements) -* [Installation](#installation) -* [Client Examples](#client-examples) - * [Execute 'uptime' on a server](#execute-uptime-on-a-server) - * [Start an interactive shell session](#start-an-interactive-shell-session) - * [Send a raw HTTP request to port 80 on the server](#send-a-raw-http-request-to-port-80-on-the-server) - * [Forward local connections to port 8000 on the server to us](#forward-local-connections-to-port-8000-on-the-server-to-us) - * [Get a directory listing via SFTP](#get-a-directory-listing-via-sftp) - * [Connection hopping](#connection-hopping) - * [Forward remote X11 connections](#forward-remote-x11-connections) - * [Dynamic (1:1) port forwarding using a SOCKSv5 proxy (using `socksv5`)](#dynamic-11-port-forwarding-using-a-socksv5-proxy-using-socksv5) - * [Make HTTP(S) connections easily using a custom http(s).Agent](#make-https-connections-easily-using-a-custom-httpsagent) - * [Invoke an arbitrary subsystem (e.g. netconf)](#invoke-an-arbitrary-subsystem) -* [Server Examples](#server-examples) - * [Password and public key authentication and non-interactive (exec) command execution](#password-and-public-key-authentication-and-non-interactive-exec-command-execution) - * [SFTP-only server](#sftp-only-server) -* [API](#api) - * [Client](#client) - * [Client events](#client-events) - * [Client methods](#client-methods) - * [Server](#server) - * [Server events](#server-events) - * [Server methods](#server-methods) - * [Connection events](#connection-events) - * [Connection methods](#connection-methods) - * [Session events](#session-events) - * [Channel](#channel) - * [Pseudo-TTY settings](#pseudo-tty-settings) - * [Terminal modes](#terminal-modes) - * [HTTPAgent](#httpagent) - * [HTTPAgent methods](#httpagent-methods) - * [HTTPSAgent](#httpsagent) - * [HTTPSAgent methods](#httpsagent-methods) - * [Utilities](#utilities) - -## Requirements - -* [node.js](http://nodejs.org/) -- v10.16.0 or newer - * node v12.0.0 or newer for Ed25519 key support -* (Optional) [`cpu-features`](https://github.com/mscdex/cpu-features) is set as an optional package dependency (you do not need to install it explicitly/separately from `ssh2`) that will be automatically built and used if possible. See the project's documentation for its own requirements. - * This addon is currently used to help generate an optimal default cipher list - -## Installation - - npm install ssh2 - -## Client Examples - -### Execute 'uptime' on a server - -```js -const { readFileSync } = require('fs'); - -const { Client } = require('ssh2'); - -const conn = new Client(); -conn.on('ready', () => { - console.log('Client :: ready'); - conn.exec('uptime', (err, stream) => { - if (err) throw err; - stream.on('close', (code, signal) => { - console.log('Stream :: close :: code: ' + code + ', signal: ' + signal); - conn.end(); - }).on('data', (data) => { - console.log('STDOUT: ' + data); - }).stderr.on('data', (data) => { - console.log('STDERR: ' + data); - }); - }); -}).connect({ - host: '192.168.100.100', - port: 22, - username: 'frylock', - privateKey: readFileSync('/path/to/my/key') -}); - -// example output: -// Client :: ready -// STDOUT: 17:41:15 up 22 days, 18:09, 1 user, load average: 0.00, 0.01, 0.05 -// -// Stream :: exit :: code: 0, signal: undefined -// Stream :: close -``` - -### Start an interactive shell session - -```js -const { readFileSync } = require('fs'); - -const { Client } = require('ssh2'); - -const conn = new Client(); -conn.on('ready', () => { - console.log('Client :: ready'); - conn.shell((err, stream) => { - if (err) throw err; - stream.on('close', () => { - console.log('Stream :: close'); - conn.end(); - }).on('data', (data) => { - console.log('OUTPUT: ' + data); - }); - stream.end('ls -l\nexit\n'); - }); -}).connect({ - host: '192.168.100.100', - port: 22, - username: 'frylock', - privateKey: readFileSync('/path/to/my/key') -}); - -// example output: -// Client :: ready -// STDOUT: Last login: Sun Jun 15 09:37:21 2014 from 192.168.100.100 -// -// STDOUT: ls -l -// exit -// -// STDOUT: frylock@athf:~$ ls -l -// -// STDOUT: total 8 -// -// STDOUT: drwxr-xr-x 2 frylock frylock 4096 Nov 18 2012 mydir -// -// STDOUT: -rw-r--r-- 1 frylock frylock 25 Apr 11 2013 test.txt -// -// STDOUT: frylock@athf:~$ exit -// -// STDOUT: logout -// -// Stream :: close -``` - -### Send a raw HTTP request to port 80 on the server - -```js -const { Client } = require('ssh2'); - -const conn = new Client(); -conn.on('ready', () => { - console.log('Client :: ready'); - conn.forwardOut('192.168.100.102', 8000, '127.0.0.1', 80, (err, stream) => { - if (err) throw err; - stream.on('close', () => { - console.log('TCP :: CLOSED'); - conn.end(); - }).on('data', (data) => { - console.log('TCP :: DATA: ' + data); - }).end([ - 'HEAD / HTTP/1.1', - 'User-Agent: curl/7.27.0', - 'Host: 127.0.0.1', - 'Accept: */*', - 'Connection: close', - '', - '' - ].join('\r\n')); - }); -}).connect({ - host: '192.168.100.100', - port: 22, - username: 'frylock', - password: 'nodejsrules' -}); - -// example output: -// Client :: ready -// TCP :: DATA: HTTP/1.1 200 OK -// Date: Thu, 15 Nov 2012 13:52:58 GMT -// Server: Apache/2.2.22 (Ubuntu) -// X-Powered-By: PHP/5.4.6-1ubuntu1 -// Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT -// Content-Encoding: gzip -// Vary: Accept-Encoding -// Connection: close -// Content-Type: text/html; charset=UTF-8 -// -// -// TCP :: CLOSED -``` - -### Forward local connections to port 8000 on the server to us - -```js -const { Client } = require('ssh2'); - -const conn = new Client(); -conn.on('ready', () => { - console.log('Client :: ready'); - conn.forwardIn('127.0.0.1', 8000, (err) => { - if (err) throw err; - console.log('Listening for connections on server on port 8000!'); - }); -}).on('tcp connection', (info, accept, reject) => { - console.log('TCP :: INCOMING CONNECTION:'); - console.dir(info); - accept().on('close', () => { - console.log('TCP :: CLOSED'); - }).on('data', (data) => { - console.log('TCP :: DATA: ' + data); - }).end([ - 'HTTP/1.1 404 Not Found', - 'Date: Thu, 15 Nov 2012 02:07:58 GMT', - 'Server: ForwardedConnection', - 'Content-Length: 0', - 'Connection: close', - '', - '' - ].join('\r\n')); -}).connect({ - host: '192.168.100.100', - port: 22, - username: 'frylock', - password: 'nodejsrules' -}); - -// example output: -// Client :: ready -// Listening for connections on server on port 8000! -// (.... then from another terminal on the server: `curl -I http://127.0.0.1:8000`) -// TCP :: INCOMING CONNECTION: { destIP: '127.0.0.1', -// destPort: 8000, -// srcIP: '127.0.0.1', -// srcPort: 41969 } -// TCP DATA: HEAD / HTTP/1.1 -// User-Agent: curl/7.27.0 -// Host: 127.0.0.1:8000 -// Accept: */* -// -// -// TCP :: CLOSED -``` - -### Get a directory listing via SFTP - -```js -const { Client } = require('ssh2'); - -const conn = new Client(); -conn.on('ready', () => { - console.log('Client :: ready'); - conn.sftp((err, sftp) => { - if (err) throw err; - sftp.readdir('foo', (err, list) => { - if (err) throw err; - console.dir(list); - conn.end(); - }); - }); -}).connect({ - host: '192.168.100.100', - port: 22, - username: 'frylock', - password: 'nodejsrules' -}); - -// example output: -// Client :: ready -// [ { filename: 'test.txt', -// longname: '-rw-r--r-- 1 frylock frylock 12 Nov 18 11:05 test.txt', -// attrs: -// { size: 12, -// uid: 1000, -// gid: 1000, -// mode: 33188, -// atime: 1353254750, -// mtime: 1353254744 } }, -// { filename: 'mydir', -// longname: 'drwxr-xr-x 2 frylock frylock 4096 Nov 18 15:03 mydir', -// attrs: -// { size: 1048576, -// uid: 1000, -// gid: 1000, -// mode: 16877, -// atime: 1353269007, -// mtime: 1353269007 } } ] -``` - -### Connection hopping - -```js -const { Client } = require('ssh2'); - -const conn1 = new Client(); -const conn2 = new Client(); - -// Checks uptime on 10.1.1.40 via 192.168.1.1 - -conn1.on('ready', () => { - console.log('FIRST :: connection ready'); - // Alternatively, you could use something like netcat or socat with exec() - // instead of forwardOut(), depending on what the server allows - conn1.forwardOut('127.0.0.1', 12345, '10.1.1.40', 22, (err, stream) => { - if (err) { - console.log('FIRST :: forwardOut error: ' + err); - return conn1.end(); - } - conn2.connect({ - sock: stream, - username: 'user2', - password: 'password2', - }); - }); -}).connect({ - host: '192.168.1.1', - username: 'user1', - password: 'password1', -}); - -conn2.on('ready', () => { - // This connection is the one to 10.1.1.40 - - console.log('SECOND :: connection ready'); - conn2.exec('uptime', (err, stream) => { - if (err) { - console.log('SECOND :: exec error: ' + err); - return conn1.end(); - } - stream.on('close', () => { - conn1.end(); // close parent (and this) connection - }).on('data', (data) => { - console.log(data.toString()); - }); - }); -}); -``` - -### Forward remote X11 connections - -```js -const { Socket } = require('net'); - -const { Client } = require('ssh2'); - -const conn = new Client(); - -conn.on('x11', (info, accept, reject) => { - const xserversock = new net.Socket(); - xserversock.on('connect', () => { - const xclientsock = accept(); - xclientsock.pipe(xserversock).pipe(xclientsock); - }); - // connects to localhost:0.0 - xserversock.connect(6000, 'localhost'); -}); - -conn.on('ready', () => { - conn.exec('xeyes', { x11: true }, (err, stream) => { - if (err) throw err; - let code = 0; - stream.on('close', () => { - if (code !== 0) - console.log('Do you have X11 forwarding enabled on your SSH server?'); - conn.end(); - }).on('exit', (exitcode) => { - code = exitcode; - }); - }); -}).connect({ - host: '192.168.1.1', - username: 'foo', - password: 'bar' -}); -``` - -### Dynamic (1:1) port forwarding using a SOCKSv5 proxy (using [socksv5](https://github.com/mscdex/socksv5)) - -```js -const socks = require('socksv5'); -const { Client } = require('ssh2'); - -const sshConfig = { - host: '192.168.100.1', - port: 22, - username: 'nodejs', - password: 'rules' -}; - -socks.createServer((info, accept, deny) => { - // NOTE: you could just use one ssh2 client connection for all forwards, but - // you could run into server-imposed limits if you have too many forwards open - // at any given time - const conn = new Client(); - conn.on('ready', () => { - conn.forwardOut(info.srcAddr, - info.srcPort, - info.dstAddr, - info.dstPort, - (err, stream) => { - if (err) { - conn.end(); - return deny(); - } - - const clientSocket = accept(true); - if (clientSocket) { - stream.pipe(clientSocket).pipe(stream).on('close', () => { - conn.end(); - }); - } else { - conn.end(); - } - }); - }).on('error', (err) => { - deny(); - }).connect(sshConfig); -}).listen(1080, 'localhost', () => { - console.log('SOCKSv5 proxy server started on port 1080'); -}).useAuth(socks.auth.None()); - -// test with cURL: -// curl -i --socks5 localhost:1080 google.com -``` - -### Make HTTP(S) connections easily using a custom http(s).Agent - -```js -const http = require('http'); - -const { Client, HTTPAgent, HTTPSAgent } = require('ssh2'); - -const sshConfig = { - host: '192.168.100.1', - port: 22, - username: 'nodejs', - password: 'rules' -}; - -// Use `HTTPSAgent` instead for an HTTPS request -const agent = new HTTPAgent(sshConfig); -http.get({ - host: '192.168.200.1', - agent, - headers: { Connection: 'close' } -}, (res) => { - console.log(res.statusCode); - console.dir(res.headers); - res.resume(); -}); -``` - - -### Invoke an arbitrary subsystem - -```js -const { Client } = require('ssh2'); - -const xmlhello = ` - - - - urn:ietf:params:netconf:base:1.0 - - ]]>]]>`; - -const conn = new Client(); - -conn.on('ready', () => { - console.log('Client :: ready'); - conn.subsys('netconf', (err, stream) => { - if (err) throw err; - stream.on('data', (data) => { - console.log(data); - }).write(xmlhello); - }); -}).connect({ - host: '1.2.3.4', - port: 22, - username: 'blargh', - password: 'honk' -}); -``` - -## Server Examples - -### Password and public key authentication and non-interactive (exec) command execution - -```js -const { timingSafeEqual } = require('crypto'); -const { readFileSync } = require('fs'); -const { inspect } = require('util'); - -const { utils: { parseKey }, Server } = require('ssh2'); - -const allowedUser = Buffer.from('foo'); -const allowedPassword = Buffer.from('bar'); -const allowedPubKey = parseKey(readFileSync('foo.pub')); - -function checkValue(input, allowed) { - const autoReject = (input.length !== allowed.length); - if (autoReject) { - // Prevent leaking length information by always making a comparison with the - // same input when lengths don't match what we expect ... - allowed = input; - } - const isMatch = timingSafeEqual(input, allowed); - return (!autoReject && isMatch); -} - -new Server({ - hostKeys: [readFileSync('host.key')] -}, (client) => { - console.log('Client connected!'); - - client.on('authentication', (ctx) => { - let allowed = true; - if (!checkValue(Buffer.from(ctx.username), allowedUser)) - allowed = false; - - switch (ctx.method) { - case 'password': - if (!checkValue(Buffer.from(ctx.password), allowedPassword)) - return ctx.reject(); - break; - case 'publickey': - if (ctx.key.algo !== allowedPubKey.type - || !checkValue(ctx.key.data, allowedPubKey.getPublicSSH()) - || (ctx.signature && allowedPubKey.verify(ctx.blob, ctx.signature) !== true)) { - return ctx.reject(); - } - break; - default: - return ctx.reject(); - } - - if (allowed) - ctx.accept(); - else - ctx.reject(); - }).on('ready', () => { - console.log('Client authenticated!'); - - client.on('session', (accept, reject) => { - const session = accept(); - session.once('exec', (accept, reject, info) => { - console.log('Client wants to execute: ' + inspect(info.command)); - const stream = accept(); - stream.stderr.write('Oh no, the dreaded errors!\n'); - stream.write('Just kidding about the errors!\n'); - stream.exit(0); - stream.end(); - }); - }); - }).on('close', () => { - console.log('Client disconnected'); - }); -}).listen(0, '127.0.0.1', function() { - console.log('Listening on port ' + this.address().port); -}); -``` - -### SFTP-only server - -```js -const { timingSafeEqual } = require('crypto'); -const { readFileSync } = require('fs'); -const { inspect } = require('util'); - -const { - Server, - sftp: { - OPEN_MODE, - STATUS_CODE, - }, -} = require('ssh2'); - -const allowedUser = Buffer.from('foo'); -const allowedPassword = Buffer.from('bar'); - -function checkValue(input, allowed) { - const autoReject = (input.length !== allowed.length); - if (autoReject) { - // Prevent leaking length information by always making a comparison with the - // same input when lengths don't match what we expect ... - allowed = input; - } - const isMatch = timingSafeEqual(input, allowed); - return (!autoReject && isMatch); -} - -// This simple SFTP server implements file uploading where the contents get -// ignored ... - -new ssh2.Server({ - hostKeys: [readFileSync('host.key')] -}, (client) => { - console.log('Client connected!'); - - client.on('authentication', (ctx) => { - let allowed = true; - if (!checkValue(Buffer.from(ctx.username), allowedUser)) - allowed = false; - - switch (ctx.method) { - case 'password': - if (!checkValue(Buffer.from(ctx.password), allowedPassword)) - return ctx.reject(); - break; - default: - return ctx.reject(); - } - - if (allowed) - ctx.accept(); - else - ctx.reject(); - }).on('ready', () => { - console.log('Client authenticated!'); - - client.on('session', (accept, reject) => { - const session = accept(); - session.on('sftp', (accept, reject) => { - console.log('Client SFTP session'); - const openFiles = new Map(); - let handleCount = 0; - const sftp = accept(); - sftp.on('OPEN', (reqid, filename, flags, attrs) => { - // Only allow opening /tmp/foo.txt for writing - if (filename !== '/tmp/foo.txt' || !(flags & OPEN_MODE.WRITE)) - return sftp.status(reqid, STATUS_CODE.FAILURE); - - // Create a fake handle to return to the client, this could easily - // be a real file descriptor number for example if actually opening - // a file on disk - const handle = Buffer.alloc(4); - openFiles.set(handleCount, true); - handle.writeUInt32BE(handleCount++, 0); - - console.log('Opening file for write') - sftp.handle(reqid, handle); - }).on('WRITE', (reqid, handle, offset, data) => { - if (handle.length !== 4 - || !openFiles.has(handle.readUInt32BE(0))) { - return sftp.status(reqid, STATUS_CODE.FAILURE); - } - - // Fake the write operation - sftp.status(reqid, STATUS_CODE.OK); - - console.log('Write to file at offset ${offset}: ${inspect(data)}'); - }).on('CLOSE', (reqid, handle) => { - let fnum; - if (handle.length !== 4 - || !openFiles.has(fnum = handle.readUInt32BE(0))) { - return sftp.status(reqid, STATUS_CODE.FAILURE); - } - - console.log('Closing file'); - openFiles.delete(fnum); - - sftp.status(reqid, STATUS_CODE.OK); - }); - }); - }); - }).on('close', () => { - console.log('Client disconnected'); - }); -}).listen(0, '127.0.0.1', function() { - console.log('Listening on port ' + this.address().port); -}); -``` - -You can find more examples in the `examples` directory of this repository. - -## API - -`require('ssh2').Client` is the **_Client_** constructor. - -`require('ssh2').Server` is the **_Server_** constructor. - -`require('ssh2').utils` is an object containing some useful [utilities](#utilities). - -`require('ssh2').HTTPAgent` is an [`http.Agent`](https://nodejs.org/docs/latest/api/http.html#http_class_http_agent) constructor. - -`require('ssh2').HTTPSAgent` is an [`https.Agent`](https://nodejs.org/docs/latest/api/https.html#https_class_https_agent) constructor. Its API is the same as `HTTPAgent` except it's for HTTPS connections. - -### Agent-related - -`require('ssh2').AgentProtocol` is a Duplex stream [class](#agentprotocol) that aids in communicating over the OpenSSH agent protocol. - -`require('ssh2').BaseAgent` is a base [class](#baseagent) for creating custom authentication agents. - -`require('ssh2').createAgent` is a helper [function](#createagent) that creates a new agent instance using the same logic as the `agent` configuration option: if the platform is Windows and it's the value "pageant", it creates a `PageantAgent`, otherwise if it's not a path to a Windows pipe it creates a `CygwinAgent`. In all other cases, it creates an `OpenSSHAgent`. - -`require('ssh2').CygwinAgent` is an agent [class](#cygwinagent) implementation that communicates with agents in a Cygwin environment. - -`require('ssh2').OpenSSHAgent` is an agent [class](#opensshagent) implementation that communicates with OpenSSH agents over a UNIX socket. - -`require('ssh2').PageantAgent` is an agent [class](#pageantagent) implementation that communicates with Pageant agent processes. - -### Client - -#### Client events - -* **banner**(< _string_ >message, < _string_ >language) - A notice was sent by the server upon connection. - -* **change password**(< _string_ >prompt, < _function_ >done) - If using password-based user authentication, the server has requested that the user's password be changed. Call `done` with the new password. - -* **close**() - The socket was closed. - -* **end**() - The socket was disconnected. - -* **error**(< _Error_ >err) - An error occurred. A 'level' property indicates 'client-socket' for socket-level errors and 'client-ssh' for SSH disconnection messages. In the case of 'client-ssh' messages, there may be a 'description' property that provides more detail. - -* **handshake**(< _object_ >negotiated) - Emitted when a handshake has completed (either initial or rekey). `negotiated` contains the negotiated details of the handshake and is of the form: - -```js - // In this particular case `mac` is empty because there is no separate MAC - // because it's integrated into AES in GCM mode - { kex: 'ecdh-sha2-nistp256', - srvHostKey: 'rsa-sha2-512', - cs: { // Client to server algorithms - cipher: 'aes128-gcm', - mac: '', - compress: 'none', - lang: '' - }, - sc: { // Server to client algorithms - cipher: 'aes128-gcm', - mac: '', - compress: 'none', - lang: '' - } - } -``` - -* **hostkeys**(< _array_ >keys) - Emitted when the server announces its available host keys. `keys` is the list of parsed (using [`parseKey()`](#utilities)) host public keys. - -* **keyboard-interactive**(< _string_ >name, < _string_ >instructions, < _string_ >instructionsLang, < _array_ >prompts, < _function_ >finish) - The server is asking for replies to the given `prompts` for keyboard-interactive user authentication. `name` is generally what you'd use as a window title (for GUI apps). `prompts` is an array of `{ prompt: 'Password: ', echo: false }` style objects (here `echo` indicates whether user input should be displayed on the screen). The answers for all prompts must be provided as an array of strings and passed to `finish` when you are ready to continue. Note: It's possible for the server to come back and ask more questions. - -* **ready**() - Authentication was successful. - -* **rekey**() - Emitted when a rekeying operation has completed (either client or server-initiated). - -* **tcp connection**(< _object_ >details, < _function_ >accept, < _function_ >reject) - An incoming forwarded TCP connection is being requested. Calling `accept` accepts the connection and returns a `Channel` object. Calling `reject` rejects the connection and no further action is needed. `details` contains: - - * **destIP** - _string_ - The remote IP the connection was received on (given in earlier call to `forwardIn()`). - - * **destPort** - _integer_ - The remote port the connection was received on (given in earlier call to `forwardIn()`). - - * **srcIP** - _string_ - The originating IP of the connection. - - * **srcPort** - _integer_ - The originating port of the connection. - -* **unix connection**(< _object_ >details, < _function_ >accept, < _function_ >reject) - An incoming forwarded UNIX socket connection is being requested. Calling `accept` accepts the connection and returns a `Channel` object. Calling `reject` rejects the connection and no further action is needed. `details` contains: - - * **socketPath** - _string_ - The originating UNIX socket path of the connection. - -* **x11**(< _object_ >details, < _function_ >accept, < _function_ >reject) - An incoming X11 connection is being requested. Calling `accept` accepts the connection and returns a `Channel` object. Calling `reject` rejects the connection and no further action is needed. `details` contains: - - * **srcIP** - _string_ - The originating IP of the connection. - - * **srcPort** - _integer_ - The originating port of the connection. - -#### Client methods - -* **(constructor)**() - Creates and returns a new Client instance. - -* **connect**(< _object_ >config) - _(void)_ - Attempts a connection to a server using the information given in `config`: - - * **agent** - _string_ - Path to ssh-agent's UNIX socket for ssh-agent-based user authentication. **Windows users: set to 'pageant' for authenticating with Pageant or (actual) path to a cygwin "UNIX socket."** **Default:** (none) - - * **agentForward** - _boolean_ - Set to `true` to use OpenSSH agent forwarding (`auth-agent@openssh.com`) for the life of the connection. `agent` must also be set to use this feature. **Default:** `false` - - * **algorithms** - _object_ - This option allows you to explicitly override the default transport layer algorithms used for the connection. The value for each category must either be an array of valid algorithm names to set an exact list (with the most preferable first) or an object containing `append`, `prepend`, and/or `remove` properties that each contain an _array_ of algorithm names or RegExps to match to adjust default lists for each category. Valid keys: - - * **cipher** - _mixed_ - Ciphers. - * Default list (in order from most to least preferable): - * `chacha20-poly1305@openssh.com` (priority of chacha20-poly1305 may vary depending upon CPU and/or optional binding availability) - * `aes128-gcm` - * `aes128-gcm@openssh.com` - * `aes256-gcm` - * `aes256-gcm@openssh.com` - * `aes128-ctr` - * `aes192-ctr` - * `aes256-ctr` - * Other supported names: - * `3des-cbc` - * `aes256-cbc` - * `aes192-cbc` - * `aes128-cbc` - * `arcfour256` - * `arcfour128` - * `arcfour` - * `blowfish-cbc` - * `cast128-cbc` - - * **compress** - _mixed_ - Compression algorithms. - * Default list (in order from most to least preferable): - * `none` - * `zlib@openssh.com` - * `zlib` - * Other supported names: - - * **hmac** - _mixed_ - (H)MAC algorithms. - * Default list (in order from most to least preferable): - * `hmac-sha2-256-etm@openssh.com` - * `hmac-sha2-512-etm@openssh.com` - * `hmac-sha1-etm@openssh.com` - * `hmac-sha2-256` - * `hmac-sha2-512` - * `hmac-sha1` - * Other supported names: - * `hmac-md5` - * `hmac-sha2-256-96` - * `hmac-sha2-512-96` - * `hmac-ripemd160` - * `hmac-sha1-96` - * `hmac-md5-96` - - * **kex** - _mixed_ - Key exchange algorithms. - * Default list (in order from most to least preferable): - * `curve25519-sha256 (node v14.0.0+)` - * `curve25519-sha256@libssh.org (node v14.0.0+)` - * `ecdh-sha2-nistp256` - * `ecdh-sha2-nistp384` - * `ecdh-sha2-nistp521` - * `diffie-hellman-group-exchange-sha256` - * `diffie-hellman-group14-sha256` - * `diffie-hellman-group15-sha512` - * `diffie-hellman-group16-sha512` - * `diffie-hellman-group17-sha512` - * `diffie-hellman-group18-sha512` - * Other supported names: - * `diffie-hellman-group-exchange-sha1` - * `diffie-hellman-group14-sha1` - * `diffie-hellman-group1-sha1` - - * **serverHostKey** - _mixed_ - Server host key formats. - * Default list (in order from most to least preferable): - * `ssh-ed25519` (node v12.0.0+) - * `ecdsa-sha2-nistp256` - * `ecdsa-sha2-nistp384` - * `ecdsa-sha2-nistp521` - * `rsa-sha2-512` - * `rsa-sha2-256` - * `ssh-rsa` - * Other supported names: - * `ssh-dss` - - * **authHandler** - _mixed_ - Either an array of objects as described below or a function with parameters `(methodsLeft, partialSuccess, callback)` where `methodsLeft` and `partialSuccess` are `null` on the first authentication attempt, otherwise are an array and boolean respectively. Return or call `callback()` with either the name of the authentication method or an object containing the method name along with method-specific details to try next (return/pass `false` to signal no more methods to try). Valid method names are: `'none', 'password', 'publickey', 'agent', 'keyboard-interactive', 'hostbased'`. **Default:** function that follows a set method order: None -> Password -> Private Key -> Agent (-> keyboard-interactive if `tryKeyboard` is `true`) -> Hostbased - - * When returning or calling `callback()` with an object, it can take one of the following forms: - - ```js - { - type: 'none', - username: 'foo', - } - ``` - - ```js - { - type: 'password' - username: 'foo', - password: 'bar', - } - ``` - - ```js - { - type: 'publickey' - username: 'foo', - // Can be a string, Buffer, or parsed key containing a private key - key: ..., - // `passphrase` only required for encrypted keys - passphrase: ..., - } - ``` - - ```js - { - type: 'hostbased' - username: 'foo', - localHostname: 'baz', - localUsername: 'quux', - // Can be a string, Buffer, or parsed key containing a private key - key: ..., - // `passphrase` only required for encrypted keys - passphrase: ..., - } - ``` - - ```js - { - type: 'agent' - username: 'foo', - // Can be a string that is interpreted exactly like the `agent` - // connection config option or can be a custom agent - // object/instance that extends and implements `BaseAgent` - agent: ..., - } - ``` - - ```js - { - type: 'keyboard-interactive' - username: 'foo', - // This works exactly the same way as a 'keyboard-interactive' - // Client event handler - prompt: (name, instructions, instructionsLang, prompts, finish) => { - // ... - }, - } - ``` - - * **debug** - _function_ - Set this to a function that receives a single string argument to get detailed (local) debug information. **Default:** (none) - - * **forceIPv4** - _boolean_ - Only connect via resolved IPv4 address for `host`. **Default:** `false` - - * **forceIPv6** - _boolean_ - Only connect via resolved IPv6 address for `host`. **Default:** `false` - - * **host** - _string_ - Hostname or IP address of the server. **Default:** `'localhost'` - - * **hostHash** - _string_ - Any valid hash algorithm supported by node. The host's key is hashed using this algorithm and passed to the **hostVerifier** function as a hex string. **Default:** (none) - - * **hostVerifier** - _function_ - Function with parameters `(hashedKey[, callback])` where `hashedKey` is a string hex hash of the host's key for verification purposes. Return `true` to continue with the handshake or `false` to reject and disconnect, or call `callback()` with `true` or `false` if you need to perform asynchronous verification. **Default:** (auto-accept if `hostVerifier` is not set) - - * **keepaliveCountMax** - _integer_ - How many consecutive, unanswered SSH-level keepalive packets that can be sent to the server before disconnection (similar to OpenSSH's ServerAliveCountMax config option). **Default:** `3` - - * **keepaliveInterval** - _integer_ - How often (in milliseconds) to send SSH-level keepalive packets to the server (in a similar way as OpenSSH's ServerAliveInterval config option). Set to 0 to disable. **Default:** `0` - - * **localAddress** - _string_ - IP address of the network interface to use to connect to the server. **Default:** (none -- determined by OS) - - * **localHostname** - _string_ - Along with **localUsername** and **privateKey**, set this to a non-empty string for hostbased user authentication. **Default:** (none) - - * **localPort** - _string_ - The local port number to connect from. **Default:** (none -- determined by OS) - - * **localUsername** - _string_ - Along with **localHostname** and **privateKey**, set this to a non-empty string for hostbased user authentication. **Default:** (none) - - * **passphrase** - _string_ - For an encrypted `privateKey`, this is the passphrase used to decrypt it. **Default:** (none) - - * **password** - _string_ - Password for password-based user authentication. **Default:** (none) - - * **port** - _integer_ - Port number of the server. **Default:** `22` - - * **privateKey** - _mixed_ - _Buffer_ or _string_ that contains a private key for either key-based or hostbased user authentication (OpenSSH format). **Default:** (none) - - * **readyTimeout** - _integer_ - How long (in milliseconds) to wait for the SSH handshake to complete. **Default:** `20000` - - * **sock** - _ReadableStream_ - A _ReadableStream_ to use for communicating with the server instead of creating and using a new TCP connection (useful for connection hopping). - - * **strictVendor** - _boolean_ - Performs a strict server vendor check before sending vendor-specific requests, etc. (e.g. check for OpenSSH server when using `openssh_noMoreSessions()`) **Default:** `true` - - * **tryKeyboard** - _boolean_ - Try keyboard-interactive user authentication if primary user authentication method fails. If you set this to `true`, you need to handle the `keyboard-interactive` event. **Default:** `false` - - * **username** - _string_ - Username for authentication. **Default:** (none) - -* **end**() - _(void)_ - Disconnects the socket. - -* **exec**(< _string_ >command[, < _object_ >options], < _function_ >callback) - _(void)_ - Executes `command` on the server. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. Valid `options` properties are: - - * **env** - _object_ - An environment to use for the execution of the command. - - * **pty** - _mixed_ - Set to `true` to allocate a pseudo-tty with defaults, or an object containing specific pseudo-tty settings (see 'Pseudo-TTY settings'). Setting up a pseudo-tty can be useful when working with remote processes that expect input from an actual terminal (e.g. sudo's password prompt). - - * **x11** - _mixed_ - Set to `true` to use defaults below, set to a number to specify a specific screen number, or an object with the following valid properties: - - * **cookie** - _mixed_ - The authentication cookie. Can be a hex _string_ or a _Buffer_ containing the raw cookie value (which will be converted to a hex string). **Default:** (random 16 byte value) - - * **protocol** - _string_ - The authentication protocol name. **Default:** `'MIT-MAGIC-COOKIE-1'` - - * **screen** - _number_ - Screen number to use **Default:** `0` - - * **single** - _boolean_ - Allow just a single connection? **Default:** `false` - -* **forwardIn**(< _string_ >remoteAddr, < _integer_ >remotePort, < _function_ >callback) - _(void)_ - Bind to `remoteAddr` on `remotePort` on the server and forward incoming TCP connections. `callback` has 2 parameters: < _Error_ >err, < _integer_ >port (`port` is the assigned port number if `remotePort` was 0). Here are some special values for `remoteAddr` and their associated binding behaviors: - - * '' - Connections are to be accepted on all protocol families supported by the server. - - * '0.0.0.0' - Listen on all IPv4 addresses. - - * '::' - Listen on all IPv6 addresses. - - * 'localhost' - Listen on all protocol families supported by the server on loopback addresses only. - - * '127.0.0.1' and '::1' - Listen on the loopback interfaces for IPv4 and IPv6, respectively. - -* **forwardOut**(< _string_ >srcIP, < _integer_ >srcPort, < _string_ >dstIP, < _integer_ >dstPort, < _function_ >callback) - _(void)_ - Open a connection with `srcIP` and `srcPort` as the originating address and port and `dstIP` and `dstPort` as the remote destination address and port. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **openssh_forwardInStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - OpenSSH extension that binds to a UNIX domain socket at `socketPath` on the server and forwards incoming connections. `callback` has 1 parameter: < _Error_ >err. - -* **openssh_forwardOutStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - OpenSSH extension that opens a connection to a UNIX domain socket at `socketPath` on the server. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **openssh_noMoreSessions**(< _function_ >callback) - _(void)_ - OpenSSH extension that sends a request to reject any new sessions (e.g. exec, shell, sftp, subsys) for this connection. `callback` has 1 parameter: < _Error_ >err. - -* **openssh_unforwardInStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - OpenSSH extension that unbinds from a UNIX domain socket at `socketPath` on the server and stops forwarding incoming connections. `callback` has 1 parameter: < _Error_ >err. - -* **rekey**([< _function_ >callback]) - _(void)_ - Initiates a rekey with the server. If `callback` is supplied, it is added as a one-time handler for the `rekey` event. - -* **sftp**(< _function_ >callback) - _(void)_ - Starts an SFTP session. `callback` has 2 parameters: < _Error_ >err, < _SFTP_ >sftp. For methods available on `sftp`, see the [`SFTP` client documentation](https://github.com/mscdex/ssh2/blob/master/SFTP.md). - -* **shell**([[< _mixed_ >window,] < _object_ >options]< _function_ >callback) - _(void)_ - Starts an interactive shell session on the server, with an optional `window` object containing pseudo-tty settings (see 'Pseudo-TTY settings'). If `window === false`, then no pseudo-tty is allocated. `options` supports the `x11` and `env` options as described in `exec()`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **subsys**(< _string_ >subsystem, < _function_ >callback) - _(void)_ - Invokes `subsystem` on the server. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **unforwardIn**(< _string_ >remoteAddr, < _integer_ >remotePort, < _function_ >callback) - _(void)_ - Unbind from `remoteAddr` on `remotePort` on the server and stop forwarding incoming TCP connections. Until `callback` is called, more connections may still come in. `callback` has 1 parameter: < _Error_ >err. - -### Server - -#### Server events - -* **connection**(< _Connection_ >client, < _object_ >info) - A new client has connected. `info` contains the following properties: - - * **family** - _string_ - The `remoteFamily` of the connection. - - * **header** - _object_ - Information about the client's header: - - * **identRaw** - _string_ - The raw client identification string. - - * **versions** - _object_ - Various version information: - - * **protocol** - _string_ - The SSH protocol version (always `1.99` or `2.0`). - - * **software** - _string_ - The software name and version of the client. - - * **comments** - _string_ - Any text that comes after the software name/version. - - Example: the identification string `SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2` would be parsed as: - -```js - { identRaw: 'SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2', - version: { - protocol: '2.0', - software: 'OpenSSH_6.6.1p1' - }, - comments: 'Ubuntu-2ubuntu2' } -``` - - * **ip** - _string_ - The `remoteAddress` of the connection. - - * **port** - _integer_ - The `remotePort` of the connection. - -#### Server methods - -* **(constructor)**(< _object_ >config[, < _function_ >connectionListener]) - Creates and returns a new Server instance. Server instances also have the same methods/properties/events as [`net.Server`](http://nodejs.org/docs/latest/api/net.html#net_class_net_server). `connectionListener` if supplied, is added as a `connection` listener. Valid `config` properties: - - * **algorithms** - _object_ - This option allows you to explicitly override the default transport layer algorithms used for incoming client connections. Each value must be an array of valid algorithms for that category. The order of the algorithms in the arrays are important, with the most favorable being first. For a list of valid and default algorithm names, please review the documentation for the version of `ssh2` used by this module. Valid keys: - - * **cipher** - _array_ - Ciphers. - - * **compress** - _array_ - Compression algorithms. - - * **hmac** - _array_ - (H)MAC algorithms. - - * **kex** - _array_ - Key exchange algorithms. - - * **serverHostKey** - _array_ - Server host key formats. - - * **banner** - _string_ - A message that is sent to clients once, right before authentication begins. **Default:** (none) - - * **debug** - _function_ - Set this to a function that receives a single string argument to get detailed (local) debug information. **Default:** (none) - - * **greeting** - _string_ - A message that is sent to clients immediately upon connection, before handshaking begins. **Note:** Most clients usually ignore this. **Default:** (none) - - * **highWaterMark** - _integer_ - This is the `highWaterMark` to use for the parser stream. **Default:** `32 * 1024` - - * **hostKeys** - _array_ - An array of either Buffers/strings that contain host private keys or objects in the format of `{ key: , passphrase: }` for encrypted private keys. (**Required**) **Default:** (none) - - * **ident** - _string_ - A custom server software name/version identifier. **Default:** `'ssh2js' + moduleVersion + 'srv'` - -* **injectSocket**(< _DuplexStream_ >socket) - Injects a bidirectional stream as though it were a TCP socket connection. Additionally, `socket` should include `net.Socket`-like properties to ensure the best compatibility (e.g. `socket.remoteAddress`, `socket.remotePort`, `socket.remoteFamily`). - -#### Connection events - -* **authentication**(< _AuthContext_ >ctx) - The client has requested authentication. `ctx.username` contains the client username, `ctx.method` contains the requested authentication method, and `ctx.accept()` and `ctx.reject([< Array >authMethodsLeft[, < Boolean >isPartialSuccess]])` are used to accept or reject the authentication request respectively. `abort` is emitted if the client aborts the authentication request. Other properties/methods available on `ctx` depends on the `ctx.method` of authentication the client has requested: - - * `hostbased`: - - * **blob** - _Buffer_ - This contains the data to be verified that is passed to (along with the signature) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities). - - * **key** - _object_ - Contains information about the public key sent by the client: - - * **algo** - _string_ - The name of the key algorithm (e.g. `ssh-rsa`). - - * **data** - _Buffer_ - The actual key data. - - * **localHostname** - _string_ - The local hostname provided by the client. - - * **localUsername** - _string_ - The local username provided by the client. - - * **signature** - _Buffer_ - This contains a signature to be verified that is passed to (along with the blob) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities). - - * `keyboard-interactive`: - - * **prompt**(< _array_ >prompts[, < _string_ >title[, < _string_ >instructions]], < _function_ >callback) - _(void)_ - Send prompts to the client. `prompts` is an array of `{ prompt: 'Prompt text', echo: true }` objects (`prompt` being the prompt text and `echo` indicating whether the client's response to the prompt should be echoed to their display). `callback` is called with `(responses)`, where `responses` is an array of string responses matching up to the `prompts`. - - * **submethods** - _array_ - A list of preferred authentication "sub-methods" sent by the client. This may be used to determine what (if any) prompts to send to the client. - - * `password`: - - * **password** - _string_ - This is the password sent by the client. - - * **requestChange**(< _string_ >prompt, < _function_ >callback) - _(void)_ - Sends a password change request to the client. `callback` is called with `(newPassword)`, where `newPassword` is the new password supplied by the client. You may accept, reject, or prompt for another password change after `callback` is called. - - * `publickey`: - - * **blob** - _mixed_ - If the value is `undefined`, the client is only checking the validity of the `key`. If the value is a _Buffer_, then this contains the data to be verified that is passed to (along with the signature) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities). - - * **key** - _object_ - Contains information about the public key sent by the client: - - * **algo** - _string_ - The name of the key algorithm (e.g. `ssh-rsa`). - - * **data** - _Buffer_ - The actual key data. - - * **signature** - _mixed_ - If the value is `undefined`, the client is only checking the validity of the `key`. If the value is a _Buffer_, then this contains a signature to be verified that is passed to (along with the blob) `key.verify()` where `key` is a public key parsed with [`parseKey()`](#utilities). - -* **close**() - The client socket was closed. - -* **end**() - The client socket disconnected. - -* **error**(< _Error_ >err) - An error occurred. - -* **handshake**(< _object_ >negotiated) - Emitted when a handshake has completed (either initial or rekey). `negotiated` contains the negotiated details of the handshake and is of the form: - -```js - // In this particular case `mac` is empty because there is no separate MAC - // because it's integrated into AES in GCM mode - { kex: 'ecdh-sha2-nistp256', - srvHostKey: 'rsa-sha2-512', - cs: { // Client to server algorithms - cipher: 'aes128-gcm', - mac: '', - compress: 'none', - lang: '' - }, - sc: { // Server to client algorithms - cipher: 'aes128-gcm', - mac: '', - compress: 'none', - lang: '' - } - } -``` - -* **openssh.streamlocal**(< _function_ >accept, < _function_ >reject, < _object_ >info) - Emitted when the client has requested a connection to a UNIX domain socket. `accept()` returns a new _Channel_ instance representing the connection. `info` contains: - - * **socketPath** - _string_ - Destination socket path of outgoing connection. - -* **ready**() - Emitted when the client has been successfully authenticated. - -* **rekey**() - Emitted when a rekeying operation has completed (either client or server-initiated). - -* **request**(< _mixed_ >accept, < _mixed_ >reject, < _string_ >name, < _object_ >info) - Emitted when the client has sent a global request for `name` (e.g. `tcpip-forward` or `cancel-tcpip-forward`). `accept` and `reject` are functions if the client requested a response. If `bindPort === 0`, you should pass the chosen port to `accept()` so that the client will know what port was bound. `info` contains additional details about the request: - - * `cancel-tcpip-forward` and `tcpip-forward`: - - * **bindAddr** - _string_ - The IP address to start/stop binding to. - - * **bindPort** - _integer_ - The port to start/stop binding to. - - * `cancel-streamlocal-forward@openssh.com` and `streamlocal-forward@openssh.com`: - - * **socketPath** - _string_ - The socket path to start/stop binding to. - -* **session**(< _function_ >accept, < _function_ >reject) - Emitted when the client has requested a new session. Sessions are used to start interactive shells, execute commands, request X11 forwarding, etc. `accept()` returns a new _Session_ instance. - -* **tcpip**(< _function_ >accept, < _function_ >reject, < _object_ >info) - Emitted when the client has requested an outbound (TCP) connection. `accept()` returns a new _Channel_ instance representing the connection. `info` contains: - - * **destIP** - _string_ - Destination IP address of outgoing connection. - - * **destPort** - _string_ - Destination port of outgoing connection. - - * **srcIP** - _string_ - Source IP address of outgoing connection. - - * **srcPort** - _string_ - Source port of outgoing connection. - -#### Connection methods - -* **end**() - _(void)_ - Closes the client connection. - -* **forwardOut**(< _string_ >boundAddr, < _integer_ >boundPort, < _string_ >remoteAddr, < _integer_ >remotePort, < _function_ >callback) - _(void)_ - Alert the client of an incoming TCP connection on `boundAddr` on port `boundPort` from `remoteAddr` on port `remotePort`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **openssh_forwardOutStreamLocal**(< _string_ >socketPath, < _function_ >callback) - _(void)_ - Alert the client of an incoming UNIX domain socket connection on `socketPath`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -* **rekey**([< _function_ >callback]) - _(void)_ - Initiates a rekey with the client. If `callback` is supplied, it is added as a one-time handler for the `rekey` event. - -* **x11**(< _string_ >originAddr, < _integer_ >originPort, < _function_ >callback) - _(void)_ - Alert the client of an incoming X11 client connection from `originAddr` on port `originPort`. `callback` has 2 parameters: < _Error_ >err, < _Channel_ >stream. - -#### Session events - -* **auth-agent**(< _mixed_ >accept, < _mixed_ >reject) - The client has requested incoming ssh-agent requests be forwarded to them. `accept` and `reject` are functions if the client requested a response. - -* **close**() - The session was closed. - -* **env**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client requested an environment variable to be set for this session. `accept` and `reject` are functions if the client requested a response. `info` has these properties: - - * **key** - _string_ - The environment variable's name. - - * **value** - _string_ - The environment variable's value. - -* **exec**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client has requested execution of a command string. `accept` and `reject` are functions if the client requested a response. `accept()` returns a _Channel_ for the command execution. `info` has these properties: - - * **command** - _string_ - The command line to be executed. - -* **pty**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client requested allocation of a pseudo-TTY for this session. `accept` and `reject` are functions if the client requested a response. `info` has these properties: - - * **cols** - _integer_ - The number of columns for the pseudo-TTY. - - * **height** - _integer_ - The height of the pseudo-TTY in pixels. - - * **modes** - _object_ - Contains the requested terminal modes of the pseudo-TTY keyed on the mode name with the value being the mode argument. (See the table at the end for valid names). - - * **rows** - _integer_ - The number of rows for the pseudo-TTY. - - * **width** - _integer_ - The width of the pseudo-TTY in pixels. - -* **sftp**(< _mixed_ >accept, < _mixed_ >reject) - The client has requested the SFTP subsystem. `accept` and `reject` are functions if the client requested a response. `accept()` returns an _SFTP_ instance in server mode (see the [`SFTP` documentation](https://github.com/mscdex/ssh2/blob/master/SFTP.md) for details). `info` has these properties: - -* **shell**(< _mixed_ >accept, < _mixed_ >reject) - The client has requested an interactive shell. `accept` and `reject` are functions if the client requested a response. `accept()` returns a _Channel_ for the interactive shell. - -* **signal**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client has sent a signal. `accept` and `reject` are functions if the client requested a response. `info` has these properties: - - * **name** - _string_ - The signal name (e.g. `SIGUSR1`). - -* **subsystem**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client has requested an arbitrary subsystem. `accept` and `reject` are functions if the client requested a response. `accept()` returns a _Channel_ for the subsystem. `info` has these properties: - - * **name** - _string_ - The name of the subsystem. - -* **window-change**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client reported a change in window dimensions during this session. `accept` and `reject` are functions if the client requested a response. `info` has these properties: - - * **cols** - _integer_ - The new number of columns for the client window. - - * **height** - _integer_ - The new height of the client window in pixels. - - * **rows** - _integer_ - The new number of rows for the client window. - - * **width** - _integer_ - The new width of the client window in pixels. - -* **x11**(< _mixed_ >accept, < _mixed_ >reject, < _object_ >info) - The client requested X11 forwarding. `accept` and `reject` are functions if the client requested a response. `info` has these properties: - - * **cookie** - _string_ - The X11 authentication cookie encoded in hexadecimal. - - * **protocol** - _string_ - The name of the X11 authentication method used (e.g. `MIT-MAGIC-COOKIE-1`). - - * **screen** - _integer_ - The screen number to forward X11 connections for. - - * **single** - _boolean_ - `true` if only a single connection should be forwarded. - -### Channel - -This is a normal **streams2** Duplex Stream (used both by clients and servers), with the following changes: - -* A boolean property `allowHalfOpen` exists and behaves similarly to the property of the same name for `net.Socket`. When the stream's end() is called, if `allowHalfOpen` is `true`, only EOF will be sent (the server can still send data if they have not already sent EOF). The default value for this property is `true`. - -* A `close` event is emitted once the channel is completely closed on both the client and server. - -* Client-specific: - - * For exec(): - - * An `exit` event *may* (the SSH2 spec says it is optional) be emitted when the process finishes. If the process finished normally, the process's return value is passed to the `exit` callback. If the process was interrupted by a signal, the following are passed to the `exit` callback: null, < _string_ >signalName, < _boolean_ >didCoreDump, < _string_ >description. - - * If there was an `exit` event, the `close` event will be passed the same arguments for convenience. - - * A `stderr` property contains a Readable stream that represents output from stderr. - - * For exec() and shell(): - - * The readable side represents stdout and the writable side represents stdin. - - * **setWindow**(< _integer_ >rows, < _integer_ >cols, < _integer_ >height, < _integer_ >width) - _(void)_ - Lets the server know that the local terminal window has been resized. The meaning of these arguments are described in the 'Pseudo-TTY settings' section. - - * **signal**(< _string_ >signalName) - _(void)_ - Sends a POSIX signal to the current process on the server. Valid signal names are: 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'KILL', 'PIPE', 'QUIT', 'SEGV', 'TERM', 'USR1', and 'USR2'. Some server implementations may ignore this request if they do not support signals. Note: If you are trying to send SIGINT and you find `signal()` doesn't work, try writing `'\x03'` to the Channel stream instead. - - -* Server-specific: - - * For exec-enabled channel instances there is an additional method available that may be called right before you close the channel. It has two different signatures: - - * **exit**(< _integer_ >exitCode) - _(void)_ - Sends an exit status code to the client. - - * **exit**(< _string_ >signalName[, < _boolean_ >coreDumped[, < _string_ >errorMsg]]) - _(void)_ - Sends an exit status code to the client. - - * For exec and shell-enabled channel instances, `channel.stderr` is a writable stream. - -### Pseudo-TTY settings - -* **cols** - < _integer_ > - Number of columns. **Default:** `80` - -* **height** - < _integer_ > - Height in pixels. **Default:** `480` - -* **modes** - < _object_ > - An object containing [Terminal Modes](#terminal-modes) as keys, with each value set to each mode argument. **Default:** `null` - -* **rows** - < _integer_ > - Number of rows. **Default:** `24` - -* **term** - < _string_ > - The value to use for $TERM. **Default:** `'vt100'` - -* **width** - < _integer_ > - Width in pixels. **Default:** `640` - -`rows` and `cols` override `width` and `height` when `rows` and `cols` are non-zero. - -Pixel dimensions refer to the drawable area of the window. - -Zero dimension parameters are ignored. - -### Terminal modes - -Name | Description --------------- | ------------ -CS7 | 7 bit mode. -CS8 | 8 bit mode. -ECHOCTL | Echo control characters as ^(Char). -ECHO | Enable echoing. -ECHOE | Visually erase chars. -ECHOKE | Visual erase for line kill. -ECHOK | Kill character discards current line. -ECHONL | Echo NL even if ECHO is off. -ICANON | Canonicalize input lines. -ICRNL | Map CR to NL on input. -IEXTEN | Enable extensions. -IGNCR | Ignore CR on input. -IGNPAR | The ignore parity flag. The parameter SHOULD be 0 if this flag is FALSE, and 1 if it is TRUE. -IMAXBEL | Ring bell on input queue full. -INLCR | Map NL into CR on input. -INPCK | Enable checking of parity errors. -ISIG | Enable signals INTR, QUIT, [D]SUSP. -ISTRIP | Strip 8th bit off characters. -IUCLC | Translate uppercase characters to lowercase. -IXANY | Any char will restart after stop. -IXOFF | Enable input flow control. -IXON | Enable output flow control. -NOFLSH | Don't flush after interrupt. -OCRNL | Translate carriage return to newline (output). -OLCUC | Convert lowercase to uppercase. -ONLCR | Map NL to CR-NL. -ONLRET | Newline performs a carriage return (output). -ONOCR | Translate newline to carriage return-newline (output). -OPOST | Enable output processing. -PARENB | Parity enable. -PARMRK | Mark parity and framing errors. -PARODD | Odd parity, else even. -PENDIN | Retype pending input. -TOSTOP | Stop background jobs from output. -TTY_OP_ISPEED | Specifies the input baud rate in bits per second. -TTY_OP_OSPEED | Specifies the output baud rate in bits per second. -VDISCARD | Toggles the flushing of terminal output. -VDSUSP | Another suspend character. -VEOF | End-of-file character (sends EOF from the terminal). -VEOL2 | Additional end-of-line character. -VEOL | End-of-line character in addition to carriage return and/or linefeed. -VERASE | Erase the character to left of the cursor. -VFLUSH | Character to flush output. -VINTR | Interrupt character; 255 if none. Similarly for the other characters. Not all of these characters are supported on all systems. -VKILL | Kill the current input line. -VLNEXT | Enter the next character typed literally, even if it is a special character -VQUIT | The quit character (sends SIGQUIT signal on POSIX systems). -VREPRINT | Reprints the current input line. -VSTART | Continues paused output (normally control-Q). -VSTATUS | Prints system status line (load, command, pid, etc). -VSTOP | Pauses output (normally control-S). -VSUSP | Suspends the current program. -VSWTCH | Switch to a different shell layer. -VWERASE | Erases a word left of cursor. -XCASE | Enable input and output of uppercase characters by preceding their lowercase equivalents with "\". - -### HTTPAgent - -#### HTTPAgent methods - -* **(constructor)**(< _object_ >sshConfig[, < _object_ >agentConfig]) - Creates and returns a new `http.Agent` instance used to tunnel an HTTP connection over SSH. `sshConfig` is what is passed to `client.connect()` and `agentOptions` is passed to the `http.Agent` constructor. - -### HTTPSAgent - -#### HTTPSAgent methods - -* **(constructor)**(< _object_ >sshConfig[, < _object_ >agentConfig]) - Creates and returns a new `https.Agent` instance used to tunnel an HTTP connection over SSH. `sshConfig` is what is passed to `client.connect()` and `agentOptions` is passed to the `https.Agent` constructor. - -### Utilities - -* **parseKey**(< _mixed_ >keyData[, < _string_ >passphrase]) - _mixed_ - Parses a private/public key in OpenSSH, RFC4716, or PPK format. For encrypted private keys, the key will be decrypted with the given `passphrase`. `keyData` can be a _Buffer_ or _string_ value containing the key contents. The returned value will be an array of objects (currently in the case of modern OpenSSH keys) or an object with these properties and methods: - - * **comment** - _string_ - The comment for the key - - * **equals**(< _mixed_ >otherKey) - _boolean_ - This returns `true` if `otherKey` (a parsed or parseable key) is the same as this key. This method does not compare the keys' comments - - * **getPrivatePEM**() - _string_ - This returns the PEM version of a private key - - * **getPublicPEM**() - _string_ - This returns the PEM version of a public key (for either public key or derived from a private key) - - * **getPublicSSH**() - _string_ - This returns the SSH version of a public key (for either public key or derived from a private key) - - * **isPrivateKey**() - _boolean_ - This returns `true` if the key is a private key or not - - * **sign**(< _mixed_ >data) - _mixed_ - This signs the given `data` using this key and returns a _Buffer_ containing the signature on success. On failure, an _Error_ will be returned. `data` can be anything accepted by node's [`sign.update()`](https://nodejs.org/docs/latest/api/crypto.html#crypto_sign_update_data_inputencoding). - - * **type** - _string_ - The full key type (e.g. `'ssh-rsa'`) - - * **verify**(< _mixed_ >data, < _Buffer_ >signature) - _mixed_ - This verifies a `signature` of the given `data` using this key and returns `true` if the signature could be verified. On failure, either `false` will be returned or an _Error_ will be returned upon a more critical failure. `data` can be anything accepted by node's [`verify.update()`](https://nodejs.org/docs/latest/api/crypto.html#crypto_verify_update_data_inputencoding). - -* **sftp.OPEN_MODE** - [`OPEN_MODE`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-data-structures) - -* **sftp.STATUS_CODE** - [`STATUS_CODE`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-data-structures) - -* **sftp.flagsToString** - [`flagsToString()`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-methods) - -* **sftp.stringToFlags** - [`stringToFlags()`](https://github.com/mscdex/ssh2/blob/master/SFTP.md#useful-standalone-methods) - -### AgentProtocol - -#### AgentProtocol events - -* **identities**(< _opaque_ >request) - **(Server mode only)** The client has requested a list of public keys stored in the agent. Use `failureReply()` or `getIdentitiesReply()` to reply appropriately. - -* **sign**(< _opaque_ >request, < _mixed_ >pubKey, < _Buffer_ >data, < _object_ >options) - **(Server mode only)** The client has requested `data` to be signed using the key identified by `pubKey`. Use `failureReply()` or `signReply()` to reply appropriately. `options` may contain any of: - - * **hash** - _string_ - The explicitly desired hash to use when computing the signature. Currently if set, this may be either `'sha256'` or `'sha512'` for RSA keys. - -#### AgentProtocol methods - -* **(constructor)**(< _boolean_ >isClient) - Creates and returns a new AgentProtocol instance. `isClient` determines whether the instance operates in client or server mode. - -* **failureReply**(< _opaque_ >request) - _(void)_ - **(Server mode only)** Replies to the given `request` with a failure response. - -* **getIdentities**(< _function_ >callback) - _(void)_ - **(Client mode only)** Requests a list of public keys from the agent. `callback` is passed `(err, keys)` where `keys` is a possible array of public keys for authentication. - -* **getIdentitiesReply**(< _opaque_ >request, < _array_ >keys) - _(void)_ - **(Server mode only)** Responds to a identities list `request` with the given array of keys in `keys`. - -* **sign**(< _mixed_ >pubKey, < _Buffer_ >data, < _object_ >options, < _function_ >callback) - _(void)_ - **(Client mode only)** Requests that the agent sign `data` using the key identified by `pubKey`. `pubKey` can be any parsed (using `utils.parseKey()`) or parseable key value. `callback` is passed `(err, signature)` where `signature` is a possible _Buffer_ containing the signature for the `data`. `options` may contain any of: - - * **hash** - _string_ - The explicitly desired hash to use when computing the signature. Currently if set, this may be either `'sha256'` or `'sha512'` for RSA keys. - -* **signReply**(< _opaque_ >request, < _Buffer_ >signature) - _(void)_ - **(Server mode only)** Responds to a sign `request` with the given signature in `signature`. - -### BaseAgent - -In order to create a custom agent, your class *must*: - - * Extend `BaseAgent` - * Call `super()` in its constructor - * Implement *at least* the following methods: - -* **getIdentities**(< _function_ >callback) - _(void)_ - Passes `(err, keys)` to `callback` where `keys` is a possible array of public keys for authentication. - -* **sign**(< _mixed_ >pubKey, < _Buffer_ >data, < _object_ >options, < _function_ >callback) - _(void)_ - Signs `data` using the key identified by `pubKey`. `pubKey` can be any parsed (using `utils.parseKey()`) or parseable key value. `callback` should be passed `(err, signature)` where `signature` is a possible _Buffer_ containing the signature for the `data`. `options` may contain any of: - - * **hash** - _string_ - The explicitly desired hash to use when computing the signature. Currently if set, this may be either `'sha256'` or `'sha512'` for RSA keys. - -Additionally your class may implement the following method in order to support agent forwarding on the client: - -* **getStream**(< _function_ >callback) - _(void)_ - Passes `(err, stream)` to `callback` where `stream` is a possible Duplex stream to be used to communicate with your agent. You will probably want to utilize `AgentProtocol` as agent forwarding is an OpenSSH feature, so the `stream` needs to be able to transmit/receive OpenSSH agent protocol packets. - -### createAgent - -* **createAgent**(< _string_ >agentValue) - _(Agent)_ - Creates and returns a new agent instance using the same logic as the `Client`'s `agent` configuration option: if the platform is Windows and it's the value "pageant", it creates a `PageantAgent`, otherwise if it's not a path to a Windows pipe it creates a `CygwinAgent`. In all other cases, it creates an `OpenSSHAgent`. - -### CygwinAgent - -#### CygwinAgent methods - -* **(constructor)**(< _string_ >socketPath) - Communicates with an agent listening at `socketPath` in a Cygwin environment. - -### OpenSSHAgent - -#### OpenSSHAgent methods - -* **(constructor)**(< _string_ >socketPath) - Communicates with an OpenSSH agent listening on the UNIX socket at `socketPath`. - -### PageantAgent - -#### PageantAgent methods - -* **(constructor)**() - Creates a new agent instance for communicating with a running Pageant agent process. diff --git a/reverse_engineering/node_modules/ssh2/SFTP.md b/reverse_engineering/node_modules/ssh2/SFTP.md deleted file mode 100644 index 60c33ba..0000000 --- a/reverse_engineering/node_modules/ssh2/SFTP.md +++ /dev/null @@ -1,403 +0,0 @@ -SFTP events ------------ - -**Client/Server events** - -* **ready**() - Emitted after initial protocol version check has passed. - -**Server-only events** - -_Responses to these client requests are sent using one of the methods listed further in this document under `Server-only methods`. The valid response(s) for each request are documented below._ - -* **OPEN**(< _integer_ >reqID, < _string_ >filename, < _integer_ >flags, < _ATTRS_ >attrs) - - `flags` is a bitfield containing any of the flags defined in `OPEN_MODE`. - Use the static method `flagsToString()` to convert the value to a mode - string to be used by `fs.open()` (e.g. `'r'`). - - Respond using one of the following: - - * `handle()` - This indicates a successful opening of the file and passes - the given handle back to the client to use to refer to this open file for - future operations (e.g. reading, writing, closing). - - * `status()` - Use this to indicate a failure to open the requested file. - -* **READ**(< _integer_ >reqID, < _Buffer_ >handle, < _integer_ >offset, < _integer_ >length) - - Respond using one of the following: - - * `data()` - Use this to send the requested chunk of data back to the client. - The amount of data sent is allowed to be less than the `length` requested, - for example if the file ends between `offset` and `offset + length`. - - * `status()` - Use this to indicate either end of file (`STATUS_CODE.EOF`) - has been reached (`offset` is past the end of the file) or if an error - occurred while reading the requested part of the file. - -* **WRITE**(< _integer_ >reqID, < _Buffer_ >handle, < _integer_ >offset, < _Buffer_ >data) - - Respond using: - - * `status()` - Use this to indicate success/failure of the write to the file. - -* **FSTAT**(< _integer_ >reqID, < _Buffer_ >handle) - - Respond using one of the following: - - * `attrs()` - Use this to send the attributes for the requested - file/directory back to the client. - - * `status()` - Use this to indicate an error occurred while accessing the - file/directory. - -* **FSETSTAT**(< _integer_ >reqID, < _Buffer_ >handle, < _ATTRS_ >attrs) - - Respond using: - - * `status()` - Use this to indicates success/failure of the setting of the - given file/directory attributes. - -* **CLOSE**(< _integer_ >reqID, < _Buffer_ >handle) - - Respond using: - - * `status()` - Use this to indicate success (`STATUS_CODE.OK`) or failure of - the closing of the file identified by `handle`. - -* **OPENDIR**(< _integer_ >reqID, < _string_ >path) - - Respond using one of the following: - - * `handle()` - This indicates a successful opening of the directory and - passes the given handle back to the client to use to refer to this open - directory for future operations (e.g. reading directory contents, closing). - - * `status()` - Use this to indicate a failure to open the requested - directory. - -* **READDIR**(< _integer_ >reqID, < _Buffer_ >handle) - - Respond using one of the following: - - * `name()` - Use this to send one or more directory listings for the open - directory back to the client. - - * `status()` - Use this to indicate either end of directory contents - (`STATUS_CODE.EOF`) or if an error occurred while reading the directory - contents. - -* **LSTAT**(< _integer_ >reqID, < _string_ >path) - - Respond using one of the following: - - * `attrs()` - Use this to send the attributes for the requested - file/directory back to the client. - - * `status()` - Use this to indicate an error occurred while accessing the - file/directory. - -* **STAT**(< _integer_ >reqID, < _string_ >path) - - Respond using one of the following: - - * `attrs()` - Use this to send the attributes for the requested - file/directory back to the client. - - * `status()` - Use this to indicate an error occurred while accessing the - file/directory. - -* **REMOVE**(< _integer_ >reqID, < _string_ >path) - - Respond using: - - * `status()` - Use this to indicate success/failure of the removal of the - file at `path`. - -* **RMDIR**(< _integer_ >reqID, < _string_ >path) - - Respond using: - - * `status()` - Use this to indicate success/failure of the removal of the - directory at `path`. - -* **REALPATH**(< _integer_ >reqID, < _string_ >path) - - Respond using one of the following: - - * `name()` - Use this to respond with a normalized version of `path`. - No file/directory attributes are required to be sent in this response. - - * `status()` - Use this to indicate a failure in normalizing `path`. - -* **READLINK**(< _integer_ >reqID, < _string_ >path) - - Respond using one of the following: - - * `name()` - Use this to respond with the target of the symlink at `path`. - No file/directory attributes are required to be sent in this response. - - * `status()` - Use this to indicate a failure in reading the symlink at - `path`. - -* **SETSTAT**(< _integer_ >reqID, < _string_ >path, < _ATTRS_ >attrs) - - Respond using: - - * `status()` - Use this to indicates success/failure of the setting of the - given file/directory attributes. - -* **MKDIR**(< _integer_ >reqID, < _string_ >path, < _ATTRS_ >attrs) - - Respond using: - - * `status()` - Use this to indicate success/failure of the creation of the - directory at `path`. - -* **RENAME**(< _integer_ >reqID, < _string_ >oldPath, < _string_ >newPath) - - Respond using: - - * `status()` - Use this to indicate success/failure of the renaming of the - file/directory at `oldPath` to `newPath`. - -* **SYMLINK**(< _integer_ >reqID, < _string_ >linkPath, < _string_ >targetPath) - - Respond using: - - * `status()` - Use this to indicate success/failure of the symlink creation. - - -Useful standalone data structures ---------------------------------- - -* **STATUS_CODE** - _object_ - Contains the various status codes (for use especially with `status()`): - - * `OK` - - * `EOF` - - * `NO_SUCH_FILE` - - * `PERMISSION_DENIED` - - * `FAILURE` - - * `BAD_MESSAGE` - - * `OP_UNSUPPORTED` - -* **OPEN_MODE** - _object_ - Contains the various open file flags: - - * `READ` - - * `WRITE` - - * `APPEND` - - * `CREAT` - - * `TRUNC` - - * `EXCL` - - -Useful standalone methods -------------------------- - -* **stringToFlags**(< _string_ >flagsStr) - _integer_ - Converts string flags (e.g. `'r'`, `'a+'`, etc.) to the appropriate `OPEN_MODE` flag mask. Returns `null` if conversion failed. - -* **flagsToString**(< _integer_ >flagsMask) - _string_ - Converts flag mask (e.g. number containing `OPEN_MODE` values) to the appropriate string value. Returns `null` if conversion failed. - - -SFTP methods ------------- - -* **(constructor)**(< _object_ >config[, < _string_ >remoteIdentRaw]) - Creates and returns a new SFTP instance. `remoteIdentRaw` can be the raw SSH identification string of the remote party. This is used to change internal behavior based on particular SFTP implementations. `config` can contain: - - * **server** - _boolean_ - Set to `true` to create an instance in server mode. **Default:** `false` - - * **debug** - _function_ - Set this to a function that receives a single string argument to get detailed (local) debug information. **Default:** (none) - - - -**Client-only methods** - -* **fastGet**(< _string_ >remotePath, < _string_ >localPath[, < _object_ >options], < _function_ >callback) - _(void)_ - Downloads a file at `remotePath` to `localPath` using parallel reads for faster throughput. `options` can have the following properties: - - * **concurrency** - _integer_ - Number of concurrent reads **Default:** `64` - - * **chunkSize** - _integer_ - Size of each read in bytes **Default:** `32768` - - * **step** - _function_(< _integer_ >total_transferred, < _integer_ >chunk, < _integer_ >total) - Called every time a part of a file was transferred - - `callback` has 1 parameter: < _Error_ >err. - -* **fastPut**(< _string_ >localPath, < _string_ >remotePath[, < _object_ >options], < _function_ >callback) - _(void)_ - Uploads a file from `localPath` to `remotePath` using parallel reads for faster throughput. `options` can have the following properties: - - * **concurrency** - _integer_ - Number of concurrent reads **Default:** `64` - - * **chunkSize** - _integer_ - Size of each read in bytes **Default:** `32768` - - * **step** - _function_(< _integer_ >total_transferred, < _integer_ >chunk, < _integer_ >total) - Called every time a part of a file was transferred - - * **mode** - _mixed_ - Integer or string representing the file mode to set for the uploaded file. - - `callback` has 1 parameter: < _Error_ >err. - -* **createReadStream**(< _string_ >path[, < _object_ >options]) - _ReadStream_ - Returns a new readable stream for `path`. `options` has the following defaults: - - ```javascript - { flags: 'r', - encoding: null, - handle: null, - mode: 0o666, - autoClose: true - } - ``` - - `options` can include `start` and `end` values to read a range of bytes from the file instead of the entire file. Both `start` and `end` are inclusive and start at 0. The `encoding` can be `'utf8'`, `'ascii'`, or `'base64'`. - - If `autoClose` is false, then the file handle won't be closed, even if there's an error. It is your responsibility to close it and make sure there's no file handle leak. If `autoClose` is set to true (default behavior), on `error` or `end` the file handle will be closed automatically. - - An example to read the last 10 bytes of a file which is 100 bytes long: - - ```javascript - sftp.createReadStream('sample.txt', {start: 90, end: 99}); - ``` - -* **createWriteStream**(< _string_ >path[, < _object_ >options]) - _WriteStream_ - Returns a new writable stream for `path`. `options` has the following defaults: - - ```javascript - { - flags: 'w', - encoding: null, - mode: 0o666, - autoClose: true - } - ``` - - `options` may also include a `start` option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a flags mode of 'r+' rather than the default mode 'w'. - - If 'autoClose' is set to false and you pipe to this stream, this stream will not automatically close after there is no more data upstream -- allowing future pipes and/or manual writes. - -* **open**(< _string_ >filename, < _string_ >flags, [< _mixed_ >attrs_mode, ]< _function_ >callback) - _(void)_ - Opens a file `filename` with `flags` with optional _ATTRS_ object or file mode `attrs_mode`. `flags` is any of the flags supported by `fs.open` (except sync flag). `callback` has 2 parameters: < _Error_ >err, < _Buffer_ >handle. - -* **close**(< _Buffer_ >handle, < _function_ >callback) - _(void)_ - Closes the resource associated with `handle` given by open() or opendir(). `callback` has 1 parameter: < _Error_ >err. - -* **read**(< _Buffer_ >handle, < _Buffer_ >buffer, < _integer_ >offset, < _integer_ >length, < _integer_ >position, < _function_ >callback) - _(void)_ - Reads `length` bytes from the resource associated with `handle` starting at `position` and stores the bytes in `buffer` starting at `offset`. `callback` has 4 parameters: < _Error_ >err, < _integer_ >bytesRead, < _Buffer_ >buffer (offset adjusted), < _integer_ >position. - -* **write**(< _Buffer_ >handle, < _Buffer_ >buffer, < _integer_ >offset, < _integer_ >length, < _integer_ >position, < _function_ >callback) - _(void)_ - Writes `length` bytes from `buffer` starting at `offset` to the resource associated with `handle` starting at `position`. `callback` has 1 parameter: < _Error_ >err. - -* **fstat**(< _Buffer_ >handle, < _function_ >callback) - _(void)_ - Retrieves attributes for the resource associated with `handle`. `callback` has 2 parameters: < _Error_ >err, < _Stats_ >stats. - -* **fsetstat**(< _Buffer_ >handle, < _ATTRS_ >attributes, < _function_ >callback) - _(void)_ - Sets the attributes defined in `attributes` for the resource associated with `handle`. `callback` has 1 parameter: < _Error_ >err. - -* **futimes**(< _Buffer_ >handle, < _mixed_ >atime, < _mixed_ >mtime, < _function_ >callback) - _(void)_ - Sets the access time and modified time for the resource associated with `handle`. `atime` and `mtime` can be Date instances or UNIX timestamps. `callback` has 1 parameter: < _Error_ >err. - -* **fchown**(< _Buffer_ >handle, < _integer_ >uid, < _integer_ >gid, < _function_ >callback) - _(void)_ - Sets the owner for the resource associated with `handle`. `callback` has 1 parameter: < _Error_ >err. - -* **fchmod**(< _Buffer_ >handle, < _mixed_ >mode, < _function_ >callback) - _(void)_ - Sets the mode for the resource associated with `handle`. `mode` can be an integer or a string containing an octal number. `callback` has 1 parameter: < _Error_ >err. - -* **opendir**(< _string_ >path, < _function_ >callback) - _(void)_ - Opens a directory `path`. `callback` has 2 parameters: < _Error_ >err, < _Buffer_ >handle. - -* **readdir**(< _mixed_ >location, < _function_ >callback) - _(void)_ - Retrieves a directory listing. `location` can either be a _Buffer_ containing a valid directory handle from opendir() or a _string_ containing the path to a directory. `callback` has 2 parameters: < _Error_ >err, < _mixed_ >list. `list` is an _Array_ of `{ filename: 'foo', longname: '....', attrs: {...} }` style objects (attrs is of type _ATTR_). If `location` is a directory handle, this function may need to be called multiple times until `list` is boolean false, which indicates that no more directory entries are available for that directory handle. - -* **unlink**(< _string_ >path, < _function_ >callback) - _(void)_ - Removes the file/symlink at `path`. `callback` has 1 parameter: < _Error_ >err. - -* **rename**(< _string_ >srcPath, < _string_ >destPath, < _function_ >callback) - _(void)_ - Renames/moves `srcPath` to `destPath`. `callback` has 1 parameter: < _Error_ >err. - -* **mkdir**(< _string_ >path, [< _ATTRS_ >attributes, ]< _function_ >callback) - _(void)_ - Creates a new directory `path`. `callback` has 1 parameter: < _Error_ >err. - -* **rmdir**(< _string_ >path, < _function_ >callback) - _(void)_ - Removes the directory at `path`. `callback` has 1 parameter: < _Error_ >err. - -* **stat**(< _string_ >path, < _function_ >callback) - _(void)_ - Retrieves attributes for `path`. `callback` has 2 parameter: < _Error_ >err, < _Stats_ >stats. - -* **lstat**(< _string_ >path, < _function_ >callback) - _(void)_ - Retrieves attributes for `path`. If `path` is a symlink, the link itself is stat'ed instead of the resource it refers to. `callback` has 2 parameters: < _Error_ >err, < _Stats_ >stats. - -* **setstat**(< _string_ >path, < _ATTRS_ >attributes, < _function_ >callback) - _(void)_ - Sets the attributes defined in `attributes` for `path`. `callback` has 1 parameter: < _Error_ >err. - -* **utimes**(< _string_ >path, < _mixed_ >atime, < _mixed_ >mtime, < _function_ >callback) - _(void)_ - Sets the access time and modified time for `path`. `atime` and `mtime` can be Date instances or UNIX timestamps. `callback` has 1 parameter: < _Error_ >err. - -* **chown**(< _string_ >path, < _integer_ >uid, < _integer_ >gid, < _function_ >callback) - _(void)_ - Sets the owner for `path`. `callback` has 1 parameter: < _Error_ >err. - -* **chmod**(< _string_ >path, < _mixed_ >mode, < _function_ >callback) - _(void)_ - Sets the mode for `path`. `mode` can be an integer or a string containing an octal number. `callback` has 1 parameter: < _Error_ >err. - -* **readlink**(< _string_ >path, < _function_ >callback) - _(void)_ - Retrieves the target for a symlink at `path`. `callback` has 2 parameters: < _Error_ >err, < _string_ >target. - -* **symlink**(< _string_ >targetPath, < _string_ >linkPath, < _function_ >callback) - _(void)_ - Creates a symlink at `linkPath` to `targetPath`. `callback` has 1 parameter: < _Error_ >err. - -* **realpath**(< _string_ >path, < _function_ >callback) - _(void)_ - Resolves `path` to an absolute path. `callback` has 2 parameters: < _Error_ >err, < _string_ >absPath. - -* **ext_openssh_rename**(< _string_ >srcPath, < _string_ >destPath, < _function_ >callback) - _(void)_ - **OpenSSH extension** Performs POSIX rename(3) from `srcPath` to `destPath`. `callback` has 1 parameter: < _Error_ >err. - -* **ext_openssh_statvfs**(< _string_ >path, < _function_ >callback) - _(void)_ - **OpenSSH extension** Performs POSIX statvfs(2) on `path`. `callback` has 2 parameters: < _Error_ >err, < _object_ >fsInfo. `fsInfo` contains the information as found in the [statvfs struct](http://linux.die.net/man/2/statvfs). - -* **ext_openssh_fstatvfs**(< _Buffer_ >handle, < _function_ >callback) - _(void)_ - **OpenSSH extension** Performs POSIX fstatvfs(2) on open handle `handle`. `callback` has 2 parameters: < _Error_ >err, < _object_ >fsInfo. `fsInfo` contains the information as found in the [statvfs struct](http://linux.die.net/man/2/statvfs). - -* **ext_openssh_hardlink**(< _string_ >targetPath, < _string_ >linkPath, < _function_ >callback) - _(void)_ - **OpenSSH extension** Performs POSIX link(2) to create a hard link to `targetPath` at `linkPath`. `callback` has 1 parameter: < _Error_ >err. - -* **ext_openssh_fsync**(< _Buffer_ >handle, < _function_ >callback) - _(void)_ - **OpenSSH extension** Performs POSIX fsync(3) on the open handle `handle`. `callback` has 1 parameter: < _Error_ >err. - - -**Server-only methods** - -* **status**(< _integer_ >reqID, < _integer_ >statusCode[, < _string_ >message]) - _(void)_ - Sends a status response for the request identified by `id`. - -* **handle**(< _integer_ >reqID, < _Buffer_ >handle) - _(void)_ - Sends a handle response for the request identified by `id`. `handle` must be less than 256 bytes and is an opaque value that could merely contain the value of a backing file descriptor or some other unique, custom value. - -* **data**(< _integer_ >reqID, < _mixed_ >data[, < _string_ >encoding]) - _(void)_ - Sends a data response for the request identified by `id`. `data` can be a _Buffer_ or _string_. If `data` is a string, `encoding` is the encoding of `data`. - -* **name**(< _integer_ >reqID, < _array_ >names) - _(void)_ - Sends a name response for the request identified by `id`. `names` must be an _array_ of _object_ where each _object_ can contain: - - * **filename** - _string_ - The entry's name. - - * **longname** - _string_ - This is the `ls -l`-style format for the entry (e.g. `-rwxr--r-- 1 bar bar 718 Dec 8 2009 foo`) - - * **attrs** - _ATTRS_ - This is an optional _ATTRS_ object that contains requested/available attributes for the entry. - -* **attrs**(< _integer_ >reqID, < _ATTRS_ >attrs) - _(void)_ - Sends an attrs response for the request identified by `id`. `attrs` contains the requested/available attributes. - - -ATTRS ------ - -An object with the following valid properties: - -* **mode** - _integer_ - Mode/permissions for the resource. - -* **uid** - _integer_ - User ID of the resource. - -* **gid** - _integer_ - Group ID of the resource. - -* **size** - _integer_ - Resource size in bytes. - -* **atime** - _integer_ - UNIX timestamp of the access time of the resource. - -* **mtime** - _integer_ - UNIX timestamp of the modified time of the resource. - -When supplying an ATTRS object to one of the SFTP methods: - -* `atime` and `mtime` can be either a Date instance or a UNIX timestamp. - -* `mode` can either be an integer or a string containing an octal number. - - -Stats ------ - -An object with the same attributes as an ATTRS object with the addition of the following methods: - -* `stats.isDirectory()` - -* `stats.isFile()` - -* `stats.isBlockDevice()` - -* `stats.isCharacterDevice()` - -* `stats.isSymbolicLink()` - -* `stats.isFIFO()` - -* `stats.isSocket()` diff --git a/reverse_engineering/node_modules/ssh2/examples/server-chat.js b/reverse_engineering/node_modules/ssh2/examples/server-chat.js deleted file mode 100644 index a82a955..0000000 --- a/reverse_engineering/node_modules/ssh2/examples/server-chat.js +++ /dev/null @@ -1,238 +0,0 @@ -// **BEFORE RUNNING THIS SCRIPT:** -// 1. The server portion is best run on non-Windows systems because they have -// terminfo databases which are needed to properly work with different -// terminal types of client connections -// 2. Install `blessed`: `npm install blessed` -// 3. Create a server host key in this same directory and name it `host.key` -'use strict'; - -const { readFileSync } = require('fs'); - -const blessed = require('blessed'); -const { Server } = require('ssh2'); - -const RE_SPECIAL = -// eslint-disable-next-line no-control-regex - /[\x00-\x1F\x7F]+|(?:\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K])/g; -const MAX_MSG_LEN = 128; -const MAX_NAME_LEN = 10; -const PROMPT_NAME = `Enter a nickname to use (max ${MAX_NAME_LEN} chars): `; - -const users = []; - -function formatMessage(msg, output) { - output.parseTags = true; - msg = output._parseTags(msg); - output.parseTags = false; - return msg; -} - -function userBroadcast(msg, source) { - const sourceMsg = `> ${msg}`; - const name = `{cyan-fg}{bold}${source.name}{/}`; - msg = `: ${msg}`; - for (const user of users) { - const output = user.output; - if (source === user) - output.add(sourceMsg); - else - output.add(formatMessage(name, output) + msg); - } -} - -function localMessage(msg, source) { - const output = source.output; - output.add(formatMessage(msg, output)); -} - -function noop(v) {} - -new Server({ - hostKeys: [readFileSync('host.key')], -}, (client) => { - let stream; - let name; - - client.on('authentication', (ctx) => { - let nick = ctx.username; - let prompt = PROMPT_NAME; - let lowered; - - // Try to use username as nickname - if (nick.length > 0 && nick.length <= MAX_NAME_LEN) { - lowered = nick.toLowerCase(); - let ok = true; - for (const user of users) { - if (user.name.toLowerCase() === lowered) { - ok = false; - prompt = `That nickname is already in use.\n${PROMPT_NAME}`; - break; - } - } - if (ok) { - name = nick; - return ctx.accept(); - } - } else if (nick.length === 0) { - prompt = 'A nickname is required.\n' + PROMPT_NAME; - } else { - prompt = 'That nickname is too long.\n' + PROMPT_NAME; - } - - if (ctx.method !== 'keyboard-interactive') - return ctx.reject(['keyboard-interactive']); - - ctx.prompt(prompt, function retryPrompt(answers) { - if (answers.length === 0) - return ctx.reject(['keyboard-interactive']); - nick = answers[0]; - if (nick.length > MAX_NAME_LEN) { - return ctx.prompt(`That nickname is too long.\n${PROMPT_NAME}`, - retryPrompt); - } else if (nick.length === 0) { - return ctx.prompt(`A nickname is required.\n${PROMPT_NAME}`, - retryPrompt); - } - lowered = nick.toLowerCase(); - for (const user of users) { - if (user.name.toLowerCase() === lowered) { - return ctx.prompt(`That nickname is already in use.\n${PROMPT_NAME}`, - retryPrompt); - } - } - name = nick; - ctx.accept(); - }); - }).on('ready', () => { - let rows; - let cols; - let term; - client.once('session', (accept, reject) => { - accept().once('pty', (accept, reject, info) => { - rows = info.rows; - cols = info.cols; - term = info.term; - accept && accept(); - }).on('window-change', (accept, reject, info) => { - rows = info.rows; - cols = info.cols; - if (stream) { - stream.rows = rows; - stream.columns = cols; - stream.emit('resize'); - } - accept && accept(); - }).once('shell', (accept, reject) => { - stream = accept(); - users.push(stream); - - stream.name = name; - stream.rows = rows || 24; - stream.columns = cols || 80; - stream.isTTY = true; - stream.setRawMode = noop; - stream.on('error', noop); - - const screen = new blessed.screen({ - autoPadding: true, - smartCSR: true, - program: new blessed.program({ - input: stream, - output: stream - }), - terminal: term || 'ansi' - }); - - screen.title = 'SSH Chatting as ' + name; - // Disable local echo - screen.program.attr('invisible', true); - - const output = stream.output = new blessed.log({ - screen: screen, - top: 0, - left: 0, - width: '100%', - bottom: 2, - scrollOnInput: true - }); - screen.append(output); - - screen.append(new blessed.box({ - screen: screen, - height: 1, - bottom: 1, - left: 0, - width: '100%', - type: 'line', - ch: '=' - })); - - const input = new blessed.textbox({ - screen: screen, - bottom: 0, - height: 1, - width: '100%', - inputOnFocus: true - }); - screen.append(input); - - input.focus(); - - // Local greetings - localMessage('{blue-bg}{white-fg}{bold}Welcome to SSH Chat!{/}\n' - + 'There are {bold}' - + (users.length - 1) - + '{/} other user(s) connected.\n' - + 'Type /quit or /exit to exit the chat.', - stream); - - // Let everyone else know that this user just joined - for (const user of users) { - const output = user.output; - if (user === stream) - continue; - output.add(formatMessage('{green-fg}*** {bold}', output) - + name - + formatMessage('{/bold} has joined the chat{/}', output)); - } - - screen.render(); - // XXX This fake resize event is needed for some terminals in order to - // have everything display correctly - screen.program.emit('resize'); - - // Read a line of input from the user - input.on('submit', (line) => { - input.clearValue(); - screen.render(); - if (!input.focused) - input.focus(); - line = line.replace(RE_SPECIAL, '').trim(); - if (line.length > MAX_MSG_LEN) - line = line.substring(0, MAX_MSG_LEN); - if (line.length > 0) { - if (line === '/quit' || line === '/exit') - stream.end(); - else - userBroadcast(line, stream); - } - }); - }); - }); - }).on('close', () => { - if (stream !== undefined) { - users.splice(users.indexOf(stream), 1); - // Let everyone else know that this user just left - for (const user of users) { - const output = user.output; - output.add(formatMessage('{magenta-fg}*** {bold}', output) - + name - + formatMessage('{/bold} has left the chat{/}', output)); - } - } - }).on('error', (err) => { - // Ignore errors - }); -}).listen(0, function() { - console.log('Listening on port ' + this.address().port); -}); diff --git a/reverse_engineering/node_modules/ssh2/examples/sftp-server-download-only.js b/reverse_engineering/node_modules/ssh2/examples/sftp-server-download-only.js deleted file mode 100644 index d4ae4c5..0000000 --- a/reverse_engineering/node_modules/ssh2/examples/sftp-server-download-only.js +++ /dev/null @@ -1,134 +0,0 @@ -'use strict'; - -const { timingSafeEqual } = require('crypto'); -const { constants, readFileSync } = require('fs'); - -const { Server, sftp: { OPEN_MODE, STATUS_CODE } } = require('ssh2'); - -const allowedUser = Buffer.from('foo'); -const allowedPassword = Buffer.from('bar'); - -function checkValue(input, allowed) { - const autoReject = (input.length !== allowed.length); - if (autoReject) { - // Prevent leaking length information by always making a comparison with the - // same input when lengths don't match what we expect ... - allowed = input; - } - const isMatch = timingSafeEqual(input, allowed); - return (!autoReject && isMatch); -} - -new Server({ - hostKeys: [readFileSync('host.key')] -}, (client) => { - console.log('Client connected!'); - - client.on('authentication', (ctx) => { - let allowed = true; - if (!checkValue(Buffer.from(ctx.username), allowedUser)) - allowed = false; - - switch (ctx.method) { - case 'password': - if (!checkValue(Buffer.from(ctx.password), allowedPassword)) - return ctx.reject(); - break; - default: - return ctx.reject(); - } - - if (allowed) - ctx.accept(); - else - ctx.reject(); - }).on('ready', () => { - console.log('Client authenticated!'); - - client.on('session', (accept, reject) => { - const session = accept(); - session.on('sftp', (accept, reject) => { - console.log('Client SFTP session'); - - const openFiles = new Map(); - let handleCount = 0; - const sftp = accept(); - sftp.on('OPEN', (reqid, filename, flags, attrs) => { - // Only allow opening /tmp/foo.txt for writing - if (filename !== '/tmp/foo.txt' || !(flags & OPEN_MODE.READ)) - return sftp.status(reqid, STATUS_CODE.FAILURE); - - // Create a fake handle to return to the client, this could easily - // be a real file descriptor number for example if actually opening - // the file on the disk - const handle = Buffer.alloc(4); - openFiles.set(handleCount, { read: false }); - handle.writeUInt32BE(handleCount++, 0, true); - - console.log('Opening file for read'); - sftp.handle(reqid, handle); - }).on('READ', (reqid, handle, offset, length) => { - let fnum; - if (handle.length !== 4 - || !openFiles.has(fnum = handle.readUInt32BE(0, true))) { - return sftp.status(reqid, STATUS_CODE.FAILURE); - } - - // Fake the read - const state = openFiles.get(fnum); - if (state.read) { - sftp.status(reqid, STATUS_CODE.EOF); - } else { - state.read = true; - - console.log( - 'Read from file at offset %d, length %d', offset, length - ); - sftp.data(reqid, 'bar'); - } - }).on('CLOSE', (reqid, handle) => { - let fnum; - if (handle.length !== 4 - || !openFiles.has(fnum = handle.readUInt32BE(0))) { - return sftp.status(reqid, STATUS_CODE.FAILURE); - } - - openFiles.delete(fnum); - - console.log('Closing file'); - sftp.status(reqid, STATUS_CODE.OK); - }).on('REALPATH', function(reqid, path) { - const name = [{ - filename: '/tmp/foo.txt', - longname: '-rwxrwxrwx 1 foo foo 3 Dec 8 2009 foo.txt', - attrs: {} - }]; - sftp.name(reqid, name); - }).on('STAT', onSTAT) - .on('LSTAT', onSTAT); - - function onSTAT(reqid, path) { - if (path !== '/tmp/foo.txt') - return sftp.status(reqid, STATUS_CODE.FAILURE); - - let mode = constants.S_IFREG; // Regular file - mode |= constants.S_IRWXU; // Read, write, execute for user - mode |= constants.S_IRWXG; // Read, write, execute for group - mode |= constants.S_IRWXO; // Read, write, execute for other - sftp.attrs(reqid, { - mode: mode, - uid: 0, - gid: 0, - size: 3, - atime: Date.now(), - mtime: Date.now(), - }); - } - }); - }); - }).on('close', () => { - console.log('Client disconnected'); - }); -}).listen(0, '127.0.0.1', function() { - console.log(`Listening on port ${this.address().port}`); -}); diff --git a/reverse_engineering/node_modules/ssh2/install.js b/reverse_engineering/node_modules/ssh2/install.js deleted file mode 100644 index e536366..0000000 --- a/reverse_engineering/node_modules/ssh2/install.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -const { spawnSync } = require('child_process'); - -// Attempt to build the bundled optional binding -const result = spawnSync('node-gyp', [ - `--target=${process.version}`, - 'rebuild' -], { - cwd: 'lib/protocol/crypto', - encoding: 'utf8', - shell: true, - stdio: 'inherit', - windowsHide: true, -}); -if (result.error || result.status !== 0) - console.log('Failed to build optional crypto binding'); -else - console.log('Succeeded in building optional crypto binding'); -process.exit(0); diff --git a/reverse_engineering/node_modules/ssh2/lib/Channel.js b/reverse_engineering/node_modules/ssh2/lib/Channel.js deleted file mode 100644 index 0bf5553..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/Channel.js +++ /dev/null @@ -1,294 +0,0 @@ -'use strict'; - -const { - Duplex: DuplexStream, - Readable: ReadableStream, - Writable: WritableStream, -} = require('stream'); - -const { - CHANNEL_EXTENDED_DATATYPE: { STDERR }, -} = require('./protocol/constants.js'); -const { bufferSlice } = require('./protocol/utils.js'); - -const PACKET_SIZE = 32 * 1024; -const MAX_WINDOW = 2 * 1024 * 1024; -const WINDOW_THRESHOLD = MAX_WINDOW / 2; - -class ClientStderr extends ReadableStream { - constructor(channel, streamOpts) { - super(streamOpts); - - this._channel = channel; - } - _read(n) { - if (this._channel._waitChanDrain) { - this._channel._waitChanDrain = false; - if (this._channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this._channel); - } - } -} - -class ServerStderr extends WritableStream { - constructor(channel) { - super({ highWaterMark: MAX_WINDOW }); - - this._channel = channel; - } - - _write(data, encoding, cb) { - const channel = this._channel; - const protocol = channel._client._protocol; - const outgoing = channel.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; - - if (outgoing.state !== 'open') - return; - - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; - - if (p === 0 && sliceLen === len) - protocol.channelExtData(id, data, STDERR); - else - protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); - - p += sliceLen; - window -= sliceLen; - } - - outgoing.window = window; - - if (len - p > 0) { - if (window === 0) - channel._waitWindow = true; - if (p > 0) - channel._chunkErr = bufferSlice(data, p, len); - else - channel._chunkErr = data; - channel._chunkcbErr = cb; - return; - } - - cb(); - } -} - -class Channel extends DuplexStream { - constructor(client, info, opts) { - const streamOpts = { - highWaterMark: MAX_WINDOW, - allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)), - emitClose: false, - }; - super(streamOpts); - this.allowHalfOpen = streamOpts.allowHalfOpen; - - const server = !!(opts && opts.server); - - this.server = server; - this.type = info.type; - this.subtype = undefined; - - /* - incoming and outgoing contain these properties: - { - id: undefined, - window: undefined, - packetSize: undefined, - state: 'closed' - } - */ - this.incoming = info.incoming; - this.outgoing = info.outgoing; - this._callbacks = []; - - this._client = client; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; - - this.stdin = this.stdout = this; - - if (server) - this.stderr = new ServerStderr(this); - else - this.stderr = new ClientStderr(this, streamOpts); - - // Outgoing data - this._waitWindow = false; // SSH-level backpressure - - // Incoming data - this._waitChanDrain = false; // Channel Readable side backpressure - - this._chunk = undefined; - this._chunkcb = undefined; - this._chunkErr = undefined; - this._chunkcbErr = undefined; - - this.on('finish', onFinish) - .on('prefinish', onFinish); // For node v0.11+ - - this.on('end', onEnd).on('close', onEnd); - } - - _read(n) { - if (this._waitChanDrain) { - this._waitChanDrain = false; - if (this.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this); - } - } - - _write(data, encoding, cb) { - const protocol = this._client._protocol; - const outgoing = this.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; - - if (outgoing.state !== 'open') - return; - - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; - - if (p === 0 && sliceLen === len) - protocol.channelData(id, data); - else - protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); - - p += sliceLen; - window -= sliceLen; - } - - outgoing.window = window; - - if (len - p > 0) { - if (window === 0) - this._waitWindow = true; - if (p > 0) - this._chunk = bufferSlice(data, p, len); - else - this._chunk = data; - this._chunkcb = cb; - return; - } - - cb(); - } - - eof() { - if (this.outgoing.state === 'open') { - this.outgoing.state = 'eof'; - this._client._protocol.channelEOF(this.outgoing.id); - } - } - - close() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._client._protocol.channelClose(this.outgoing.id); - } - } - - destroy() { - this.end(); - this.close(); - } - - // Session type-specific methods ============================================= - setWindow(rows, cols, height, width) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (this.type === 'session' - && (this.subtype === 'shell' || this.subtype === 'exec') - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.windowChange(this.outgoing.id, - rows, - cols, - height, - width); - } - } - - signal(signalName) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.signal(this.outgoing.id, signalName); - } - } - - exit(statusOrSignal, coreDumped, msg) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - if (typeof statusOrSignal === 'number') { - this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); - } else { - this._client._protocol.exitSignal(this.outgoing.id, - statusOrSignal, - coreDumped, - msg); - } - } - } - -} - -function onFinish() { - this.eof(); - if (this.server || !this.allowHalfOpen) - this.close(); - this.writable = false; -} - -function onEnd() { - this.readable = false; -} - -function windowAdjust(self) { - if (self.outgoing.state === 'closed') - return; - const amt = MAX_WINDOW - self.incoming.window; - if (amt <= 0) - return; - self.incoming.window += amt; - self._client._protocol.channelWindowAdjust(self.outgoing.id, amt); -} - -module.exports = { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/agent.js b/reverse_engineering/node_modules/ssh2/lib/agent.js deleted file mode 100644 index bb495d1..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/agent.js +++ /dev/null @@ -1,1123 +0,0 @@ -'use strict'; - -const { Socket } = require('net'); -const { Duplex } = require('stream'); -const { resolve } = require('path'); -const { readFile } = require('fs'); -const { execFile, spawn } = require('child_process'); - -const { isParsedKey, parseKey } = require('./protocol/keyParser.js'); - -const { - makeBufferParser, - readUInt32BE, - writeUInt32BE, - writeUInt32LE, -} = require('./protocol/utils.js'); - -function once(cb) { - let called = false; - return (...args) => { - if (called) - return; - called = true; - cb(...args); - }; -} - -function concat(buf1, buf2) { - const combined = Buffer.allocUnsafe(buf1.length + buf2.length); - buf1.copy(combined, 0); - buf2.copy(combined, buf1.length); - return combined; -} - -function noop() {} - -const EMPTY_BUF = Buffer.alloc(0); - -const binaryParser = makeBufferParser(); - -class BaseAgent { - getIdentities(cb) { - cb(new Error('Missing getIdentities() implementation')); - } - sign(pubKey, data, options, cb) { - if (typeof options === 'function') - cb = options; - cb(new Error('Missing sign() implementation')); - } -} - -class OpenSSHAgent extends BaseAgent { - constructor(socketPath) { - super(); - this.socketPath = socketPath; - } - - getStream(cb) { - cb = once(cb); - const sock = new Socket(); - sock.on('connect', () => { - cb(null, sock); - }); - sock.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - sock.connect(this.socketPath); - - function onFail() { - try { - sock.destroy(); - } catch {} - - cb(new Error('Failed to connect to agent')); - } - } - - getIdentities(cb) { - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to retrieve identities from agent'); - cb(err); - } - - if (err) - return onFail(err); - - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); - - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - - protocol.getIdentities((err, keys) => { - if (err) - return onFail(err); - try { - stream.destroy(); - } catch {} - cb(null, keys); - }); - }); - } - - sign(pubKey, data, options, cb) { - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; - } - - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to sign data with agent'); - cb(err); - } - - if (err) - return onFail(err); - - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); - - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - - protocol.sign(pubKey, data, options, (err, sig) => { - if (err) - return onFail(err); - - try { - stream.destroy(); - } catch {} - - cb(null, sig); - }); - }); - } -} - -const PageantAgent = (() => { - const RET_ERR_BADARGS = 10; - const RET_ERR_UNAVAILABLE = 11; - const RET_ERR_NOMAP = 12; - const RET_ERR_BINSTDIN = 13; - const RET_ERR_BINSTDOUT = 14; - const RET_ERR_BADLEN = 15; - - const EXEPATH = resolve(__dirname, '..', 'util/pagent.exe'); - const ERROR = { - [RET_ERR_BADARGS]: new Error('Invalid pagent.exe arguments'), - [RET_ERR_UNAVAILABLE]: new Error('Pageant is not running'), - [RET_ERR_NOMAP]: new Error('pagent.exe could not create an mmap'), - [RET_ERR_BINSTDIN]: new Error('pagent.exe could not set mode for stdin'), - [RET_ERR_BINSTDOUT]: new Error('pagent.exe could not set mode for stdout'), - [RET_ERR_BADLEN]: - new Error('pagent.exe did not get expected input payload'), - }; - - function destroy(stream) { - stream.buffer = null; - if (stream.proc) { - stream.proc.kill(); - stream.proc = undefined; - } - } - - class PageantSocket extends Duplex { - constructor() { - super(); - this.proc = undefined; - this.buffer = null; - } - _read(n) {} - _write(data, encoding, cb) { - if (this.buffer === null) { - this.buffer = data; - } else { - const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); - this.buffer.copy(newBuffer, 0); - data.copy(newBuffer, this.buffer.length); - this.buffer = newBuffer; - } - // Wait for at least all length bytes - if (this.buffer.length < 4) - return cb(); - - const len = readUInt32BE(this.buffer, 0); - // Make sure we have a full message before querying pageant - if ((this.buffer.length - 4) < len) - return cb(); - - data = this.buffer.slice(0, 4 + len); - if (this.buffer.length > (4 + len)) - return cb(new Error('Unexpected multiple agent requests')); - this.buffer = null; - - let error; - const proc = this.proc = spawn(EXEPATH, [ data.length ]); - proc.stdout.on('data', (data) => { - this.push(data); - }); - proc.on('error', (err) => { - error = err; - cb(error); - }); - proc.on('close', (code) => { - this.proc = undefined; - if (!error) { - if (error = ERROR[code]) - return cb(error); - cb(); - } - }); - proc.stdin.end(data); - } - _final(cb) { - destroy(this); - cb(); - } - _destroy(err, cb) { - destroy(this); - cb(); - } - } - - return class PageantAgent extends OpenSSHAgent { - getStream(cb) { - cb(null, new PageantSocket()); - } - }; -})(); - -const CygwinAgent = (() => { - const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; - - return class CygwinAgent extends OpenSSHAgent { - getStream(cb) { - cb = once(cb); - - // The cygwin ssh-agent connection process looks like this: - // 1. Read the "socket" as a file to get the underlying TCP port and a - // special "secret" that must be sent to the TCP server. - // 2. Connect to the server listening on localhost at the TCP port. - // 3. Send the "secret" to the server. - // 4. The server sends back the same "secret". - // 5. Send three 32-bit integer values of zero. This is ordinarily the - // pid, uid, and gid of this process, but cygwin will actually - // send us the correct values as a response. - // 6. The server sends back the pid, uid, gid. - // 7. Disconnect. - // 8. Repeat steps 2-6, except send the received pid, uid, and gid in - // step 5 instead of zeroes. - // 9. Connection is ready to be used. - - let socketPath = this.socketPath; - let triedCygpath = false; - readFile(socketPath, function readCygsocket(err, data) { - if (err) { - if (triedCygpath) - return cb(new Error('Invalid cygwin unix socket path')); - - // Try using `cygpath` to convert a possible *nix-style path to the - // real Windows path before giving up ... - execFile('cygpath', ['-w', socketPath], (err, stdout, stderr) => { - if (err || stdout.length === 0) - return cb(new Error('Invalid cygwin unix socket path')); - - triedCygpath = true; - socketPath = stdout.toString().replace(/[\r\n]/g, ''); - readFile(socketPath, readCygsocket); - }); - return; - } - - const m = RE_CYGWIN_SOCK.exec(data.toString('ascii')); - if (!m) - return cb(new Error('Malformed cygwin unix socket file')); - - let state; - let bc = 0; - let isRetrying = false; - const inBuf = []; - let sock; - - // Use 0 for pid, uid, and gid to ensure we get an error and also - // a valid uid and gid from cygwin so that we don't have to figure it - // out ourselves - let credsBuf = Buffer.alloc(12); - - // Parse cygwin unix socket file contents - const port = parseInt(m[1], 10); - const secret = m[2].replace(/-/g, ''); - const secretBuf = Buffer.allocUnsafe(16); - for (let i = 0, j = 0; j < 32; ++i, j += 2) - secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); - - // Convert to host order (always LE for Windows) - for (let i = 0; i < 16; i += 4) - writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); - - tryConnect(); - - function _onconnect() { - bc = 0; - state = 'secret'; - sock.write(secretBuf); - } - - function _ondata(data) { - bc += data.length; - - if (state === 'secret') { - // The secret we sent is echoed back to us by cygwin, not sure of - // the reason for that, but we ignore it nonetheless ... - if (bc === 16) { - bc = 0; - state = 'creds'; - sock.write(credsBuf); - } - return; - } - - if (state === 'creds') { - // If this is the first attempt, make sure to gather the valid - // uid and gid for our next attempt - if (!isRetrying) - inBuf.push(data); - - if (bc === 12) { - sock.removeListener('connect', _onconnect); - sock.removeListener('data', _ondata); - sock.removeListener('error', onFail); - sock.removeListener('end', onFail); - sock.removeListener('close', onFail); - - if (isRetrying) - return cb(null, sock); - - isRetrying = true; - credsBuf = Buffer.concat(inBuf); - writeUInt32LE(credsBuf, process.pid, 0); - sock.on('error', () => {}); - sock.destroy(); - - tryConnect(); - } - } - } - - function onFail() { - cb(new Error('Problem negotiating cygwin unix socket security')); - } - - function tryConnect() { - sock = new Socket(); - sock.on('connect', _onconnect); - sock.on('data', _ondata); - sock.on('error', onFail); - sock.on('end', onFail); - sock.on('close', onFail); - sock.connect(port); - } - }); - } - }; -})(); - -// Format of `//./pipe/ANYTHING`, with forward slashes and backward slashes -// being interchangeable -const WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; -function createAgent(path) { - if (process.platform === 'win32' && !WINDOWS_PIPE_REGEX.test(path)) { - return (path === 'pageant' - ? new PageantAgent() - : new CygwinAgent(path)); - } - return new OpenSSHAgent(path); -} - -const AgentProtocol = (() => { - // Client->Server messages - const SSH_AGENTC_REQUEST_IDENTITIES = 11; - const SSH_AGENTC_SIGN_REQUEST = 13; - // const SSH_AGENTC_ADD_IDENTITY = 17; - // const SSH_AGENTC_REMOVE_IDENTITY = 18; - // const SSH_AGENTC_REMOVE_ALL_IDENTITIES = 19; - // const SSH_AGENTC_ADD_SMARTCARD_KEY = 20; - // const SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21; - // const SSH_AGENTC_LOCK = 22; - // const SSH_AGENTC_UNLOCK = 23; - // const SSH_AGENTC_ADD_ID_CONSTRAINED = 25; - // const SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26; - // const SSH_AGENTC_EXTENSION = 27; - // Server->Client messages - const SSH_AGENT_FAILURE = 5; - // const SSH_AGENT_SUCCESS = 6; - const SSH_AGENT_IDENTITIES_ANSWER = 12; - const SSH_AGENT_SIGN_RESPONSE = 14; - // const SSH_AGENT_EXTENSION_FAILURE = 28; - - // const SSH_AGENT_CONSTRAIN_LIFETIME = 1; - // const SSH_AGENT_CONSTRAIN_CONFIRM = 2; - // const SSH_AGENT_CONSTRAIN_EXTENSION = 255; - - const SSH_AGENT_RSA_SHA2_256 = (1 << 1); - const SSH_AGENT_RSA_SHA2_512 = (1 << 2); - - const ROLE_CLIENT = 0; - const ROLE_SERVER = 1; - - // Ensures that responses get sent back in the same order the requests were - // received - function processResponses(protocol) { - let ret; - while (protocol[SYM_REQS].length) { - const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; - if (nextResponse === undefined) - break; - - protocol[SYM_REQS].shift(); - ret = protocol.push(nextResponse); - } - return ret; - } - - const SYM_TYPE = Symbol('Inbound Request Type'); - const SYM_RESP = Symbol('Inbound Request Response'); - const SYM_CTX = Symbol('Inbound Request Context'); - class AgentInboundRequest { - constructor(type, ctx) { - this[SYM_TYPE] = type; - this[SYM_RESP] = undefined; - this[SYM_CTX] = ctx; - } - hasResponded() { - return (this[SYM_RESP] !== undefined); - } - getType() { - return this[SYM_TYPE]; - } - getContext() { - return this[SYM_CTX]; - } - } - function respond(protocol, req, data) { - req[SYM_RESP] = data; - return processResponses(protocol); - } - - function cleanup(protocol) { - protocol[SYM_BUFFER] = null; - if (protocol[SYM_MODE] === ROLE_CLIENT) { - const reqs = protocol[SYM_REQS]; - if (reqs && reqs.length) { - protocol[SYM_REQS] = []; - for (const req of reqs) - req.cb(new Error('No reply from server')); - } - } - - // Node streams hackery to make streams do the "right thing" - try { - protocol.end(); - } catch {} - setImmediate(() => { - if (!protocol[SYM_ENDED]) - protocol.emit('end'); - if (!protocol[SYM_CLOSED]) - protocol.emit('close'); - }); - } - - function onClose() { - this[SYM_CLOSED] = true; - } - - function onEnd() { - this[SYM_ENDED] = true; - } - - const SYM_REQS = Symbol('Requests'); - const SYM_MODE = Symbol('Agent Protocol Role'); - const SYM_BUFFER = Symbol('Agent Protocol Buffer'); - const SYM_MSGLEN = Symbol('Agent Protocol Current Message Length'); - const SYM_CLOSED = Symbol('Agent Protocol Closed'); - const SYM_ENDED = Symbol('Agent Protocol Ended'); - // Implementation based on: - // https://tools.ietf.org/html/draft-miller-ssh-agent-04 - return class AgentProtocol extends Duplex { - /* - Notes: - - `constraint` type consists of: - byte constraint_type - byte[] constraint_data - where `constraint_type` is one of: - * SSH_AGENT_CONSTRAIN_LIFETIME - - `constraint_data` consists of: - uint32 seconds - * SSH_AGENT_CONSTRAIN_CONFIRM - - `constraint_data` N/A - * SSH_AGENT_CONSTRAIN_EXTENSION - - `constraint_data` consists of: - string extension name - byte[] extension-specific details - */ - - constructor(isClient) { - super({ autoDestroy: true, emitClose: false }); - this[SYM_MODE] = (isClient ? ROLE_CLIENT : ROLE_SERVER); - this[SYM_REQS] = []; - this[SYM_BUFFER] = null; - this[SYM_MSGLEN] = -1; - this.once('end', onEnd); - this.once('close', onClose); - } - - _read(n) {} - - _write(data, encoding, cb) { - /* - Messages are of the format: - uint32 message length - byte message type - byte[message length - 1] message contents - */ - if (this[SYM_BUFFER] === null) - this[SYM_BUFFER] = data; - else - this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); - - let buffer = this[SYM_BUFFER]; - let bufferLen = buffer.length; - - let p = 0; - while (p < bufferLen) { - // Wait for length + type - if (bufferLen < 5) - break; - - if (this[SYM_MSGLEN] === -1) - this[SYM_MSGLEN] = readUInt32BE(buffer, p); - - // Check if we have the entire message - if (bufferLen < (4 + this[SYM_MSGLEN])) - break; - - const msgType = buffer[p += 4]; - ++p; - - if (this[SYM_MODE] === ROLE_CLIENT) { - if (this[SYM_REQS].length === 0) - return cb(new Error('Received unexpected message from server')); - - const req = this[SYM_REQS].shift(); - - switch (msgType) { - case SSH_AGENT_FAILURE: - req.cb(new Error('Agent responded with failure')); - break; - case SSH_AGENT_IDENTITIES_ANSWER: { - if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) - return cb(new Error('Agent responded with wrong message type')); - - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys - - where `nkeys` is 0 or more of: - string key blob - string comment - */ - - binaryParser.init(buffer, p); - - const numKeys = binaryParser.readUInt32BE(); - - if (numKeys === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - const keys = []; - for (let i = 0; i < numKeys; ++i) { - let pubKey = binaryParser.readString(); - if (pubKey === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - const comment = binaryParser.readString(true); - if (comment === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - pubKey = parseKey(pubKey); - // We continue parsing the packet if we encounter an error - // in case the error is due to the key being an unsupported - // type - if (pubKey instanceof Error) - continue; - - pubKey.comment = pubKey.comment || comment; - - keys.push(pubKey); - } - p = binaryParser.pos(); - binaryParser.clear(); - - req.cb(null, keys); - break; - } - case SSH_AGENT_SIGN_RESPONSE: { - if (req.type !== SSH_AGENTC_SIGN_REQUEST) - return cb(new Error('Agent responded with wrong message type')); - - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ - - binaryParser.init(buffer, p); - let signature = binaryParser.readString(); - p = binaryParser.pos(); - binaryParser.clear(); - - if (signature === undefined) - return cb(new Error('Malformed agent response')); - - // We strip the algorithm from OpenSSH's output and assume it's - // using the algorithm we specified. This makes it easier on - // custom Agent implementations so they don't have to construct - // the correct binary format for a (OpenSSH-style) signature. - - // TODO: verify signature type based on key and options used - // during initial sign request - binaryParser.init(signature, 0); - binaryParser.readString(true); - signature = binaryParser.readString(); - binaryParser.clear(); - - if (signature === undefined) - return cb(new Error('Malformed OpenSSH signature format')); - - req.cb(null, signature); - break; - } - default: - return cb( - new Error('Agent responded with unsupported message type') - ); - } - } else { - switch (msgType) { - case SSH_AGENTC_REQUEST_IDENTITIES: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - this.emit('identities', req); - break; - } - case SSH_AGENTC_SIGN_REQUEST: { - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - binaryParser.init(buffer, p); - let pubKey = binaryParser.readString(); - const data = binaryParser.readString(); - const flagsVal = binaryParser.readUInt32BE(); - p = binaryParser.pos(); - binaryParser.clear(); - if (flagsVal === undefined) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } - - const flags = { - hash: undefined, - }; - let ctx; - if (pubKey.type === 'ssh-rsa') { - if (flagsVal & SSH_AGENT_RSA_SHA2_256) { - ctx = 'rsa-sha2-256'; - flags.hash = 'sha256'; - } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { - ctx = 'rsa-sha2-512'; - flags.hash = 'sha512'; - } - } - if (ctx === undefined) - ctx = pubKey.type; - - const req = new AgentInboundRequest(msgType, ctx); - this[SYM_REQS].push(req); - - this.emit('sign', req, pubKey, data, flags); - break; - } - default: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - this.failureReply(req); - } - } - } - - // Get ready for next message - this[SYM_MSGLEN] = -1; - if (p === bufferLen) { - // Nothing left to process for now - this[SYM_BUFFER] = null; - break; - } else { - this[SYM_BUFFER] = buffer = buffer.slice(p); - bufferLen = buffer.length; - p = 0; - } - } - - cb(); - } - - _destroy(err, cb) { - cleanup(this); - cb(); - } - - _final(cb) { - cleanup(this); - cb(); - } - - // Client->Server messages ================================================= - sign(pubKey, data, options, cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); - - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; - } - - let flags = 0; - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid public key argument'); - - if (pubKey.type === 'ssh-rsa' && options) { - switch (options.hash) { - case 'sha256': - flags = SSH_AGENT_RSA_SHA2_256; - break; - case 'sha512': - flags = SSH_AGENT_RSA_SHA2_512; - break; - } - } - pubKey = pubKey.getPublicSSH(); - - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - const type = SSH_AGENTC_SIGN_REQUEST; - const keyLen = pubKey.length; - const dataLen = data.length; - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = type; - - writeUInt32BE(buf, keyLen, ++p); - pubKey.copy(buf, p += 4); - - writeUInt32BE(buf, dataLen, p += keyLen); - data.copy(buf, p += 4); - - writeUInt32BE(buf, flags, p += dataLen); - - if (typeof cb !== 'function') - cb = noop; - - this[SYM_REQS].push({ type, cb }); - - return this.push(buf); - } - getIdentities(cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); - - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - const type = SSH_AGENTC_REQUEST_IDENTITIES; - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = type; - - if (typeof cb !== 'function') - cb = noop; - - this[SYM_REQS].push({ type, cb }); - - return this.push(buf); - } - - // Server->Client messages ================================================= - failureReply(req) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = SSH_AGENT_FAILURE; - - return respond(this, req, buf); - } - getIdentitiesReply(req, keys) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys - - where `nkeys` is 0 or more of: - string key blob - string comment - */ - - if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) - throw new Error('Invalid response to request'); - - if (!Array.isArray(keys)) - throw new Error('Keys argument must be an array'); - - let totalKeysLen = 4; // Include `nkeys` size - - const newKeys = []; - for (let i = 0; i < keys.length; ++i) { - const entry = keys[i]; - if (typeof entry !== 'object' || entry === null) - throw new Error(`Invalid key entry: ${entry}`); - - let pubKey; - let comment; - if (isParsedKey(entry)) { - pubKey = entry; - } else if (isParsedKey(entry.pubKey)) { - pubKey = entry.pubKey; - } else { - if (typeof entry.pubKey !== 'object' || entry.pubKey === null) - continue; - ({ pubKey, comment } = entry.pubKey); - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - continue; // TODO: add debug output - } - comment = pubKey.comment || comment; - pubKey = pubKey.getPublicSSH(); - - totalKeysLen += 4 + pubKey.length; - - if (comment && typeof comment === 'string') - comment = Buffer.from(comment); - else if (!Buffer.isBuffer(comment)) - comment = EMPTY_BUF; - - totalKeysLen += 4 + comment.length; - - newKeys.push({ pubKey, comment }); - } - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; - - writeUInt32BE(buf, newKeys.length, ++p); - p += 4; - for (let i = 0; i < newKeys.length; ++i) { - const { pubKey, comment } = newKeys[i]; - - writeUInt32BE(buf, pubKey.length, p); - pubKey.copy(buf, p += 4); - - writeUInt32BE(buf, comment.length, p += pubKey.length); - p += 4; - if (comment.length) { - comment.copy(buf, p); - p += comment.length; - } - } - - return respond(this, req, buf); - } - signReply(req, signature) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ - - if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) - throw new Error('Invalid response to request'); - - if (!Buffer.isBuffer(signature)) - throw new Error('Signature argument must be a Buffer'); - - if (signature.length === 0) - throw new Error('Signature argument must be non-empty'); - - /* - OpenSSH agent signatures are encoded as: - - string signature format identifier (as specified by the - public key/certificate format) - byte[n] signature blob in format specific encoding. - - This is actually a `string` for: rsa, dss, ecdsa, and ed25519 - types - */ - - let p = 0; - const sigFormat = req.getContext(); - const sigFormatLen = Buffer.byteLength(sigFormat); - const buf = Buffer.allocUnsafe( - 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length - ); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; - - writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); - writeUInt32BE(buf, sigFormatLen, p += 4); - buf.utf8Write(sigFormat, p += 4, sigFormatLen); - writeUInt32BE(buf, signature.length, p += sigFormatLen); - signature.copy(buf, p += 4); - - return respond(this, req, buf); - } - }; -})(); - -const SYM_AGENT = Symbol('Agent'); -const SYM_AGENT_KEYS = Symbol('Agent Keys'); -const SYM_AGENT_KEYS_IDX = Symbol('Agent Keys Index'); -const SYM_AGENT_CBS = Symbol('Agent Init Callbacks'); -class AgentContext { - constructor(agent) { - if (typeof agent === 'string') - agent = createAgent(agent); - else if (!isAgent(agent)) - throw new Error('Invalid agent argument'); - this[SYM_AGENT] = agent; - this[SYM_AGENT_KEYS] = null; - this[SYM_AGENT_KEYS_IDX] = -1; - this[SYM_AGENT_CBS] = null; - } - init(cb) { - if (typeof cb !== 'function') - cb = noop; - - if (this[SYM_AGENT_KEYS] === null) { - if (this[SYM_AGENT_CBS] === null) { - this[SYM_AGENT_CBS] = [cb]; - - const doCbs = (...args) => { - process.nextTick(() => { - const cbs = this[SYM_AGENT_CBS]; - this[SYM_AGENT_CBS] = null; - for (const cb of cbs) - cb(...args); - }); - }; - - this[SYM_AGENT].getIdentities(once((err, keys) => { - if (err) - return doCbs(err); - - if (!Array.isArray(keys)) { - return doCbs(new Error( - 'Agent implementation failed to provide keys' - )); - } - - const newKeys = []; - for (let key of keys) { - key = parseKey(key); - if (key instanceof Error) { - // TODO: add debug output - continue; - } - newKeys.push(key); - } - - this[SYM_AGENT_KEYS] = newKeys; - this[SYM_AGENT_KEYS_IDX] = -1; - doCbs(); - })); - } else { - this[SYM_AGENT_CBS].push(cb); - } - } else { - process.nextTick(cb); - } - } - nextKey() { - if (this[SYM_AGENT_KEYS] === null - || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return false; - } - - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - currentKey() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return null; - } - - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - pos() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return -1; - } - - return this[SYM_AGENT_KEYS_IDX]; - } - reset() { - this[SYM_AGENT_KEYS_IDX] = -1; - } - - sign(...args) { - this[SYM_AGENT].sign(...args); - } -} - -function isAgent(val) { - return (val instanceof BaseAgent); -} - -module.exports = { - AgentContext, - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - isAgent, - OpenSSHAgent, - PageantAgent, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/client.js b/reverse_engineering/node_modules/ssh2/lib/client.js deleted file mode 100644 index 7c16c7b..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/client.js +++ /dev/null @@ -1,2013 +0,0 @@ -// TODO: -// * add `.connected` or similar property to allow immediate connection -// status checking -// * add/improve debug output during user authentication phase -'use strict'; - -const { - createHash, - getHashes, - randomFillSync, -} = require('crypto'); -const { Socket } = require('net'); -const { lookup: dnsLookup } = require('dns'); -const EventEmitter = require('events'); -const HASHES = getHashes(); - -const { - COMPAT, - CHANNEL_EXTENDED_DATATYPE: { STDERR }, - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = require('./protocol/constants.js'); -const { init: cryptoInit } = require('./protocol/crypto.js'); -const Protocol = require('./protocol/Protocol.js'); -const { parseKey } = require('./protocol/keyParser.js'); -const { SFTP } = require('./protocol/SFTP.js'); -const { - bufferCopy, - makeBufferParser, - makeError, - readUInt32BE, - sigSSHToASN1, - writeUInt32BE, -} = require('./protocol/utils.js'); - -const { AgentContext, createAgent, isAgent } = require('./agent.js'); -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = require('./Channel.js'); -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = require('./utils.js'); - -const bufferParser = makeBufferParser(); -const sigParser = makeBufferParser(); -const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; -const noop = (err) => {}; - -class Client extends EventEmitter { - constructor() { - super(); - - this.config = { - host: undefined, - port: undefined, - localAddress: undefined, - localPort: undefined, - forceIPv4: undefined, - forceIPv6: undefined, - keepaliveCountMax: undefined, - keepaliveInterval: undefined, - readyTimeout: undefined, - ident: undefined, - - username: undefined, - password: undefined, - privateKey: undefined, - tryKeyboard: undefined, - agent: undefined, - allowAgentFwd: undefined, - authHandler: undefined, - - hostHashAlgo: undefined, - hostHashCb: undefined, - strictVendor: undefined, - debug: undefined - }; - - this._agent = undefined; - this._readyTimeout = undefined; - this._chanMgr = undefined; - this._callbacks = undefined; - this._forwarding = undefined; - this._forwardingUnix = undefined; - this._acceptX11 = undefined; - this._agentFwdEnabled = undefined; - this._remoteVer = undefined; - - this._protocol = undefined; - this._sock = undefined; - this._resetKA = undefined; - } - - connect(cfg) { - if (this._sock && isWritable(this._sock)) { - this.once('close', () => { - this.connect(cfg); - }); - this.end(); - return this; - } - - this.config.host = cfg.hostname || cfg.host || 'localhost'; - this.config.port = cfg.port || 22; - this.config.localAddress = (typeof cfg.localAddress === 'string' - ? cfg.localAddress - : undefined); - this.config.localPort = (typeof cfg.localPort === 'string' - || typeof cfg.localPort === 'number' - ? cfg.localPort - : undefined); - this.config.forceIPv4 = cfg.forceIPv4 || false; - this.config.forceIPv6 = cfg.forceIPv6 || false; - this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number' - && cfg.keepaliveCountMax >= 0 - ? cfg.keepaliveCountMax - : 3); - this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number' - && cfg.keepaliveInterval > 0 - ? cfg.keepaliveInterval - : 0); - this.config.readyTimeout = (typeof cfg.readyTimeout === 'number' - && cfg.readyTimeout >= 0 - ? cfg.readyTimeout - : 20000); - this.config.ident = (typeof cfg.ident === 'string' - || Buffer.isBuffer(cfg.ident) - ? cfg.ident - : undefined); - - const algorithms = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: [], - }, - sc: undefined, - }; - let allOfferDefaults = true; - if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) { - algorithms.kex = generateAlgorithmList(cfg.algorithms.kex, - DEFAULT_KEX, - SUPPORTED_KEX); - if (algorithms.kex !== DEFAULT_KEX) - allOfferDefaults = false; - - algorithms.serverHostKey = - generateAlgorithmList(cfg.algorithms.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY); - if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) - allOfferDefaults = false; - - algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER); - if (algorithms.cs.cipher !== DEFAULT_CIPHER) - allOfferDefaults = false; - - algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac, - DEFAULT_MAC, - SUPPORTED_MAC); - if (algorithms.cs.mac !== DEFAULT_MAC) - allOfferDefaults = false; - - algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION); - if (algorithms.cs.compress !== DEFAULT_COMPRESSION) - allOfferDefaults = false; - - if (!allOfferDefaults) - algorithms.sc = algorithms.cs; - } - - if (typeof cfg.username === 'string') - this.config.username = cfg.username; - else if (typeof cfg.user === 'string') - this.config.username = cfg.user; - else - throw new Error('Invalid username'); - - this.config.password = (typeof cfg.password === 'string' - ? cfg.password - : undefined); - this.config.privateKey = (typeof cfg.privateKey === 'string' - || Buffer.isBuffer(cfg.privateKey) - ? cfg.privateKey - : undefined); - this.config.localHostname = (typeof cfg.localHostname === 'string' - ? cfg.localHostname - : undefined); - this.config.localUsername = (typeof cfg.localUsername === 'string' - ? cfg.localUsername - : undefined); - this.config.tryKeyboard = (cfg.tryKeyboard === true); - if (typeof cfg.agent === 'string' && cfg.agent.length) - this.config.agent = createAgent(cfg.agent); - else if (isAgent(cfg.agent)) - this.config.agent = cfg.agent; - else - this.config.agent = undefined; - this.config.allowAgentFwd = (cfg.agentForward === true - && this.config.agent !== undefined); - let authHandler = this.config.authHandler = ( - typeof cfg.authHandler === 'function' - || Array.isArray(cfg.authHandler) - ? cfg.authHandler - : undefined - ); - - this.config.strictVendor = (typeof cfg.strictVendor === 'boolean' - ? cfg.strictVendor - : true); - - const debug = this.config.debug = (typeof cfg.debug === 'function' - ? cfg.debug - : undefined); - - if (cfg.agentForward === true && !this.config.allowAgentFwd) { - throw new Error( - 'You must set a valid agent path to allow agent forwarding' - ); - } - - let callbacks = this._callbacks = []; - this._chanMgr = new ChannelManager(this); - this._forwarding = {}; - this._forwardingUnix = {}; - this._acceptX11 = 0; - this._agentFwdEnabled = false; - this._agent = (this.config.agent ? this.config.agent : undefined); - this._remoteVer = undefined; - let privateKey; - - if (this.config.privateKey) { - privateKey = parseKey(this.config.privateKey, cfg.passphrase); - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } - if (privateKey.getPrivatePEM() === null) { - throw new Error( - 'privateKey value does not contain a (valid) private key' - ); - } - } - - let hostVerifier; - if (typeof cfg.hostVerifier === 'function') { - const hashCb = cfg.hostVerifier; - let hasher; - if (HASHES.indexOf(cfg.hostHash) !== -1) { - // Default to old behavior of hashing on user's behalf - hasher = createHash(cfg.hostHash); - } - hostVerifier = (key, verify) => { - if (hasher) { - hasher.update(key); - key = hasher.digest('hex'); - } - const ret = hashCb(key, verify); - if (ret !== undefined) - verify(ret); - }; - } - - const sock = this._sock = (cfg.sock || new Socket()); - let ready = false; - let sawHeader = false; - if (this._protocol) - this._protocol.cleanup(); - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from server: ${JSON.stringify(msg)}`); - }); - const proto = this._protocol = new Protocol({ - ident: this.config.ident, - offer: (allOfferDefaults ? undefined : algorithms), - onWrite: (data) => { - if (isWritable(sock)) - sock.write(data); - }, - onError: (err) => { - if (err.level === 'handshake') - clearTimeout(this._readyTimeout); - if (!proto._destruct) - sock.removeAllListeners('data'); - this.emit('error', err); - try { - sock.end(); - } catch {} - }, - onHeader: (header) => { - sawHeader = true; - this._remoteVer = header.versions.software; - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - this.emit('handshake', negotiated); - if (!ready) { - ready = true; - proto.service('ssh-userauth'); - } - }, - debug, - hostVerifier, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - sock.end(); - }, - SERVICE_ACCEPT: (p, name) => { - if (name === 'ssh-userauth') - tryNextAuth(); - }, - USERAUTH_BANNER: (p, msg) => { - this.emit('banner', msg); - }, - USERAUTH_SUCCESS: (p) => { - // Start keepalive mechanism - resetKA(); - - clearTimeout(this._readyTimeout); - - this.emit('ready'); - }, - USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { - if (curAuth.type === 'agent') { - const pos = curAuth.agentCtx.pos(); - debug && debug(`Client: Agent key #${pos + 1} failed`); - return tryNextAgentKey(); - } - - debug && debug(`Client: ${curAuth.type} auth failed`); - - curPartial = partialSuccess; - curAuthsLeft = authMethods; - tryNextAuth(); - }, - USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { - if (curAuth.type === 'password') { - // TODO: support a `changePrompt()` on `curAuth` that defaults to - // emitting 'change password' as before - this.emit('change password', prompt, (newPassword) => { - proto.authPassword( - this.config.username, - this.config.password, - newPassword - ); - }); - } - }, - USERAUTH_PK_OK: (p) => { - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.currentKey(); - proto.authPK(curAuth.username, key, (buf, cb) => { - curAuth.agentCtx.sign(key, buf, {}, (err, signed) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - } else { - return cb(signed); - } - - tryNextAgentKey(); - }); - }); - } else if (curAuth.type === 'publickey') { - proto.authPK(curAuth.username, curAuth.key, (buf, cb) => { - const signature = curAuth.key.sign(buf); - if (signature instanceof Error) { - signature.message = - `Error signing data with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } - cb(signature); - }); - } - }, - USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { - if (curAuth.type === 'keyboard-interactive') { - const nprompts = (Array.isArray(prompts) ? prompts.length : 0); - if (nprompts === 0) { - debug && debug( - 'Client: Sending automatic USERAUTH_INFO_RESPONSE' - ); - proto.authInfoRes(); - return; - } - // We sent a keyboard-interactive user authentication request and - // now the server is sending us the prompts we need to present to - // the user - curAuth.prompt( - name, - instructions, - '', - prompts, - (answers) => { - proto.authInfoRes(answers); - } - ); - } - }, - REQUEST_SUCCESS: (p, data) => { - if (callbacks.length) - callbacks.shift()(false, data); - }, - REQUEST_FAILURE: (p) => { - if (callbacks.length) - callbacks.shift()(true); - }, - GLOBAL_REQUEST: (p, name, wantReply, data) => { - switch (name) { - case 'hostkeys-00@openssh.com': - // Automatically verify keys before passing to end user - hostKeysProve(this, data, (err, keys) => { - if (err) - return; - this.emit('hostkeys', keys); - }); - if (wantReply) - proto.requestSuccess(); - break; - default: - // Auto-reject all other global requests, this can be especially - // useful if the server is sending us dummy keepalive global - // requests - if (wantReply) - proto.requestFailure(); - } - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from server, typically a forwarded TCP or - // X11 connection - onCHANNEL_OPEN(this, info); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; - - const isSFTP = (channel.type === 'sftp'); - const type = (isSFTP ? 'session' : channel.type); - const chanInfo = { - type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const instance = ( - isSFTP - ? new SFTP(this, chanInfo, { debug }) - : new Channel(this, chanInfo) - ); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; - - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - if (type !== STDERR) - return; - - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (!channel.stderr.push(data)) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; - - if (channel._waitWindow) { - channel._waitWindow = false; - - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); - } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - this._resetKA(); - - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - this._resetKA(); - - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - const exit = channel._exit; - if (exit.code !== undefined) - return; - switch (type) { - case 'exit-status': - channel.emit('exit', exit.code = data); - return; - case 'exit-signal': - channel.emit('exit', - exit.code = null, - exit.signal = `SIG${data.signal}`, - exit.dump = data.coreDumped, - exit.desc = data.errorMessage); - return; - } - - // Keepalive request? OpenSSH will send one as a channel request if - // there is a channel open - - if (wantReply) - p.channelFailure(channel.outgoing.id); - }, - CHANNEL_EOF: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; - - if (channel.readable) - channel.push(null); - if (channel.stderr.readable) - channel.stderr.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); - }, - }, - }); - - sock.pause(); - - // TODO: check keepalive implementation - // Keepalive-related - const kainterval = this.config.keepaliveInterval; - const kacountmax = this.config.keepaliveCountMax; - let kacount = 0; - let katimer; - const sendKA = () => { - if (++kacount > kacountmax) { - clearInterval(katimer); - if (sock.readable) { - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); - } - return; - } - if (isWritable(sock)) { - // Append dummy callback to keep correct callback order - callbacks.push(resetKA); - proto.ping(); - } else { - clearInterval(katimer); - } - }; - function resetKA() { - if (kainterval > 0) { - kacount = 0; - clearInterval(katimer); - if (isWritable(sock)) - katimer = setInterval(sendKA, kainterval); - } - } - this._resetKA = resetKA; - - const onDone = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (wasConnected && !sawHeader) { - const err = - makeError('Connection lost before handshake', 'protocol', true); - this.emit('error', err); - } - }; - })(); - const onConnect = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - - wasConnected = true; - debug && debug('Socket connected'); - this.emit('connect'); - - cryptoInit.then(() => { - sock.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - } - }); - - // Drain stderr if we are connection hopping using an exec stream - if (sock.stderr && typeof sock.stderr.resume === 'function') - sock.stderr.resume(); - - sock.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - }); - }; - })(); - let wasConnected = false; - sock.on('connect', onConnect) - .on('timeout', () => { - this.emit('timeout'); - }).on('error', (err) => { - debug && debug(`Socket error: ${err.message}`); - clearTimeout(this._readyTimeout); - err.level = 'client-socket'; - this.emit('error', err); - }).on('end', () => { - debug && debug('Socket ended'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('end'); - }).on('close', () => { - debug && debug('Socket closed'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('close'); - - // Notify outstanding channel requests of disconnection ... - const callbacks_ = callbacks; - callbacks = this._callbacks = []; - const err = new Error('No response from server'); - for (let i = 0; i < callbacks_.length; ++i) - callbacks_[i](err); - - // Simulate error for any channels waiting to be opened - this._chanMgr.cleanup(err); - }); - - // Begin authentication handling =========================================== - let curAuth; - let curPartial = null; - let curAuthsLeft = null; - const authsAllowed = ['none']; - if (this.config.password !== undefined) - authsAllowed.push('password'); - if (privateKey !== undefined) - authsAllowed.push('publickey'); - if (this._agent !== undefined) - authsAllowed.push('agent'); - if (this.config.tryKeyboard) - authsAllowed.push('keyboard-interactive'); - if (privateKey !== undefined - && this.config.localHostname !== undefined - && this.config.localUsername !== undefined) { - authsAllowed.push('hostbased'); - } - - if (Array.isArray(authHandler)) - authHandler = makeSimpleAuthHandler(authHandler); - else if (typeof authHandler !== 'function') - authHandler = makeSimpleAuthHandler(authsAllowed); - - let hasSentAuth = false; - const doNextAuth = (nextAuth) => { - if (hasSentAuth) - return; - hasSentAuth = true; - - if (nextAuth === false) { - const err = new Error('All configured authentication methods failed'); - err.level = 'client-authentication'; - this.emit('error', err); - this.end(); - return; - } - - if (typeof nextAuth === 'string') { - // Remain backwards compatible with original `authHandler()` usage, - // which only supported passing names of next method to try using data - // from the `connect()` config object - - const type = nextAuth; - if (authsAllowed.indexOf(type) === -1) - return skipAuth(`Authentication method not allowed: ${type}`); - - const username = this.config.username; - switch (type) { - case 'password': - nextAuth = { type, username, password: this.config.password }; - break; - case 'publickey': - nextAuth = { type, username, key: privateKey }; - break; - case 'hostbased': - nextAuth = { - type, - username, - key: privateKey, - localHostname: this.config.localHostname, - localUsername: this.config.localUsername, - }; - break; - case 'agent': - nextAuth = { - type, - username, - agentCtx: new AgentContext(this._agent), - }; - break; - case 'keyboard-interactive': - nextAuth = { - type, - username, - prompt: (...args) => this.emit('keyboard-interactive', ...args), - }; - break; - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } else if (typeof nextAuth !== 'object' || nextAuth === null) { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } else { - const username = nextAuth.username; - if (typeof username !== 'string') { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } - const type = nextAuth.type; - switch (type) { - case 'password': { - const { password } = nextAuth; - if (typeof password !== 'string' && !Buffer.isBuffer(password)) - return skipAuth('Skipping invalid password auth attempt'); - nextAuth = { type, username, password }; - break; - } - case 'publickey': { - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error) - return skipAuth('Skipping invalid key auth attempt'); - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key }; - break; - } - case 'hostbased': { - const { localHostname, localUsername } = nextAuth; - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error - || typeof localHostname !== 'string' - || typeof localUsername !== 'string') { - return skipAuth('Skipping invalid hostbased auth attempt'); - } - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key, localHostname, localUsername }; - break; - } - case 'agent': { - let agent = nextAuth.agent; - if (typeof agent === 'string' && agent.length) { - agent = createAgent(agent); - } else if (!isAgent(agent)) { - return skipAuth( - `Skipping invalid agent: ${nextAuth.agent}` - ); - } - nextAuth = { type, username, agentCtx: new AgentContext(agent) }; - break; - } - case 'keyboard-interactive': { - const { prompt } = nextAuth; - if (typeof prompt !== 'function') { - return skipAuth( - 'Skipping invalid keyboard-interactive auth attempt' - ); - } - nextAuth = { type, username, prompt }; - break; - } - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } - curAuth = nextAuth; - - // Begin authentication method's process - try { - const username = curAuth.username; - switch (curAuth.type) { - case 'password': - proto.authPassword(username, curAuth.password); - break; - case 'publickey': - proto.authPK(username, curAuth.key); - break; - case 'hostbased': - proto.authHostbased(username, - curAuth.key, - curAuth.localHostname, - curAuth.localUsername, - (buf, cb) => { - const signature = curAuth.key.sign(buf); - if (signature instanceof Error) { - signature.message = - `Error while signing with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } - - cb(signature); - }); - break; - case 'agent': - curAuth.agentCtx.init((err) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - return tryNextAuth(); - } - tryNextAgentKey(); - }); - break; - case 'keyboard-interactive': - proto.authKeyboard(username); - break; - case 'none': - proto.authNone(username); - break; - } - } finally { - hasSentAuth = false; - } - }; - - function skipAuth(msg) { - debug && debug(msg); - process.nextTick(tryNextAuth); - } - - function tryNextAuth() { - hasSentAuth = false; - const auth = authHandler(curAuthsLeft, curPartial, doNextAuth); - if (hasSentAuth || auth === undefined) - return; - doNextAuth(auth); - } - - const tryNextAgentKey = () => { - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.nextKey(); - if (key === false) { - debug && debug('Agent: No more keys left to try'); - debug && debug('Client: agent auth failed'); - tryNextAuth(); - } else { - const pos = curAuth.agentCtx.pos(); - debug && debug(`Agent: Trying key #${pos + 1}`); - proto.authPK(curAuth.username, key); - } - } - }; - - const startTimeout = () => { - if (this.config.readyTimeout > 0) { - this._readyTimeout = setTimeout(() => { - const err = new Error('Timed out while waiting for handshake'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); - }, this.config.readyTimeout); - } - }; - - if (!cfg.sock) { - let host = this.config.host; - const forceIPv4 = this.config.forceIPv4; - const forceIPv6 = this.config.forceIPv6; - - debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`); - - const doConnect = () => { - startTimeout(); - sock.connect({ - host, - port: this.config.port, - localAddress: this.config.localAddress, - localPort: this.config.localPort - }); - sock.setNoDelay(true); - sock.setMaxListeners(0); - sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0); - }; - - if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) { - doConnect(); - } else { - dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => { - if (err) { - const type = (forceIPv4 ? 'IPv4' : 'IPv6'); - const error = new Error( - `Error while looking up ${type} address for '${host}': ${err}` - ); - clearTimeout(this._readyTimeout); - error.level = 'client-dns'; - this.emit('error', error); - this.emit('close'); - return; - } - host = address; - doConnect(); - }); - } - } else { - // Custom socket passed in - startTimeout(); - if (typeof sock.connecting === 'boolean') { - // net.Socket - - if (!sock.connecting) { - // Already connected - onConnect(); - } - } else { - // Assume socket/stream is already "connected" - onConnect(); - } - } - - return this; - } - - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); - } - return this; - } - - destroy() { - this._sock && isWritable(this._sock) && this._sock.destroy(); - return this; - } - - exec(cmd, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) }; - - openChannel(this, 'session', extraOpts, (err, chan) => { - if (err) { - cb(err); - return; - } - - const todo = []; - - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } - - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } - - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.pty === 'object' && opts.pty !== null) - || opts.pty === true) { - todo.push(() => reqPty(chan, opts.pty, reqCb)); - } - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } - - todo.push(() => reqExec(chan, cmd, opts, cb)); - todo.shift()(); - }); - - return this; - } - - shell(wndopts, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof wndopts === 'function') { - cb = wndopts; - wndopts = opts = undefined; - } else if (typeof opts === 'function') { - cb = opts; - opts = undefined; - } - if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) { - opts = wndopts; - wndopts = undefined; - } - - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } - - const todo = []; - - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } - - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } - - if (wndopts !== false) - todo.push(() => reqPty(chan, wndopts, reqCb)); - - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } - - todo.push(() => reqShell(chan, cb)); - todo.shift()(); - }); - - return this; - } - - subsys(name, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } - - reqSubsystem(chan, name, (err, stream) => { - if (err) { - cb(err); - return; - } - - cb(undefined, stream); - }); - }); - - return this; - } - - forwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - // Send a request for the server to start forwarding TCP connections to us - // on a particular address and port - - const wantReply = (typeof cb === 'function'); - - if (wantReply) { - this._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); - return; - } - - let realPort = bindPort; - if (bindPort === 0 && data && data.length >= 4) { - realPort = readUInt32BE(data, 0); - if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) - bindPort = realPort; - } - - this._forwarding[`${bindAddr}:${bindPort}`] = realPort; - - cb(undefined, realPort); - }); - } - - this._protocol.tcpipForward(bindAddr, bindPort, wantReply); - - return this; - } - - unforwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - // Send a request to stop forwarding us new connections for a particular - // address and port - - const wantReply = (typeof cb === 'function'); - - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); - return; - } - - delete this._forwarding[`${bindAddr}:${bindPort}`]; - - cb(); - }); - } - - this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); - - return this; - } - - forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - // Send a request to forward a TCP connection to the server - - const cfg = { - srcIP: srcIP, - srcPort: srcPort, - dstIP: dstIP, - dstPort: dstPort - }; - - if (typeof cb !== 'function') - cb = noop; - - openChannel(this, 'direct-tcpip', cfg, cb); - - return this; - } - - openssh_noMoreSessions(cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - const wantReply = (typeof cb === 'function'); - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to disable future sessions')); - return; - } - - cb(); - }); - } - - this._protocol.openssh_noMoreSessions(wantReply); - return this; - } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_forwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - const wantReply = (typeof cb === 'function'); - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${socketPath}`)); - return; - } - this._forwardingUnix[socketPath] = true; - cb(); - }); - } - - this._protocol.openssh_streamLocalForward(socketPath, wantReply); - return this; - } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_unforwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - const wantReply = (typeof cb === 'function'); - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${socketPath}`)); - return; - } - delete this._forwardingUnix[socketPath]; - cb(); - }); - } - - this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); - return this; - } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_forwardOutStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof cb !== 'function') - cb = noop; - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb); - return this; - } - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - sftp(cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - openChannel(this, 'sftp', (err, sftp) => { - if (err) { - cb(err); - return; - } - - reqSubsystem(sftp, 'sftp', (err, sftp_) => { - if (err) { - cb(err); - return; - } - - function removeListeners() { - sftp.removeListener('ready', onReady); - sftp.removeListener('error', onError); - sftp.removeListener('exit', onExit); - sftp.removeListener('close', onExit); - } - - function onReady() { - // TODO: do not remove exit/close in case remote end closes the - // channel abruptly and we need to notify outstanding callbacks - removeListeners(); - cb(undefined, sftp); - } - - function onError(err) { - removeListeners(); - cb(err); - } - - function onExit(code, signal) { - removeListeners(); - let msg; - if (typeof code === 'number') - msg = `Received exit code ${code} while establishing SFTP session`; - else if (signal !== undefined) - msg = `Received signal ${signal} while establishing SFTP session`; - else - msg = 'Received unexpected SFTP session termination'; - const err = new Error(msg); - err.code = code; - err.signal = signal; - cb(err); - } - - sftp.on('ready', onReady) - .on('error', onError) - .on('exit', onExit) - .on('close', onExit); - - sftp._init(); - }); - }); - - return this; - } -} - -function openChannel(self, type, opts, cb) { - // Ask the server to open a channel for some purpose - // (e.g. session (sftp, exec, shell), or forwarding a TCP connection - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; - - const localChan = self._chanMgr.add(wrapper); - - if (localChan === -1) { - cb(new Error('No free channels available')); - return; - } - - switch (type) { - case 'session': - case 'sftp': - self._protocol.session(localChan, initWindow, maxPacket); - break; - case 'direct-tcpip': - self._protocol.directTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'direct-streamlocal@openssh.com': - self._protocol.openssh_directStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } -} - -function reqX11(chan, screen, cb) { - // Asks server to start sending us X11 connections - const cfg = { - single: false, - protocol: 'MIT-MAGIC-COOKIE-1', - cookie: undefined, - screen: 0 - }; - - if (typeof screen === 'function') { - cb = screen; - } else if (typeof screen === 'object' && screen !== null) { - if (typeof screen.single === 'boolean') - cfg.single = screen.single; - if (typeof screen.screen === 'number') - cfg.screen = screen.screen; - if (typeof screen.protocol === 'string') - cfg.protocol = screen.protocol; - if (typeof screen.cookie === 'string') - cfg.cookie = screen.cookie; - else if (Buffer.isBuffer(screen.cookie)) - cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); - } - if (cfg.cookie === undefined) - cfg.cookie = randomCookie(); - - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; - } - - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to request X11')); - return; - } - - chan._hasX11 = true; - ++chan._client._acceptX11; - chan.once('close', () => { - if (chan._client._acceptX11) - --chan._client._acceptX11; - }); - - cb(); - }); - } - - chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); -} - -function reqPty(chan, opts, cb) { - let rows = 24; - let cols = 80; - let width = 640; - let height = 480; - let term = 'vt100'; - let modes = null; - - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.rows === 'number') - rows = opts.rows; - if (typeof opts.cols === 'number') - cols = opts.cols; - if (typeof opts.width === 'number') - width = opts.width; - if (typeof opts.height === 'number') - height = opts.height; - if (typeof opts.term === 'string') - term = opts.term; - if (typeof opts.modes === 'object') - modes = opts.modes; - } - - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; - } - - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to request a pseudo-terminal')); - return; - } - cb(); - }); - } - - chan._client._protocol.pty(chan.outgoing.id, - rows, - cols, - height, - width, - term, - modes, - wantReply); -} - -function reqAgentFwd(chan, cb) { - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - wantReply && cb(new Error('Channel is not open')); - return; - } - if (chan._client._agentFwdEnabled) { - wantReply && cb(false); - return; - } - - chan._client._agentFwdEnabled = true; - - chan._callbacks.push((had_err) => { - if (had_err) { - chan._client._agentFwdEnabled = false; - if (wantReply) { - cb(had_err !== true - ? had_err - : new Error('Unable to request agent forwarding')); - } - return; - } - - if (wantReply) - cb(); - }); - - chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); -} - -function reqShell(chan, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to open shell')); - return; - } - chan.subtype = 'shell'; - cb(undefined, chan); - }); - - chan._client._protocol.shell(chan.outgoing.id, true); -} - -function reqExec(chan, cmd, opts, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to exec')); - return; - } - chan.subtype = 'exec'; - chan.allowHalfOpen = (opts.allowHalfOpen !== false); - cb(undefined, chan); - }); - - chan._client._protocol.exec(chan.outgoing.id, cmd, true); -} - -function reqEnv(chan, env) { - if (chan.outgoing.state !== 'open') - return; - - const keys = Object.keys(env || {}); - - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - const val = env[key]; - chan._client._protocol.env(chan.outgoing.id, key, val, false); - } -} - -function reqSubsystem(chan, name, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to start subsystem: ${name}`)); - return; - } - chan.subtype = 'subsystem'; - cb(undefined, chan); - }); - - chan._client._protocol.subsystem(chan.outgoing.id, name, true); -} - -// TODO: inline implementation into single call site -function onCHANNEL_OPEN(self, info) { - // The server is trying to open a channel with us, this is usually when - // we asked the server to forward us connections on some port and now they - // are asking us to accept/deny an incoming connection on their side - - let localChan = -1; - let reason; - - const accept = () => { - const chanInfo = { - type: info.type, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const stream = new Channel(self, chanInfo); - self._chanMgr.update(localChan, stream); - - self._protocol.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - return stream; - }; - const reject = () => { - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } - - if (localChan !== -1) - self._chanMgr.remove(localChan); - - self._protocol.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = self._chanMgr.add(); - - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of incoming channel open: ' - + 'no channels available' - ); - } - } - - return (localChan !== -1); - }; - - const data = info.data; - switch (info.type) { - case 'forwarded-tcpip': { - const val = self._forwarding[`${data.destIP}:${data.destPort}`]; - if (val !== undefined && reserveChannel()) { - if (data.destPort === 0) - data.destPort = val; - self.emit('tcp connection', data, accept, reject); - return; - } - break; - } - case 'forwarded-streamlocal@openssh.com': - if (self._forwardingUnix[data.socketPath] !== undefined - && reserveChannel()) { - self.emit('unix connection', data, accept, reject); - return; - } - break; - case 'auth-agent@openssh.com': - if (self._agentFwdEnabled - && typeof self._agent.getStream === 'function' - && reserveChannel()) { - self._agent.getStream((err, stream) => { - if (err) - return reject(); - - const upstream = accept(); - upstream.pipe(stream).pipe(upstream); - }); - return; - } - break; - case 'x11': - if (self._acceptX11 !== 0 && reserveChannel()) { - self.emit('x11', data, accept, reject); - return; - } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unsupported incoming channel open ' - + `type: ${info.type}` - ); - } - } - - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unexpected incoming channel open for: ' - + info.type - ); - } - } - - reject(); -} - -const randomCookie = (() => { - const buffer = Buffer.allocUnsafe(16); - return () => { - randomFillSync(buffer, 0, 16); - return buffer.hexSlice(0, 16); - }; -})(); - -function makeSimpleAuthHandler(authList) { - if (!Array.isArray(authList)) - throw new Error('authList must be an array'); - - let a = 0; - return (authsLeft, partialSuccess, cb) => { - if (a === authList.length) - return false; - return authList[a++]; - }; -} - -function hostKeysProve(client, keys_, cb) { - if (!client._sock || !isWritable(client._sock)) - return; - - if (typeof cb !== 'function') - cb = noop; - - if (!Array.isArray(keys_)) - throw new TypeError('Invalid keys argument type'); - - const keys = []; - for (const key of keys_) { - const parsed = parseKey(key); - if (parsed instanceof Error) - throw parsed; - keys.push(parsed); - } - - if (!client.config.strictVendor - || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) { - client._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Server failed to prove supplied keys')); - return; - } - - // TODO: move all of this parsing/verifying logic out of the client? - const ret = []; - let keyIdx = 0; - bufferParser.init(data, 0); - while (bufferParser.avail()) { - if (keyIdx === keys.length) - break; - const key = keys[keyIdx++]; - const keyPublic = key.getPublicSSH(); - - const sigEntry = bufferParser.readString(); - sigParser.init(sigEntry, 0); - const type = sigParser.readString(true); - let value = sigParser.readString(); - - let algo; - if (type !== key.type) { - if (key.type === 'ssh-rsa') { - switch (type) { - case 'rsa-sha2-256': - algo = 'sha256'; - break; - case 'rsa-sha2-512': - algo = 'sha512'; - break; - default: - continue; - } - } else { - continue; - } - } - - const sessionID = client._protocol._kex.sessionID; - const verifyData = Buffer.allocUnsafe( - 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length - ); - let p = 0; - writeUInt32BE(verifyData, 29, p); - verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); - writeUInt32BE(verifyData, sessionID.length, p += 29); - bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); - writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); - bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); - - if (!(value = sigSSHToASN1(value, type))) - continue; - if (key.verify(verifyData, value, algo) === true) - ret.push(key); - } - sigParser.clear(); - bufferParser.clear(); - - cb(null, ret); - }); - - client._protocol.openssh_hostKeysProve(keys); - return; - } - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); -} - -module.exports = Client; diff --git a/reverse_engineering/node_modules/ssh2/lib/http-agents.js b/reverse_engineering/node_modules/ssh2/lib/http-agents.js deleted file mode 100644 index 770a0e6..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/http-agents.js +++ /dev/null @@ -1,84 +0,0 @@ -'use strict'; - -const { Agent: HttpAgent } = require('http'); -const { Agent: HttpsAgent } = require('https'); -const { connect: tlsConnect } = require('tls'); - -let Client; - -for (const ctor of [HttpAgent, HttpsAgent]) { - class SSHAgent extends ctor { - constructor(connectCfg, agentOptions) { - super(agentOptions); - - this._connectCfg = connectCfg; - this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost'; - } - - createConnection(options, cb) { - const srcIP = (options && options.localAddress) || this._defaultSrcIP; - const srcPort = (options && options.localPort) || 0; - const dstIP = options.host; - const dstPort = options.port; - - if (Client === undefined) - Client = require('./client.js'); - - const client = new Client(); - let triedForward = false; - client.on('ready', () => { - client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => { - triedForward = true; - if (err) { - client.end(); - return cb(err); - } - stream.once('close', () => client.end()); - cb(null, decorateStream(stream, ctor, options)); - }); - }).on('error', cb).on('close', () => { - if (!triedForward) - cb(new Error('Unexpected connection close')); - }).connect(this._connectCfg); - } - } - - exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent; -} - -function noop() {} - -function decorateStream(stream, ctor, options) { - if (ctor === HttpAgent) { - // HTTP - stream.setKeepAlive = noop; - stream.setNoDelay = noop; - stream.setTimeout = noop; - stream.ref = noop; - stream.unref = noop; - stream.destroySoon = stream.destroy; - return stream; - } - - // HTTPS - options.socket = stream; - const wrapped = tlsConnect(options); - - // This is a workaround for a regression in node v12.16.3+ - // https://github.com/nodejs/node/issues/35904 - const onClose = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (stream.isPaused()) - stream.resume(); - }; - })(); - // 'end' listener is needed because 'close' is not emitted in some scenarios - // in node v12.x for some unknown reason - wrapped.on('end', onClose).on('close', onClose); - - return wrapped; -} diff --git a/reverse_engineering/node_modules/ssh2/lib/index.js b/reverse_engineering/node_modules/ssh2/lib/index.js deleted file mode 100644 index 459952e..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/index.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -const { - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - OpenSSHAgent, - PageantAgent, -} = require('./agent.js'); -const { - SSHTTPAgent: HTTPAgent, - SSHTTPSAgent: HTTPSAgent, -} = require('./http-agents.js'); -const { parseKey } = require('./protocol/keyParser.js'); -const { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, -} = require('./protocol/SFTP.js'); - -module.exports = { - AgentProtocol, - BaseAgent, - createAgent, - Client: require('./client.js'), - CygwinAgent, - HTTPAgent, - HTTPSAgent, - OpenSSHAgent, - PageantAgent, - Server: require('./server.js'), - utils: { - parseKey, - sftp: { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, - }, - }, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/Protocol.js b/reverse_engineering/node_modules/ssh2/lib/protocol/Protocol.js deleted file mode 100644 index e00f1eb..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/Protocol.js +++ /dev/null @@ -1,2076 +0,0 @@ -/* - TODO: - * Replace `buffer._pos` usage in keyParser.js and elsewhere - * Utilize optional "writev" support when writing packets from - cipher.encrypt() - * Built-in support for automatic re-keying, on by default - * Revisit receiving unexpected/unknown packets - * Error (fatal or otherwise) or ignore or pass on to user (in some or all - cases)? - * Including server/client check for single directional packet types? - * Check packets for validity or bail as early as possible? - * Automatic re-key every 2**31 packets after the last key exchange (sent or - received), as suggested by RFC4344. OpenSSH currently does this. - * Automatic re-key every so many blocks depending on cipher. RFC4344: - Because of a birthday property of block ciphers and some modes of - operation, implementations must be careful not to encrypt too many - blocks with the same encryption key. - - Let L be the block length (in bits) of an SSH encryption method's - block cipher (e.g., 128 for AES). If L is at least 128, then, after - rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4) - blocks before rekeying again. If L is at least 128, then SSH - implementations should also attempt to force a rekey before receiving - more than 2**(L/4) blocks. If L is less than 128 (which is the case - for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then, - although it may be too expensive to rekey every 2**(L/4) blocks, it - is still advisable for SSH implementations to follow the original - recommendation in [RFC4253]: rekey at least once for every gigabyte - of transmitted data. - - Note that if L is less than or equal to 128, then the recommendation - in this subsection supersedes the recommendation in Section 3.1. If - an SSH implementation uses a block cipher with a larger block size - (e.g., Rijndael with 256-bit blocks), then the recommendations in - Section 3.1 may supersede the recommendations in this subsection - (depending on the lengths of the packets). -*/ - -'use strict'; - -const { inspect } = require('util'); - -const { bindingAvailable, NullCipher, NullDecipher } = require('./crypto.js'); -const { - COMPAT_CHECKS, - DISCONNECT_REASON, - MESSAGE, - SIGNALS, - TERMINAL_MODE, -} = require('./constants.js'); -const { - DEFAULT_KEXINIT, - KexInit, - kexinit, - onKEXPayload, -} = require('./kex.js'); -const { - parseKey, -} = require('./keyParser.js'); -const MESSAGE_HANDLERS = require('./handlers.js'); -const { - bufferCopy, - bufferFill, - bufferSlice, - convertSignature, - sendPacket, - writeUInt32BE, -} = require('./utils.js'); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = require('./zlib.js'); - -const MODULE_VER = require('../../package.json').version; - -const VALID_DISCONNECT_REASONS = new Map( - Object.values(DISCONNECT_REASON).map((n) => [n, 1]) -); -const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); -const IDENT = Buffer.from(`${IDENT_RAW}\r\n`); -const MAX_LINE_LEN = 8192; -const MAX_LINES = 1024; -const PING_PAYLOAD = Buffer.from([ - MESSAGE.GLOBAL_REQUEST, - // "keepalive@openssh.com" - 0, 0, 0, 21, - 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, - 115, 104, 46, 99, 111, 109, - // Request a reply - 1, -]); -const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]); - -function noop() {} - -/* - Inbound: - * kexinit payload (needed only until exchange hash is generated) - * raw ident - * rekey packet queue - * expected packet (implemented as separate _parse() function?) - Outbound: - * kexinit payload (needed only until exchange hash is generated) - * rekey packet queue - * kex secret (needed only until NEWKEYS) - * exchange hash (needed only until NEWKEYS) - * session ID (set to exchange hash from initial handshake) -*/ -class Protocol { - constructor(config) { - const onWrite = config.onWrite; - if (typeof onWrite !== 'function') - throw new Error('Missing onWrite function'); - this._onWrite = (data) => { onWrite(data); }; - - const onError = config.onError; - if (typeof onError !== 'function') - throw new Error('Missing onError function'); - this._onError = (err) => { onError(err); }; - - const debug = config.debug; - this._debug = (typeof debug === 'function' - ? (msg) => { debug(msg); } - : undefined); - - const onHeader = config.onHeader; - this._onHeader = (typeof onHeader === 'function' - ? (...args) => { onHeader(...args); } - : noop); - - const onPacket = config.onPacket; - this._onPacket = (typeof onPacket === 'function' - ? () => { onPacket(); } - : noop); - - let onHandshakeComplete = config.onHandshakeComplete; - if (typeof onHandshakeComplete !== 'function') - onHandshakeComplete = noop; - this._onHandshakeComplete = (...args) => { - this._debug && this._debug('Handshake completed'); - - // Process packets queued during a rekey where necessary - const oldQueue = this._queue; - if (oldQueue) { - this._queue = undefined; - this._debug && this._debug( - `Draining outbound queue (${oldQueue.length}) ...` - ); - for (let i = 0; i < oldQueue.length; ++i) { - const data = oldQueue[i]; - // data === payload only - - // XXX: hacky - let finalized = this._packetRW.write.finalize(data); - if (finalized === data) { - const packet = this._cipher.allocPacket(data.length); - packet.set(data, 5); - finalized = packet; - } - - sendPacket(this, finalized); - } - this._debug && this._debug('... finished draining outbound queue'); - } - - onHandshakeComplete(...args); - }; - this._queue = undefined; - - const messageHandlers = config.messageHandlers; - if (typeof messageHandlers === 'object' && messageHandlers !== null) - this._handlers = messageHandlers; - else - this._handlers = {}; - - this._onPayload = onPayload.bind(this); - - this._server = !!config.server; - this._banner = undefined; - let greeting; - if (this._server) { - if (typeof config.hostKeys !== 'object' || config.hostKeys === null) - throw new Error('Missing server host key(s)'); - this._hostKeys = config.hostKeys; - - // Greeting displayed before the ssh identification string is sent, this - // is usually ignored by most clients - if (typeof config.greeting === 'string' && config.greeting.length) { - greeting = (config.greeting.slice(-2) === '\r\n' - ? config.greeting - : `${config.greeting}\r\n`); - } - - // Banner shown after the handshake completes, but before user - // authentication begins - if (typeof config.banner === 'string' && config.banner.length) { - this._banner = (config.banner.slice(-2) === '\r\n' - ? config.banner - : `${config.banner}\r\n`); - } - } else { - this._hostKeys = undefined; - } - - let offer = config.offer; - if (typeof offer !== 'object' || offer === null) - offer = DEFAULT_KEXINIT; - else if (offer.constructor !== KexInit) - offer = new KexInit(offer); - this._kex = undefined; - this._kexinit = undefined; - this._offer = offer; - this._cipher = new NullCipher(0, this._onWrite); - this._decipher = undefined; - this._skipNextInboundPacket = false; - this._packetRW = { - read: new PacketReader(), - write: new PacketWriter(this), - }; - this._hostVerifier = (!this._server - && typeof config.hostVerifier === 'function' - ? config.hostVerifier - : undefined); - - this._parse = parseHeader; - this._buffer = undefined; - this._authsQueue = []; - this._authenticated = false; - this._remoteIdentRaw = undefined; - let sentIdent; - if (typeof config.ident === 'string') { - this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); - - sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); - sentIdent.set(this._identRaw, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else if (Buffer.isBuffer(config.ident)) { - const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); - fullIdent.latin1Write('SSH-2.0-', 0, 8); - fullIdent.set(config.ident, 8); - this._identRaw = fullIdent; - - sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); - sentIdent.set(fullIdent, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else { - this._identRaw = IDENT_RAW; - sentIdent = IDENT; - } - this._compatFlags = 0; - - if (this._debug) { - if (bindingAvailable) - this._debug('Custom crypto binding available'); - else - this._debug('Custom crypto binding not available'); - } - - process.nextTick(() => { - this._debug && this._debug( - `Local ident: ${inspect(this._identRaw.toString())}` - ); - if (greeting) - this._onWrite(greeting); - this._onWrite(sentIdent); - }); - } - _destruct(reason) { - this._packetRW.read.cleanup(); - this._packetRW.write.cleanup(); - this._cipher && this._cipher.free(); - this._decipher && this._decipher.free(); - if (typeof reason !== 'string' || reason.length === 0) - reason = 'fatal error'; - this.parse = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._onWrite = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._destruct = undefined; - } - cleanup() { - this._destruct && this._destruct(); - } - parse(chunk, i, len) { - while (i < len) - i = this._parse(chunk, i, len); - } - - // Protocol message API - - // =========================================================================== - // Common/Shared ============================================================= - // =========================================================================== - - // Global - // ------ - disconnect(reason) { - const pktLen = 1 + 4 + 4 + 4; - // We don't use _packetRW.write.* here because we need to make sure that - // we always get a full packet allocated because this message can be sent - // at any time -- even during a key exchange - let p = this._packetRW.write.allocStartKEX; - const packet = this._packetRW.write.alloc(pktLen, true); - const end = p + pktLen; - - if (!VALID_DISCONNECT_REASONS.has(reason)) - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - - packet[p] = MESSAGE.DISCONNECT; - writeUInt32BE(packet, reason, ++p); - packet.fill(0, p += 4, end); - - this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); - sendPacket(this, this._packetRW.write.finalize(packet, true), true); - } - ping() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); - - packet.set(PING_PAYLOAD, p); - - this._debug && this._debug( - 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - rekey() { - if (this._kexinit === undefined) { - this._debug && this._debug('Outbound: Initiated explicit rekey'); - this._queue = []; - kexinit(this); - } else { - this._debug && this._debug('Outbound: Ignoring rekey during handshake'); - } - } - - // 'ssh-connection' service-specific - // --------------------------------- - requestSuccess(data) { - let p = this._packetRW.write.allocStart; - let packet; - if (Buffer.isBuffer(data)) { - packet = this._packetRW.write.alloc(1 + data.length); - - packet[p] = MESSAGE.REQUEST_SUCCESS; - - packet.set(data, ++p); - } else { - packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.REQUEST_SUCCESS; - } - - this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - requestFailure() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.REQUEST_FAILURE; - - this._debug && this._debug('Outbound: Sending REQUEST_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelSuccess(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_SUCCESS; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelFailure(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_FAILURE; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelEOF(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_EOF; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelClose(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_CLOSE; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelWindowAdjust(chan, amount) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, amount, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelData(chan, data) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); - - packet[p] = MESSAGE.CHANNEL_DATA; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, dataLen, p += 4); - - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelExtData(chan, data, type) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); - - packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, type, p += 4); - - writeUInt32BE(packet, dataLen, p += 4); - - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelOpenConfirm(remote, local, initWindow, maxPacket) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; - - writeUInt32BE(packet, remote, ++p); - - writeUInt32BE(packet, local, p += 4); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelOpenFail(remote, reason, desc) { - if (typeof desc !== 'string') - desc = ''; - - const descLen = Buffer.byteLength(desc); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; - - writeUInt32BE(packet, remote, ++p); - - writeUInt32BE(packet, reason, p += 4); - - writeUInt32BE(packet, descLen, p += 4); - - p += 4; - if (descLen) { - packet.utf8Write(desc, p, descLen); - p += descLen; - } - - writeUInt32BE(packet, 0, p); // Empty language tag - - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - - // Global - // ------ - service(name) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + nameLen); - - packet[p] = MESSAGE.SERVICE_REQUEST; - - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); - - this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // 'ssh-userauth' service-specific - // ------------------------------- - authPassword(username, password, newPassword) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - const passLen = Buffer.byteLength(password); - const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen - + (newPassword ? 4 + newPassLen : 0) - ); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 8, p += 14); - packet.utf8Write('password', p += 4, 8); - - packet[p += 8] = (newPassword ? 1 : 0); - - writeUInt32BE(packet, passLen, ++p); - if (Buffer.isBuffer(password)) - bufferCopy(password, packet, 0, passLen, p += 4); - else - packet.utf8Write(password, p += 4, passLen); - - if (newPassword) { - writeUInt32BE(packet, newPassLen, p += passLen); - if (Buffer.isBuffer(newPassword)) - bufferCopy(newPassword, packet, 0, newPassLen, p += 4); - else - packet.utf8Write(newPassword, p += 4, newPassLen); - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (changed password)' - ); - } else { - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (password)' - ); - } - - this._authsQueue.push('password'); - - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPK(username, pubKey, cbSign) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); - - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); - - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyType); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const payloadLen = - (cbSign ? 4 + sesLen : 0) - + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; - let packet; - let p; - if (cbSign) { - packet = Buffer.allocUnsafe(payloadLen); - p = 0; - writeUInt32BE(packet, sesLen, p); - packet.set(sessionID, p += 4); - p += sesLen; - } else { - packet = this._packetRW.write.alloc(payloadLen); - p = this._packetRW.write.allocStart; - } - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); - - packet[p += 9] = (cbSign ? 1 : 0); - - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyType, p += 4, algoLen); - - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); - - if (!cbSign) { - this._authsQueue.push('publickey'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - return; - } - - cbSign(packet, (signature) => { - signature = convertSignature(signature, keyType); - if (signature === false) - throw new Error('Error while converting handshake signature'); - - const sigLen = signature.length; - p = this._packetRW.write.allocStart; - packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 - + 4 + algoLen + 4 + sigLen - ); - - // TODO: simply copy from original "packet" to new `packet` to avoid - // having to write each individual field a second time? - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); - - packet[p += 9] = 1; - - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyType, p += 4, algoLen); - - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); - - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); - - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyType, p += 4, algoLen); - - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); - - // Servers shouldn't send packet type 60 in response to signed publickey - // attempts, but if they do, interpret as type 60. - this._authsQueue.push('publickey'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authHostbased(username, pubKey, hostname, userlocal, cbSign) { - // TODO: Make DRY by sharing similar code with authPK() - if (this._server) - throw new Error('Client-only method called in server mode'); - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); - - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); - - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyType); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const hostnameLen = Buffer.byteLength(hostname); - const userlocalLen = Buffer.byteLength(userlocal); - const data = Buffer.allocUnsafe( - 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen - + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen - ); - let p = 0; - - writeUInt32BE(data, sesLen, p); - data.set(sessionID, p += 4); - - data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(data, userLen, ++p); - data.utf8Write(username, p += 4, userLen); - - writeUInt32BE(data, 14, p += userLen); - data.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(data, 9, p += 14); - data.utf8Write('hostbased', p += 4, 9); - - writeUInt32BE(data, algoLen, p += 9); - data.utf8Write(keyType, p += 4, algoLen); - - writeUInt32BE(data, pubKeyLen, p += algoLen); - data.set(pubKey, p += 4); - - writeUInt32BE(data, hostnameLen, p += pubKeyLen); - data.utf8Write(hostname, p += 4, hostnameLen); - - writeUInt32BE(data, userlocalLen, p += hostnameLen); - data.utf8Write(userlocal, p += 4, userlocalLen); - - cbSign(data, (signature) => { - signature = convertSignature(signature, keyType); - if (!signature) - throw new Error('Error while converting handshake signature'); - - const sigLen = signature.length; - const reqDataLen = (data.length - sesLen - 4); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - reqDataLen + 4 + 4 + algoLen + 4 + sigLen - ); - - bufferCopy(data, packet, 4 + sesLen, data.length, p); - - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyType, p += 4, algoLen); - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); - - this._authsQueue.push('hostbased'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (hostbased)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authKeyboard(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 - ); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 20, p += 14); - packet.utf8Write('keyboard-interactive', p += 4, 20); - - writeUInt32BE(packet, 0, p += 20); - - writeUInt32BE(packet, 0, p += 4); - - this._authsQueue.push('keyboard-interactive'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authNone(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 4, p += 14); - packet.utf8Write('none', p += 4, 4); - - this._authsQueue.push('none'); - - this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoRes(responses) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let responsesTotalLen = 0; - let responseLens; - - if (responses) { - responseLens = new Array(responses.length); - for (let i = 0; i < responses.length; ++i) { - const len = Buffer.byteLength(responses[i]); - responseLens[i] = len; - responsesTotalLen += 4 + len; - } - } - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); - - packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; - - if (responses) { - writeUInt32BE(packet, responses.length, ++p); - p += 4; - for (let i = 0; i < responses.length; ++i) { - const len = responseLens[i]; - writeUInt32BE(packet, len, p); - p += 4; - if (len) { - packet.utf8Write(responses[i], p, len); - p += len; - } - } - } else { - writeUInt32BE(packet, 0, ++p); - } - - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // 'ssh-connection' service-specific - // --------------------------------- - tcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 13, ++p); - packet.utf8Write('tcpip-forward', p += 4, 13); - - packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); - - writeUInt32BE(packet, bindPort, p += addrLen); - - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - cancelTcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 20, ++p); - packet.utf8Write('cancel-tcpip-forward', p += 4, 20); - - packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); - - writeUInt32BE(packet, bindPort, p += addrLen); - - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_streamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 31 + 1 + 4 + socketPathLen - ); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 31, ++p); - packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31); - - packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); - - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_cancelStreamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 38 + 1 + 4 + socketPathLen - ); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 38, ++p); - packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38); - - packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); - - if (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST ' - + '(cancel-streamlocal-forward@openssh.com)' - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - directTcpip(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const srcLen = Buffer.byteLength(cfg.srcIP); - const dstLen = Buffer.byteLength(cfg.dstIP); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 12, ++p); - packet.utf8Write('direct-tcpip', p += 4, 12); - - writeUInt32BE(packet, chan, p += 12); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, dstLen, p += 4); - packet.utf8Write(cfg.dstIP, p += 4, dstLen); - - writeUInt32BE(packet, cfg.dstPort, p += dstLen); - - writeUInt32BE(packet, srcLen, p += 4); - packet.utf8Write(cfg.srcIP, p += 4, srcLen); - - writeUInt32BE(packet, cfg.srcPort, p += srcLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 30, ++p); - packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30); - - writeUInt32BE(packet, chan, p += 30); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); - - // zero-fill reserved fields (string and uint32) - bufferFill(packet, 0, p += pathLen, p + 8); - - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, direct-streamlocal@openssh.com)` - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_noMoreSessions(wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 28, ++p); - packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28); - - packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0); - - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - session(chan, initWindow, maxPacket) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 7, ++p); - packet.utf8Write('session', p += 4, 7); - - writeUInt32BE(packet, chan, p += 7); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - windowChange(chan, rows, cols, height, width) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 13, p += 4); - packet.utf8Write('window-change', p += 4, 13); - - packet[p += 13] = 0; - - writeUInt32BE(packet, cols, ++p); - - writeUInt32BE(packet, rows, p += 4); - - writeUInt32BE(packet, width, p += 4); - - writeUInt32BE(packet, height, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - pty(chan, rows, cols, height, width, term, modes, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - if (!term || !term.length) - term = 'vt100'; - if (modes - && !Buffer.isBuffer(modes) - && !Array.isArray(modes) - && typeof modes === 'object' - && modes !== null) { - modes = modesToBytes(modes); - } - if (!modes || !modes.length) - modes = NO_TERMINAL_MODES_BUFFER; - - const termLen = term.length; - const modesLen = modes.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('pty-req', p += 4, 7); - - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, termLen, ++p); - packet.utf8Write(term, p += 4, termLen); - - writeUInt32BE(packet, cols, p += termLen); - - writeUInt32BE(packet, rows, p += 4); - - writeUInt32BE(packet, width, p += 4); - - writeUInt32BE(packet, height, p += 4); - - writeUInt32BE(packet, modesLen, p += 4); - p += 4; - if (Array.isArray(modes)) { - for (let i = 0; i < modesLen; ++i) - packet[p++] = modes[i]; - } else if (Buffer.isBuffer(modes)) { - packet.set(modes, p); - } - - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - shell(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 5, p += 4); - packet.utf8Write('shell', p += 4, 5); - - packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exec(chan, cmd, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const isBuf = Buffer.isBuffer(cmd); - const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 4, p += 4); - packet.utf8Write('exec', p += 4, 4); - - packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, cmdLen, ++p); - if (isBuf) - packet.set(cmd, p += 4); - else - packet.utf8Write(cmd, p += 4, cmdLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - signal(chan, signal) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const origSignal = signal; - - signal = signal.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); - - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); - - const signalLen = signal.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 6 + 1 + 4 + signalLen - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 6, p += 4); - packet.utf8Write('signal', p += 4, 6); - - packet[p += 6] = 0; - - writeUInt32BE(packet, signalLen, ++p); - packet.utf8Write(signal, p += 4, signalLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - env(chan, key, val, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const keyLen = Buffer.byteLength(key); - const isBuf = Buffer.isBuffer(val); - const valLen = (isBuf ? val.length : Buffer.byteLength(val)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 3, p += 4); - packet.utf8Write('env', p += 4, 3); - - packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, keyLen, ++p); - packet.utf8Write(key, p += 4, keyLen); - - writeUInt32BE(packet, valLen, p += keyLen); - if (isBuf) - packet.set(val, p += 4); - else - packet.utf8Write(val, p += 4, valLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11Forward(chan, cfg, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const protocol = cfg.protocol; - const cookie = cfg.cookie; - const isBufProto = Buffer.isBuffer(protocol); - const protoLen = (isBufProto - ? protocol.length - : Buffer.byteLength(protocol)); - const isBufCookie = Buffer.isBuffer(cookie); - const cookieLen = (isBufCookie - ? cookie.length - : Buffer.byteLength(cookie)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('x11-req', p += 4, 7); - - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); - - packet[++p] = (cfg.single ? 1 : 0); - - writeUInt32BE(packet, protoLen, ++p); - if (isBufProto) - packet.set(protocol, p += 4); - else - packet.utf8Write(protocol, p += 4, protoLen); - - writeUInt32BE(packet, cookieLen, p += protoLen); - if (isBufCookie) - packet.set(cookie, p += 4); - else - packet.latin1Write(cookie, p += 4, cookieLen); - - writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - subsystem(chan, name, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 9, p += 4); - packet.utf8Write('subsystem', p += 4, 9); - - packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_agentForward(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 26, p += 4); - packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26); - - packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0); - - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_REQUEST ' - + `(r:${chan}, auth-agent-req@openssh.com)` - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_hostKeysProve(keys) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let keysTotal = 0; - const publicKeys = []; - for (const key of keys) { - const publicKey = key.getPublicSSH(); - keysTotal += 4 + publicKey.length; - publicKeys.push(publicKey); - } - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 29, ++p); - packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); - - packet[p += 29] = 1; // want reply - - ++p; - for (const buf of publicKeys) { - writeUInt32BE(packet, buf.length, p); - bufferCopy(buf, packet, 0, buf.length, p += 4); - p += buf.length; - } - - if (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)' - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - - // Global - // ------ - serviceAccept(svcName) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const svcNameLen = Buffer.byteLength(svcName); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); - - packet[p] = MESSAGE.SERVICE_ACCEPT; - - writeUInt32BE(packet, svcNameLen, ++p); - packet.utf8Write(svcName, p += 4, svcNameLen); - - this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - - if (this._server && this._banner && svcName === 'ssh-userauth') { - const banner = this._banner; - this._banner = undefined; // Prevent banner from being displayed again - const bannerLen = Buffer.byteLength(banner); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); - - packet[p] = MESSAGE.USERAUTH_BANNER; - - writeUInt32BE(packet, bannerLen, ++p); - packet.utf8Write(banner, p += 4, bannerLen); - - writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag - - this._debug && this._debug('Outbound: Sending USERAUTH_BANNER'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - } - // 'ssh-connection' service-specific - forwardedTcpip(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const boundAddrLen = Buffer.byteLength(cfg.boundAddr); - const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 15, ++p); - packet.utf8Write('forwarded-tcpip', p += 4, 15); - - writeUInt32BE(packet, chan, p += 15); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, boundAddrLen, p += 4); - packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); - - writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); - - writeUInt32BE(packet, remoteAddrLen, p += 4); - packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); - - writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const addrLen = Buffer.byteLength(cfg.originAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 3, ++p); - packet.utf8Write('x11', p += 4, 3); - - writeUInt32BE(packet, chan, p += 3); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, addrLen, p += 4); - packet.utf8Write(cfg.originAddr, p += 4, addrLen); - - writeUInt32BE(packet, cfg.originPort, p += addrLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_authAgent(chan, initWindow, maxPacket) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 22, ++p); - packet.utf8Write('auth-agent@openssh.com', p += 4, 22); - - writeUInt32BE(packet, chan, p += 22); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 33, ++p); - packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33); - - writeUInt32BE(packet, chan, p += 33); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); - - writeUInt32BE(packet, 0, p += pathLen); - - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, forwarded-streamlocal@openssh.com)` - ); - } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exitStatus(chan, status) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - // Does not consume window space - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-status', p += 4, 11); - - packet[p += 11] = 0; - - writeUInt32BE(packet, status, ++p); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exitSignal(chan, name, coreDumped, msg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - // Does not consume window space - - const origSignal = name; - - if (typeof origSignal !== 'string' || !origSignal) - throw new Error(`Invalid signal: ${origSignal}`); - - let signal = name.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); - - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); - - const nameLen = Buffer.byteLength(signal); - const msgLen = (msg ? Buffer.byteLength(msg) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-signal', p += 4, 11); - - packet[p += 11] = 0; - - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(signal, p += 4, nameLen); - - packet[p += nameLen] = (coreDumped ? 1 : 0); - - writeUInt32BE(packet, msgLen, ++p); - - p += 4; - if (msgLen) { - packet.utf8Write(msg, p, msgLen); - p += msgLen; - } - - writeUInt32BE(packet, 0, p); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - // 'ssh-userauth' service-specific - authFailure(authMethods, isPartial) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); - - let methods; - - if (typeof authMethods === 'boolean') { - isPartial = authMethods; - authMethods = undefined; - } - - if (authMethods) { - methods = []; - for (let i = 0; i < authMethods.length; ++i) { - if (authMethods[i].toLowerCase() === 'none') - continue; - methods.push(authMethods[i]); - } - methods = methods.join(','); - } else { - methods = ''; - } - - const methodsLen = methods.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); - - packet[p] = MESSAGE.USERAUTH_FAILURE; - - writeUInt32BE(packet, methodsLen, ++p); - packet.utf8Write(methods, p += 4, methodsLen); - - packet[p += methodsLen] = (isPartial === true ? 1 : 0); - - this._authsQueue.shift(); - - this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authSuccess() { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); - - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.USERAUTH_SUCCESS; - - this._authsQueue.shift(); - this._authenticated = true; - - this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); - - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - } - authPKOK(keyAlgo, key) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey') - throw new Error('"publickey" auth not in progress'); - - // TODO: support parsed key for `key` - - const keyAlgoLen = Buffer.byteLength(keyAlgo); - const keyLen = key.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); - - packet[p] = MESSAGE.USERAUTH_PK_OK; - - writeUInt32BE(packet, keyAlgoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); - - writeUInt32BE(packet, keyLen, p += keyAlgoLen); - packet.set(key, p += 4); - - this._authsQueue.shift(); - - this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPasswdChg(prompt) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const promptLen = Buffer.byteLength(prompt); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); - - packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; - - writeUInt32BE(packet, promptLen, ++p); - packet.utf8Write(prompt, p += 4, promptLen); - - writeUInt32BE(packet, 0, p += promptLen); // Empty language tag - - this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoReq(name, instructions, prompts) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - let promptsLen = 0; - const nameLen = name ? Buffer.byteLength(name) : 0; - const instrLen = instructions ? Buffer.byteLength(instructions) : 0; - - for (let i = 0; i < prompts.length; ++i) - promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen - ); - - packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; - - writeUInt32BE(packet, nameLen, ++p); - p += 4; - if (name) { - packet.utf8Write(name, p, nameLen); - p += nameLen; - } - - writeUInt32BE(packet, instrLen, p); - p += 4; - if (instructions) { - packet.utf8Write(instructions, p, instrLen); - p += instrLen; - } - - writeUInt32BE(packet, 0, p); - - writeUInt32BE(packet, prompts.length, p += 4); - p += 4; - for (let i = 0; i < prompts.length; ++i) { - const prompt = prompts[i]; - const promptLen = Buffer.byteLength(prompt.prompt); - - writeUInt32BE(packet, promptLen, p); - p += 4; - if (promptLen) { - packet.utf8Write(prompt.prompt, p, promptLen); - p += promptLen; - } - packet[p++] = (prompt.echo ? 1 : 0); - } - - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } -} - -// SSH-protoversion-softwareversion (SP comments) CR LF -const RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; - -// TODO: optimize this by starting n bytes from the end of this._buffer instead -// of the beginning -function parseHeader(chunk, p, len) { - let data; - let chunkOffset; - if (this._buffer) { - data = Buffer.allocUnsafe(this._buffer.length + (len - p)); - data.set(this._buffer, 0); - if (p === 0) { - data.set(chunk, this._buffer.length); - } else { - data.set(new Uint8Array(chunk.buffer, - chunk.byteOffset + p, - (len - p)), - this._buffer.length); - } - chunkOffset = this._buffer.length; - p = 0; - } else { - data = chunk; - chunkOffset = 0; - } - const op = p; - let start = p; - let end = p; - let needNL = false; - let lineLen = 0; - let lines = 0; - for (; p < data.length; ++p) { - const ch = data[p]; - - if (ch === 13 /* '\r' */) { - needNL = true; - continue; - } - - if (ch === 10 /* '\n' */) { - if (end > start - && end - start > 4 - && data[start] === 83 /* 'S' */ - && data[start + 1] === 83 /* 'S' */ - && data[start + 2] === 72 /* 'H' */ - && data[start + 3] === 45 /* '-' */) { - - const full = data.latin1Slice(op, end + 1); - const identRaw = (start === op ? full : full.slice(start - op)); - const m = RE_IDENT.exec(identRaw); - if (!m) - throw new Error('Invalid identification string'); - - const header = { - greeting: (start === op ? '' : full.slice(0, start - op)), - identRaw, - versions: { - protocol: m[1], - software: m[2], - }, - comments: m[3] - }; - - // Needed during handshake - this._remoteIdentRaw = Buffer.from(identRaw); - - this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); - this._compatFlags = getCompatFlags(header); - - this._buffer = undefined; - this._decipher = - new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); - this._parse = parsePacket; - - this._onHeader(header); - if (!this._destruct) { - // We disconnected inside _onHeader - return len; - } - - kexinit(this); - - return p + 1 - chunkOffset; - } - - // Only allow pre-ident greetings when we're a client - if (this._server) - throw new Error('Greetings from clients not permitted'); - - if (++lines > MAX_LINES) - throw new Error('Max greeting lines exceeded'); - - needNL = false; - start = p + 1; - lineLen = 0; - } else if (needNL) { - throw new Error('Invalid header: expected newline'); - } else if (++lineLen >= MAX_LINE_LEN) { - throw new Error('Header line too long'); - } - - end = p; - } - if (!this._buffer) - this._buffer = bufferSlice(data, op); - - return p - chunkOffset; -} - -function parsePacket(chunk, p, len) { - return this._decipher.decrypt(chunk, p, len); -} - -function onPayload(payload) { - // XXX: move this to the Decipher implementations? - - this._onPacket(); - - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; - } - - payload = this._packetRW.read.read(payload); - - const type = payload[0]; - if (type === MESSAGE.USERAUTH_SUCCESS - && !this._server - && !this._authenticated) { - this._authenticated = true; - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); - } - const handler = MESSAGE_HANDLERS[type]; - if (handler === undefined) { - this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); - return; - } - - return handler(this, payload); -} - -function getCompatFlags(header) { - const software = header.versions.software; - - let flags = 0; - - for (const rule of COMPAT_CHECKS) { - if (typeof rule[0] === 'string') { - if (software === rule[0]) - flags |= rule[1]; - } else if (rule[0].test(software)) { - flags |= rule[1]; - } - } - - return flags; -} - -function modesToBytes(modes) { - const keys = Object.keys(modes); - const bytes = Buffer.allocUnsafe((5 * keys.length) + 1); - let b = 0; - - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (key === 'TTY_OP_END') - continue; - - const opcode = TERMINAL_MODE[key]; - if (opcode === undefined) - continue; - - const val = modes[key]; - if (typeof val === 'number' && isFinite(val)) { - bytes[b++] = opcode; - bytes[b++] = val >>> 24; - bytes[b++] = val >>> 16; - bytes[b++] = val >>> 8; - bytes[b++] = val; - } - } - - bytes[b++] = TERMINAL_MODE.TTY_OP_END; - - if (b < bytes.length) - return bufferSlice(bytes, 0, b); - - return bytes; -} - -module.exports = Protocol; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/SFTP.js b/reverse_engineering/node_modules/ssh2/lib/protocol/SFTP.js deleted file mode 100644 index b10d9e5..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/SFTP.js +++ /dev/null @@ -1,3778 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'); -const fs = require('fs'); -const { constants } = fs; -const { - Readable: ReadableStream, - Writable: WritableStream -} = require('stream'); -const { inherits, isDate } = require('util'); - -const FastBuffer = Buffer[Symbol.species]; - -const { - bufferCopy, - bufferSlice, - makeBufferParser, - writeUInt32BE, -} = require('./utils.js'); - -const ATTR = { - SIZE: 0x00000001, - UIDGID: 0x00000002, - PERMISSIONS: 0x00000004, - ACMODTIME: 0x00000008, - EXTENDED: 0x80000000, -}; - -// Large enough to store all possible attributes -const ATTRS_BUF = Buffer.alloc(28); - -const STATUS_CODE = { - OK: 0, - EOF: 1, - NO_SUCH_FILE: 2, - PERMISSION_DENIED: 3, - FAILURE: 4, - BAD_MESSAGE: 5, - NO_CONNECTION: 6, - CONNECTION_LOST: 7, - OP_UNSUPPORTED: 8 -}; - -const VALID_STATUS_CODES = new Map( - Object.values(STATUS_CODE).map((n) => [n, 1]) -); - -const STATUS_CODE_STR = { - [STATUS_CODE.OK]: 'No error', - [STATUS_CODE.EOF]: 'End of file', - [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory', - [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied', - [STATUS_CODE.FAILURE]: 'Failure', - [STATUS_CODE.BAD_MESSAGE]: 'Bad message', - [STATUS_CODE.NO_CONNECTION]: 'No connection', - [STATUS_CODE.CONNECTION_LOST]: 'Connection lost', - [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported', -}; - -const REQUEST = { - INIT: 1, - OPEN: 3, - CLOSE: 4, - READ: 5, - WRITE: 6, - LSTAT: 7, - FSTAT: 8, - SETSTAT: 9, - FSETSTAT: 10, - OPENDIR: 11, - READDIR: 12, - REMOVE: 13, - MKDIR: 14, - RMDIR: 15, - REALPATH: 16, - STAT: 17, - RENAME: 18, - READLINK: 19, - SYMLINK: 20, - EXTENDED: 200 -}; - -const RESPONSE = { - VERSION: 2, - STATUS: 101, - HANDLE: 102, - DATA: 103, - NAME: 104, - ATTRS: 105, - EXTENDED: 201 -}; - -const OPEN_MODE = { - READ: 0x00000001, - WRITE: 0x00000002, - APPEND: 0x00000004, - CREAT: 0x00000008, - TRUNC: 0x00000010, - EXCL: 0x00000020 -}; - -const PKT_RW_OVERHEAD = 2 * 1024; -const MAX_REQID = 2 ** 32 - 1; -const CLIENT_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - REQUEST.INIT, - 0, 0, 0, 3 /* version */ -]); -const SERVER_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - RESPONSE.VERSION, - 0, 0, 0, 3 /* version */ -]); - -const RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; -const OPENSSH_MAX_PKT_LEN = 256 * 1024; - -const bufferParser = makeBufferParser(); - -const fakeStderr = { - readable: false, - writable: false, - push: (data) => {}, - once: () => {}, - on: () => {}, - emit: () => {}, - end: () => {}, -}; - -function noop() {} - -// Emulates enough of `Channel` to be able to be used as a drop-in replacement -// in order to process incoming data with as little overhead as possible -class SFTP extends EventEmitter { - constructor(client, chanInfo, cfg) { - super(); - - if (typeof cfg !== 'object' || !cfg) - cfg = {}; - - const remoteIdentRaw = client._protocol._remoteIdentRaw; - - this.server = !!cfg.server; - this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw)); - - this._version = -1; - this._extensions = {}; - this._biOpt = cfg.biOpt; - this._pktLenBytes = 0; - this._pktLen = 0; - this._pktPos = 0; - this._pktType = 0; - this._pktData = undefined; - this._writeReqid = -1; - this._requests = {}; - this._maxInPktLen = OPENSSH_MAX_PKT_LEN; - this._maxOutPktLen = 34000; - this._maxReadLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; - this._maxWriteLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; - - this.maxOpenHandles = undefined; - - // Channel compatibility - this._client = client; - this._protocol = client._protocol; - this._callbacks = []; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; - this._waitWindow = false; // SSH-level backpressure - this._chunkcb = undefined; - this._buffer = []; - this.type = chanInfo.type; - this.subtype = undefined; - this.incoming = chanInfo.incoming; - this.outgoing = chanInfo.outgoing; - this.stderr = fakeStderr; - this.readable = true; - } - - // This handles incoming data to parse - push(data) { - if (data === null) { - cleanupRequests(this); - if (!this.readable) - return; - // No more incoming data from the remote side - this.readable = false; - this.emit('end'); - return; - } - /* - uint32 length - byte type - byte[length - 1] data payload - */ - let p = 0; - - while (p < data.length) { - if (this._pktLenBytes < 4) { - let nb = Math.min(4 - this._pktLenBytes, data.length - p); - this._pktLenBytes += nb; - - while (nb--) - this._pktLen = (this._pktLen << 8) + data[p++]; - - if (this._pktLenBytes < 4) - return; - if (this._pktLen === 0) - return doFatalSFTPError(this, 'Invalid packet length'); - if (this._pktLen > this._maxInPktLen) { - const max = this._maxInPktLen; - return doFatalSFTPError( - this, - `Packet length ${this._pktLen} exceeds max length of ${max}` - ); - } - if (p >= data.length) - return; - } - if (this._pktPos < this._pktLen) { - const nb = Math.min(this._pktLen - this._pktPos, data.length - p); - if (p !== 0 || nb !== data.length) { - if (nb === this._pktLen) { - this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._pktPos - ); - } - } else if (nb === this._pktLen) { - this._pkt = data; - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set(data, this._pktPos); - } - p += nb; - this._pktPos += nb; - if (this._pktPos < this._pktLen) - return; - } - - const type = this._pkt[0]; - const payload = this._pkt; - - // Prepare for next packet - this._pktLen = 0; - this._pktLenBytes = 0; - this._pkt = undefined; - this._pktPos = 0; - - const handler = (this.server - ? SERVER_HANDLERS[type] - : CLIENT_HANDLERS[type]); - if (!handler) - return doFatalSFTPError(this, `Unknown packet type ${type}`); - - if (this._version === -1) { - if (this.server) { - if (type !== REQUEST.INIT) - return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); - } else if (type !== RESPONSE.VERSION) { - return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); - } - } - - if (handler(this, payload) === false) - return; - } - } - - end() { - this.destroy(); - } - destroy() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._protocol.channelClose(this.outgoing.id); - } - } - _init() { - this._init = noop; - if (!this.server) - sendOrBuffer(this, CLIENT_VERSION_BUFFER); - } - - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - createReadStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - return new ReadStream(this, path, options); - } - createWriteStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - return new WriteStream(this, path, options); - } - open(path, flags_, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; - } - - const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_)); - if (flags === null) - throw new Error(`Unknown flags string: ${flags_}`); - - let attrsFlags = 0; - let attrsLen = 0; - if (typeof attrs === 'string' || typeof attrs === 'number') - attrs = { mode: attrs }; - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - attrsFlags = attrs.flags; - attrsLen = attrs.nb; - } - - /* - uint32 id - string filename - uint32 pflags - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPEN; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - writeUInt32BE(buf, attrsFlags, p += 4); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN` - ); - } - close(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.CLOSE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE` - ); - } - read(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off >= buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); - - read_(this, handle, buf, off, len, position, cb); - } - readData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.read(handle, buf, off, len, position, cb); - } - write(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off > buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); - - if (!len) { - cb && process.nextTick(cb, undefined, 0); - return; - } - - const maxDataLen = this._maxWriteLen; - const overflow = Math.max(len - maxDataLen, 0); - const origPosition = position; - - if (overflow) - len = maxDataLen; - - /* - uint32 id - string handle - uint64 offset - string data - */ - const handleLen = handle.length; - let p = 9; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); - - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.WRITE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); - - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = position & 0xFF; - position /= 256; - } - writeUInt32BE(out, len, p += 8); - bufferCopy(buf, out, off, off + len, p += 4); - - this._requests[reqid] = { - cb: (err) => { - if (err) { - if (typeof cb === 'function') - cb(err); - } else if (overflow) { - this.write(handle, - buf, - off + len, - overflow, - origPosition + len, - cb); - } else if (typeof cb === 'function') { - cb(undefined, off + len); - } - } - }; - - const isSent = sendOrBuffer(this, out); - if (this._debug) { - const how = (isSent ? 'Sent' : 'Buffered'); - this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); - } - } - writeData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.write(handle, buf, off, len, position, cb); - } - fastGet(remotePath, localPath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - fastXfer(this, fs, remotePath, localPath, opts, cb); - } - fastPut(localPath, remotePath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - fastXfer(fs, this, localPath, remotePath, opts, cb); - } - readFile(path, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; - } - - if (typeof options === 'string') - options = { encoding: options, flag: 'r' }; - else if (!options) - options = { encoding: null, flag: 'r' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - const encoding = options.encoding; - if (encoding && !Buffer.isEncoding(encoding)) - throw new Error(`Unknown encoding: ${encoding}`); - - // First stat the file, so we know the size. - let size; - let buffer; // Single buffer with file data - let buffers; // List for when size is unknown - let pos = 0; - let handle; - - // SFTPv3 does not support using -1 for read position, so we have to track - // read position manually - let bytesRead = 0; - - const flag = options.flag || 'r'; - - const read = () => { - if (size === 0) { - buffer = Buffer.allocUnsafe(8192); - this.read(handle, buffer, 0, 8192, bytesRead, afterRead); - } else { - this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); - } - }; - - const afterRead = (er, nbytes) => { - let eof; - if (er) { - eof = (er.code === STATUS_CODE.EOF); - if (!eof) { - return this.close(handle, () => { - return callback && callback(er); - }); - } - } else { - eof = false; - } - - if (eof || (size === 0 && nbytes === 0)) - return close(); - - bytesRead += nbytes; - pos += nbytes; - if (size !== 0) { - if (pos === size) - close(); - else - read(); - } else { - // Unknown size, just read until we don't get bytes. - buffers.push(bufferSlice(buffer, 0, nbytes)); - read(); - } - }; - afterRead._wantEOFError = true; - - const close = () => { - this.close(handle, (er) => { - if (size === 0) { - // Collect the data into the buffers list. - buffer = Buffer.concat(buffers, pos); - } else if (pos < size) { - buffer = bufferSlice(buffer, 0, pos); - } - - if (encoding) - buffer = buffer.toString(encoding); - return callback && callback(er, buffer); - }); - }; - - this.open(path, flag, 0o666, (er, handle_) => { - if (er) - return callback && callback(er); - handle = handle_; - - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; - } - - size = st.size || 0; - if (size === 0) { - // The kernel lies about many files. - // Go ahead and try to read some bytes. - buffers = []; - return read(); - } - - buffer = Buffer.allocUnsafe(size); - read(); - }; - this.fstat(handle, tryStat); - }); - } - writeFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; - } - - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'w' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - if (options.encoding && !Buffer.isEncoding(options.encoding)) - throw new Error(`Unknown encoding: ${options.encoding}`); - - const flag = options.flag || 'w'; - this.open(path, flag, options.mode, (openErr, handle) => { - if (openErr) { - callback && callback(openErr); - } else { - const buffer = (Buffer.isBuffer(data) - ? data - : Buffer.from('' + data, options.encoding || 'utf8')); - const position = (/a/.test(flag) ? null : 0); - - // SFTPv3 does not support the notion of 'current position' - // (null position), so we just attempt to append to the end of the file - // instead - if (position === null) { - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; - } - writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); - }; - this.fstat(handle, tryStat); - return; - } - writeAll(this, handle, buffer, 0, buffer.length, position, callback); - } - }); - } - appendFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; - } - - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'a' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - if (!options.flag) - options = Object.assign({ flag: 'a' }, options); - this.writeFile(path, data, options, callback); - } - exists(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - this.stat(path, (err) => { - cb && cb(err ? false : true); - }); - } - unlink(filename, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string filename - */ - const fnameLen = Buffer.byteLength(filename); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REMOVE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, fnameLen, p); - buf.utf8Write(filename, p += 4, fnameLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE` - ); - } - rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RENAME; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, oldLen, p); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME` - ); - } - mkdir(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; - } - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } - - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.MKDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR` - ); - } - rmdir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RMDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR` - ); - } - readdir(where, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - if (typeof opts !== 'object' || opts === null) - opts = {}; - - const doFilter = (opts && opts.full ? false : true); - - if (!Buffer.isBuffer(where) && typeof where !== 'string') - throw new Error('missing directory handle or path'); - - if (typeof where === 'string') { - const entries = []; - let e = 0; - - const reread = (err, handle) => { - if (err) - return cb(err); - - this.readdir(handle, opts, (err, list) => { - const eof = (err && err.code === STATUS_CODE.EOF); - - if (err && !eof) - return this.close(handle, () => cb(err)); - - if (eof) { - return this.close(handle, (err) => { - if (err) - return cb(err); - cb(undefined, entries); - }); - } - - for (let i = 0; i < list.length; ++i, ++e) - entries[e] = list[i]; - - reread(undefined, handle); - }); - }; - return this.opendir(where, reread); - } - - /* - uint32 id - string handle - */ - const handleLen = where.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(where, p += 4); - - this._requests[reqid] = { - cb: (doFilter - ? (err, list) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - - for (let i = list.length - 1; i >= 0; --i) { - if (list[i].filename === '.' || list[i].filename === '..') - list.splice(i, 1); - } - - cb(undefined, list); - } - : cb) - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR` - ); - } - fstat(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT` - ); - } - stat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.STAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT` - ); - } - lstat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.LSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT` - ); - } - opendir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPENDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR` - ); - } - setstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } - - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT` - ); - } - fsetstat(handle, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } - - /* - uint32 id - string handle - ATTRS attrs - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - writeUInt32BE(buf, flags, p += handleLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT` - ); - } - futimes(handle, atime, mtime, cb) { - return this.fsetstat(handle, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - utimes(path, atime, mtime, cb) { - return this.setstat(path, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - fchown(handle, uid, gid, cb) { - return this.fsetstat(handle, { - uid: uid, - gid: gid - }, cb); - } - chown(path, uid, gid, cb) { - return this.setstat(path, { - uid: uid, - gid: gid - }, cb); - } - fchmod(handle, mode, cb) { - return this.fsetstat(handle, { - mode: mode - }, cb); - } - chmod(path, mode, cb) { - return this.setstat(path, { - mode: mode - }, cb); - } - readlink(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing link info')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK` - ); - } - symlink(targetPath, linkPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string linkpath - string targetpath - */ - const linkLen = Buffer.byteLength(linkPath); - const targetLen = Buffer.byteLength(targetPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SYMLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - if (this._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - writeUInt32BE(buf, targetLen, p); - buf.utf8Write(targetPath, p += 4, targetLen); - writeUInt32BE(buf, linkLen, p += targetLen); - buf.utf8Write(linkPath, p += 4, linkLen); - } else { - writeUInt32BE(buf, linkLen, p); - buf.utf8Write(linkPath, p += 4, linkLen); - writeUInt32BE(buf, targetLen, p += linkLen); - buf.utf8Write(targetPath, p += 4, targetLen); - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK` - ); - } - realpath(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REALPATH; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing path info')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH` - ); - } - // extended requests - ext_openssh_rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['posix-rename@openssh.com']; - if (!ext || ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "posix-rename@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 24, p); - buf.utf8Write('posix-rename@openssh.com', p += 4, 24); - writeUInt32BE(buf, oldLen, p += 24); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); - } - } - ext_openssh_statvfs(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['statvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "statvfs@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 19, p); - buf.utf8Write('statvfs@openssh.com', p += 4, 19); - writeUInt32BE(buf, pathLen, p += 19); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { extended: 'statvfs@openssh.com', cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); - } - } - ext_openssh_fstatvfs(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['fstatvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string "fstatvfs@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 20, p); - buf.utf8Write('fstatvfs@openssh.com', p += 4, 20); - writeUInt32BE(buf, handleLen, p += 20); - buf.set(handle, p += 4); - - this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); - } - } - ext_openssh_hardlink(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['hardlink@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "hardlink@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 20, p); - buf.utf8Write('hardlink@openssh.com', p += 4, 20); - writeUInt32BE(buf, oldLen, p += 20); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); - } - } - ext_openssh_fsync(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['fsync@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string "fsync@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 17, p); - buf.utf8Write('fsync@openssh.com', p += 4, 17); - writeUInt32BE(buf, handleLen, p += 17); - buf.set(handle, p += 4); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com` - ); - } - ext_openssh_lsetstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['lsetstat@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } - - /* - uint32 id - string "lsetstat@openssh.com" - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 20, p); - buf.utf8Write('lsetstat@openssh.com', p += 4, 20); - - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); - - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); - } - } - ext_openssh_expandPath(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['expand-path@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "expand-path@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 23, p); - buf.utf8Write('expand-path@openssh.com', p += 4, 23); - - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); - } - } - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - handle(reqid, handle) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - const handleLen = handle.length; - - if (handleLen > 256) - throw new Error('handle too large (> 256 bytes)'); - - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.HANDLE; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - if (handleLen) - buf.set(handle, p += 4); - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE` - ); - } - status(reqid, code, message) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!VALID_STATUS_CODES.has(code)) - throw new Error(`Bad status code: ${code}`); - - message || (message = ''); - - const msgLen = Buffer.byteLength(message); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.STATUS; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, code, p); - - writeUInt32BE(buf, msgLen, p += 4); - p += 4; - if (msgLen) { - buf.utf8Write(message, p, msgLen); - p += msgLen; - } - - writeUInt32BE(buf, 0, p); // Empty language tag - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS` - ); - } - data(reqid, data, encoding) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - const isBuffer = Buffer.isBuffer(data); - - if (!isBuffer && typeof data !== 'string') - throw new Error('data is not a Buffer or string'); - - let isUTF8; - if (!isBuffer && !encoding) { - encoding = undefined; - isUTF8 = true; - } - - const dataLen = ( - isBuffer - ? data.length - : Buffer.byteLength(data, encoding) - ); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.DATA; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, dataLen, p); - if (dataLen) { - if (isBuffer) - buf.set(data, p += 4); - else if (isUTF8) - buf.utf8Write(data, p += 4, dataLen); - else - buf.write(data, p += 4, dataLen, encoding); - } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA` - ); - } - name(reqid, names) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!Array.isArray(names)) { - if (typeof names !== 'object' || names === null) - throw new Error('names is not an object or array'); - names = [ names ]; - } - - const count = names.length; - let namesLen = 0; - let nameAttrs; - const attrs = []; - - for (let i = 0; i < count; ++i) { - const name = names[i]; - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - namesLen += 4 + Buffer.byteLength(filename); - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - namesLen += 4 + Buffer.byteLength(longname); - - if (typeof name.attrs === 'object' && name.attrs !== null) { - nameAttrs = attrsToBytes(name.attrs); - namesLen += 4 + nameAttrs.nb; - - if (nameAttrs.nb) { - let bytes; - - if (nameAttrs.nb === ATTRS_BUF.length) { - bytes = new Uint8Array(ATTRS_BUF); - } else { - bytes = new Uint8Array(nameAttrs.nb); - bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); - } - - nameAttrs.bytes = bytes; - } - - attrs.push(nameAttrs); - } else { - namesLen += 4; - attrs.push(null); - } - } - - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.NAME; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, count, p); - - p += 4; - - for (let i = 0; i < count; ++i) { - const name = names[i]; - - { - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - const len = Buffer.byteLength(filename); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(filename, p, len); - p += len; - } - } - - { - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - const len = Buffer.byteLength(longname); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(longname, p, len); - p += len; - } - } - - const attr = attrs[i]; - if (attr) { - writeUInt32BE(buf, attr.flags, p); - p += 4; - if (attr.flags && attr.bytes) { - buf.set(attr.bytes, p); - p += attr.nb; - } - } else { - writeUInt32BE(buf, 0, p); - p += 4; - } - } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME` - ); - } - attrs(reqid, attrs) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (typeof attrs !== 'object' || attrs === null) - throw new Error('attrs is not an object'); - - attrs = attrsToBytes(attrs); - const flags = attrs.flags; - const attrsLen = attrs.nb; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.ATTRS; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, flags, p); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS` - ); - } -} - -function tryCreateBuffer(size) { - try { - return Buffer.allocUnsafe(size); - } catch (ex) { - return ex; - } -} - -function read_(self, handle, buf, off, len, position, cb, req_) { - const maxDataLen = self._maxReadLen; - const overflow = Math.max(len - maxDataLen, 0); - - if (overflow) - len = maxDataLen; - - /* - uint32 id - string handle - uint64 offset - uint32 len - */ - const handleLen = handle.length; - let p = 9; - let pos = position; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); - - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.READ; - const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); - - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = pos & 0xFF; - pos /= 256; - } - writeUInt32BE(out, len, p += 8); - - if (typeof cb !== 'function') - cb = noop; - - const req = (req_ || { - nb: 0, - position, - off, - origOff: off, - len: undefined, - overflow: undefined, - cb: (err, data, nb) => { - const len = req.len; - const overflow = req.overflow; - - if (err) { - if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) - return cb(err); - } else if (nb > len) { - return cb(new Error('Received more data than requested')); - } else if (nb === len && overflow) { - req.nb += nb; - req.position += nb; - req.off += nb; - read_(self, handle, buf, req.off, overflow, req.position, cb, req); - return; - } - - if (req.origOff === 0 && buf.length === req.nb) - data = buf; - else - data = bufferSlice(buf, req.origOff, req.origOff + req.nb); - cb(undefined, req.nb + (nb || 0), data, req.position); - }, - buffer: undefined, - }); - - req.len = len; - req.overflow = overflow; - - // TODO: avoid creating multiple buffer slices when we need to re-call read_() - // because of overflow - req.buffer = bufferSlice(buf, off, off + len); - - self._requests[reqid] = req; - - const isBuffered = sendOrBuffer(self, out); - self._debug && self._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ` - ); -} - -function fastXfer(src, dst, srcPath, dstPath, opts, cb) { - let concurrency = 64; - let chunkSize = 32768; - let onstep; - let mode; - let fileSize; - - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.concurrency === 'number' - && opts.concurrency > 0 - && !isNaN(opts.concurrency)) { - concurrency = opts.concurrency; - } - if (typeof opts.chunkSize === 'number' - && opts.chunkSize > 0 - && !isNaN(opts.chunkSize)) { - chunkSize = opts.chunkSize; - } - if (typeof opts.fileSize === 'number' - && opts.fileSize > 0 - && !isNaN(opts.fileSize)) { - fileSize = opts.fileSize; - } - if (typeof opts.step === 'function') - onstep = opts.step; - - if (typeof opts.mode === 'string' || typeof opts.mode === 'number') - mode = modeNum(opts.mode); - } - - // Internal state variables - let fsize; - let pdst = 0; - let total = 0; - let hadError = false; - let srcHandle; - let dstHandle; - let readbuf; - let bufsize = chunkSize * concurrency; - - function onerror(err) { - if (hadError) - return; - - hadError = true; - - let left = 0; - let cbfinal; - - if (srcHandle || dstHandle) { - cbfinal = () => { - if (--left === 0) - cb(err); - }; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - ++left; - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - ++left; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - src.close(srcHandle, cbfinal); - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - dst.close(dstHandle, cbfinal); - } else { - cb(err); - } - } - - src.open(srcPath, 'r', (err, sourceHandle) => { - if (err) - return onerror(err); - - srcHandle = sourceHandle; - - if (fileSize === undefined) - src.fstat(srcHandle, tryStat); - else - tryStat(null, { size: fileSize }); - - function tryStat(err, attrs) { - if (err) { - if (src !== fs) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - src.stat(srcPath, (err_, attrs_) => { - if (err_) - return onerror(err); - tryStat(null, attrs_); - }); - return; - } - return onerror(err); - } - fsize = attrs.size; - - dst.open(dstPath, 'w', (err, destHandle) => { - if (err) - return onerror(err); - - dstHandle = destHandle; - - if (fsize <= 0) - return onerror(); - - // Use less memory where possible - while (bufsize > fsize) { - if (concurrency === 1) { - bufsize = fsize; - break; - } - bufsize -= chunkSize; - --concurrency; - } - - readbuf = tryCreateBuffer(bufsize); - if (readbuf instanceof Error) - return onerror(readbuf); - - if (mode !== undefined) { - dst.fchmod(dstHandle, mode, function tryAgain(err) { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() - // for whatever reason - dst.chmod(dstPath, mode, (err_) => tryAgain()); - return; - } - startReads(); - }); - } else { - startReads(); - } - - function onread(err, nb, data, dstpos, datapos, origChunkLen) { - if (err) - return onerror(err); - - datapos = datapos || 0; - - dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); - - function writeCb(err) { - if (err) - return onerror(err); - - total += nb; - onstep && onstep(total, nb, fsize); - - if (nb < origChunkLen) - return singleRead(datapos, dstpos + nb, origChunkLen - nb); - - if (total === fsize) { - dst.close(dstHandle, (err) => { - dstHandle = undefined; - if (err) - return onerror(err); - src.close(srcHandle, (err) => { - srcHandle = undefined; - if (err) - return onerror(err); - cb(); - }); - }); - return; - } - - if (pdst >= fsize) - return; - - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(datapos, pdst, chunk); - pdst += chunk; - } - } - - function makeCb(psrc, pdst, chunk) { - return (err, nb, data) => { - onread(err, nb, data, pdst, psrc, chunk); - }; - } - - function singleRead(psrc, pdst, chunk) { - src.read(srcHandle, - readbuf, - psrc, - chunk, - pdst, - makeCb(psrc, pdst, chunk)); - } - - function startReads() { - let reads = 0; - let psrc = 0; - while (pdst < fsize && reads < concurrency) { - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(psrc, pdst, chunk); - psrc += chunk; - pdst += chunk; - ++reads; - } - } - }); - } - }); -} - -function writeAll(sftp, handle, buffer, offset, length, position, callback_) { - const callback = (typeof callback_ === 'function' ? callback_ : undefined); - - sftp.write(handle, - buffer, - offset, - length, - position, - (writeErr, written) => { - if (writeErr) { - return sftp.close(handle, () => { - callback && callback(writeErr); - }); - } - if (written === length) { - sftp.close(handle, callback); - } else { - offset += written; - length -= written; - position += written; - writeAll(sftp, handle, buffer, offset, length, position, callback); - } - }); -} - -class Stats { - constructor(initial) { - this.mode = (initial && initial.mode); - this.uid = (initial && initial.uid); - this.gid = (initial && initial.gid); - this.size = (initial && initial.size); - this.atime = (initial && initial.atime); - this.mtime = (initial && initial.mtime); - this.extended = (initial && initial.extended); - } - isDirectory() { - return ((this.mode & constants.S_IFMT) === constants.S_IFDIR); - } - isFile() { - return ((this.mode & constants.S_IFMT) === constants.S_IFREG); - } - isBlockDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFBLK); - } - isCharacterDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFCHR); - } - isSymbolicLink() { - return ((this.mode & constants.S_IFMT) === constants.S_IFLNK); - } - isFIFO() { - return ((this.mode & constants.S_IFMT) === constants.S_IFIFO); - } - isSocket() { - return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK); - } -} - -function attrsToBytes(attrs) { - let flags = 0; - let nb = 0; - - if (typeof attrs === 'object' && attrs !== null) { - if (typeof attrs.size === 'number') { - flags |= ATTR.SIZE; - const val = attrs.size; - // Big Endian - ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56 - ATTRS_BUF[nb++] = val / 281474976710656; // 2**48 - ATTRS_BUF[nb++] = val / 1099511627776; // 2**40 - ATTRS_BUF[nb++] = val / 4294967296; // 2**32 - ATTRS_BUF[nb++] = val / 16777216; // 2**24 - ATTRS_BUF[nb++] = val / 65536; // 2**16 - ATTRS_BUF[nb++] = val / 256; // 2**8 - ATTRS_BUF[nb++] = val; - } - if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') { - flags |= ATTR.UIDGID; - const uid = attrs.uid; - const gid = attrs.gid; - // Big Endian - ATTRS_BUF[nb++] = uid >>> 24; - ATTRS_BUF[nb++] = uid >>> 16; - ATTRS_BUF[nb++] = uid >>> 8; - ATTRS_BUF[nb++] = uid; - ATTRS_BUF[nb++] = gid >>> 24; - ATTRS_BUF[nb++] = gid >>> 16; - ATTRS_BUF[nb++] = gid >>> 8; - ATTRS_BUF[nb++] = gid; - } - if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') { - const mode = modeNum(attrs.mode); - flags |= ATTR.PERMISSIONS; - // Big Endian - ATTRS_BUF[nb++] = mode >>> 24; - ATTRS_BUF[nb++] = mode >>> 16; - ATTRS_BUF[nb++] = mode >>> 8; - ATTRS_BUF[nb++] = mode; - } - if ((typeof attrs.atime === 'number' || isDate(attrs.atime)) - && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) { - const atime = toUnixTimestamp(attrs.atime); - const mtime = toUnixTimestamp(attrs.mtime); - - flags |= ATTR.ACMODTIME; - // Big Endian - ATTRS_BUF[nb++] = atime >>> 24; - ATTRS_BUF[nb++] = atime >>> 16; - ATTRS_BUF[nb++] = atime >>> 8; - ATTRS_BUF[nb++] = atime; - ATTRS_BUF[nb++] = mtime >>> 24; - ATTRS_BUF[nb++] = mtime >>> 16; - ATTRS_BUF[nb++] = mtime >>> 8; - ATTRS_BUF[nb++] = mtime; - } - // TODO: extended attributes - } - - return { flags, nb }; -} - -function toUnixTimestamp(time) { - // eslint-disable-next-line no-self-compare - if (typeof time === 'number' && time === time) // Valid, non-NaN number - return time; - if (isDate(time)) - return parseInt(time.getTime() / 1000, 10); - throw new Error(`Cannot parse time: ${time}`); -} - -function modeNum(mode) { - // eslint-disable-next-line no-self-compare - if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number - return mode; - if (typeof mode === 'string') - return modeNum(parseInt(mode, 8)); - throw new Error(`Cannot parse mode: ${mode}`); -} - -const stringFlagMap = { - 'r': OPEN_MODE.READ, - 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE, - 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL -}; - -function stringToFlags(str) { - const flags = stringFlagMap[str]; - return (flags !== undefined ? flags : null); -} - -const flagsToString = (() => { - const stringFlagMapKeys = Object.keys(stringFlagMap); - return (flags) => { - for (let i = 0; i < stringFlagMapKeys.length; ++i) { - const key = stringFlagMapKeys[i]; - if (stringFlagMap[key] === flags) - return key; - } - return null; - }; -})(); - -function readAttrs(biOpt) { - /* - uint32 flags - uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE - uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS - uint32 atime present only if flag SSH_FILEXFER_ACMODTIME - uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME - uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED - string extended_type - string extended_data - ... more extended data (extended_type - extended_data pairs), - so that number of pairs equals extended_count - */ - const flags = bufferParser.readUInt32BE(); - if (flags === undefined) - return; - - const attrs = new Stats(); - if (flags & ATTR.SIZE) { - const size = bufferParser.readUInt64BE(biOpt); - if (size === undefined) - return; - attrs.size = size; - } - - if (flags & ATTR.UIDGID) { - const uid = bufferParser.readUInt32BE(); - const gid = bufferParser.readUInt32BE(); - if (gid === undefined) - return; - attrs.uid = uid; - attrs.gid = gid; - } - - if (flags & ATTR.PERMISSIONS) { - const mode = bufferParser.readUInt32BE(); - if (mode === undefined) - return; - attrs.mode = mode; - } - - if (flags & ATTR.ACMODTIME) { - const atime = bufferParser.readUInt32BE(); - const mtime = bufferParser.readUInt32BE(); - if (mtime === undefined) - return; - attrs.atime = atime; - attrs.mtime = mtime; - } - - if (flags & ATTR.EXTENDED) { - const count = bufferParser.readUInt32BE(); - if (count === undefined) - return; - const extended = {}; - for (let i = 0; i < count; ++i) { - const type = bufferParser.readString(true); - const data = bufferParser.readString(); - if (data === undefined) - return; - extended[type] = data; - } - attrs.extended = extended; - } - - return attrs; -} - -function sendOrBuffer(sftp, payload) { - const ret = tryWritePayload(sftp, payload); - if (ret !== undefined) { - sftp._buffer.push(ret); - return false; - } - return true; -} - -function tryWritePayload(sftp, payload) { - const outgoing = sftp.outgoing; - if (outgoing.state !== 'open') - return; - - if (outgoing.window === 0) { - sftp._waitWindow = true; // XXX: Unnecessary? - return payload; - } - - let ret; - const len = payload.length; - let p = 0; - - while (len - p > 0 && outgoing.window > 0) { - const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); - outgoing.window -= actualLen; - if (outgoing.window === 0) { - sftp._waitWindow = true; - sftp._chunkcb = drainBuffer; - } - - if (p === 0 && actualLen === len) { - sftp._protocol.channelData(sftp.outgoing.id, payload); - } else { - sftp._protocol.channelData(sftp.outgoing.id, - bufferSlice(payload, p, p + actualLen)); - } - - p += actualLen; - } - - if (len - p > 0) { - if (p > 0) - ret = bufferSlice(payload, p, len); - else - ret = payload; // XXX: should never get here? - } - - return ret; -} - -function drainBuffer() { - this._chunkcb = undefined; - const buffer = this._buffer; - let i = 0; - while (i < buffer.length) { - const payload = buffer[i]; - const ret = tryWritePayload(this, payload); - if (ret !== undefined) { - if (ret !== payload) - buffer[i] = ret; - if (i > 0) - this._buffer = buffer.slice(i); - return; - } - ++i; - } - if (i > 0) - this._buffer = []; -} - -function doFatalSFTPError(sftp, msg, noDebug) { - const err = new Error(msg); - err.level = 'sftp-protocol'; - if (!noDebug && sftp._debug) - sftp._debug(`SFTP: Inbound: ${msg}`); - sftp.emit('error', err); - sftp.destroy(); - cleanupRequests(sftp); - return false; -} - -function cleanupRequests(sftp) { - const keys = Object.keys(sftp._requests); - if (keys.length === 0) - return; - - const reqs = sftp._requests; - sftp._requests = {}; - const err = new Error('No response from server'); - for (let i = 0; i < keys.length; ++i) { - const req = reqs[keys[i]]; - if (typeof req.cb === 'function') - req.cb(err); - } -} - -function requestLimits(sftp, cb) { - /* - uint32 id - string "limits@openssh.com" - */ - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 18, p); - buf.utf8Write('limits@openssh.com', p += 4, 18); - - sftp._requests[reqid] = { extended: 'limits@openssh.com', cb }; - - const isBuffered = sendOrBuffer(sftp, buf); - if (sftp._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); - } -} - -const CLIENT_HANDLERS = { - [RESPONSE.VERSION]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate VERSION packet'); - - const extensions = {}; - - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; - } - extensions[extName] = extData; - } - bufferParser.clear(); - - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed VERSION packet'); - - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); - } - } - - sftp._version = version; - sftp._extensions = extensions; - - if (extensions['limits@openssh.com'] === '1') { - return requestLimits(sftp, (err, limits) => { - if (!err) { - if (limits.maxPktLen > 0) - sftp._maxOutPktLen = limits.maxPktLen; - if (limits.maxReadLen > 0) - sftp._maxReadLen = limits.maxReadLen; - if (limits.maxWriteLen > 0) - sftp._maxWriteLen = limits.maxWriteLen; - sftp.maxOpenHandles = ( - limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity - ); - } - sftp.emit('ready'); - }); - } - - sftp.emit('ready'); - }, - [RESPONSE.STATUS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - uint32 error/status code - string error message (ISO-10646 UTF-8) - string language tag - */ - const errorCode = bufferParser.readUInt32BE(); - const errorMsg = bufferParser.readString(true); - const lang = bufferParser.skipString(); - bufferParser.clear(); - - if (lang === undefined) { - if (reqID !== undefined) - delete sftp._requests[reqID]; - return doFatalSFTPError(sftp, 'Malformed STATUS packet'); - } - - if (sftp._debug) { - const jsonMsg = JSON.stringify(errorMsg); - sftp._debug( - `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` - ); - } - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') { - if (errorCode === STATUS_CODE.OK) { - req.cb(); - return; - } - const err = new Error(errorMsg - || STATUS_CODE_STR[errorCode] - || 'Unknown status'); - err.code = errorCode; - req.cb(err); - } - }, - [RESPONSE.HANDLE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined) { - if (reqID !== undefined) - delete sftp._requests[reqID]; - return doFatalSFTPError(sftp, 'Malformed HANDLE packet'); - } - - sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); - - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') - req.cb(undefined, handle); - }, - [RESPONSE.DATA]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - /* - string data - */ - if (req && typeof req.cb === 'function') { - if (req.buffer) { - // We have already pre-allocated space to store the data - - const nb = bufferParser.readString(req.buffer); - bufferParser.clear(); - - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - req.cb(undefined, req.buffer, nb); - return; - } - } else { - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` - ); - req.cb(undefined, data); - return; - } - } - } else { - const nb = bufferParser.skipString(); - bufferParser.clear(); - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - return; - } - } - - return doFatalSFTPError(sftp, 'Malformed DATA packet'); - }, - [RESPONSE.NAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - /* - uint32 count - repeats count times: - string filename - string longname - ATTRS attrs - */ - const count = bufferParser.readUInt32BE(); - if (count !== undefined) { - let names = []; - for (let i = 0; i < count; ++i) { - // We are going to assume UTF-8 for filenames despite the SFTPv3 - // spec not specifying an encoding because the specs for newer - // versions of the protocol all explicitly specify UTF-8 for - // filenames - const filename = bufferParser.readString(true); - - // `longname` only exists in SFTPv3 and since it typically will - // contain the filename, we assume it is also UTF-8 - const longname = bufferParser.readString(true); - - const attrs = readAttrs(sftp._biOpt); - if (attrs === undefined) { - names = undefined; - break; - } - names.push({ filename, longname, attrs }); - } - if (names !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` - ); - bufferParser.clear(); - if (req && typeof req.cb === 'function') - req.cb(undefined, names); - return; - } - } - - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed NAME packet'); - }, - [RESPONSE.ATTRS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - /* - ATTRS attrs - */ - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs !== undefined) { - sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); - if (req && typeof req.cb === 'function') - req.cb(undefined, attrs); - return; - } - - return doFatalSFTPError(sftp, 'Malformed ATTRS packet'); - }, - [RESPONSE.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - if (reqID !== undefined) { - const req = sftp._requests[reqID]; - if (req) { - delete sftp._requests[reqID]; - switch (req.extended) { - case 'statvfs@openssh.com': - case 'fstatvfs@openssh.com': { - /* - uint64 f_bsize // file system block size - uint64 f_frsize // fundamental fs block size - uint64 f_blocks // number of blocks (unit f_frsize) - uint64 f_bfree // free blocks in file system - uint64 f_bavail // free blocks for non-root - uint64 f_files // total file inodes - uint64 f_ffree // free file inodes - uint64 f_favail // free file inodes for to non-root - uint64 f_fsid // file system id - uint64 f_flag // bit mask of f_flag values - uint64 f_namemax // maximum filename length - */ - const biOpt = sftp._biOpt; - const stats = { - f_bsize: bufferParser.readUInt64BE(biOpt), - f_frsize: bufferParser.readUInt64BE(biOpt), - f_blocks: bufferParser.readUInt64BE(biOpt), - f_bfree: bufferParser.readUInt64BE(biOpt), - f_bavail: bufferParser.readUInt64BE(biOpt), - f_files: bufferParser.readUInt64BE(biOpt), - f_ffree: bufferParser.readUInt64BE(biOpt), - f_favail: bufferParser.readUInt64BE(biOpt), - f_sid: bufferParser.readUInt64BE(biOpt), - f_flag: bufferParser.readUInt64BE(biOpt), - f_namemax: bufferParser.readUInt64BE(biOpt), - }; - if (stats.f_namemax === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, stats); - return; - } - case 'limits@openssh.com': { - /* - uint64 max-packet-length - uint64 max-read-length - uint64 max-write-length - uint64 max-open-handles - */ - const limits = { - maxPktLen: bufferParser.readUInt64BE(), - maxReadLen: bufferParser.readUInt64BE(), - maxWriteLen: bufferParser.readUInt64BE(), - maxOpenHandles: bufferParser.readUInt64BE(), - }; - if (limits.maxOpenHandles === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, limits); - return; - } - default: - // Unknown extended request - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(); - return; - } - } else { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - return; - } - } - - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet'); - }, -}; -const SERVER_HANDLERS = { - [REQUEST.INIT]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate INIT packet'); - - const extensions = {}; - - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; - } - extensions[extName] = extData; - } - bufferParser.clear(); - - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed INIT packet'); - - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received INIT (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); - } - } - - sendOrBuffer(sftp, SERVER_VERSION_BUFFER); - - sftp._version = version; - sftp._extensions = extensions; - sftp.emit('ready'); - }, - [REQUEST.OPEN]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string filename - uint32 pflags - ATTRS attrs - */ - const filename = bufferParser.readString(true); - const pflags = bufferParser.readUInt32BE(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed OPEN packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); - - if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.CLOSE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed CLOSE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); - - if (!sftp.emit('CLOSE', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READ]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - uint32 len - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const len = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (len === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READ packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); - - if (!sftp.emit('READ', reqID, handle, offset, len)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.WRITE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - string data - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed WRITE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); - - if (!sftp.emit('WRITE', reqID, handle, offset, data)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.LSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed LSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); - - if (!sftp.emit('LSTAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.FSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); - - if (!sftp.emit('FSTAT', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.SETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed SETSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); - - if (!sftp.emit('SETSTAT', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.FSETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - ATTRS attrs - */ - const handle = bufferParser.readString(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received FSETSTAT (id:${reqID})` - ); - - if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.OPENDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed OPENDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); - - if (!sftp.emit('OPENDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); - - if (!sftp.emit('READDIR', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.REMOVE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REMOVE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); - - if (!sftp.emit('REMOVE', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.MKDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed MKDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); - - if (!sftp.emit('MKDIR', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.RMDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed RMDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); - - if (!sftp.emit('RMDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.REALPATH]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REALPATH packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received REALPATH (id:${reqID})` - ); - - if (!sftp.emit('REALPATH', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.STAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed STAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); - - if (!sftp.emit('STAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.RENAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string oldpath - string newpath - */ - const oldPath = bufferParser.readString(true); - const newPath = bufferParser.readString(true); - bufferParser.clear(); - - if (newPath === undefined) - return doFatalSFTPError(sftp, 'Malformed RENAME packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); - - if (!sftp.emit('RENAME', reqID, oldPath, newPath)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed READLINK packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received READLINK (id:${reqID})` - ); - - if (!sftp.emit('READLINK', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.SYMLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string linkpath - string targetpath - */ - const linkPath = bufferParser.readString(true); - const targetPath = bufferParser.readString(true); - bufferParser.clear(); - - if (targetPath === undefined) - return doFatalSFTPError(sftp, 'Malformed SYMLINK packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); - - let handled; - if (sftp._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath); - } else { - handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath); - } - if (!handled) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string extended-request - ... any request-specific data ... - */ - const extName = bufferParser.readString(true); - if (extName === undefined) { - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED packet'); - } - - let extData; - if (bufferParser.avail()) - extData = bufferParser.readRaw(); - bufferParser.clear(); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED (id:${reqID})` - ); - - if (!sftp.emit('EXTENDED', reqID, extName, extData)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, -}; - -// ============================================================================= -// ReadStream/WriteStream-related ============================================== -// ============================================================================= -const { - ERR_INVALID_ARG_TYPE, - ERR_OUT_OF_RANGE, - validateNumber -} = require('./node-fs-compat'); - -const kMinPoolSpace = 128; - -let pool; -// It can happen that we expect to read a large chunk of data, and reserve -// a large chunk of the pool accordingly, but the read() call only filled -// a portion of it. If a concurrently executing read() then uses the same pool, -// the "reserved" portion cannot be used, so we allow it to be re-used as a -// new pool later. -const poolFragments = []; - -function allocNewPool(poolSize) { - if (poolFragments.length > 0) - pool = poolFragments.pop(); - else - pool = Buffer.allocUnsafe(poolSize); - pool.used = 0; -} - -// Check the `this.start` and `this.end` of stream. -function checkPosition(pos, name) { - if (!Number.isSafeInteger(pos)) { - validateNumber(pos, name); - if (!Number.isInteger(pos)) - throw new ERR_OUT_OF_RANGE(name, 'an integer', pos); - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); - } - if (pos < 0) - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); -} - -function roundUpToMultipleOf8(n) { - return (n + 7) & ~7; // Align to 8 byte boundary. -} - -function ReadStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); - - // A little bit bigger buffer and water marks by default - if (options.highWaterMark === undefined) - options.highWaterMark = 64 * 1024; - - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. - - ReadableStream.call(this, options); - - this.path = path; - this.flags = options.flags === undefined ? 'r' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; - - this.start = options.start; - this.end = options.end; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesRead = 0; - this.closed = false; - - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; - - if (this.start !== undefined) { - checkPosition(this.start, 'start'); - - this.pos = this.start; - } - - if (this.end === undefined) { - this.end = Infinity; - } else if (this.end !== Infinity) { - checkPosition(this.end, 'end'); - - if (this.start !== undefined && this.start > this.end) { - throw new ERR_OUT_OF_RANGE( - 'start', - `<= "end" (here: ${this.end})`, - this.start - ); - } - } - - this.on('end', function() { - if (this.autoClose) - this.destroy(); - }); - - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(ReadStream, ReadableStream); - -ReadStream.prototype.open = function() { - if (this._opening) - return; - - this._opening = true; - - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; - - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; - } - - this.handle = handle; - this.emit('open', handle); - this.emit('ready'); - // Start the flow of data. - this.read(); - }); -}; - -ReadStream.prototype._read = function(n) { - if (!Buffer.isBuffer(this.handle)) - return this.once('open', () => this._read(n)); - - // XXX: safe to remove this? - if (this.destroyed) - return; - - if (!pool || pool.length - pool.used < kMinPoolSpace) { - // Discard the old pool. - allocNewPool(this.readableHighWaterMark - || this._readableState.highWaterMark); - } - - // Grab another reference to the pool in the case that while we're - // in the thread pool another read() finishes up the pool, and - // allocates a new one. - const thisPool = pool; - let toRead = Math.min(pool.length - pool.used, n); - const start = pool.used; - - if (this.end !== undefined) - toRead = Math.min(this.end - this.pos + 1, toRead); - - // Already read everything we were supposed to read! - // treat as EOF. - if (toRead <= 0) - return this.push(null); - - // the actual read. - this.sftp.read(this.handle, - pool, - pool.used, - toRead, - this.pos, - (er, bytesRead) => { - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; - } - let b = null; - - // Now that we know how much data we have actually read, re-wind the - // 'used' field if we can, and otherwise allow the remainder of our - // reservation to be used as a new pool later. - if (start + toRead === thisPool.used && thisPool === pool) { - thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); - } else { - // Round down to the next lowest multiple of 8 to ensure the new pool - // fragment start and end positions are aligned to an 8 byte boundary. - const alignedEnd = (start + toRead) & ~7; - const alignedStart = roundUpToMultipleOf8(start + bytesRead); - if (alignedEnd - alignedStart >= kMinPoolSpace) - poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); - } - - if (bytesRead > 0) { - this.bytesRead += bytesRead; - b = thisPool.slice(start, start + bytesRead); - } - - // Move the pool positions, and internal position for reading. - this.pos += bytesRead; - - this.push(b); - }); - - pool.used = roundUpToMultipleOf8(pool.used + toRead); -}; - -ReadStream.prototype._destroy = function(err, cb) { - if (this._opening && !Buffer.isBuffer(this.handle)) { - this.once('open', closeStream.bind(null, this, cb, err)); - return; - } - - closeStream(this, cb, err); - this.handle = null; - this._opening = false; -}; - -function closeStream(stream, cb, err) { - if (!stream.handle) - return onclose(); - - stream.sftp.close(stream.handle, onclose); - - function onclose(er) { - er = er || err; - cb(er); - stream.closed = true; - if (!er) - stream.emit('close'); - } -} - -ReadStream.prototype.close = function(cb) { - this.destroy(null, cb); -}; - -Object.defineProperty(ReadStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); - -// TODO: add `concurrency` setting to allow more than one in-flight WRITE -// request to server to improve throughput -function WriteStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); - - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. - - WritableStream.call(this, options); - - this.path = path; - this.flags = options.flags === undefined ? 'w' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; - - this.start = options.start; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesWritten = 0; - this.closed = false; - - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; - - if (this.start !== undefined) { - checkPosition(this.start, 'start'); - - this.pos = this.start; - } - - if (options.encoding) - this.setDefaultEncoding(options.encoding); - - // Node v6.x only - this.on('finish', function() { - if (this._writableState.finalCalled) - return; - if (this.autoClose) - this.destroy(); - }); - - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(WriteStream, WritableStream); - -WriteStream.prototype._final = function(cb) { - if (this.autoClose) - this.destroy(); - cb(); -}; - -WriteStream.prototype.open = function() { - if (this._opening) - return; - - this._opening = true; - - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; - - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; - } - - this.handle = handle; - - const tryAgain = (err) => { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() for - // whatever reason - this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); - return; - } - - // SFTPv3 requires absolute offsets, no matter the open flag used - if (this.flags[0] === 'a') { - const tryStat = (err, st) => { - if (err) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.sftp.stat(this.path, (err_, st_) => { - if (err_) { - this.destroy(); - this.emit('error', err); - return; - } - tryStat(null, st_); - }); - return; - } - - this.pos = st.size; - this.emit('open', handle); - this.emit('ready'); - }; - - this.sftp.fstat(handle, tryStat); - return; - } - - this.emit('open', handle); - this.emit('ready'); - }; - - this.sftp.fchmod(handle, this.mode, tryAgain); - }); -}; - -WriteStream.prototype._write = function(data, encoding, cb) { - if (!Buffer.isBuffer(data)) { - const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); - return this.emit('error', err); - } - - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._write(data, encoding, cb); - }); - } - - this.sftp.write(this.handle, - data, - 0, - data.length, - this.pos, - (er, bytes) => { - if (er) { - if (this.autoClose) - this.destroy(); - return cb(er); - } - this.bytesWritten += bytes; - cb(); - }); - - this.pos += data.length; -}; - -WriteStream.prototype._writev = function(data, cb) { - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._writev(data, cb); - }); - } - - const sftp = this.sftp; - const handle = this.handle; - let writesLeft = data.length; - - const onwrite = (er, bytes) => { - if (er) { - this.destroy(); - return cb(er); - } - this.bytesWritten += bytes; - if (--writesLeft === 0) - cb(); - }; - - // TODO: try to combine chunks to reduce number of requests to the server? - for (let i = 0; i < data.length; ++i) { - const chunk = data[i].chunk; - - sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); - this.pos += chunk.length; - } -}; - -if (typeof WritableStream.prototype.destroy !== 'function') - WriteStream.prototype.destroy = ReadStream.prototype.destroy; - -WriteStream.prototype._destroy = ReadStream.prototype._destroy; -WriteStream.prototype.close = function(cb) { - if (cb) { - if (this.closed) { - process.nextTick(cb); - return; - } - this.on('close', cb); - } - - // If we are not autoClosing, we should call - // destroy on 'finish'. - if (!this.autoClose) - this.on('finish', this.destroy.bind(this)); - - this.end(); -}; - -// There is no shutdown() for files. -WriteStream.prototype.destroySoon = WriteStream.prototype.end; - -Object.defineProperty(WriteStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); -// ============================================================================= - -module.exports = { - flagsToString, - OPEN_MODE, - SFTP, - Stats, - STATUS_CODE, - stringToFlags, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/constants.js b/reverse_engineering/node_modules/ssh2/lib/protocol/constants.js deleted file mode 100644 index 632b7aa..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/constants.js +++ /dev/null @@ -1,344 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); - -let cpuInfo; -try { - cpuInfo = require('cpu-features')(); -} catch {} - -const { bindingAvailable } = require('./crypto.js'); - -const eddsaSupported = (() => { - if (typeof crypto.sign === 'function' - && typeof crypto.verify === 'function') { - const key = - '-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD' - + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----'; - const data = Buffer.from('a'); - let sig; - let verified; - try { - sig = crypto.sign(null, data, key); - verified = crypto.verify(null, data, key, sig); - } catch {} - return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true); - } - - return false; -})(); - -const curve25519Supported = (typeof crypto.diffieHellman === 'function' - && typeof crypto.generateKeyPairSync === 'function' - && typeof crypto.createPublicKey === 'function'); - -const DEFAULT_KEX = [ - // https://tools.ietf.org/html/rfc5656#section-10.1 - 'ecdh-sha2-nistp256', - 'ecdh-sha2-nistp384', - 'ecdh-sha2-nistp521', - - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha256', - - // https://tools.ietf.org/html/rfc8268 - 'diffie-hellman-group14-sha256', - 'diffie-hellman-group15-sha512', - 'diffie-hellman-group16-sha512', - 'diffie-hellman-group17-sha512', - 'diffie-hellman-group18-sha512', -]; -if (curve25519Supported) { - DEFAULT_KEX.unshift('curve25519-sha256'); - DEFAULT_KEX.unshift('curve25519-sha256@libssh.org'); -} -const SUPPORTED_KEX = DEFAULT_KEX.concat([ - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha1', - - 'diffie-hellman-group14-sha1', // REQUIRED - 'diffie-hellman-group1-sha1', // REQUIRED -]); - - -const DEFAULT_SERVER_HOST_KEY = [ - 'ecdsa-sha2-nistp256', - 'ecdsa-sha2-nistp384', - 'ecdsa-sha2-nistp521', - 'rsa-sha2-512', // RFC 8332 - 'rsa-sha2-256', // RFC 8332 - 'ssh-rsa', -]; -if (eddsaSupported) - DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519'); -const SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ - 'ssh-dss', -]); - - -const DEFAULT_CIPHER = [ - // http://tools.ietf.org/html/rfc5647 - 'aes128-gcm', - 'aes128-gcm@openssh.com', - 'aes256-gcm', - 'aes256-gcm@openssh.com', - - // http://tools.ietf.org/html/rfc4344#section-4 - 'aes128-ctr', - 'aes192-ctr', - 'aes256-ctr', -]; -if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { - // We know for sure the CPU does not support AES acceleration - if (bindingAvailable) - DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com'); - else - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); -} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') { - // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers - // seem to outperform it on x86, but it seems to be faster than CTR ciphers - DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com'); -} else { - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); -} -const SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ - 'aes256-cbc', - 'aes192-cbc', - 'aes128-cbc', - 'blowfish-cbc', - '3des-cbc', - - // http://tools.ietf.org/html/rfc4345#section-4: - 'arcfour256', - 'arcfour128', - - 'cast128-cbc', - 'arcfour', -]); - - -const DEFAULT_MAC = [ - 'hmac-sha2-256-etm@openssh.com', - 'hmac-sha2-512-etm@openssh.com', - 'hmac-sha1-etm@openssh.com', - 'hmac-sha2-256', - 'hmac-sha2-512', - 'hmac-sha1', -]; -const SUPPORTED_MAC = DEFAULT_MAC.concat([ - 'hmac-md5', - 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256 - 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512 - 'hmac-ripemd160', - 'hmac-sha1-96', // first 96 bits of HMAC-SHA1 - 'hmac-md5-96', // first 96 bits of HMAC-MD5 -]); - -const DEFAULT_COMPRESSION = [ - 'none', - 'zlib@openssh.com', // ZLIB (LZ77) compression, except - // compression/decompression does not start until after - // successful user authentication - 'zlib', // ZLIB (LZ77) compression -]; -const SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([ -]); - - -const COMPAT = { - BAD_DHGEX: 1 << 0, - OLD_EXIT: 1 << 1, - DYN_RPORT_BUG: 1 << 2, - BUG_DHGEX_LARGE: 1 << 3, -}; - -module.exports = { - MESSAGE: { - // Transport layer protocol -- generic (1-19) - DISCONNECT: 1, - IGNORE: 2, - UNIMPLEMENTED: 3, - DEBUG: 4, - SERVICE_REQUEST: 5, - SERVICE_ACCEPT: 6, - - // Transport layer protocol -- algorithm negotiation (20-29) - KEXINIT: 20, - NEWKEYS: 21, - - // Transport layer protocol -- key exchange method-specific (30-49) - KEXDH_INIT: 30, - KEXDH_REPLY: 31, - - KEXDH_GEX_GROUP: 31, - KEXDH_GEX_INIT: 32, - KEXDH_GEX_REPLY: 33, - KEXDH_GEX_REQUEST: 34, - - KEXECDH_INIT: 30, - KEXECDH_REPLY: 31, - - // User auth protocol -- generic (50-59) - USERAUTH_REQUEST: 50, - USERAUTH_FAILURE: 51, - USERAUTH_SUCCESS: 52, - USERAUTH_BANNER: 53, - - // User auth protocol -- user auth method-specific (60-79) - USERAUTH_PASSWD_CHANGEREQ: 60, - - USERAUTH_PK_OK: 60, - - USERAUTH_INFO_REQUEST: 60, - USERAUTH_INFO_RESPONSE: 61, - - // Connection protocol -- generic (80-89) - GLOBAL_REQUEST: 80, - REQUEST_SUCCESS: 81, - REQUEST_FAILURE: 82, - - // Connection protocol -- channel-related (90-127) - CHANNEL_OPEN: 90, - CHANNEL_OPEN_CONFIRMATION: 91, - CHANNEL_OPEN_FAILURE: 92, - CHANNEL_WINDOW_ADJUST: 93, - CHANNEL_DATA: 94, - CHANNEL_EXTENDED_DATA: 95, - CHANNEL_EOF: 96, - CHANNEL_CLOSE: 97, - CHANNEL_REQUEST: 98, - CHANNEL_SUCCESS: 99, - CHANNEL_FAILURE: 100 - - // Reserved for client protocols (128-191) - - // Local extensions (192-155) - }, - DISCONNECT_REASON: { - HOST_NOT_ALLOWED_TO_CONNECT: 1, - PROTOCOL_ERROR: 2, - KEY_EXCHANGE_FAILED: 3, - RESERVED: 4, - MAC_ERROR: 5, - COMPRESSION_ERROR: 6, - SERVICE_NOT_AVAILABLE: 7, - PROTOCOL_VERSION_NOT_SUPPORTED: 8, - HOST_KEY_NOT_VERIFIABLE: 9, - CONNECTION_LOST: 10, - BY_APPLICATION: 11, - TOO_MANY_CONNECTIONS: 12, - AUTH_CANCELED_BY_USER: 13, - NO_MORE_AUTH_METHODS_AVAILABLE: 14, - ILLEGAL_USER_NAME: 15, - }, - DISCONNECT_REASON_STR: undefined, - CHANNEL_OPEN_FAILURE: { - ADMINISTRATIVELY_PROHIBITED: 1, - CONNECT_FAILED: 2, - UNKNOWN_CHANNEL_TYPE: 3, - RESOURCE_SHORTAGE: 4 - }, - TERMINAL_MODE: { - TTY_OP_END: 0, // Indicates end of options. - VINTR: 1, // Interrupt character; 255 if none. Similarly for the - // other characters. Not all of these characters are - // supported on all systems. - VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX - // systems). - VERASE: 3, // Erase the character to left of the cursor. - VKILL: 4, // Kill the current input line. - VEOF: 5, // End-of-file character (sends EOF from the - // terminal). - VEOL: 6, // End-of-line character in addition to carriage - // return and/or linefeed. - VEOL2: 7, // Additional end-of-line character. - VSTART: 8, // Continues paused output (normally control-Q). - VSTOP: 9, // Pauses output (normally control-S). - VSUSP: 10, // Suspends the current program. - VDSUSP: 11, // Another suspend character. - VREPRINT: 12, // Reprints the current input line. - VWERASE: 13, // Erases a word left of cursor. - VLNEXT: 14, // Enter the next character typed literally, even if - // it is a special character - VFLUSH: 15, // Character to flush output. - VSWTCH: 16, // Switch to a different shell layer. - VSTATUS: 17, // Prints system status line (load, command, pid, - // etc). - VDISCARD: 18, // Toggles the flushing of terminal output. - IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0 - // if this flag is FALSE, and 1 if it is TRUE. - PARMRK: 31, // Mark parity and framing errors. - INPCK: 32, // Enable checking of parity errors. - ISTRIP: 33, // Strip 8th bit off characters. - INLCR: 34, // Map NL into CR on input. - IGNCR: 35, // Ignore CR on input. - ICRNL: 36, // Map CR to NL on input. - IUCLC: 37, // Translate uppercase characters to lowercase. - IXON: 38, // Enable output flow control. - IXANY: 39, // Any char will restart after stop. - IXOFF: 40, // Enable input flow control. - IMAXBEL: 41, // Ring bell on input queue full. - ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP. - ICANON: 51, // Canonicalize input lines. - XCASE: 52, // Enable input and output of uppercase characters by - // preceding their lowercase equivalents with "\". - ECHO: 53, // Enable echoing. - ECHOE: 54, // Visually erase chars. - ECHOK: 55, // Kill character discards current line. - ECHONL: 56, // Echo NL even if ECHO is off. - NOFLSH: 57, // Don't flush after interrupt. - TOSTOP: 58, // Stop background jobs from output. - IEXTEN: 59, // Enable extensions. - ECHOCTL: 60, // Echo control characters as ^(Char). - ECHOKE: 61, // Visual erase for line kill. - PENDIN: 62, // Retype pending input. - OPOST: 70, // Enable output processing. - OLCUC: 71, // Convert lowercase to uppercase. - ONLCR: 72, // Map NL to CR-NL. - OCRNL: 73, // Translate carriage return to newline (output). - ONOCR: 74, // Translate newline to carriage return-newline - // (output). - ONLRET: 75, // Newline performs a carriage return (output). - CS7: 90, // 7 bit mode. - CS8: 91, // 8 bit mode. - PARENB: 92, // Parity enable. - PARODD: 93, // Odd parity, else even. - TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second. - TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second. - }, - CHANNEL_EXTENDED_DATATYPE: { - STDERR: 1, - }, - - SIGNALS: [ - 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1', - 'USR2', 'KILL', 'PIPE' - ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), - - COMPAT, - COMPAT_CHECKS: [ - [ 'Cisco-1.25', COMPAT.BAD_DHGEX ], - [ /^Cisco-1\./, COMPAT.BUG_DHGEX_LARGE ], - [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations - [ /^OpenSSH_5\.\d+/, COMPAT.DYN_RPORT_BUG ], - ], - - // KEX proposal-related - DEFAULT_KEX, - SUPPORTED_KEX, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY, - DEFAULT_CIPHER, - SUPPORTED_CIPHER, - DEFAULT_MAC, - SUPPORTED_MAC, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION, - - curve25519Supported, - eddsaSupported, -}; - -module.exports.DISCONNECT_REASON_BY_VALUE = - Array.from(Object.entries(module.exports.DISCONNECT_REASON)) - .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto.js b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto.js deleted file mode 100644 index b4c3ecb..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto.js +++ /dev/null @@ -1,1607 +0,0 @@ -// TODO: -// * make max packet size configurable -// * if decompression is enabled, use `._packet` in decipher instances as -// input to (sync) zlib inflater with appropriate offset and length to -// avoid an additional copy of payload data before inflation -// * factor decompression status into packet length checks -'use strict'; - -const { - createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual -} = require('crypto'); - -const { readUInt32BE, writeUInt32BE } = require('./utils.js'); - -const FastBuffer = Buffer[Symbol.species]; -const MAX_SEQNO = 2 ** 32 - 1; -const EMPTY_BUFFER = Buffer.alloc(0); -const BUF_INT = Buffer.alloc(4); -const DISCARD_CACHE = new Map(); -const MAX_PACKET_SIZE = 35000; - -let binding; -let AESGCMCipher; -let ChaChaPolyCipher; -let GenericCipher; -let AESGCMDecipher; -let ChaChaPolyDecipher; -let GenericDecipher; -try { - binding = require('./crypto/build/Release/sshcrypto.node'); - ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher, - AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding); -} catch {} - -const CIPHER_STREAM = 1 << 0; -const CIPHER_INFO = (() => { - function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { - return { - sslName, - blockLen, - keyLen, - ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM) - ? ivLen - : blockLen), - authLen, - discardLen, - stream: !!(flags & CIPHER_STREAM), - }; - } - - return { - 'chacha20-poly1305@openssh.com': - info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM), - - 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - 'aes128-gcm@openssh.com': - info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm@openssh.com': - info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - - 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0), - 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0), - 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0), - 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0), - 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0), - 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0), - - 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM), - 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM), - 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM), - '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM), - 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), - 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), - - /* The "arcfour128" algorithm is the RC4 cipher, as described in - [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream - generated by the cipher MUST be discarded, and the first byte of the - first encrypted packet MUST be encrypted using the 1537th byte of - keystream. - - -- http://tools.ietf.org/html/rfc4345#section-4 */ - 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM), - 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM), - }; -})(); - -const MAC_INFO = (() => { - function info(sslName, len, actualLen, isETM) { - return { - sslName, - len, - actualLen, - isETM, - }; - } - - return { - 'hmac-md5': info('md5', 16, 16, false), - 'hmac-md5-96': info('md5', 16, 12, false), - 'hmac-ripemd160': info('ripemd160', 20, 20, false), - 'hmac-sha1': info('sha1', 20, 20, false), - 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true), - 'hmac-sha1-96': info('sha1', 20, 12, false), - 'hmac-sha2-256': info('sha256', 32, 32, false), - 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true), - 'hmac-sha2-256-96': info('sha256', 32, 12, false), - 'hmac-sha2-512': info('sha512', 64, 64, false), - 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true), - 'hmac-sha2-512-96': info('sha512', 64, 12, false), - }; -})(); - - -// Should only_be used during the initial handshake -class NullCipher { - constructor(seqno, onWrite) { - this.outSeqno = seqno; - this._onWrite = onWrite; - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - (pktLen & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -const POLY1305_ZEROS = Buffer.alloc(32); -const POLY1305_OUT_COMPUTE = Buffer.alloc(16); -let POLY1305_WASM_MODULE; -let POLY1305_RESULT_MALLOC; -let poly1305_auth; -class ChaChaPolyCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encKeyMain = enc.cipherKey.slice(0, 32); - this._encKeyPktLen = enc.cipherKey.slice(32); - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); - - // Encrypt packet length - const pktLenEnc = - createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE) - .update(packet.slice(0, 4)); - this._onWrite(pktLenEnc); - - // Encrypt rest of packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const payloadEnc = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(packet.slice(4)); - this._onWrite(payloadEnc); - - // Calculate Poly1305 MAC - poly1305_auth(POLY1305_RESULT_MALLOC, - pktLenEnc, - pktLenEnc.length, - payloadEnc, - payloadEnc.length, - polyKey); - const mac = Buffer.allocUnsafe(16); - mac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - this._onWrite(mac); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class ChaChaPolyCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new ChaChaPolyCipher(enc.cipherKey); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class AESGCMCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encSSLName = enc.cipherInfo.sslName; - this._encKey = enc.cipherKey; - this._encIV = enc.cipherIV; - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); - cipher.setAutoPadding(false); - - const lenData = packet.slice(0, 4); - cipher.setAAD(lenData); - this._onWrite(lenData); - - // Encrypt pad length, payload, and padding - const encrypted = cipher.update(packet.slice(4)); - this._onWrite(encrypted); - const final = cipher.final(); - // XXX: final.length === 0 always? - if (final.length) - this._onWrite(final); - - // Generate MAC - const tag = cipher.getAuthTag(); - this._onWrite(tag); - - // Increment counter in IV by 1 for next packet - ivIncrement(this._encIV); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class AESGCMCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new AESGCMCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet); - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class GenericCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._cipherInstance = createCipheriv(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._macSSLName = enc.macInfo.sslName; - this._macKey = enc.macKey; - this._macActualLen = enc.macInfo.actualLen; - this._macETM = enc.macInfo.isETM; - this._aadLen = (this._macETM ? 4 : 0); - this._dead = false; - - const discardLen = enc.cipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._cipherInstance.update(discard); - } - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; - - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - let mac; - if (this._macETM) { - // Encrypt pad length, payload, and padding - const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); - const encrypted = this._cipherInstance.update( - new Uint8Array(packet.buffer, - packet.byteOffset + 4, - packet.length - 4) - ); - - this._onWrite(lenBytes); - this._onWrite(encrypted); - - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(lenBytes); - mac.update(encrypted); - } else { - // Encrypt length field, pad length, payload, and padding - const encrypted = this._cipherInstance.update(packet); - this._onWrite(encrypted); - - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(packet); - } - - let digest = mac.digest(); - if (digest.length > this._macActualLen) - digest = digest.slice(0, this._macActualLen); - this._onWrite(digest); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class GenericCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._macLen = enc.macInfo.len; - this._macActualLen = enc.macInfo.actualLen; - this._aadLen = (enc.macInfo.isETM ? 4 : 0); - this._instance = new GenericCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV, - enc.macInfo.sslName, - enc.macKey, - enc.macInfo.isETM); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; - - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + this._macLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); - - if (this._macActualLen < this._macLen) { - packet = new FastBuffer(packet.buffer, - packet.byteOffset, - (packet.length - - (this._macLen - this._macActualLen))); - } - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class NullDecipher { - constructor(seqno, onPayload) { - this.inSeqno = seqno; - this._onPayload = onPayload; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - while (p < dataLen) { - // Read packet length - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - - if (this._lenBytes < 4) - return; - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (4 + this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._packetPos < this._len) { - const nb = Math.min(this._len - this._packetPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - if (nb === this._len) { - this._packet = new FastBuffer(data.buffer, data.byteOffset + p, nb); - } else { - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._packetPos - ); - } - } else if (nb === this._len) { - this._packet = data; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(data, this._packetPos); - } - p += nb; - this._packetPos += nb; - if (this._packetPos < this._len) - return; - } - - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -class ChaChaPolyDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decKeyMain = dec.decipherKey.slice(0, 32); - this._decKeyPktLen = dec.decipherKey.slice(32); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._calcMac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; - - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - - const decLenBytes = - createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE) - .update(this._lenBuf); - this._len = readUInt32BE(decLenBytes, 0); - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } - - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); - - // Calculate and compare Poly1305 MACs - poly1305_auth(POLY1305_RESULT_MALLOC, - this._lenBuf, - 4, - this._packet, - this._packet.length, - polyKey); - - this._calcMac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - if (!timingSafeEqual(this._calcMac, this._mac)) - throw new Error('Invalid MAC'); - - // Decrypt packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const packet = - createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(this._packet); - - const payload = new FastBuffer(packet.buffer, - packet.byteOffset + 1, - packet.length - packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -class ChaChaPolyDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new ChaChaPolyDecipher(dec.decipherKey); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() { - this._instance.free(); - } - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; - - this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } - - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } - - this._instance.decrypt(this._packet, this._mac, this.inSeqno); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -class AESGCMDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = null; - this._decipherSSLName = dec.decipherInfo.sslName; - this._decipherKey = dec.decipherKey; - this._decipherIV = dec.decipherIV; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; - - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error('Bad packet length'); - } - - this._decipherInstance = createDecipheriv( - this._decipherSSLName, - this._decipherKey, - this._decipherIV - ); - this._decipherInstance.setAutoPadding(false); - this._decipherInstance.setAAD(intToBytes(this._len)); - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let decrypted; - if (p !== 0 || nb !== dataLen) { - decrypted = this._decipherInstance.update( - new Uint8Array(data.buffer, data.byteOffset + p, nb) - ); - } else { - decrypted = this._decipherInstance.update(data); - } - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); - } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } - - { - // Verify authentication tag - this._decipherInstance.setAuthTag(this._tag); - - const decrypted = this._decipherInstance.final(); - - // XXX: this should never output any data since stream ciphers always - // return data from .update() and block ciphers must end on a multiple - // of the block length, which would have caused an exception to be - // thrown if the total input was not... - if (decrypted.length) { - if (this._packet) - this._packet.set(decrypted, this._packetPos); - else - this._packet = decrypted; - } - } - - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - ivIncrement(this._decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tagPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -class AESGCMDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new AESGCMDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; - - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error(`Bad packet length: ${this._len}`); - } - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); - } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } - - this._instance.decrypt(this._packet, this._len, this._tag); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tagPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -// TODO: test incremental .update()s vs. copying to _packet and doing a single -// .update() after entire packet read -- a single .update() would allow -// verifying MAC before decrypting for ETM MACs -class GenericDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._decipherInstance.setAutoPadding(false); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen - ); - this._blockSize = dec.decipherInfo.blockLen; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macSSLName = dec.macInfo.sslName; - this._macKey = dec.macKey; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - this._macInstance = null; - - const discardLen = dec.decipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._decipherInstance.update(discard); - } - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); - } - - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; - - let decrypted; - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - // Decrypt first block to get packet length - decrypted = this._decipherInstance.update(this._block); - this._len = readUInt32BE(decrypted, 0); - need = 4 + this._len - this._blockSize; - } - - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._blockSize - 1)) !== 0) { - throw new Error('Bad packet length'); - } - - // Create MAC up front to calculate in parallel with decryption - this._macInstance = createHmac(this._macSSLName, this._macKey); - - writeUInt32BE(BUF_INT, this.inSeqno, 0); - this._macInstance.update(BUF_INT); - if (this._macETM) { - this._macInstance.update(this._block); - } else { - this._macInstance.update(new Uint8Array(decrypted.buffer, - decrypted.byteOffset, - 4)); - this._pktLen = decrypted.length - 4; - this._packetPos = this._pktLen; - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(decrypted.buffer, - decrypted.byteOffset + 4, - this._packetPos), - 0 - ); - } - - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (this._macETM) - this._macInstance.update(encrypted); - const decrypted = this._decipherInstance.update(encrypted); - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } - - // Verify MAC - if (!this._macETM) - this._macInstance.update(this._packet); - let calculated = this._macInstance.digest(); - if (this._macActualLen < calculated.length) { - calculated = new Uint8Array(calculated.buffer, - calculated.byteOffset, - this._macActualLen); - } - if (!timingSafeEquals(calculated, this._mac)) - throw new Error('Invalid MAC'); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -class GenericDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new GenericDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV, - dec.macInfo.sslName, - dec.macKey, - dec.macInfo.isETM, - dec.macInfo.actualLen); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM || dec.decipherInfo.stream - ? 4 - : dec.decipherInfo.blockLen - ); - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - } - free() { - this._instance.free(); - } - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); - } - - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; - - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - // Decrypt first block to get packet length - this._instance.decryptBlock(this._block); - this._len = readUInt32BE(this._block, 0); - need = 4 + this._len - this._block.length; - } - - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._block.length - 1)) !== 0) { - throw new Error('Bad packet length'); - } - - if (!this._macETM) { - this._pktLen = (this._block.length - 4); - if (this._pktLen) { - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(this._block.buffer, - this._block.byteOffset + 4, - this._pktLen), - 0 - ); - } - } - - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } - - // Decrypt and verify MAC - this._instance.decrypt(this._packet, - this.inSeqno, - this._block, - this._mac); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV -function ivIncrement(iv) { - // eslint-disable-next-line no-unused-expressions - ++iv[11] >>> 8 - && ++iv[10] >>> 8 - && ++iv[9] >>> 8 - && ++iv[8] >>> 8 - && ++iv[7] >>> 8 - && ++iv[6] >>> 8 - && ++iv[5] >>> 8 - && ++iv[4] >>> 8; -} - -const intToBytes = (() => { - const ret = Buffer.alloc(4); - return (n) => { - ret[0] = (n >>> 24); - ret[1] = (n >>> 16); - ret[2] = (n >>> 8); - ret[3] = n; - return ret; - }; -})(); - -function timingSafeEquals(a, b) { - if (a.length !== b.length) { - timingSafeEqual(a, a); - return false; - } - return timingSafeEqual(a, b); -} - -function createCipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); - - if (typeof config.outbound !== 'object' || config.outbound === null) - throw new Error('Invalid outbound'); - - const outbound = config.outbound; - - if (typeof outbound.onWrite !== 'function') - throw new Error('Invalid outbound.onWrite'); - - if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null) - throw new Error('Invalid outbound.cipherInfo'); - - if (!Buffer.isBuffer(outbound.cipherKey) - || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { - throw new Error('Invalid outbound.cipherKey'); - } - - if (outbound.cipherInfo.ivLen - && (!Buffer.isBuffer(outbound.cipherIV) - || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { - throw new Error('Invalid outbound.cipherIV'); - } - - if (typeof outbound.seqno !== 'number' - || outbound.seqno < 0 - || outbound.seqno > MAX_SEQNO) { - throw new Error('Invalid outbound.seqno'); - } - - const forceNative = !!outbound.forceNative; - - switch (outbound.cipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMCipher && !forceNative - ? new AESGCMCipherBinding(config) - : new AESGCMCipherNative(config)); - case 'chacha20': - return (ChaChaPolyCipher && !forceNative - ? new ChaChaPolyCipherBinding(config) - : new ChaChaPolyCipherNative(config)); - default: { - if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null) - throw new Error('Invalid outbound.macInfo'); - if (!Buffer.isBuffer(outbound.macKey) - || outbound.macKey.length !== outbound.macInfo.len) { - throw new Error('Invalid outbound.macKey'); - } - return (GenericCipher && !forceNative - ? new GenericCipherBinding(config) - : new GenericCipherNative(config)); - } - } -} - -function createDecipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); - - if (typeof config.inbound !== 'object' || config.inbound === null) - throw new Error('Invalid inbound'); - - const inbound = config.inbound; - - if (typeof inbound.onPayload !== 'function') - throw new Error('Invalid inbound.onPayload'); - - if (typeof inbound.decipherInfo !== 'object' - || inbound.decipherInfo === null) { - throw new Error('Invalid inbound.decipherInfo'); - } - - if (!Buffer.isBuffer(inbound.decipherKey) - || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { - throw new Error('Invalid inbound.decipherKey'); - } - - if (inbound.decipherInfo.ivLen - && (!Buffer.isBuffer(inbound.decipherIV) - || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { - throw new Error('Invalid inbound.decipherIV'); - } - - if (typeof inbound.seqno !== 'number' - || inbound.seqno < 0 - || inbound.seqno > MAX_SEQNO) { - throw new Error('Invalid inbound.seqno'); - } - - const forceNative = !!inbound.forceNative; - - switch (inbound.decipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMDecipher && !forceNative - ? new AESGCMDecipherBinding(config) - : new AESGCMDecipherNative(config)); - case 'chacha20': - return (ChaChaPolyDecipher && !forceNative - ? new ChaChaPolyDecipherBinding(config) - : new ChaChaPolyDecipherNative(config)); - default: { - if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null) - throw new Error('Invalid inbound.macInfo'); - if (!Buffer.isBuffer(inbound.macKey) - || inbound.macKey.length !== inbound.macInfo.len) { - throw new Error('Invalid inbound.macKey'); - } - return (GenericDecipher && !forceNative - ? new GenericDecipherBinding(config) - : new GenericDecipherNative(config)); - } - } -} - -module.exports = { - CIPHER_INFO, - MAC_INFO, - bindingAvailable: !!binding, - init: (() => { - // eslint-disable-next-line no-async-promise-executor - return new Promise(async (resolve, reject) => { - try { - POLY1305_WASM_MODULE = await require('./crypto/poly1305.js')(); - POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); - poly1305_auth = POLY1305_WASM_MODULE.cwrap( - 'poly1305_auth', - null, - ['number', 'array', 'number', 'array', 'number', 'array'] - ); - } catch (ex) { - return reject(ex); - } - resolve(); - }); - })(), - - NullCipher, - createCipher, - NullDecipher, - createDecipher, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/binding.gyp b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/binding.gyp deleted file mode 100644 index 29c3282..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/binding.gyp +++ /dev/null @@ -1,14 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'sshcrypto', - 'include_dirs': [ - "> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = AR($(TOOLSET)) $@ -cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) - -quiet_cmd_alink_thin = AR($(TOOLSET)) $@ -cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) - -# Due to circular dependencies between libraries :(, we wrap the -# special "figure out circular dependencies" flags around the entire -# input list during linking. -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) $(LIBS) -Wl,--end-group - -# We support two kinds of shared objects (.so): -# 1) shared_library, which is just bundling together many dependent libraries -# into a link line. -# 2) loadable_module, which is generating a module intended for dlopen(). -# -# They differ only slightly: -# In the former case, we want to package all dependent code into the .so. -# In the latter case, we want to package just the API exposed by the -# outermost module. -# This means shared_library uses --whole-archive, while loadable_module doesn't. -# (Note that --whole-archive is incompatible with the --start-group used in -# normal linking.) - -# Other shared-object link notes: -# - Set SONAME to the library filename so our binaries don't reference -# the local, absolute paths used on the link command-line. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 1,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,sshcrypto.target.mk)))),) - include sshcrypto.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/config.gypi -I/usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/vitalii/.cache/node-gyp/14.17.6/include/node/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/vitalii/.cache/node-gyp/14.17.6" "-Dnode_gyp_dir=/usr/lib/node_modules/npm/node_modules/node-gyp" "-Dnode_lib_file=/home/vitalii/.cache/node-gyp/14.17.6/<(target_arch)/node.lib" "-Dmodule_root_dir=/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/ssh2/lib/protocol/crypto" "-Dnode_engine=v8" binding.gyp -Makefile: $(srcdir)/../../../../../../../../../../.cache/node-gyp/14.17.6/include/node/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../../../../usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto.node.d b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto.node.d deleted file mode 100644 index 320d7f9..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/sshcrypto.node := g++ -shared -pthread -rdynamic -m64 -Wl,-soname=sshcrypto.node -o Release/obj.target/sshcrypto.node -Wl,--start-group Release/obj.target/sshcrypto/src/binding.o -Wl,--end-group diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto/src/binding.o.d b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto/src/binding.o.d deleted file mode 100644 index 2c2990d..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/obj.target/sshcrypto/src/binding.o.d +++ /dev/null @@ -1,117 +0,0 @@ -cmd_Release/obj.target/sshcrypto/src/binding.o := g++ '-DNODE_GYP_MODULE_NAME=sshcrypto' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__STDC_FORMAT_MACROS' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-DBUILDING_NODE_EXTENSION' -I/home/vitalii/.cache/node-gyp/14.17.6/include/node -I/home/vitalii/.cache/node-gyp/14.17.6/src -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/config -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/openssl/include -I/home/vitalii/.cache/node-gyp/14.17.6/deps/uv/include -I/home/vitalii/.cache/node-gyp/14.17.6/deps/zlib -I/home/vitalii/.cache/node-gyp/14.17.6/deps/v8/include -I../../../../../nan -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -O3 -fno-omit-frame-pointer -fno-rtti -fno-exceptions -std=gnu++1y -MMD -MF ./Release/.deps/Release/obj.target/sshcrypto/src/binding.o.d.raw -c -o Release/obj.target/sshcrypto/src/binding.o ../src/binding.cc -Release/obj.target/sshcrypto/src/binding.o: ../src/binding.cc \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/cppgc/common.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8config.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-internal.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-version.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8config.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-platform.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node_version.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node_buffer.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node.h \ - ../../../../../nan/nan.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node_version.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/errno.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/version.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/unix.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/threadpool.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/linux.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/node_object_wrap.h \ - ../../../../../nan/nan_callbacks.h \ - ../../../../../nan/nan_callbacks_12_inl.h \ - ../../../../../nan/nan_maybe_43_inl.h \ - ../../../../../nan/nan_converters.h \ - ../../../../../nan/nan_converters_43_inl.h ../../../../../nan/nan_new.h \ - ../../../../../nan/nan_implementation_12_inl.h \ - ../../../../../nan/nan_persistent_12_inl.h ../../../../../nan/nan_weak.h \ - ../../../../../nan/nan_object_wrap.h ../../../../../nan/nan_private.h \ - ../../../../../nan/nan_typedarray_contents.h \ - ../../../../../nan/nan_json.h ../../../../../nan/nan_scriptorigin.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/err.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/e_os2.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/opensslconf.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/./opensslconf_asm.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/././archs/linux-x86_64/asm/include/openssl/opensslconf.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/opensslv.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/ossl_typ.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/bio.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/crypto.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/safestack.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/stack.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/cryptoerr.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/symhacks.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/bioerr.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/lhash.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/evp.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/evperr.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/objects.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/obj_mac.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/asn1.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/asn1err.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/bn.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/bnerr.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/objectserr.h \ - /home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/hmac.h -../src/binding.cc: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/cppgc/common.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8config.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-internal.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-version.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8config.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/v8-platform.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node_version.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node_buffer.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node.h: -../../../../../nan/nan.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node_version.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/errno.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/version.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/unix.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/threadpool.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/uv/linux.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/node_object_wrap.h: -../../../../../nan/nan_callbacks.h: -../../../../../nan/nan_callbacks_12_inl.h: -../../../../../nan/nan_maybe_43_inl.h: -../../../../../nan/nan_converters.h: -../../../../../nan/nan_converters_43_inl.h: -../../../../../nan/nan_new.h: -../../../../../nan/nan_implementation_12_inl.h: -../../../../../nan/nan_persistent_12_inl.h: -../../../../../nan/nan_weak.h: -../../../../../nan/nan_object_wrap.h: -../../../../../nan/nan_private.h: -../../../../../nan/nan_typedarray_contents.h: -../../../../../nan/nan_json.h: -../../../../../nan/nan_scriptorigin.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/err.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/e_os2.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/opensslconf.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/./opensslconf_asm.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/././archs/linux-x86_64/asm/include/openssl/opensslconf.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/opensslv.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/ossl_typ.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/bio.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/crypto.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/safestack.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/stack.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/cryptoerr.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/symhacks.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/bioerr.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/lhash.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/evp.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/evperr.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/objects.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/obj_mac.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/asn1.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/asn1err.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/bn.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/bnerr.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/objectserr.h: -/home/vitalii/.cache/node-gyp/14.17.6/include/node/openssl/hmac.h: diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/sshcrypto.node.d b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/sshcrypto.node.d deleted file mode 100644 index ece811f..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/.deps/Release/sshcrypto.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/sshcrypto.node := rm -rf "Release/sshcrypto.node" && cp -af "Release/obj.target/sshcrypto.node" "Release/sshcrypto.node" diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto.node b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto.node deleted file mode 100644 index 8ee354f..0000000 Binary files a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto.node and /dev/null differ diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto/src/binding.o b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto/src/binding.o deleted file mode 100644 index 6881b82..0000000 Binary files a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/obj.target/sshcrypto/src/binding.o and /dev/null differ diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node deleted file mode 100644 index 8ee354f..0000000 Binary files a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node and /dev/null differ diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/binding.Makefile b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/binding.Makefile deleted file mode 100644 index 64db433..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= ./build/. -.PHONY: all -all: - $(MAKE) sshcrypto diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/config.gypi b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/config.gypi deleted file mode 100644 index 5c73a43..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/config.gypi +++ /dev/null @@ -1,205 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "asan": 0, - "build_v8_with_gn": "false", - "coverage": "false", - "dcheck_always_on": 0, - "debug_nghttp2": "false", - "debug_node": "false", - "enable_lto": "false", - "enable_pgo_generate": "false", - "enable_pgo_use": "false", - "error_on_warn": "false", - "force_dynamic_crt": 0, - "gas_version": "2.30", - "host_arch": "x64", - "icu_data_in": "../../deps/icu-tmp/icudt69l.dat", - "icu_endianness": "l", - "icu_gyp_path": "tools/icu/icu-generic.gyp", - "icu_path": "deps/icu-small", - "icu_small": "false", - "icu_ver_major": "69", - "is_debug": 0, - "llvm_version": "0.0", - "napi_build_version": "8", - "node_byteorder": "little", - "node_debug_lib": "false", - "node_enable_d8": "false", - "node_install_npm": "true", - "node_module_version": 83, - "node_no_browser_globals": "false", - "node_prefix": "/", - "node_release_urlbase": "https://nodejs.org/download/release/", - "node_section_ordering_info": "", - "node_shared": "false", - "node_shared_brotli": "false", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_nghttp2": "false", - "node_shared_openssl": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_target_type": "executable", - "node_use_bundled_v8": "true", - "node_use_dtrace": "false", - "node_use_etw": "false", - "node_use_node_code_cache": "true", - "node_use_node_snapshot": "true", - "node_use_openssl": "true", - "node_use_v8_platform": "true", - "node_with_ltcg": "false", - "node_without_node_options": "false", - "openssl_fips": "", - "openssl_is_fips": "false", - "ossfuzz": "false", - "shlib_suffix": "so.83", - "target_arch": "x64", - "v8_enable_31bit_smis_on_64bit_arch": 0, - "v8_enable_gdbjit": 0, - "v8_enable_i18n_support": 1, - "v8_enable_inspector": 1, - "v8_enable_lite_mode": 0, - "v8_enable_object_print": 1, - "v8_enable_pointer_compression": 0, - "v8_no_strict_aliasing": 1, - "v8_optimized_debug": 1, - "v8_promise_internal_field_count": 1, - "v8_random_seed": 0, - "v8_trace_maps": 0, - "v8_use_siphash": 1, - "want_separate_host_toolset": 0, - "nodedir": "/home/vitalii/.cache/node-gyp/14.17.6", - "standalone_static_library": 1, - "target": "v14.17.6", - "cache_lock_stale": "60000", - "ham_it_up": "", - "legacy_bundling": "", - "sign_git_tag": "", - "user_agent": "npm/6.14.15 node/v14.17.6 linux x64", - "always_auth": "", - "bin_links": "true", - "key": "", - "allow_same_version": "", - "description": "true", - "fetch_retries": "2", - "heading": "npm", - "if_present": "", - "init_version": "1.0.0", - "user": "", - "prefer_online": "", - "force": "", - "only": "", - "read_only": "", - "cache_min": "10", - "init_license": "ISC", - "editor": "vi", - "rollback": "true", - "tag_version_prefix": "v", - "cache_max": "Infinity", - "timing": "", - "userconfig": "/home/vitalii/.npmrc", - "engine_strict": "", - "init_author_name": "", - "init_author_url": "", - "preid": "", - "tmp": "/tmp", - "depth": "Infinity", - "package_lock_only": "", - "save_dev": "", - "usage": "", - "metrics_registry": "https://registry.npmjs.org/", - "otp": "", - "package_lock": "true", - "progress": "true", - "https_proxy": "", - "save_prod": "", - "audit": "true", - "cidr": "", - "onload_script": "", - "sso_type": "oauth", - "rebuild_bundle": "true", - "save_bundle": "", - "shell": "/bin/bash", - "dry_run": "", - "format_package_lock": "true", - "prefix": "/usr", - "scope": "", - "browser": "", - "cache_lock_wait": "10000", - "ignore_prepublish": "", - "registry": "https://registry.npmjs.org/", - "save_optional": "", - "searchopts": "", - "versions": "", - "cache": "/home/vitalii/.npm", - "send_metrics": "", - "global_style": "", - "ignore_scripts": "", - "version": "", - "local_address": "", - "viewer": "man", - "node_gyp": "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js", - "audit_level": "low", - "prefer_offline": "", - "color": "true", - "sign_git_commit": "", - "fetch_retry_mintimeout": "10000", - "maxsockets": "50", - "offline": "", - "sso_poll_frequency": "500", - "umask": "0002", - "fund": "true", - "fetch_retry_maxtimeout": "60000", - "logs_max": "10", - "message": "%s", - "ca": "", - "cert": "", - "global": "", - "link": "", - "access": "", - "also": "", - "save": "true", - "unicode": "true", - "before": "", - "long": "", - "production": "", - "searchlimit": "20", - "unsafe_perm": "true", - "update_notifier": "true", - "auth_type": "legacy", - "node_version": "14.17.6", - "tag": "latest", - "git_tag_version": "true", - "commit_hooks": "true", - "script_shell": "", - "shrinkwrap": "true", - "fetch_retry_factor": "10", - "save_exact": "", - "strict_ssl": "true", - "dev": "", - "globalconfig": "/usr/etc/npmrc", - "init_module": "/home/vitalii/.npm-init.js", - "parseable": "", - "globalignorefile": "/usr/etc/npmignore", - "cache_lock_retries": "10", - "searchstaleness": "900", - "node_options": "", - "save_prefix": "^", - "scripts_prepend_node_path": "warn-only", - "group": "1000", - "init_author_email": "", - "searchexclude": "", - "git": "git", - "optional": "true", - "json": "" - } -} diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/sshcrypto.target.mk b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/sshcrypto.target.mk deleted file mode 100644 index 04a5e8e..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/build/sshcrypto.target.mk +++ /dev/null @@ -1,161 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := sshcrypto -DEFS_Debug := \ - '-DNODE_GYP_MODULE_NAME=sshcrypto' \ - '-DUSING_UV_SHARED=1' \ - '-DUSING_V8_SHARED=1' \ - '-DV8_DEPRECATION_WARNINGS=1' \ - '-DV8_DEPRECATION_WARNINGS' \ - '-DV8_IMMINENT_DEPRECATION_WARNINGS' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-D__STDC_FORMAT_MACROS' \ - '-DOPENSSL_NO_PINSHARED' \ - '-DOPENSSL_THREADS' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' \ - '-DV8_ENABLE_CHECKS' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -fPIC \ - -pthread \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -m64 \ - -O3 \ - -g \ - -O0 - -# Flags passed to only C files. -CFLAGS_C_Debug := - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti \ - -fno-exceptions \ - -std=gnu++1y - -INCS_Debug := \ - -I/home/vitalii/.cache/node-gyp/14.17.6/include/node \ - -I/home/vitalii/.cache/node-gyp/14.17.6/src \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/config \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/openssl/include \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/uv/include \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/zlib \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/v8/include \ - -I$(srcdir)/../../../../nan - -DEFS_Release := \ - '-DNODE_GYP_MODULE_NAME=sshcrypto' \ - '-DUSING_UV_SHARED=1' \ - '-DUSING_V8_SHARED=1' \ - '-DV8_DEPRECATION_WARNINGS=1' \ - '-DV8_DEPRECATION_WARNINGS' \ - '-DV8_IMMINENT_DEPRECATION_WARNINGS' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-D__STDC_FORMAT_MACROS' \ - '-DOPENSSL_NO_PINSHARED' \ - '-DOPENSSL_THREADS' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -fPIC \ - -pthread \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -m64 \ - -O3 \ - -O3 \ - -fno-omit-frame-pointer - -# Flags passed to only C files. -CFLAGS_C_Release := - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti \ - -fno-exceptions \ - -std=gnu++1y - -INCS_Release := \ - -I/home/vitalii/.cache/node-gyp/14.17.6/include/node \ - -I/home/vitalii/.cache/node-gyp/14.17.6/src \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/config \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/openssl/openssl/include \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/uv/include \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/zlib \ - -I/home/vitalii/.cache/node-gyp/14.17.6/deps/v8/include \ - -I$(srcdir)/../../../../nan - -OBJS := \ - $(obj).target/$(TARGET)/src/binding.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -pthread \ - -rdynamic \ - -m64 - -LDFLAGS_Release := \ - -pthread \ - -rdynamic \ - -m64 - -LIBS := - -$(obj).target/sshcrypto.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(obj).target/sshcrypto.node: LIBS := $(LIBS) -$(obj).target/sshcrypto.node: TOOLSET := $(TOOLSET) -$(obj).target/sshcrypto.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(obj).target/sshcrypto.node -# Add target alias -.PHONY: sshcrypto -sshcrypto: $(builddir)/sshcrypto.node - -# Copy this to the executable output path. -$(builddir)/sshcrypto.node: TOOLSET := $(TOOLSET) -$(builddir)/sshcrypto.node: $(obj).target/sshcrypto.node FORCE_DO_CMD - $(call do_cmd,copy) - -all_deps += $(builddir)/sshcrypto.node -# Short alias for building this executable. -.PHONY: sshcrypto.node -sshcrypto.node: $(obj).target/sshcrypto.node $(builddir)/sshcrypto.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/sshcrypto.node - diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/poly1305.js b/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/poly1305.js deleted file mode 100644 index a6953fe..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/crypto/poly1305.js +++ /dev/null @@ -1,43 +0,0 @@ - -var createPoly1305 = (function() { - var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; - if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; - return ( -function(createPoly1305) { - createPoly1305 = createPoly1305 || {}; - - -var b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x="object"===typeof window,y="function"===typeof importScripts,z="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node,B="",C,D,E,F,G; -if(z)B=y?require("path").dirname(B)+"/":__dirname+"/",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=require("fs"));G||(G=require("path"));a=G.normalize(a);return F.readFileSync(a,c?null:"utf8")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=require("fs"));G||(G=require("path"));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]= -0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g="";else g="boolean"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0,ha,Q,P; -function ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={}; -function K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");r(a);throw a;}var V="data:application/octet-stream;base64,",W;W="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw"both async and sync fetching of the wasm failed";}catch(d){K(d)}} -function qa(){if(!J&&(x||y)){if("function"===typeof fetch&&!W.startsWith("file://"))return fetch(W,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+W+"'";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})} -function X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}}; -(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I("failed to asynchronously prepare wasm: "+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e, -a)}catch(f){return I("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return J||"function"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith("file://")||"function"!==typeof fetch?d(c):fetch(W,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I("wasm streaming compile failed: "+l);I("falling back to ArrayBuffer instantiation");return d(c)})})})().catch(r);return{}})(); -b.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)}; -b._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return"number"===l});return"string"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)}; -function Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 -#include -#include - -#include -#include -#include - -#include -#include -#include - -using namespace node; -using namespace v8; -using namespace std; - -struct MarkPopErrorOnReturn { - MarkPopErrorOnReturn() { ERR_set_mark(); } - ~MarkPopErrorOnReturn() { ERR_pop_to_mark(); } -}; - -enum ErrorType { - kErrNone, - kErrOpenSSL, - kErrBadIVLen, - kErrBadKeyLen, - kErrAADFailure, - kErrTagFailure, - kErrPartialEncrypt, - kErrBadCipherName, - kErrBadHMACName, - kErrBadHMACLen, - kErrBadInit, - kErrPartialDecrypt, - kErrInvalidMAC, - kErrBadBlockLen -}; - -#define MAX_MAC_LEN 64 - -#define POLY1305_KEYLEN 32 -#define POLY1305_TAGLEN 16 -class ChaChaPolyCipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("ChaChaPolyCipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "encrypt", Encrypt); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("ChaChaPolyCipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit ChaChaPolyCipher() - : ctx_main_(nullptr), - ctx_pktlen_(nullptr), - md_ctx_(nullptr), - polykey_(nullptr) {} - - ~ChaChaPolyCipher() { - clear(); - } - - void clear() { - if (ctx_pktlen_) { - EVP_CIPHER_CTX_cleanup(ctx_pktlen_); - EVP_CIPHER_CTX_free(ctx_pktlen_); - ctx_pktlen_ = nullptr; - } - if (ctx_main_) { - EVP_CIPHER_CTX_cleanup(ctx_main_); - EVP_CIPHER_CTX_free(ctx_main_); - ctx_main_ = nullptr; - } - if (polykey_) { - EVP_PKEY_free(polykey_); - polykey_ = nullptr; - } - if (md_ctx_) { - EVP_MD_CTX_free(md_ctx_); - md_ctx_ = nullptr; - } - // `polykey_ctx_` is not explicitly freed as it is freed implicitly when - // `md_ctx_` is freed - } - - ErrorType init(unsigned char* keys, size_t keys_len) { - ErrorType r = kErrNone; - const EVP_CIPHER* const cipher = EVP_get_cipherbyname("chacha20"); - - if (keys_len != 64) { - r = kErrBadKeyLen; - goto out; - } - - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if ((ctx_pktlen_ = EVP_CIPHER_CTX_new()) == nullptr - || (ctx_main_ = EVP_CIPHER_CTX_new()) == nullptr - || (md_ctx_ = EVP_MD_CTX_new()) == nullptr - || EVP_EncryptInit_ex(ctx_pktlen_, - cipher, - nullptr, - keys + 32, - nullptr) != 1 - || EVP_EncryptInit_ex(ctx_main_, - cipher, - nullptr, - keys, - nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_CIPHER_CTX_iv_length(ctx_pktlen_) != 16) { - r = kErrBadIVLen; - goto out; - } - -out: - return r; - } - - ErrorType encrypt(unsigned char* packet, - uint32_t packet_len, - uint32_t seqno) { - ErrorType r = kErrNone; - size_t sig_len = 16; - int outlen = 0; - - // `packet` layout: - // - uint32_t data_len = packet_len - POLY1305_TAGLEN; - - unsigned char polykey[POLY1305_KEYLEN] = {0}; - - uint8_t seqbuf[16] = {0}; - ((uint8_t*)(seqbuf))[12] = (seqno >> 24) & 0xff; - ((uint8_t*)(seqbuf))[13] = (seqno >> 16) & 0xff; - ((uint8_t*)(seqbuf))[14] = (seqno >> 8) & 0xff; - ((uint8_t*)(seqbuf))[15] = seqno & 0xff; - - // Generate Poly1305 key - if (EVP_EncryptInit_ex(ctx_main_, nullptr, nullptr, nullptr, seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_EncryptUpdate(ctx_main_, - polykey, - &outlen, - polykey, - sizeof(polykey)) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != sizeof(polykey)) { - r = kErrPartialEncrypt; - goto out; - } - - // Encrypt packet length - if (EVP_EncryptInit_ex(ctx_pktlen_, - nullptr, - nullptr, - nullptr, - seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_EncryptUpdate(ctx_pktlen_, packet, &outlen, packet, 4) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != 4) { - r = kErrPartialEncrypt; - goto out; - } - - // Encrypt rest of packet - seqbuf[0] = 1; - if (EVP_EncryptInit_ex(ctx_main_, nullptr, nullptr, nullptr, seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_EncryptUpdate(ctx_main_, - packet + 4, - &outlen, - packet + 4, - data_len - 4) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != data_len - 4) { - r = kErrPartialEncrypt; - goto out; - } - - // Poly1305 over ciphertext - if (polykey_) { - if (EVP_PKEY_CTX_ctrl(polykey_ctx_, - -1, - EVP_PKEY_OP_SIGNCTX, - EVP_PKEY_CTRL_SET_MAC_KEY, - sizeof(polykey), - (void*)polykey) <= 0) { - r = kErrOpenSSL; - goto out; - } - } else { - polykey_ = EVP_PKEY_new_raw_private_key(EVP_PKEY_POLY1305, - nullptr, - polykey, - sizeof(polykey)); - if (polykey_ == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if (!EVP_DigestSignInit(md_ctx_, - &polykey_ctx_, - nullptr, - nullptr, - polykey_)) { - r = kErrOpenSSL; - goto out; - } - } - - // Generate and write Poly1305 tag - if (EVP_DigestSign(md_ctx_, - packet + data_len, - &sig_len, - packet, - data_len) != 1) { - r = kErrOpenSSL; - goto out; - } - - out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid keys"); - - ChaChaPolyCipher* obj = new ChaChaPolyCipher(); - ErrorType r = obj->init( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]) - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid keys length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid IV length"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(Encrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - ChaChaPolyCipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - if (!info[1]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid sequence number"); - - ErrorType r = obj->encrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]), - Nan::To(info[1]).FromJust() - ); - switch (r) { - case kErrNone: - return; - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown encrypt failure"); - } - } - - static NAN_METHOD(Free) { - ChaChaPolyCipher* obj = ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - EVP_CIPHER_CTX* ctx_main_; - EVP_CIPHER_CTX* ctx_pktlen_; - EVP_MD_CTX* md_ctx_; - EVP_PKEY* polykey_; - EVP_PKEY_CTX* polykey_ctx_; -}; - -class AESGCMCipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("AESGCMCipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "encrypt", Encrypt); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("AESGCMCipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit AESGCMCipher() : ctx_(nullptr) {} - - ~AESGCMCipher() { - clear(); - } - - void clear() { - if (ctx_) { - EVP_CIPHER_CTX_cleanup(ctx_); - EVP_CIPHER_CTX_free(ctx_); - ctx_ = nullptr; - } - } - - ErrorType init(const char* name, - unsigned char* key, - size_t key_len, - unsigned char* iv, - size_t iv_len) { - ErrorType r = kErrNone; - - const EVP_CIPHER* const cipher = EVP_get_cipherbyname(name); - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if (cipher != EVP_aes_128_gcm() && cipher != EVP_aes_256_gcm()) { - r = kErrBadCipherName; - goto out; - } - - if ((ctx_ = EVP_CIPHER_CTX_new()) == nullptr - || EVP_EncryptInit_ex(ctx_, cipher, nullptr, nullptr, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_AEAD_SET_IVLEN, iv_len, nullptr)) { - r = kErrOpenSSL; - goto out; - } - - //~ if (iv_len != static_cast(EVP_CIPHER_CTX_iv_length(ctx_))) { - //~ r = kErrBadIVLen; - //~ goto out; - //~ } - - if (key_len != static_cast(EVP_CIPHER_CTX_key_length(ctx_))) { - if (!EVP_CIPHER_CTX_set_key_length(ctx_, key_len)) { - r = kErrBadKeyLen; - goto out; - } - } - - // Set key and IV - if (EVP_EncryptInit_ex(ctx_, nullptr, nullptr, key, iv) != 1) { - r = kErrOpenSSL; - goto out; - } - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_GCM_SET_IV_FIXED, -1, iv)) { - r = kErrOpenSSL; - goto out; - } - - // Disable padding - EVP_CIPHER_CTX_set_padding(ctx_, 0); - -out: - return r; - } - - ErrorType encrypt(unsigned char* packet, uint32_t packet_len) { - ErrorType r = kErrNone; - - // `packet` layout: - // - uint32_t data_len = packet_len - 16; - - int outlen = 0; - - // Increment IV - unsigned char lastiv[1]; - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_GCM_IV_GEN, 1, lastiv)) { - r = kErrOpenSSL; - goto out; - } - - // Set AAD (the packet length) - if (!EVP_EncryptUpdate(ctx_, nullptr, &outlen, packet, 4)) { - r = kErrOpenSSL; - goto out; - } - if (outlen != 4) { - r = kErrAADFailure; - goto out; - } - - // Encrypt everything but the packet length - if (EVP_EncryptUpdate(ctx_, - packet + 4, - &outlen, - packet + 4, - data_len - 4) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != data_len - 4) { - r = kErrPartialEncrypt; - goto out; - } - - // Generate authentication tag - if (!EVP_EncryptFinal_ex(ctx_, nullptr, &outlen)) { - r = kErrOpenSSL; - goto out; - } - - // Write authentication tag - if (EVP_CIPHER_CTX_ctrl(ctx_, - EVP_CTRL_AEAD_GET_TAG, - 16, - packet + data_len) != 1) { - r = kErrOpenSSL; - goto out; - } - -out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!info[0]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid OpenSSL cipher name"); - - if (!Buffer::HasInstance(info[1])) - return Nan::ThrowTypeError("Missing/Invalid key"); - - if (!Buffer::HasInstance(info[2])) - return Nan::ThrowTypeError("Missing/Invalid iv"); - - const Nan::Utf8String cipher_name(info[0]); - - AESGCMCipher* obj = new AESGCMCipher(); - ErrorType r = obj->init( - *cipher_name, - reinterpret_cast(Buffer::Data(info[1])), - Buffer::Length(info[1]), - reinterpret_cast(Buffer::Data(info[2])), - Buffer::Length(info[2]) - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid keys length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid IV length"); - case kErrBadCipherName: - return Nan::ThrowError("Invalid AES GCM cipher name"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(Encrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - AESGCMCipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - ErrorType r = obj->encrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]) - ); - switch (r) { - case kErrNone: - return; - case kErrAADFailure: - return Nan::ThrowError("Error setting AAD"); - case kErrPartialEncrypt: - return Nan::ThrowError("Failed to completely encrypt packet"); - case kErrTagFailure: - return Nan::ThrowError("Error generating authentication tag"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown encrypt failure"); - } - } - - static NAN_METHOD(Free) { - AESGCMCipher* obj = ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - EVP_CIPHER_CTX* ctx_; -}; - -class GenericCipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("GenericCipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "encrypt", Encrypt); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("GenericCipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit GenericCipher() - : ctx_(nullptr), - ctx_hmac_(nullptr), - hmac_len_(0), - is_etm_(0) {} - - ~GenericCipher() { - clear(); - } - - void clear() { - if (ctx_) { - EVP_CIPHER_CTX_cleanup(ctx_); - EVP_CIPHER_CTX_free(ctx_); - ctx_ = nullptr; - } - if (ctx_hmac_) { - HMAC_CTX_free(ctx_hmac_); - ctx_hmac_ = nullptr; - } - } - - ErrorType init(const char* name, - unsigned char* key, - size_t key_len, - unsigned char* iv, - size_t iv_len, - const char* hmac_name, - unsigned char* hmac_key, - size_t hmac_key_len, - int is_etm) { - ErrorType r = kErrNone; - - const EVP_MD* md; - const EVP_CIPHER* const cipher = EVP_get_cipherbyname(name); - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if ((ctx_ = EVP_CIPHER_CTX_new()) == nullptr - || EVP_EncryptInit_ex(ctx_, cipher, nullptr, nullptr, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (iv_len != static_cast(EVP_CIPHER_CTX_iv_length(ctx_))) { - r = kErrBadIVLen; - goto out; - } - - if (key_len != static_cast(EVP_CIPHER_CTX_key_length(ctx_))) { - if (!EVP_CIPHER_CTX_set_key_length(ctx_, key_len)) { - r = kErrBadKeyLen; - goto out; - } - } - - // Set key and IV - if (EVP_EncryptInit_ex(ctx_, nullptr, nullptr, key, iv) != 1) { - r = kErrOpenSSL; - goto out; - } - - // Disable padding - EVP_CIPHER_CTX_set_padding(ctx_, 0); - - if (cipher == EVP_rc4()) { - /* The "arcfour128" algorithm is the RC4 cipher, as described in - [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream - generated by the cipher MUST be discarded, and the first byte of the - first encrypted packet MUST be encrypted using the 1537th byte of - keystream. - - -- http://tools.ietf.org/html/rfc4345#section-4 */ - unsigned char zeros[1536] = {0}; - int outlen = sizeof(zeros); - if (EVP_EncryptUpdate(ctx_, - zeros, - &outlen, - zeros, - sizeof(zeros)) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != sizeof(zeros)) { - r = kErrBadInit; - goto out; - } - } - - md = EVP_get_digestbyname(hmac_name); - if (md == nullptr) { - r = kErrBadHMACName; - goto out; - } - - if ((ctx_hmac_ = HMAC_CTX_new()) == nullptr - || HMAC_Init_ex(ctx_hmac_, hmac_key, hmac_key_len, md, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - hmac_len_ = HMAC_size(ctx_hmac_); - is_etm_ = is_etm; - -out: - return r; - } - - ErrorType encrypt(unsigned char* packet, - uint32_t packet_len, - uint32_t seqno) { - ErrorType r = kErrNone; - - // `packet` layout: - // - uint32_t data_len = packet_len - hmac_len_; - - int outlen; - - uint8_t seqbuf[4] = {0}; - ((uint8_t*)(seqbuf))[0] = (seqno >> 24) & 0xff; - ((uint8_t*)(seqbuf))[1] = (seqno >> 16) & 0xff; - ((uint8_t*)(seqbuf))[2] = (seqno >> 8) & 0xff; - ((uint8_t*)(seqbuf))[3] = seqno & 0xff; - - if (is_etm_) { - // Encrypt everything but packet length - if (EVP_EncryptUpdate(ctx_, - packet + 4, - &outlen, - packet + 4, - data_len - 4) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != data_len - 4) { - r = kErrPartialEncrypt; - goto out; - } - - // HMAC over unencrypted packet length and ciphertext - { - unsigned int outlen = hmac_len_; - if (HMAC_Init_ex(ctx_hmac_, nullptr, 0, nullptr, nullptr) != 1 - || HMAC_Update(ctx_hmac_, seqbuf, sizeof(seqbuf)) != 1 - || HMAC_Update(ctx_hmac_, packet, data_len) != 1 - || HMAC_Final(ctx_hmac_, packet + data_len, &outlen) != 1) { - r = kErrOpenSSL; - goto out; - } - if (outlen != hmac_len_) { - r = kErrBadHMACLen; - goto out; - } - } - } else { - // HMAC over plaintext - { - unsigned int outlen = hmac_len_; - if (HMAC_Init_ex(ctx_hmac_, nullptr, 0, nullptr, nullptr) != 1 - || HMAC_Update(ctx_hmac_, seqbuf, sizeof(seqbuf)) != 1 - || HMAC_Update(ctx_hmac_, packet, data_len) != 1 - || HMAC_Final(ctx_hmac_, packet + data_len, &outlen) != 1) { - r = kErrOpenSSL; - goto out; - } - if (outlen != hmac_len_) { - r = kErrBadHMACLen; - goto out; - } - } - - // Encrypt packet - if (EVP_EncryptUpdate(ctx_, - packet, - &outlen, - packet, - data_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != data_len) { - - r = kErrPartialEncrypt; - goto out; - } - } - -out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!info[0]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid cipher name"); - - if (!Buffer::HasInstance(info[1])) - return Nan::ThrowTypeError("Missing/Invalid cipher key"); - - if (!Buffer::HasInstance(info[2])) - return Nan::ThrowTypeError("Missing/Invalid cipher IV"); - - if (!info[3]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid HMAC name"); - - if (!Buffer::HasInstance(info[4])) - return Nan::ThrowTypeError("Missing/Invalid HMAC key"); - - if (!info[5]->IsBoolean()) - return Nan::ThrowTypeError("Missing/Invalid HMAC ETM flag"); - - const Nan::Utf8String cipher_name(info[0]); - const Nan::Utf8String mac_name(info[3]); - int is_etm = (Nan::To(info[5]).FromJust() ? 1 : 0); - - GenericCipher* obj = new GenericCipher(); - ErrorType r = obj->init( - *cipher_name, - reinterpret_cast(Buffer::Data(info[1])), - Buffer::Length(info[1]), - reinterpret_cast(Buffer::Data(info[2])), - Buffer::Length(info[2]), - *mac_name, - reinterpret_cast(Buffer::Data(info[4])), - Buffer::Length(info[4]), - is_etm - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid keys length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid IV length"); - case kErrBadCipherName: - return Nan::ThrowError("Invalid cipher name"); - case kErrBadHMACName: - return Nan::ThrowError("Invalid MAC name"); - case kErrBadInit: - return Nan::ThrowError("Failed to properly initialize cipher"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(Encrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - GenericCipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - if (!info[1]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid sequence number"); - - ErrorType r = obj->encrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]), - Nan::To(info[1]).FromJust() - ); - switch (r) { - case kErrNone: - return; - case kErrPartialEncrypt: - return Nan::ThrowError("Failed to completely encrypt packet"); - case kErrBadHMACLen: - return Nan::ThrowError("Unexpected HMAC length"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown encrypt failure"); - } - } - - static NAN_METHOD(Free) { - GenericCipher* obj = ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - EVP_CIPHER_CTX* ctx_; - HMAC_CTX* ctx_hmac_; - unsigned int hmac_len_; - int is_etm_; -}; - -// ============================================================================= - -class ChaChaPolyDecipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("ChaChaPolyDecipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "decrypt", Decrypt); - SetPrototypeMethod(tpl, "decryptLen", DecryptLen); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("ChaChaPolyDecipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit ChaChaPolyDecipher() - : ctx_main_(nullptr), - ctx_pktlen_(nullptr), - md_ctx_(nullptr), - polykey_(nullptr) {} - - ~ChaChaPolyDecipher() { - clear(); - } - - void clear() { - if (ctx_pktlen_) { - EVP_CIPHER_CTX_cleanup(ctx_pktlen_); - EVP_CIPHER_CTX_free(ctx_pktlen_); - ctx_pktlen_ = nullptr; - } - if (ctx_main_) { - EVP_CIPHER_CTX_cleanup(ctx_main_); - EVP_CIPHER_CTX_free(ctx_main_); - ctx_main_ = nullptr; - } - if (polykey_) { - EVP_PKEY_free(polykey_); - polykey_ = nullptr; - } - if (md_ctx_) { - EVP_MD_CTX_free(md_ctx_); - md_ctx_ = nullptr; - } - // `polykey_ctx_` is not explicitly freed as it is freed implicitly when - // `md_ctx_` is freed - } - - ErrorType init(unsigned char* keys, size_t keys_len) { - ErrorType r = kErrNone; - const EVP_CIPHER* const cipher = EVP_get_cipherbyname("chacha20"); - - if (keys_len != 64) { - r = kErrBadKeyLen; - goto out; - } - - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if ((ctx_pktlen_ = EVP_CIPHER_CTX_new()) == nullptr - || (ctx_main_ = EVP_CIPHER_CTX_new()) == nullptr - || (md_ctx_ = EVP_MD_CTX_new()) == nullptr - || EVP_DecryptInit_ex(ctx_pktlen_, - cipher, - nullptr, - keys + 32, - nullptr) != 1 - || EVP_DecryptInit_ex(ctx_main_, - cipher, - nullptr, - keys, - nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_CIPHER_CTX_iv_length(ctx_pktlen_) != 16) { - r = kErrBadIVLen; - goto out; - } - -out: - return r; - } - - ErrorType decrypt_length(unsigned char* data, - size_t data_len, - uint32_t seqno, - uint32_t* packet_length) { - ErrorType r = kErrNone; - int outlen; - - unsigned char dec_length_bytes[4]; - - uint8_t seqbuf[16] = {0}; - ((uint8_t*)(seqbuf))[12] = (seqno >> 24) & 0xff; - ((uint8_t*)(seqbuf))[13] = (seqno >> 16) & 0xff; - ((uint8_t*)(seqbuf))[14] = (seqno >> 8) & 0xff; - ((uint8_t*)(seqbuf))[15] = seqno & 0xff; - - if (EVP_DecryptInit_ex(ctx_pktlen_, - nullptr, - nullptr, - nullptr, - seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_DecryptUpdate(ctx_pktlen_, - dec_length_bytes, - &outlen, - data, - data_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != 4) { - r = kErrPartialDecrypt; - goto out; - } - - *packet_length = (uint32_t)dec_length_bytes[0] << 24 - | (uint32_t)dec_length_bytes[1] << 16 - | (uint32_t)dec_length_bytes[2] << 8 - | (uint32_t)dec_length_bytes[3]; - memcpy(length_bytes, data, data_len); -out: - return r; - } - - ErrorType decrypt(unsigned char* packet, - uint32_t packet_len, - unsigned char* mac, - uint32_t seqno) { - ErrorType r = kErrNone; - size_t sig_len = 16; - int outlen = 0; - - // `packet` layout: - // - - unsigned char polykey[POLY1305_KEYLEN] = {0}; - unsigned char calc_mac[POLY1305_TAGLEN] = {0}; - - uint8_t seqbuf[16] = {0}; - ((uint8_t*)(seqbuf))[12] = (seqno >> 24) & 0xff; - ((uint8_t*)(seqbuf))[13] = (seqno >> 16) & 0xff; - ((uint8_t*)(seqbuf))[14] = (seqno >> 8) & 0xff; - ((uint8_t*)(seqbuf))[15] = seqno & 0xff; - - // Generate Poly1305 key - if (EVP_EncryptInit_ex(ctx_main_, nullptr, nullptr, nullptr, seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_EncryptUpdate(ctx_main_, - polykey, - &outlen, - polykey, - sizeof(polykey)) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != sizeof(polykey)) { - r = kErrPartialEncrypt; - goto out; - } - - // Poly1305 over ciphertext - if (polykey_) { - if (EVP_PKEY_CTX_ctrl(polykey_ctx_, - -1, - EVP_PKEY_OP_SIGNCTX, - EVP_PKEY_CTRL_SET_MAC_KEY, - sizeof(polykey), - (void*)polykey) <= 0) { - r = kErrOpenSSL; - goto out; - } - } else { - polykey_ = EVP_PKEY_new_raw_private_key(EVP_PKEY_POLY1305, - nullptr, - polykey, - sizeof(polykey)); - if (polykey_ == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if (!EVP_DigestSignInit(md_ctx_, - &polykey_ctx_, - nullptr, - nullptr, - polykey_)) { - r = kErrOpenSSL; - goto out; - } - } - if (EVP_DigestSignUpdate(md_ctx_, - length_bytes, - sizeof(length_bytes)) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_DigestSignUpdate(md_ctx_, packet, packet_len) != 1) { - r = kErrOpenSSL; - goto out; - } - - // Generate Poly1305 MAC - if (EVP_DigestSignFinal(md_ctx_, calc_mac, &sig_len) != 1) { - r = kErrOpenSSL; - goto out; - } - - // Compare MACs - if (CRYPTO_memcmp(mac, calc_mac, sizeof(calc_mac))) { - r = kErrInvalidMAC; - goto out; - } - - // Decrypt packet - seqbuf[0] = 1; - if (EVP_DecryptInit_ex(ctx_main_, nullptr, nullptr, nullptr, seqbuf) != 1) { - r = kErrOpenSSL; - goto out; - } - if (EVP_DecryptUpdate(ctx_main_, - packet, - &outlen, - packet, - packet_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != packet_len) { - r = kErrPartialDecrypt; - goto out; - } - - out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid keys"); - - ChaChaPolyDecipher* obj = new ChaChaPolyDecipher(); - ErrorType r = obj->init( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]) - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid keys length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid IV length"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(DecryptLen) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - ChaChaPolyDecipher* obj = - ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0]) || Buffer::Length(info[0]) != 4) - return Nan::ThrowTypeError("Missing/Invalid length bytes"); - - if (!info[1]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid sequence number"); - - unsigned char* length_bytes = - reinterpret_cast(Buffer::Data(info[0])); - - uint32_t dec_packet_length; - ErrorType r = obj->decrypt_length( - length_bytes, - Buffer::Length(info[0]), - Nan::To(info[1]).FromJust(), - &dec_packet_length - ); - - switch (r) { - case kErrNone: - return info.GetReturnValue().Set(dec_packet_length); - case kErrPartialDecrypt: - return Nan::ThrowError("Failed to completely decrypt packet length"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown decrypt failure"); - } - } - - static NAN_METHOD(Decrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - ChaChaPolyDecipher* obj = - ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - if (!Buffer::HasInstance(info[1]) - || Buffer::Length(info[1]) != POLY1305_TAGLEN) { - return Nan::ThrowTypeError("Missing/Invalid mac"); - } - - if (!info[2]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid sequence number"); - - ErrorType r = obj->decrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]), - reinterpret_cast(Buffer::Data(info[1])), - Nan::To(info[2]).FromJust() - ); - - switch (r) { - case kErrNone: - return; - case kErrInvalidMAC: - return Nan::ThrowError("Invalid MAC"); - case kErrPartialDecrypt: - return Nan::ThrowError("Failed to completely decrypt packet length"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown decrypt failure"); - } - } - - static NAN_METHOD(Free) { - ChaChaPolyDecipher* obj = - ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - unsigned char length_bytes[4]; - EVP_CIPHER_CTX* ctx_main_; - EVP_CIPHER_CTX* ctx_pktlen_; - EVP_MD_CTX* md_ctx_; - EVP_PKEY* polykey_; - EVP_PKEY_CTX* polykey_ctx_; -}; - -class AESGCMDecipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("AESGCMDecipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "decrypt", Decrypt); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("AESGCMDecipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit AESGCMDecipher() : ctx_(nullptr) {} - - ~AESGCMDecipher() { - clear(); - } - - void clear() { - if (ctx_) { - EVP_CIPHER_CTX_cleanup(ctx_); - EVP_CIPHER_CTX_free(ctx_); - ctx_ = nullptr; - } - } - - ErrorType init(const char* name, - unsigned char* key, - size_t key_len, - unsigned char* iv, - size_t iv_len) { - ErrorType r = kErrNone; - - const EVP_CIPHER* const cipher = EVP_get_cipherbyname(name); - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if (cipher != EVP_aes_128_gcm() && cipher != EVP_aes_256_gcm()) { - r = kErrBadCipherName; - goto out; - } - - if ((ctx_ = EVP_CIPHER_CTX_new()) == nullptr - || EVP_DecryptInit_ex(ctx_, cipher, nullptr, nullptr, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_AEAD_SET_IVLEN, iv_len, nullptr)) { - r = kErrOpenSSL; - goto out; - } - - //~ if (iv_len != static_cast(EVP_CIPHER_CTX_iv_length(ctx_))) { - //~ r = kErrBadIVLen; - //~ goto out; - //~ } - - if (key_len != static_cast(EVP_CIPHER_CTX_key_length(ctx_))) { - if (!EVP_CIPHER_CTX_set_key_length(ctx_, key_len)) { - r = kErrBadKeyLen; - goto out; - } - } - - // Set key and IV - if (EVP_DecryptInit_ex(ctx_, nullptr, nullptr, key, iv) != 1) { - r = kErrOpenSSL; - goto out; - } - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_GCM_SET_IV_FIXED, -1, iv)) { - r = kErrOpenSSL; - goto out; - } - - // Disable padding - EVP_CIPHER_CTX_set_padding(ctx_, 0); - -out: - return r; - } - - ErrorType decrypt(unsigned char* packet, - uint32_t packet_len, - unsigned char* length_bytes, - unsigned char* tag) { - ErrorType r = kErrNone; - - // `packet` layout: - // - - int outlen; - - // Increment IV - unsigned char lastiv[1]; - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_GCM_IV_GEN, 1, lastiv)) { - r = kErrOpenSSL; - goto out; - } - - // Set AAD (the packet length) - if (!EVP_DecryptUpdate(ctx_, nullptr, &outlen, length_bytes, 4)) { - r = kErrOpenSSL; - goto out; - } - if (outlen != 4) { - r = kErrAADFailure; - goto out; - } - - // Decrypt everything but the packet length - if (EVP_DecryptUpdate(ctx_, packet, &outlen, packet, packet_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != packet_len) { - r = kErrPartialDecrypt; - goto out; - } - - // Set authentication tag - if (EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_AEAD_SET_TAG, 16, tag) != 1) { - r = kErrOpenSSL; - goto out; - } - - // Verify authentication tag - if (!EVP_DecryptFinal_ex(ctx_, nullptr, &outlen)) { - r = kErrOpenSSL; - goto out; - } - -out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!info[0]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid OpenSSL cipher name"); - - if (!Buffer::HasInstance(info[1])) - return Nan::ThrowTypeError("Missing/Invalid key"); - - if (!Buffer::HasInstance(info[2])) - return Nan::ThrowTypeError("Missing/Invalid iv"); - - const Nan::Utf8String cipher_name(info[0]); - - AESGCMDecipher* obj = new AESGCMDecipher(); - ErrorType r = obj->init( - *cipher_name, - reinterpret_cast(Buffer::Data(info[1])), - Buffer::Length(info[1]), - reinterpret_cast(Buffer::Data(info[2])), - Buffer::Length(info[2]) - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid keys length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid IV length"); - case kErrBadCipherName: - return Nan::ThrowError("Invalid AES GCM cipher name"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(Decrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - AESGCMDecipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - if (!info[1]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid length"); - - if (!Buffer::HasInstance(info[2]) || Buffer::Length(info[2]) != 16) - return Nan::ThrowTypeError("Missing/Invalid tag"); - - uint32_t length = Nan::To(info[1]).FromJust(); - unsigned char length_bytes[4]; - length_bytes[0] = (length >> 24) & 0xFF; - length_bytes[1] = (length >> 16) & 0xFF; - length_bytes[2] = (length >> 8) & 0xFF; - length_bytes[3] = length & 0xFF; - - ErrorType r = obj->decrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]), - length_bytes, - reinterpret_cast(Buffer::Data(info[2])) - ); - switch (r) { - case kErrNone: - return; - case kErrAADFailure: - return Nan::ThrowError("Error setting AAD"); - case kErrPartialDecrypt: - return Nan::ThrowError("Failed to completely decrypt packet"); - case kErrTagFailure: - return Nan::ThrowError("Error generating authentication tag"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown decrypt failure"); - } - } - - static NAN_METHOD(Free) { - AESGCMDecipher* obj = ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - EVP_CIPHER_CTX* ctx_; -}; - -class GenericDecipher : public ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("GenericDecipher").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - SetPrototypeMethod(tpl, "decryptBlock", DecryptBlock); - SetPrototypeMethod(tpl, "decrypt", Decrypt); - SetPrototypeMethod(tpl, "free", Free); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - - Nan::Set(target, - Nan::New("GenericDecipher").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit GenericDecipher() - : ctx_(nullptr), - ctx_hmac_(nullptr), - hmac_len_(0), - is_etm_(0) {} - - ~GenericDecipher() { - clear(); - } - - void clear() { - if (ctx_) { - EVP_CIPHER_CTX_cleanup(ctx_); - EVP_CIPHER_CTX_free(ctx_); - ctx_ = nullptr; - } - if (ctx_hmac_) { - HMAC_CTX_free(ctx_hmac_); - ctx_hmac_ = nullptr; - } - } - - ErrorType init(const char* name, - unsigned char* key, - size_t key_len, - unsigned char* iv, - size_t iv_len, - const char* hmac_name, - unsigned char* hmac_key, - size_t hmac_key_len, - int is_etm, - size_t hmac_actual_len) { - ErrorType r = kErrNone; - - const EVP_MD* md; - const EVP_CIPHER* const cipher = EVP_get_cipherbyname(name); - if (cipher == nullptr) { - r = kErrOpenSSL; - goto out; - } - - if ((ctx_ = EVP_CIPHER_CTX_new()) == nullptr - || EVP_DecryptInit_ex(ctx_, cipher, nullptr, nullptr, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (iv_len != static_cast(EVP_CIPHER_CTX_iv_length(ctx_))) { - r = kErrBadIVLen; - goto out; - } - - if (key_len != static_cast(EVP_CIPHER_CTX_key_length(ctx_))) { - if (!EVP_CIPHER_CTX_set_key_length(ctx_, key_len)) { - r = kErrBadKeyLen; - goto out; - } - } - - // Set key and IV - if (EVP_DecryptInit_ex(ctx_, nullptr, nullptr, key, iv) != 1) { - r = kErrOpenSSL; - goto out; - } - - // Disable padding - EVP_CIPHER_CTX_set_padding(ctx_, 0); - - if (cipher == EVP_rc4()) { - /* The "arcfour128" algorithm is the RC4 cipher, as described in - [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream - generated by the cipher MUST be discarded, and the first byte of the - first encrypted packet MUST be encrypted using the 1537th byte of - keystream. - - -- http://tools.ietf.org/html/rfc4345#section-4 */ - unsigned char zeros[1536] = {0}; - int outlen = sizeof(zeros); - if (EVP_DecryptUpdate(ctx_, - zeros, - &outlen, - zeros, - sizeof(zeros)) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != sizeof(zeros)) { - r = kErrBadInit; - goto out; - } - } - - md = EVP_get_digestbyname(hmac_name); - if (md == nullptr) { - r = kErrBadHMACName; - goto out; - } - - if ((ctx_hmac_ = HMAC_CTX_new()) == nullptr - || HMAC_Init_ex(ctx_hmac_, hmac_key, hmac_key_len, md, nullptr) != 1) { - r = kErrOpenSSL; - goto out; - } - - hmac_len_ = HMAC_size(ctx_hmac_); - hmac_actual_len_ = hmac_actual_len; - is_etm_ = is_etm; - switch (EVP_CIPHER_CTX_mode(ctx_)) { - case EVP_CIPH_STREAM_CIPHER: - case EVP_CIPH_CTR_MODE: - is_stream_ = 1; - break; - default: - is_stream_ = 0; - } - block_size_ = EVP_CIPHER_CTX_block_size(ctx_); - -out: - return r; - } - - ErrorType decrypt_block(unsigned char* data, uint32_t data_len) { - ErrorType r = kErrNone; - - int outlen; - - if (!is_stream_ && data_len != block_size_) { - r = kErrBadBlockLen; - goto out; - } - - // Decrypt block - if (EVP_DecryptUpdate(ctx_, data, &outlen, data, data_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != data_len) { - r = kErrPartialDecrypt; - goto out; - } - -out: - return r; - } - - ErrorType decrypt(unsigned char* packet, - uint32_t packet_len, - uint32_t seqno, - unsigned char* first_block, - uint32_t first_block_len, - unsigned char* mac, - uint32_t mac_len) { - ErrorType r = kErrNone; - - int outlen; - unsigned char calc_mac[MAX_MAC_LEN] = {0}; - - uint8_t seqbuf[4] = {0}; - ((uint8_t*)(seqbuf))[0] = (seqno >> 24) & 0xff; - ((uint8_t*)(seqbuf))[1] = (seqno >> 16) & 0xff; - ((uint8_t*)(seqbuf))[2] = (seqno >> 8) & 0xff; - ((uint8_t*)(seqbuf))[3] = seqno & 0xff; - - if (is_etm_) { - // `first_block` for ETM should just be the unencrypted packet length - if (first_block_len != 4) { - r = kErrBadBlockLen; - goto out; - } - - // HMAC over unencrypted packet length and ciphertext - { - unsigned int outlen = hmac_len_; - if (HMAC_Init_ex(ctx_hmac_, nullptr, 0, nullptr, nullptr) != 1 - || HMAC_Update(ctx_hmac_, seqbuf, sizeof(seqbuf)) != 1 - || HMAC_Update(ctx_hmac_, first_block, 4) != 1 - || HMAC_Update(ctx_hmac_, packet, packet_len) != 1 - || HMAC_Final(ctx_hmac_, calc_mac, &outlen) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (outlen != hmac_len_ || mac_len != hmac_len_) { - r = kErrBadHMACLen; - goto out; - } - - // Compare MACs - if (CRYPTO_memcmp(mac, calc_mac, hmac_len_)) { - r = kErrInvalidMAC; - goto out; - } - } - - // Decrypt packet - if (EVP_DecryptUpdate(ctx_, packet, &outlen, packet, packet_len) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != packet_len) { - r = kErrPartialDecrypt; - goto out; - } - } else { - // `first_block` for non-ETM should be a completely decrypted first block - if (!is_stream_ && first_block_len != block_size_) { - r = kErrBadBlockLen; - goto out; - } - - const int offset = (is_stream_ ? 0 : block_size_ - 4); - // Decrypt the rest of the packet - if (EVP_DecryptUpdate(ctx_, - packet + offset, - &outlen, - packet + offset, - packet_len - offset) != 1) { - r = kErrOpenSSL; - goto out; - } - if (static_cast(outlen) != packet_len - offset) { - r = kErrPartialDecrypt; - goto out; - } - - // HMAC over plaintext - { - unsigned int outlen = hmac_len_; - if (HMAC_Init_ex(ctx_hmac_, nullptr, 0, nullptr, nullptr) != 1 - || HMAC_Update(ctx_hmac_, seqbuf, sizeof(seqbuf)) != 1 - || HMAC_Update(ctx_hmac_, first_block, 4) != 1 - || HMAC_Update(ctx_hmac_, packet, packet_len) != 1 - || HMAC_Final(ctx_hmac_, calc_mac, &outlen) != 1) { - r = kErrOpenSSL; - goto out; - } - - if (outlen != hmac_len_ || mac_len != hmac_actual_len_) { - r = kErrBadHMACLen; - goto out; - } - - // Compare MACs - if (CRYPTO_memcmp(mac, calc_mac, hmac_actual_len_)) { - r = kErrInvalidMAC; - goto out; - } - } - } - -out: - return r; - } - - static NAN_METHOD(New) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - if (!info[0]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid decipher name"); - - if (!Buffer::HasInstance(info[1])) - return Nan::ThrowTypeError("Missing/Invalid decipher key"); - - if (!Buffer::HasInstance(info[2])) - return Nan::ThrowTypeError("Missing/Invalid decipher IV"); - - if (!info[3]->IsString()) - return Nan::ThrowTypeError("Missing/Invalid HMAC name"); - - if (!Buffer::HasInstance(info[4])) - return Nan::ThrowTypeError("Missing/Invalid HMAC key"); - - if (!info[5]->IsBoolean()) - return Nan::ThrowTypeError("Missing/Invalid HMAC ETM flag"); - - if (!info[6]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid HMAC ETM flag"); - - const Nan::Utf8String cipher_name(info[0]); - const Nan::Utf8String mac_name(info[3]); - int is_etm = (Nan::To(info[5]).FromJust() ? 1 : 0); - - GenericDecipher* obj = new GenericDecipher(); - ErrorType r = obj->init( - *cipher_name, - reinterpret_cast(Buffer::Data(info[1])), - Buffer::Length(info[1]), - reinterpret_cast(Buffer::Data(info[2])), - Buffer::Length(info[2]), - *mac_name, - reinterpret_cast(Buffer::Data(info[4])), - Buffer::Length(info[4]), - is_etm, - Nan::To(info[6]).FromJust() - ); - if (r != kErrNone) { - if (r == kErrOpenSSL) { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - obj->clear(); - delete obj; - return Nan::ThrowError(msg_buf); - } - obj->clear(); - delete obj; - switch (r) { - case kErrBadKeyLen: - return Nan::ThrowError("Invalid decipher key length"); - case kErrBadIVLen: - return Nan::ThrowError("Invalid decipher IV length"); - case kErrBadCipherName: - return Nan::ThrowError("Invalid decipher name"); - case kErrBadHMACName: - return Nan::ThrowError("Invalid MAC name"); - case kErrBadInit: - return Nan::ThrowError("Failed to properly initialize decipher"); - default: - return Nan::ThrowError("Unknown init failure"); - } - } - - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } - - static NAN_METHOD(DecryptBlock) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - GenericDecipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid block"); - - ErrorType r = obj->decrypt_block( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]) - ); - switch (r) { - case kErrNone: - return; - case kErrBadBlockLen: - return Nan::ThrowError("Invalid block length"); - case kErrPartialDecrypt: - return Nan::ThrowError("Failed to completely decrypt packet"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown decrypt failure"); - } - } - - static NAN_METHOD(Decrypt) { - MarkPopErrorOnReturn mark_pop_error_on_return; - - GenericDecipher* obj = ObjectWrap::Unwrap(info.Holder()); - - if (!Buffer::HasInstance(info[0])) - return Nan::ThrowTypeError("Missing/Invalid packet"); - - if (!info[1]->IsUint32()) - return Nan::ThrowTypeError("Missing/Invalid sequence number"); - - if (!Buffer::HasInstance(info[2])) - return Nan::ThrowTypeError("Missing/Invalid first block"); - - if (!Buffer::HasInstance(info[3])) - return Nan::ThrowTypeError("Missing/Invalid MAC"); - - ErrorType r = obj->decrypt( - reinterpret_cast(Buffer::Data(info[0])), - Buffer::Length(info[0]), - Nan::To(info[1]).FromJust(), - reinterpret_cast(Buffer::Data(info[2])), - Buffer::Length(info[2]), - reinterpret_cast(Buffer::Data(info[3])), - Buffer::Length(info[3]) - ); - switch (r) { - case kErrNone: - return; - case kErrBadBlockLen: - return Nan::ThrowError("Invalid block length"); - case kErrPartialDecrypt: - return Nan::ThrowError("Failed to completely decrypt packet"); - case kErrBadHMACLen: - return Nan::ThrowError("Unexpected HMAC length"); - case kErrInvalidMAC: - return Nan::ThrowError("Invalid MAC"); - case kErrOpenSSL: { - char msg_buf[128] = {0}; - ERR_error_string_n(ERR_get_error(), msg_buf, sizeof(msg_buf)); - ERR_clear_error(); - return Nan::ThrowError(msg_buf); - } - default: - return Nan::ThrowError("Unknown decrypt failure"); - } - } - - static NAN_METHOD(Free) { - GenericDecipher* obj = ObjectWrap::Unwrap(info.Holder()); - obj->clear(); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - EVP_CIPHER_CTX* ctx_; - HMAC_CTX* ctx_hmac_; - unsigned int hmac_len_; - unsigned int hmac_actual_len_; - uint8_t is_etm_; - uint8_t is_stream_; - uint32_t block_size_; -}; - - -NAN_MODULE_INIT(init) { - ChaChaPolyCipher::Init(target); - AESGCMCipher::Init(target); - GenericCipher::Init(target); - - ChaChaPolyDecipher::Init(target); - AESGCMDecipher::Init(target); - GenericDecipher::Init(target); -} - -NODE_MODULE(sshcrypto, init) diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.js b/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.js deleted file mode 100644 index 35fb9f2..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const MESSAGE_HANDLERS = new Array(256); -[ - require('./kex.js').HANDLERS, - require('./handlers.misc.js'), -].forEach((handlers) => { - // eslint-disable-next-line prefer-const - for (let [type, handler] of Object.entries(handlers)) { - type = +type; - if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) - MESSAGE_HANDLERS[type] = handler; - } -}); - -module.exports = MESSAGE_HANDLERS; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.misc.js b/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.misc.js deleted file mode 100644 index 647564b..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/handlers.misc.js +++ /dev/null @@ -1,1214 +0,0 @@ -'use strict'; - -const { - bufferSlice, - bufferParser, - doFatalError, - sigSSHToASN1, - writeUInt32BE, -} = require('./utils.js'); - -const { - CHANNEL_OPEN_FAILURE, - COMPAT, - MESSAGE, - TERMINAL_MODE, -} = require('./constants.js'); - -const { - parseKey, -} = require('./keyParser.js'); - -const TERMINAL_MODE_BY_VALUE = - Array.from(Object.entries(TERMINAL_MODE)) - .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); - -module.exports = { - // Transport layer protocol ================================================== - [MESSAGE.DISCONNECT]: (self, payload) => { - /* - byte SSH_MSG_DISCONNECT - uint32 reason code - string description in ISO-10646 UTF-8 encoding - string language tag - */ - bufferParser.init(payload, 1); - const reason = bufferParser.readUInt32BE(); - const desc = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DISCONNECT packet' - ); - } - - self._debug && self._debug( - `Inbound: Received DISCONNECT (${reason}, "${desc}")` - ); - - const handler = self._handlers.DISCONNECT; - handler && handler(self, reason, desc); - }, - [MESSAGE.IGNORE]: (self, payload) => { - /* - byte SSH_MSG_IGNORE - string data - */ - self._debug && self._debug('Inbound: Received IGNORE'); - }, - [MESSAGE.UNIMPLEMENTED]: (self, payload) => { - /* - byte SSH_MSG_UNIMPLEMENTED - uint32 packet sequence number of rejected message - */ - bufferParser.init(payload, 1); - const seqno = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (seqno === undefined) { - return doFatalError( - self, - 'Inbound: Malformed UNIMPLEMENTED packet' - ); - } - - self._debug - && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); - }, - [MESSAGE.DEBUG]: (self, payload) => { - /* - byte SSH_MSG_DEBUG - boolean always_display - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const display = bufferParser.readBool(); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DEBUG packet' - ); - } - - self._debug && self._debug('Inbound: Received DEBUG'); - - const handler = self._handlers.DEBUG; - handler && handler(self, display, msg); - }, - [MESSAGE.SERVICE_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_SERVICE_REQUEST - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_REQUEST packet' - ); - } - - self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`); - - const handler = self._handlers.SERVICE_REQUEST; - handler && handler(self, name); - }, - [MESSAGE.SERVICE_ACCEPT]: (self, payload) => { - // S->C - /* - byte SSH_MSG_SERVICE_ACCEPT - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_ACCEPT packet' - ); - } - - self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); - - const handler = self._handlers.SERVICE_ACCEPT; - handler && handler(self, name); - }, - - // User auth protocol -- generic ============================================= - [MESSAGE.USERAUTH_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_USERAUTH_REQUEST - string user name in ISO-10646 UTF-8 encoding [RFC3629] - string service name in US-ASCII - string method name in US-ASCII - .... method specific fields - */ - bufferParser.init(payload, 1); - const user = bufferParser.readString(true); - const service = bufferParser.readString(true); - const method = bufferParser.readString(true); - let methodData; - let methodDesc; - switch (method) { - case 'none': - methodData = null; - break; - case 'password': { - /* - boolean - string plaintext password in ISO-10646 UTF-8 encoding [RFC3629] - [string new password] - */ - const isChange = bufferParser.readBool(); - if (isChange !== undefined) { - methodData = bufferParser.readString(true); - if (methodData !== undefined && isChange) { - const newPassword = bufferParser.readString(true); - if (newPassword !== undefined) - methodData = { oldPassword: methodData, newPassword }; - else - methodData = undefined; - } - } - break; - } - case 'publickey': { - /* - boolean - string public key algorithm name - string public key blob - [string signature] - */ - const hasSig = bufferParser.readBool(); - if (hasSig !== undefined) { - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - if (hasSig) { - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } - - signature = sigSSHToASN1(signature, keyAlgo); - if (signature) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo, - key, - signature, - blob, - }; - } - } - } else { - methodData = { keyAlgo, key }; - methodDesc = 'publickey -- check'; - } - } - break; - } - case 'hostbased': { - /* - string public key algorithm for host key - string public host key and certificates for client host - string client host name expressed as the FQDN in US-ASCII - string user name on the client host in ISO-10646 UTF-8 encoding - [RFC3629] - string signature - */ - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - const localHostname = bufferParser.readString(true); - const localUsername = bufferParser.readString(true); - - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } - - signature = sigSSHToASN1(signature, keyAlgo); - if (signature !== undefined) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo, - key, - signature, - blob, - localHostname, - localUsername, - }; - } - } - break; - } - case 'keyboard-interactive': - /* - string language tag (as defined in [RFC-3066]) - string submethods (ISO-10646 UTF-8) - */ - // Skip/ignore language field -- it's deprecated in RFC 4256 - bufferParser.skipString(); - - methodData = bufferParser.readList(); - break; - default: - if (method !== undefined) - methodData = bufferParser.readRaw(); - } - bufferParser.clear(); - - if (methodData === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_REQUEST packet' - ); - } - - if (methodDesc === undefined) - methodDesc = method; - - self._authsQueue.push(method); - - self._debug - && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); - - const handler = self._handlers.USERAUTH_REQUEST; - handler && handler(self, user, service, method, methodData); - }, - [MESSAGE.USERAUTH_FAILURE]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_FAILURE - name-list authentications that can continue - boolean partial success - */ - bufferParser.init(payload, 1); - const authMethods = bufferParser.readList(); - const partialSuccess = bufferParser.readBool(); - bufferParser.clear(); - - if (partialSuccess === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_FAILURE packet' - ); - } - - self._debug - && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_FAILURE; - handler && handler(self, authMethods, partialSuccess); - }, - [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_SUCCESS - */ - self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS'); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_SUCCESS; - handler && handler(self); - }, - [MESSAGE.USERAUTH_BANNER]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_BANNER - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_BANNER packet' - ); - } - - self._debug && self._debug('Inbound: Received USERAUTH_BANNER'); - - const handler = self._handlers.USERAUTH_BANNER; - handler && handler(self, msg); - }, - - // User auth protocol -- method-specific ===================================== - 60: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 60 without auth'); - return; - } - - switch (self._authsQueue[0]) { - case 'password': { - // S->C - /* - byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ - string prompt in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const prompt = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet' - ); - } - - self._debug - && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ'); - - const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ; - handler && handler(self, prompt); - break; - } - case 'publickey': { - // S->C - /* - byte SSH_MSG_USERAUTH_PK_OK - string public key algorithm name from the request - string public key blob from the request - */ - bufferParser.init(payload, 1); - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - bufferParser.clear(); - - if (key === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PK_OK packet' - ); - } - - self._debug && self._debug('Inbound: Received USERAUTH_PK_OK'); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_PK_OK; - handler && handler(self, keyAlgo, key); - break; - } - case 'keyboard-interactive': { - // S->C - /* - byte SSH_MSG_USERAUTH_INFO_REQUEST - string name (ISO-10646 UTF-8) - string instruction (ISO-10646 UTF-8) - string language tag (as defined in [RFC-3066]) - int num-prompts - string prompt[1] (ISO-10646 UTF-8) - boolean echo[1] - ... - string prompt[num-prompts] (ISO-10646 UTF-8) - boolean echo[num-prompts] - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const instructions = bufferParser.readString(true); - bufferParser.readString(); // skip lang - const numPrompts = bufferParser.readUInt32BE(); - let prompts; - if (numPrompts !== undefined) { - prompts = new Array(numPrompts); - let i; - for (i = 0; i < numPrompts; ++i) { - const prompt = bufferParser.readString(true); - const echo = bufferParser.readBool(); - if (echo === undefined) - break; - prompts[i] = { prompt, echo }; - } - if (i !== numPrompts) - prompts = undefined; - } - bufferParser.clear(); - - if (prompts === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_REQUEST packet' - ); - } - - self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST'); - - const handler = self._handlers.USERAUTH_INFO_REQUEST; - handler && handler(self, name, instructions, prompts); - break; - } - default: - self._debug - && self._debug('Inbound: Received unexpected payload type 60'); - } - }, - 61: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 61 without auth'); - return; - } - /* - byte SSH_MSG_USERAUTH_INFO_RESPONSE - int num-responses - string response[1] (ISO-10646 UTF-8) - ... - string response[num-responses] (ISO-10646 UTF-8) - */ - if (self._authsQueue[0] !== 'keyboard-interactive') { - return doFatalError( - self, - 'Inbound: Received unexpected payload type 61' - ); - } - bufferParser.init(payload, 1); - const numResponses = bufferParser.readUInt32BE(); - let responses; - if (numResponses !== undefined) { - responses = new Array(numResponses); - let i; - for (i = 0; i < numResponses; ++i) { - const response = bufferParser.readString(true); - if (response === undefined) - break; - responses[i] = response; - } - if (i !== numResponses) - responses = undefined; - } - bufferParser.clear(); - - if (responses === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet' - ); - } - - self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE'); - - const handler = self._handlers.USERAUTH_INFO_RESPONSE; - handler && handler(self, responses); - }, - - // Connection protocol -- generic ============================================ - [MESSAGE.GLOBAL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_GLOBAL_REQUEST - string request name in US-ASCII only - boolean want reply - .... request-specific data follows - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (name) { - case 'tcpip-forward': - case 'cancel-tcpip-forward': { - /* - string address to bind (e.g., "0.0.0.0") - uint32 port number to bind - */ - const bindAddr = bufferParser.readString(true); - const bindPort = bufferParser.readUInt32BE(); - if (bindPort !== undefined) - data = { bindAddr, bindPort }; - break; - } - case 'streamlocal-forward@openssh.com': - case 'cancel-streamlocal-forward@openssh.com': { - /* - string socket path - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) - data = { socketPath }; - break; - } - case 'no-more-sessions@openssh.com': - data = null; - break; - case 'hostkeys-00@openssh.com': { - data = []; - while (bufferParser.avail() > 0) { - const keyRaw = bufferParser.readString(); - if (keyRaw === undefined) { - data = undefined; - break; - } - const key = parseKey(keyRaw); - if (!(key instanceof Error)) - data.push(key); - } - break; - } - default: - data = bufferParser.readRaw(); - } - } - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed GLOBAL_REQUEST packet' - ); - } - - self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`); - - const handler = self._handlers.GLOBAL_REQUEST; - if (handler) - handler(self, name, wantReply, data); - else - self.requestFailure(); // Auto reject - }, - [MESSAGE.REQUEST_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_SUCCESS - .... response specific data - */ - const data = (payload.length > 1 ? bufferSlice(payload, 1) : null); - - self._debug && self._debug('Inbound: REQUEST_SUCCESS'); - - const handler = self._handlers.REQUEST_SUCCESS; - handler && handler(self, data); - }, - [MESSAGE.REQUEST_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_FAILURE - */ - self._debug && self._debug('Inbound: Received REQUEST_FAILURE'); - - const handler = self._handlers.REQUEST_FAILURE; - handler && handler(self); - }, - - // Connection protocol -- channel-related ==================================== - [MESSAGE.CHANNEL_OPEN]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN - string channel type in US-ASCII only - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - bufferParser.init(payload, 1); - const type = bufferParser.readString(true); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - let channelInfo; - - switch (type) { - case 'forwarded-tcpip': // S->C - case 'direct-tcpip': { // C->S - /* - string address that was connected / host to connect - uint32 port that was connected / port to connect - string originator IP address - uint32 originator port - */ - const destIP = bufferParser.readString(true); - const destPort = bufferParser.readUInt32BE(); - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { destIP, destPort, srcIP, srcPort } - }; - } - break; - } - case 'forwarded-streamlocal@openssh.com': // S->C - case 'direct-streamlocal@openssh.com': { // C->S - /* - string socket path - string reserved for future use - - (direct-streamlocal@openssh.com additionally has:) - uint32 reserved - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { socketPath } - }; - } - break; - } - case 'x11': { // S->C - /* - string originator address (e.g., "192.168.7.38") - uint32 originator port - */ - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { srcIP, srcPort } - }; - } - break; - } - default: - // Includes: - // 'session' (C->S) - // 'auth-agent@openssh.com' (S->C) - channelInfo = { - type, - sender, - window, - packetSize, - data: {} - }; - } - bufferParser.clear(); - - if (channelInfo === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN packet' - ); - } - - self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); - - const handler = self._handlers.CHANNEL_OPEN; - if (handler) { - handler(self, channelInfo); - } else { - self.channelOpenFail( - channelInfo.sender, - CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, - '', - '' - ); - } - }, - [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION - uint32 recipient channel - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - // "The 'recipient channel' is the channel number given in the - // original open request, and 'sender channel' is the channel number - // allocated by the other side." - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined); - bufferParser.clear(); - - if (packetSize === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet' - ); - } - - self._debug && self._debug( - `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` - ); - - const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION; - if (handler) - handler(self, { recipient, sender, window, packetSize, data }); - }, - [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_FAILURE - uint32 recipient channel - uint32 reason code - string description in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const reason = bufferParser.readUInt32BE(); - const description = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet' - ); - } - - self._debug - && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); - - const handler = self._handlers.CHANNEL_OPEN_FAILURE; - handler && handler(self, recipient, reason, description); - }, - [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_WINDOW_ADJUST - uint32 recipient channel - uint32 bytes to add - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const bytesToAdd = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (bytesToAdd === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet' - ); - } - - self._debug && self._debug( - `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` - ); - - const handler = self._handlers.CHANNEL_WINDOW_ADJUST; - handler && handler(self, recipient, bytesToAdd); - }, - [MESSAGE.CHANNEL_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_DATA - uint32 recipient channel - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_DATA packet' - ); - } - - self._debug - && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); - - const handler = self._handlers.CHANNEL_DATA; - handler && handler(self, recipient, data); - }, - [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EXTENDED_DATA - uint32 recipient channel - uint32 data_type_code - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet' - ); - } - - self._debug && self._debug( - `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` - ); - - const handler = self._handlers.CHANNEL_EXTENDED_DATA; - handler && handler(self, recipient, data, type); - }, - [MESSAGE.CHANNEL_EOF]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EOF - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EOF packet' - ); - } - - self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); - - const handler = self._handlers.CHANNEL_EOF; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_CLOSE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_CLOSE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_CLOSE packet' - ); - } - - self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); - - const handler = self._handlers.CHANNEL_CLOSE; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_REQUEST - uint32 recipient channel - string request type in US-ASCII characters only - boolean want reply - .... type-specific data follows - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (type) { - case 'exit-status': // S->C - /* - uint32 exit_status - */ - data = bufferParser.readUInt32BE(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'exit-signal': { // S->C - /* - string signal name (without the "SIG" prefix) - boolean core dumped - string error message in ISO-10646 UTF-8 encoding - string language tag - */ - let signal; - let coreDumped; - if (self._compatFlags & COMPAT.OLD_EXIT) { - /* - Instead of `signal name` and `core dumped`, we have just: - uint32 signal number - */ - const num = bufferParser.readUInt32BE(); - switch (num) { - case 1: - signal = 'HUP'; - break; - case 2: - signal = 'INT'; - break; - case 3: - signal = 'QUIT'; - break; - case 6: - signal = 'ABRT'; - break; - case 9: - signal = 'KILL'; - break; - case 14: - signal = 'ALRM'; - break; - case 15: - signal = 'TERM'; - break; - default: - if (num !== undefined) { - // Unknown or OS-specific - signal = `UNKNOWN (${num})`; - } - } - coreDumped = false; - } else { - signal = bufferParser.readString(true); - coreDumped = bufferParser.readBool(); - if (coreDumped === undefined) - signal = undefined; - } - const errorMessage = bufferParser.readString(true); - if (bufferParser.skipString() !== undefined) - data = { signal, coreDumped, errorMessage }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` - ); - break; - } - case 'pty-req': { // C->S - /* - string TERM environment variable value (e.g., vt100) - uint32 terminal width, characters (e.g., 80) - uint32 terminal height, rows (e.g., 24) - uint32 terminal width, pixels (e.g., 640) - uint32 terminal height, pixels (e.g., 480) - string encoded terminal modes - */ - const term = bufferParser.readString(true); - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - const modesBinary = bufferParser.readString(); - if (modesBinary !== undefined) { - bufferParser.init(modesBinary, 1); - let modes = {}; - while (bufferParser.avail()) { - const opcode = bufferParser.readByte(); - if (opcode === TERMINAL_MODE.TTY_OP_END) - break; - const name = TERMINAL_MODE_BY_VALUE[opcode]; - const value = bufferParser.readUInt32BE(); - if (opcode === undefined - || name === undefined - || value === undefined) { - modes = undefined; - break; - } - modes[name] = value; - } - if (modes !== undefined) - data = { term, cols, rows, width, height, modes }; - } - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'window-change': { // C->S - /* - uint32 terminal width, columns - uint32 terminal height, rows - uint32 terminal width, pixels - uint32 terminal height, pixels - */ - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - if (height !== undefined) - data = { cols, rows, width, height }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'x11-req': { // C->S - /* - boolean single connection - string x11 authentication protocol - string x11 authentication cookie - uint32 x11 screen number - */ - const single = bufferParser.readBool(); - const protocol = bufferParser.readString(true); - const cookie = bufferParser.readString(); - const screen = bufferParser.readUInt32BE(); - if (screen !== undefined) - data = { single, protocol, cookie, screen }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'env': { // C->S - /* - string variable name - string variable value - */ - const name = bufferParser.readString(true); - const value = bufferParser.readString(true); - if (value !== undefined) - data = { name, value }; - if (self._debug) { - self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ` - + `${name}=${value})` - ); - } - break; - } - case 'shell': // C->S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - case 'exec': // C->S - /* - string command - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'subsystem': // C->S - /* - string subsystem name - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'signal': // C->S - /* - string signal name (without the "SIG" prefix) - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'xon-xoff': // C->S - /* - boolean client can do - */ - data = bufferParser.readBool(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'auth-agent-req@openssh.com': // C-S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - default: - data = (bufferParser.avail() ? bufferParser.readRaw() : null); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - } - } - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_REQUEST packet' - ); - } - - const handler = self._handlers.CHANNEL_REQUEST; - handler && handler(self, recipient, type, wantReply, data); - }, - [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_SUCCESS - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_SUCCESS packet' - ); - } - - self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); - - const handler = self._handlers.CHANNEL_SUCCESS; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_FAILURE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_FAILURE packet' - ); - } - - self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); - - const handler = self._handlers.CHANNEL_FAILURE; - handler && handler(self, recipient); - }, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/kex.js b/reverse_engineering/node_modules/ssh2/lib/protocol/kex.js deleted file mode 100644 index 507c88a..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/kex.js +++ /dev/null @@ -1,1831 +0,0 @@ -'use strict'; - -const { - createDiffieHellman, - createDiffieHellmanGroup, - createECDH, - createHash, - createPublicKey, - diffieHellman, - generateKeyPairSync, - randomFillSync, -} = require('crypto'); - -const { Ber } = require('asn1'); - -const { - COMPAT, - curve25519Supported, - DEFAULT_KEX, - DEFAULT_SERVER_HOST_KEY, - DEFAULT_CIPHER, - DEFAULT_MAC, - DEFAULT_COMPRESSION, - DISCONNECT_REASON, - MESSAGE, -} = require('./constants.js'); -const { - CIPHER_INFO, - createCipher, - createDecipher, - MAC_INFO, -} = require('./crypto.js'); -const { parseDERKey } = require('./keyParser.js'); -const { - bufferFill, - bufferParser, - convertSignature, - doFatalError, - FastBuffer, - sigSSHToASN1, - writeUInt32BE, -} = require('./utils.js'); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = require('./zlib.js'); - -let MESSAGE_HANDLERS; - -const GEX_MIN_BITS = 2048; // RFC 8270 -const GEX_MAX_BITS = 8192; // RFC 8270 - -const EMPTY_BUFFER = Buffer.alloc(0); - -// Client/Server -function kexinit(self) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ - - let payload; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - const entry = self._offer.lists.kex; - let kex = entry.array; - let found = false; - for (let i = 0; i < kex.length; ++i) { - if (kex[i].indexOf('group-exchange') !== -1) { - if (!found) { - found = true; - // Copy array lazily - kex = kex.slice(); - } - kex.splice(i--, 1); - } - } - if (found) { - let len = 1 + 16 + self._offer.totalSize + 1 + 4; - const newKexBuf = Buffer.from(kex.join(',')); - len -= (entry.buffer.length - newKexBuf.length); - - const all = self._offer.lists.all; - const rest = new Uint8Array( - all.buffer, - all.byteOffset + 4 + entry.buffer.length, - all.length - (4 + entry.buffer.length) - ); - - payload = Buffer.allocUnsafe(len); - writeUInt32BE(payload, newKexBuf.length, 0); - payload.set(newKexBuf, 4); - payload.set(rest, 4 + newKexBuf.length); - } - } - - if (payload === undefined) { - payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4); - self._offer.copyAllTo(payload, 17); - } - - self._debug && self._debug('Outbound: Sending KEXINIT'); - - payload[0] = MESSAGE.KEXINIT; - randomFillSync(payload, 1, 16); - - // Zero-fill first_kex_packet_follows and reserved bytes - bufferFill(payload, 0, payload.length - 5); - - self._kexinit = payload; - - // Needed to correct the starting position in allocated "packets" when packets - // will be buffered due to active key exchange - self._packetRW.write.allocStart = 0; - - // TODO: only create single buffer and set _kexinit as slice of packet instead - { - const p = self._packetRW.write.allocStartKEX; - const packet = self._packetRW.write.alloc(payload.length, true); - packet.set(payload, p); - self._cipher.encrypt(self._packetRW.write.finalize(packet, true)); - } -} - -function handleKexInit(self, payload) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ - const init = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - }; - - bufferParser.init(payload, 17); - - if ((init.kex = bufferParser.readList()) === undefined - || (init.serverHostKey = bufferParser.readList()) === undefined - || (init.cs.cipher = bufferParser.readList()) === undefined - || (init.sc.cipher = bufferParser.readList()) === undefined - || (init.cs.mac = bufferParser.readList()) === undefined - || (init.sc.mac = bufferParser.readList()) === undefined - || (init.cs.compress = bufferParser.readList()) === undefined - || (init.sc.compress = bufferParser.readList()) === undefined - || (init.cs.lang = bufferParser.readList()) === undefined - || (init.sc.lang = bufferParser.readList()) === undefined) { - bufferParser.clear(); - return doFatalError( - self, - 'Received malformed KEXINIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - const pos = bufferParser.pos(); - const firstFollows = (pos < payload.length && payload[pos] === 1); - bufferParser.clear(); - - const local = self._offer; - const remote = init; - - let localKex = local.lists.kex.array; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - let found = false; - for (let i = 0; i < localKex.length; ++i) { - if (localKex[i].indexOf('group-exchange') !== -1) { - if (!found) { - found = true; - // Copy array lazily - localKex = localKex.slice(); - } - localKex.splice(i--, 1); - } - } - } - - let clientList; - let serverList; - let i; - const debug = self._debug; - - debug && debug('Inbound: Handshake in progress'); - - // Key exchange method ======================================================= - debug && debug(`Handshake: (local) KEX method: ${localKex}`); - debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`); - if (self._server) { - serverList = localKex; - clientList = remote.kex; - } else { - serverList = remote.kex; - clientList = localKex; - } - // Check for agreeable key exchange algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching key exchange algorithm'); - return doFatalError( - self, - 'Handshake failed: no matching key exchange algorithm', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.kex = clientList[i]; - debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`); - if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { - // Ignore next inbound packet, it was a wrong first guess at KEX algorithm - self._skipNextInboundPacket = true; - } - - - // Server host key format ==================================================== - const localSrvHostKey = local.lists.serverHostKey.array; - debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`); - debug && debug( - `Handshake: (remote) Host key format: ${remote.serverHostKey}` - ); - if (self._server) { - serverList = localSrvHostKey; - clientList = remote.serverHostKey; - } else { - serverList = remote.serverHostKey; - clientList = localSrvHostKey; - } - // Check for agreeable server host key format - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching host key format'); - return doFatalError( - self, - 'Handshake failed: no matching host key format', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.serverHostKey = clientList[i]; - debug && debug(`Handshake: Host key format: ${clientList[i]}`); - - - // Client->Server cipher ===================================================== - const localCSCipher = local.lists.cs.cipher.array; - debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`); - debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); - if (self._server) { - serverList = localCSCipher; - clientList = remote.cs.cipher; - } else { - serverList = remote.cs.cipher; - clientList = localCSCipher; - } - // Check for agreeable client->server cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S cipher'); - return doFatalError( - self, - 'Handshake failed: no matching C->S cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.cipher = clientList[i]; - debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`); - - - // Server->Client cipher ===================================================== - const localSCCipher = local.lists.sc.cipher.array; - debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`); - debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); - if (self._server) { - serverList = localSCCipher; - clientList = remote.sc.cipher; - } else { - serverList = remote.sc.cipher; - clientList = localSCCipher; - } - // Check for agreeable server->client cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C cipher'); - return doFatalError( - self, - 'Handshake failed: no matching S->C cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.cipher = clientList[i]; - debug && debug(`Handshake: S->C cipher: ${clientList[i]}`); - - - // Client->Server MAC ======================================================== - const localCSMAC = local.lists.cs.mac.array; - debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`); - debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); - if (CIPHER_INFO[init.cs.cipher].authLen > 0) { - init.cs.mac = ''; - debug && debug('Handshake: C->S MAC: '); - } else { - if (self._server) { - serverList = localCSMAC; - clientList = remote.cs.mac; - } else { - serverList = remote.cs.mac; - clientList = localCSMAC; - } - // Check for agreeable client->server hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S MAC'); - return doFatalError( - self, - 'Handshake failed: no matching C->S MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.mac = clientList[i]; - debug && debug(`Handshake: C->S MAC: ${clientList[i]}`); - } - - - // Server->Client MAC ======================================================== - const localSCMAC = local.lists.sc.mac.array; - debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`); - debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); - if (CIPHER_INFO[init.sc.cipher].authLen > 0) { - init.sc.mac = ''; - debug && debug('Handshake: S->C MAC: '); - } else { - if (self._server) { - serverList = localSCMAC; - clientList = remote.sc.mac; - } else { - serverList = remote.sc.mac; - clientList = localSCMAC; - } - // Check for agreeable server->client hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C MAC'); - return doFatalError( - self, - 'Handshake failed: no matching S->C MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.mac = clientList[i]; - debug && debug(`Handshake: S->C MAC: ${clientList[i]}`); - } - - - // Client->Server compression ================================================ - const localCSCompress = local.lists.cs.compress.array; - debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`); - debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); - if (self._server) { - serverList = localCSCompress; - clientList = remote.cs.compress; - } else { - serverList = remote.cs.compress; - clientList = localCSCompress; - } - // Check for agreeable client->server compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S compression'); - return doFatalError( - self, - 'Handshake failed: no matching C->S compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.compress = clientList[i]; - debug && debug(`Handshake: C->S compression: ${clientList[i]}`); - - - // Server->Client compression ================================================ - const localSCCompress = local.lists.sc.compress.array; - debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`); - debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); - if (self._server) { - serverList = localSCCompress; - clientList = remote.sc.compress; - } else { - serverList = remote.sc.compress; - clientList = localSCCompress; - } - // Check for agreeable server->client compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C compression'); - return doFatalError( - self, - 'Handshake failed: no matching S->C compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.compress = clientList[i]; - debug && debug(`Handshake: S->C compression: ${clientList[i]}`); - - init.cs.lang = ''; - init.sc.lang = ''; - - // XXX: hack -- find a better way to do this - if (self._kex) { - if (!self._kexinit) { - // We received a rekey request, but we haven't sent a KEXINIT in response - // yet - kexinit(self); - } - self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false }); - } - - self._kex = createKeyExchange(init, self, payload); - self._kex.start(); -} - -const createKeyExchange = (() => { - function convertToMpint(buf) { - let idx = 0; - let length = buf.length; - while (buf[idx] === 0x00) { - ++idx; - --length; - } - let newBuf; - if (buf[idx] & 0x80) { - newBuf = Buffer.allocUnsafe(1 + length); - newBuf[0] = 0; - buf.copy(newBuf, 1, idx); - buf = newBuf; - } else if (length !== buf.length) { - newBuf = Buffer.allocUnsafe(length); - buf.copy(newBuf, 0, idx); - buf = newBuf; - } - return buf; - } - - class KeyExchange { - constructor(negotiated, protocol, remoteKexinit) { - this._protocol = protocol; - - this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined); - this.negotiated = negotiated; - this._step = 1; - this._public = null; - this._dh = null; - this._sentNEWKEYS = false; - this._receivedNEWKEYS = false; - this._finished = false; - this._hostVerified = false; - - // Data needed for initializing cipher/decipher/etc. - this._kexinit = protocol._kexinit; - this._remoteKexinit = remoteKexinit; - this._identRaw = protocol._identRaw; - this._remoteIdentRaw = protocol._remoteIdentRaw; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; - } - finish() { - if (this._finished) - return false; - this._finished = true; - - const isServer = this._protocol._server; - const negotiated = this.negotiated; - - const pubKey = this.convertPublicKey(this._dhData); - let secret = this.computeSecret(this._dhData); - if (secret instanceof Error) { - secret.message = - `Error while computing DH secret (${this.type}): ${secret.message}`; - secret.level = 'handshake'; - return doFatalError( - this._protocol, - secret, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - const hash = createHash(this.hashName); - // V_C - hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw)); - // "V_S" - hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw)); - // "I_C" - hashString(hash, (isServer ? this._remoteKexinit : this._kexinit)); - // "I_S" - hashString(hash, (isServer ? this._kexinit : this._remoteKexinit)); - // "K_S" - const serverPublicHostKey = (isServer - ? this._hostKey.getPublicSSH() - : this._hostKey); - hashString(hash, serverPublicHostKey); - - if (this.type === 'groupex') { - // Group exchange-specific - const params = this.getDHParams(); - const num = Buffer.allocUnsafe(4); - // min (uint32) - writeUInt32BE(num, this._minBits, 0); - hash.update(num); - // preferred (uint32) - writeUInt32BE(num, this._prefBits, 0); - hash.update(num); - // max (uint32) - writeUInt32BE(num, this._maxBits, 0); - hash.update(num); - // prime - hashString(hash, params.prime); - // generator - hashString(hash, params.generator); - } - - // method-specific data sent by client - hashString(hash, (isServer ? pubKey : this.getPublicKey())); - // method-specific data sent by server - const serverPublicKey = (isServer ? this.getPublicKey() : pubKey); - hashString(hash, serverPublicKey); - // shared secret ("K") - hashString(hash, secret); - - // "H" - const exchangeHash = hash.digest(); - - if (!isServer) { - bufferParser.init(this._sig, 0); - const sigType = bufferParser.readString(true); - - if (!sigType) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (sigType !== negotiated.serverHostKey) { - return doFatalError( - this._protocol, - `Wrong signature type: ${sigType}, ` - + `expected: ${negotiated.serverHostKey}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // "s" - let sigValue = bufferParser.readString(); - - bufferParser.clear(); - - if (sigValue === undefined) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { - return doFatalError( - this._protocol, - 'Malformed signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - let parsedHostKey; - { - bufferParser.init(this._hostKey, 0); - const name = bufferParser.readString(true); - const hostKey = this._hostKey.slice(bufferParser.pos()); - bufferParser.clear(); - parsedHostKey = parseDERKey(hostKey, name); - if (parsedHostKey instanceof Error) { - parsedHostKey.level = 'handshake'; - return doFatalError( - this._protocol, - parsedHostKey, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } - - this._protocol._debug - && this._protocol._debug('Verifying signature ...'); - - const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); - if (verified !== true) { - if (verified instanceof Error) { - this._protocol._debug && this._protocol._debug( - `Signature verification failed: ${verified.stack}` - ); - } else { - this._protocol._debug && this._protocol._debug( - 'Signature verification failed' - ); - } - return doFatalError( - this._protocol, - 'Handshake failed: signature verification failed', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug('Verified signature'); - } else { - // Server - - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } - - this._protocol._debug && this._protocol._debug( - 'Generating signature ...' - ); - - let signature = this._hostKey.sign(exchangeHash, hashAlgo); - if (signature instanceof Error) { - return doFatalError( - this._protocol, - 'Handshake failed: signature generation failed for ' - + `${this._hostKey.type} host key: ${signature.message}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - signature = convertSignature(signature, this._hostKey.type); - if (signature === false) { - return doFatalError( - this._protocol, - 'Handshake failed: signature conversion failed for ' - + `${this._hostKey.type} host key`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // Send KEX reply - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - const sigType = this.negotiated.serverHostKey; - const sigTypeLen = Buffer.byteLength(sigType); - const sigLen = 4 + sigTypeLen + 4 + signature.length; - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 - + 4 + serverPublicHostKey.length - + 4 + serverPublicKey.length - + 4 + sigLen, - true - ); - - packet[p] = MESSAGE.KEXDH_REPLY; - - writeUInt32BE(packet, serverPublicHostKey.length, ++p); - packet.set(serverPublicHostKey, p += 4); - - writeUInt32BE(packet, - serverPublicKey.length, - p += serverPublicHostKey.length); - packet.set(serverPublicKey, p += 4); - - writeUInt32BE(packet, sigLen, p += serverPublicKey.length); - - writeUInt32BE(packet, sigTypeLen, p += 4); - packet.utf8Write(sigType, p += 4, sigTypeLen); - - writeUInt32BE(packet, signature.length, p += sigTypeLen); - packet.set(signature, p += 4); - - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_REPLY'; - break; - case 'groupex': - type = 'KEXDH_GEX_REPLY'; - break; - default: - type = 'KEXECDH_REPLY'; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - trySendNEWKEYS(this); - - const completeHandshake = () => { - if (!this.sessionID) - this.sessionID = exchangeHash; - - { - const newSecret = Buffer.allocUnsafe(4 + secret.length); - writeUInt32BE(newSecret, secret.length, 0); - newSecret.set(secret, 4); - secret = newSecret; - } - - // Initialize new ciphers, deciphers, etc. - - const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; - const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; - - const csIV = generateKEXVal(csCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'A'); - const scIV = generateKEXVal(scCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'B'); - const csKey = generateKEXVal(csCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'C'); - const scKey = generateKEXVal(scCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'D'); - let csMacInfo; - let csMacKey; - if (!csCipherInfo.authLen) { - csMacInfo = MAC_INFO[negotiated.cs.mac]; - csMacKey = generateKEXVal(csMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'E'); - } - let scMacInfo; - let scMacKey; - if (!scCipherInfo.authLen) { - scMacInfo = MAC_INFO[negotiated.sc.mac]; - scMacKey = generateKEXVal(scMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'F'); - } - - const config = { - inbound: { - onPayload: this._protocol._onPayload, - seqno: this._protocol._decipher.inSeqno, - decipherInfo: (!isServer ? scCipherInfo : csCipherInfo), - decipherIV: (!isServer ? scIV : csIV), - decipherKey: (!isServer ? scKey : csKey), - macInfo: (!isServer ? scMacInfo : csMacInfo), - macKey: (!isServer ? scMacKey : csMacKey), - }, - outbound: { - onWrite: this._protocol._onWrite, - seqno: this._protocol._cipher.outSeqno, - cipherInfo: (isServer ? scCipherInfo : csCipherInfo), - cipherIV: (isServer ? scIV : csIV), - cipherKey: (isServer ? scKey : csKey), - macInfo: (isServer ? scMacInfo : csMacInfo), - macKey: (isServer ? scMacKey : csMacKey), - }, - }; - this._protocol._cipher && this._protocol._cipher.free(); - this._protocol._decipher && this._protocol._decipher.free(); - this._protocol._cipher = createCipher(config); - this._protocol._decipher = createDecipher(config); - - const rw = { - read: undefined, - write: undefined, - }; - switch (negotiated.cs.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication - - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression - - if (isServer) - rw.read = new PacketReader(); - else - rw.write = new PacketWriter(this._protocol); - } - switch (negotiated.sc.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication - - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression - - if (isServer) - rw.write = new PacketWriter(this._protocol); - else - rw.read = new PacketReader(); - } - this._protocol._packetRW.read.cleanup(); - this._protocol._packetRW.write.cleanup(); - this._protocol._packetRW = rw; - - // Cleanup/reset various state - this._public = null; - this._dh = null; - this._kexinit = this._protocol._kexinit = undefined; - this._remoteKexinit = undefined; - this._identRaw = undefined; - this._remoteIdentRaw = undefined; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; - - this._protocol._onHandshakeComplete(negotiated); - - return false; - }; - if (!isServer) - return completeHandshake(); - this.finish = completeHandshake; - } - - start() { - if (!this._protocol._server) { - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_INIT'; - break; - default: - type = 'KEXECDH_INIT'; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - - const pubKey = this.getPublicKey(); - - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + pubKey.length, - true - ); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - } - getPublicKey() { - this.generateKeys(); - - const key = this._public; - - if (key) - return this.convertPublicKey(key); - } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } - - if (key[idx] & 0x80) { - newKey = Buffer.allocUnsafe(1 + len); - newKey[0] = 0; - key.copy(newKey, 1, idx); - return newKey; - } - - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; - } - computeSecret(otherPublicKey) { - this.generateKeys(); - - try { - return convertToMpint(this._dh.computeSecret(otherPublicKey)); - } catch (ex) { - return ex; - } - } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: - if (this._protocol._server) { - // Server - if (type !== MESSAGE.KEXDH_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Init' - ); - /* - byte SSH_MSG_KEXDH_INIT - / SSH_MSG_KEX_ECDH_INIT - string - */ - bufferParser.init(payload, 1); - const dhData = bufferParser.readString(); - bufferParser.clear(); - if (dhData === undefined) { - return doFatalError( - this._protocol, - 'Received malformed KEX*_INIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // Client public key - this._dhData = dhData; - - let hostKey = - this._protocol._hostKeys[this.negotiated.serverHostKey]; - if (Array.isArray(hostKey)) - hostKey = hostKey[0]; - this._hostKey = hostKey; - - this.finish(); - } else { - // Client - if (type !== MESSAGE.KEXDH_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Reply' - ); - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - bufferParser.init(payload, 1); - let hostPubKey; - let dhData; - let sig; - if ((hostPubKey = bufferParser.readString()) === undefined - || (dhData = bufferParser.readString()) === undefined - || (sig = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEX*_REPLY', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); - - // Check that the host public key type matches what was negotiated - // during KEXINIT swap - bufferParser.init(hostPubKey, 0); - const hostPubKeyType = bufferParser.readString(true); - bufferParser.clear(); - if (hostPubKeyType === undefined) { - return doFatalError( - this._protocol, - 'Received malformed host public key', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - if (hostPubKeyType !== this.negotiated.serverHostKey) { - // Check if we need to make an exception - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': - case 'rsa-sha2-512': - if (hostPubKeyType === 'ssh-rsa') - break; - // FALLTHROUGH - default: - return doFatalError( - this._protocol, - 'Host key does not match negotiated type', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - - this._hostKey = hostPubKey; - this._dhData = dhData; - this._sig = sig; - - let checked = false; - let ret; - if (this._protocol._hostVerifier === undefined) { - ret = true; - this._protocol._debug && this._protocol._debug( - 'Host accepted by default (no verification)' - ); - } else { - ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { - if (checked) - return; - checked = true; - if (permitted === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - if (this._receivedNEWKEYS) - this.finish(); - else - trySendNEWKEYS(this); - }); - } - if (ret === undefined) { - // Async host verification - ++this._step; - return; - } - checked = true; - if (ret === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - trySendNEWKEYS(this); - } - ++this._step; - break; - case 2: - if (type !== MESSAGE.NEWKEYS) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Inbound: NEWKEYS' - ); - this._receivedNEWKEYS = true; - ++this._step; - if (this._protocol._server || this._hostVerified) - return this.finish(); - - // Signal to current decipher that we need to change to a new decipher - // for the next packet - return false; - default: - return doFatalError( - this._protocol, - `Received unexpected packet ${type} after NEWKEYS`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - } - - class Curve25519Exchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); - - this.type = '25519'; - this.hashName = hashName; - this._keys = null; - } - generateKeys() { - if (!this._keys) - this._keys = generateKeyPairSync('x25519'); - } - getPublicKey() { - this.generateKeys(); - - const key = this._keys.publicKey.export({ type: 'spki', format: 'der' }); - return key.slice(-32); // HACK: avoids parsing DER/BER header - } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } - - if (key.length === 32) - return key; - - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; - } - computeSecret(otherPublicKey) { - this.generateKeys(); - - try { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.110'); // id-X25519 - asnWriter.endSequence(); - - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(otherPublicKey.length); - otherPublicKey.copy(asnWriter._buf, - asnWriter._offset, - 0, - otherPublicKey.length); - asnWriter._offset += otherPublicKey.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - - return convertToMpint(diffieHellman({ - privateKey: this._keys.privateKey, - publicKey: createPublicKey({ - key: asnWriter.buffer, - type: 'spki', - format: 'der', - }), - })); - } catch (ex) { - return ex; - } - } - } - - class ECDHExchange extends KeyExchange { - constructor(curveName, hashName, ...args) { - super(...args); - - this.type = 'ecdh'; - this.curveName = curveName; - this.hashName = hashName; - } - generateKeys() { - if (!this._dh) { - this._dh = createECDH(this.curveName); - this._public = this._dh.generateKeys(); - } - } - } - - class DHGroupExchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); - - this.type = 'groupex'; - this.hashName = hashName; - this._prime = null; - this._generator = null; - this._minBits = GEX_MIN_BITS; - this._prefBits = dhEstimate(this.negotiated); - if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) - this._prefBits = Math.min(this._prefBits, 4096); - this._maxBits = GEX_MAX_BITS; - } - start() { - if (this._protocol._server) - return; - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_REQUEST' - ); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + 4 + 4, - true - ); - packet[p] = MESSAGE.KEXDH_GEX_REQUEST; - writeUInt32BE(packet, this._minBits, ++p); - writeUInt32BE(packet, this._prefBits, p += 4); - writeUInt32BE(packet, this._maxBits, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - generateKeys() { - if (!this._dh && this._prime && this._generator) { - this._dh = createDiffieHellman(this._prime, this._generator); - this._public = this._dh.generateKeys(); - } - } - setDHParams(prime, generator) { - if (!Buffer.isBuffer(prime)) - throw new Error('Invalid prime value'); - if (!Buffer.isBuffer(generator)) - throw new Error('Invalid generator value'); - this._prime = prime; - this._generator = generator; - } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; - } - } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_REQUEST) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ` - + MESSAGE.KEXDH_GEX_REQUEST, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - // TODO: allow user implementation to provide safe prime and - // generator on demand to support group exchange on server side - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (type !== MESSAGE.KEXDH_GEX_GROUP) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Group' - ); - - /* - byte SSH_MSG_KEX_DH_GEX_GROUP - mpint p, safe prime - mpint g, generator for subgroup in GF(p) - */ - bufferParser.init(payload, 1); - let prime; - let gen; - if ((prime = bufferParser.readString()) === undefined - || (gen = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEXDH_GEX_GROUP', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); - - // TODO: validate prime - this.setDHParams(prime, gen); - this.generateKeys(); - const pubkey = this.getPublicKey(); - - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_INIT' - ); - - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); - packet[p] = MESSAGE.KEXDH_GEX_INIT; - writeUInt32BE(packet, pubkey.length, ++p); - packet.set(pubkey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - - ++this._step; - break; - case 2: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Init' - ); - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Reply' - ); - this._step = 1; - payload[0] = MESSAGE.KEXDH_REPLY; - this.parse = KeyExchange.prototype.parse; - this.parse(payload); - } - } - } - - class DHExchange extends KeyExchange { - constructor(groupName, hashName, ...args) { - super(...args); - - this.type = 'group'; - this.groupName = groupName; - this.hashName = hashName; - } - start() { - if (!this._protocol._server) { - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_INIT' - ); - const pubKey = this.getPublicKey(); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - } - generateKeys() { - if (!this._dh) { - this._dh = createDiffieHellmanGroup(this.groupName); - this._public = this._dh.generateKeys(); - } - } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; - } - } - } - - return (negotiated, ...args) => { - if (typeof negotiated !== 'object' || negotiated === null) - throw new Error('Invalid negotiated argument'); - const kexType = negotiated.kex; - if (typeof kexType === 'string') { - args = [negotiated, ...args]; - switch (kexType) { - case 'curve25519-sha256': - case 'curve25519-sha256@libssh.org': - if (!curve25519Supported) - break; - return new Curve25519Exchange('sha256', ...args); - - case 'ecdh-sha2-nistp256': - return new ECDHExchange('prime256v1', 'sha256', ...args); - case 'ecdh-sha2-nistp384': - return new ECDHExchange('secp384r1', 'sha384', ...args); - case 'ecdh-sha2-nistp521': - return new ECDHExchange('secp521r1', 'sha512', ...args); - - case 'diffie-hellman-group1-sha1': - return new DHExchange('modp2', 'sha1', ...args); - case 'diffie-hellman-group14-sha1': - return new DHExchange('modp14', 'sha1', ...args); - case 'diffie-hellman-group14-sha256': - return new DHExchange('modp14', 'sha256', ...args); - case 'diffie-hellman-group15-sha512': - return new DHExchange('modp15', 'sha512', ...args); - case 'diffie-hellman-group16-sha512': - return new DHExchange('modp16', 'sha512', ...args); - case 'diffie-hellman-group17-sha512': - return new DHExchange('modp17', 'sha512', ...args); - case 'diffie-hellman-group18-sha512': - return new DHExchange('modp18', 'sha512', ...args); - - case 'diffie-hellman-group-exchange-sha1': - return new DHGroupExchange('sha1', ...args); - case 'diffie-hellman-group-exchange-sha256': - return new DHGroupExchange('sha256', ...args); - } - throw new Error(`Unsupported key exchange algorithm: ${kexType}`); - } - throw new Error(`Invalid key exchange type: ${kexType}`); - }; -})(); - -const KexInit = (() => { - const KEX_PROPERTY_NAMES = [ - 'kex', - 'serverHostKey', - ['cs', 'cipher' ], - ['sc', 'cipher' ], - ['cs', 'mac' ], - ['sc', 'mac' ], - ['cs', 'compress' ], - ['sc', 'compress' ], - ['cs', 'lang' ], - ['sc', 'lang' ], - ]; - return class KexInit { - constructor(obj) { - if (typeof obj !== 'object' || obj === null) - throw new TypeError('Argument must be an object'); - - const lists = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - - all: undefined, - }; - let totalSize = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let base; - let val; - let desc; - let key; - if (typeof prop === 'string') { - base = lists; - val = obj[prop]; - desc = key = prop; - } else { - const parent = prop[0]; - base = lists[parent]; - key = prop[1]; - val = obj[parent][key]; - desc = `${parent}.${key}`; - } - const entry = { array: undefined, buffer: undefined }; - if (Buffer.isBuffer(val)) { - entry.array = ('' + val).split(','); - entry.buffer = val; - totalSize += 4 + val.length; - } else { - if (typeof val === 'string') - val = val.split(','); - if (Array.isArray(val)) { - entry.array = val; - entry.buffer = Buffer.from(val.join(',')); - } else { - throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); - } - totalSize += 4 + entry.buffer.length; - } - base[key] = entry; - } - - const all = Buffer.allocUnsafe(totalSize); - lists.all = all; - - let allPos = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let data; - if (typeof prop === 'string') - data = lists[prop].buffer; - else - data = lists[prop[0]][prop[1]].buffer; - allPos = writeUInt32BE(all, data.length, allPos); - all.set(data, allPos); - allPos += data.length; - } - - this.totalSize = totalSize; - this.lists = lists; - } - copyAllTo(buf, offset) { - const src = this.lists.all; - if (typeof offset !== 'number') - throw new TypeError(`Invalid offset value: ${typeof offset}`); - if (buf.length - offset < src.length) - throw new Error('Insufficient space to copy list'); - buf.set(src, offset); - return src.length; - } - }; -})(); - -const hashString = (() => { - const LEN = Buffer.allocUnsafe(4); - return (hash, buf) => { - writeUInt32BE(LEN, buf.length, 0); - hash.update(LEN); - hash.update(buf); - }; -})(); - -function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { - let ret; - if (len) { - let digest = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(char) - .update(sessionID) - .digest(); - while (digest.length < len) { - const chunk = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(digest) - .digest(); - const extended = Buffer.allocUnsafe(digest.length + chunk.length); - extended.set(digest, 0); - extended.set(chunk, digest.length); - digest = extended; - } - if (digest.length === len) - ret = digest; - else - ret = new FastBuffer(digest.buffer, digest.byteOffset, len); - } else { - ret = EMPTY_BUFFER; - } - return ret; -} - -function onKEXPayload(state, payload) { - // XXX: move this to the Decipher implementations? - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; - } - - if (this._skipNextInboundPacket) { - this._skipNextInboundPacket = false; - return; - } - - payload = this._packetRW.read.read(payload); - - const type = payload[0]; - switch (type) { - case MESSAGE.DISCONNECT: - case MESSAGE.IGNORE: - case MESSAGE.UNIMPLEMENTED: - case MESSAGE.DEBUG: - if (!MESSAGE_HANDLERS) - MESSAGE_HANDLERS = require('./handlers.js'); - return MESSAGE_HANDLERS[type](this, payload); - case MESSAGE.KEXINIT: - if (!state.firstPacket) { - return doFatalError( - this, - 'Received extra KEXINIT during handshake', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - state.firstPacket = false; - return handleKexInit(this, payload); - default: - if (type < 20 || type > 49) { - return doFatalError( - this, - `Received unexpected packet type ${type}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - - return this._kex.parse(payload); -} - -function dhEstimate(neg) { - const csCipher = CIPHER_INFO[neg.cs.cipher]; - const scCipher = CIPHER_INFO[neg.sc.cipher]; - // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will - // also need to be considered when calculating `bits` - const bits = Math.max( - 0, - (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen), - csCipher.blockLen, - csCipher.ivLen, - (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen), - scCipher.blockLen, - scCipher.ivLen - ) * 8; - if (bits <= 112) - return 2048; - if (bits <= 128) - return 3072; - if (bits <= 192) - return 7680; - return 8192; -} - -function trySendNEWKEYS(kex) { - if (!kex._sentNEWKEYS) { - kex._protocol._debug && kex._protocol._debug( - 'Outbound: Sending NEWKEYS' - ); - const p = kex._protocol._packetRW.write.allocStartKEX; - const packet = kex._protocol._packetRW.write.alloc(1, true); - packet[p] = MESSAGE.NEWKEYS; - kex._protocol._cipher.encrypt( - kex._protocol._packetRW.write.finalize(packet, true) - ); - kex._sentNEWKEYS = true; - } -} - -module.exports = { - KexInit, - kexinit, - onKEXPayload, - DEFAULT_KEXINIT: new KexInit({ - kex: DEFAULT_KEX, - serverHostKey: DEFAULT_SERVER_HOST_KEY, - cs: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - sc: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - }), - HANDLERS: { - [MESSAGE.KEXINIT]: handleKexInit, - }, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/keyParser.js b/reverse_engineering/node_modules/ssh2/lib/protocol/keyParser.js deleted file mode 100644 index 9860e3f..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/keyParser.js +++ /dev/null @@ -1,1481 +0,0 @@ -// TODO: -// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()` -// * handle multi-line header values (OpenSSH)? -// * more thorough validation? -'use strict'; - -const { - createDecipheriv, - createECDH, - createHash, - createHmac, - createSign, - createVerify, - getCiphers, - sign: sign_, - verify: verify_, -} = require('crypto'); -const supportedOpenSSLCiphers = getCiphers(); - -const { Ber } = require('asn1'); -const bcrypt_pbkdf = require('bcrypt-pbkdf').pbkdf; - -const { CIPHER_INFO } = require('./crypto.js'); -const { eddsaSupported, SUPPORTED_CIPHER } = require('./constants.js'); -const { - bufferSlice, - makeBufferParser, - readString, - readUInt32BE, - writeUInt32BE, -} = require('./utils.js'); - -const SYM_HASH_ALGO = Symbol('Hash Algorithm'); -const SYM_PRIV_PEM = Symbol('Private key PEM'); -const SYM_PUB_PEM = Symbol('Public key PEM'); -const SYM_PUB_SSH = Symbol('Public key SSH'); -const SYM_DECRYPTED = Symbol('Decrypted Key'); - -// Create OpenSSL cipher name -> SSH cipher name conversion table -const CIPHER_INFO_OPENSSL = Object.create(null); -{ - const keys = Object.keys(CIPHER_INFO); - for (let i = 0; i < keys.length; ++i) { - const cipherName = CIPHER_INFO[keys[i]].sslName; - if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) - continue; - CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; - } -} - -const binaryKeyParser = makeBufferParser(); - -function makePEM(type, data) { - data = data.base64Slice(0, data.length); - let formatted = data.replace(/.{64}/g, '$&\n'); - if (data.length & 63) - formatted += '\n'; - return `-----BEGIN ${type} KEY-----\n${formatted}-----END ${type} KEY-----`; -} - -function combineBuffers(buf1, buf2) { - const result = Buffer.allocUnsafe(buf1.length + buf2.length); - result.set(buf1, 0); - result.set(buf2, buf1.length); - return result; -} - -function skipFields(buf, nfields) { - const bufLen = buf.length; - let pos = (buf._pos || 0); - for (let i = 0; i < nfields; ++i) { - const left = (bufLen - pos); - if (pos >= bufLen || left < 4) - return false; - const len = readUInt32BE(buf, pos); - if (left < 4 + len) - return false; - pos += 4 + len; - } - buf._pos = pos; - return true; -} - -function genOpenSSLRSAPub(n, e) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption - // algorithm parameters (RSA has none) - asnWriter.writeNull(); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.startSequence(); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHRSAPub(n, e) { - const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); - - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-rsa', 4, 7); - - let i = 4 + 7; - writeUInt32BE(publicKey, e.length, i); - publicKey.set(e, i += 4); - - writeUInt32BE(publicKey, n.length, i += e.length); - publicKey.set(n, i + 4); - - return publicKey; -} - -const genOpenSSLRSAPriv = (() => { - function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.writeBuffer(d, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(dmp1, Ber.Integer); - asnWriter.writeBuffer(dmq1, Ber.Integer); - asnWriter.writeBuffer(iqmp, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - - function bigIntFromBuffer(buf) { - return BigInt(`0x${buf.hexSlice(0, buf.length)}`); - } - - function bigIntToBuffer(bn) { - let hex = bn.toString(16); - if ((hex.length & 1) !== 0) { - hex = `0${hex}`; - } else { - const sigbit = hex.charCodeAt(0); - // BER/DER integers require leading zero byte to denote a positive value - // when first byte >= 0x80 - if (sigbit === 56/* '8' */ - || sigbit === 57/* '9' */ - || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) { - hex = `00${hex}`; - } - } - return Buffer.from(hex, 'hex'); - } - - return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) { - const bn_d = bigIntFromBuffer(d); - const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); - const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); - return makePEM('RSA PRIVATE', - genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp)); - }; -})(); - -function genOpenSSLDSAPub(p, q, g, y) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa - // algorithm parameters - asnWriter.startSequence(); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHDSAPub(p, q, g, y) { - const publicKey = Buffer.allocUnsafe( - 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length - ); - - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-dss', 4, 7); - - let i = 4 + 7; - writeUInt32BE(publicKey, p.length, i); - publicKey.set(p, i += 4); - - writeUInt32BE(publicKey, q.length, i += p.length); - publicKey.set(q, i += 4); - - writeUInt32BE(publicKey, g.length, i += q.length); - publicKey.set(g, i += 4); - - writeUInt32BE(publicKey, y.length, i += g.length); - publicKey.set(y, i + 4); - - return publicKey; -} - -function genOpenSSLDSAPriv(p, q, g, y, x) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.writeBuffer(x, Ber.Integer); - asnWriter.endSequence(); - return makePEM('DSA PRIVATE', asnWriter.buffer); -} - -function genOpenSSLEdPub(pub) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); - - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHEdPub(pub) { - const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); - - writeUInt32BE(publicKey, 11, 0); - publicKey.utf8Write('ssh-ed25519', 4, 11); - - writeUInt32BE(publicKey, pub.length, 15); - publicKey.set(pub, 19); - - return publicKey; -} - -function genOpenSSLEdPriv(priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x00, Ber.Integer); - - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); - - // PrivateKey - asnWriter.startSequence(Ber.OctetString); - asnWriter.writeBuffer(priv, Ber.OctetString); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PRIVATE', asnWriter.buffer); -} - -function genOpenSSLECDSAPub(oid, Q) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey - // algorithm parameters (namedCurve) - asnWriter.writeOID(oid); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(Q.length); - asnWriter._buf.set(Q, asnWriter._offset); - asnWriter._offset += Q.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHECDSAPub(oid, Q) { - let curveName; - switch (oid) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - curveName = 'nistp256'; - break; - case '1.3.132.0.34': - // secp384r1 - curveName = 'nistp384'; - break; - case '1.3.132.0.35': - // secp521r1 - curveName = 'nistp521'; - break; - default: - return; - } - - const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); - - writeUInt32BE(publicKey, 19, 0); - publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); - - writeUInt32BE(publicKey, 8, 23); - publicKey.utf8Write(curveName, 27, 8); - - writeUInt32BE(publicKey, Q.length, 35); - publicKey.set(Q, 39); - - return publicKey; -} - -function genOpenSSLECDSAPriv(oid, pub, priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x01, Ber.Integer); - // privateKey - asnWriter.writeBuffer(priv, Ber.OctetString); - // parameters (optional) - asnWriter.startSequence(0xA0); - asnWriter.writeOID(oid); - asnWriter.endSequence(); - // publicKey (optional) - asnWriter.startSequence(0xA1); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('EC PRIVATE', asnWriter.buffer); -} - -function genOpenSSLECDSAPubFromPriv(curveName, priv) { - const tempECDH = createECDH(curveName); - tempECDH.setPrivateKey(priv); - return tempECDH.getPublicKey(); -} - -const BaseKey = { - sign: (() => { - if (typeof sign_ === 'function') { - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return sign_(algo, data, pem); - } catch (ex) { - return ex; - } - }; - } - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const signature = createSign(algo); - signature.update(data); - try { - return signature.sign(pem); - } catch (ex) { - return ex; - } - }; - })(), - verify: (() => { - if (typeof verify_ === 'function') { - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return verify_(algo, data, pem, signature); - } catch (ex) { - return ex; - } - }; - } - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const verifier = createVerify(algo); - verifier.update(data); - try { - return verifier.verify(pem, signature); - } catch (ex) { - return ex; - } - }; - })(), - isPrivateKey: function isPrivateKey() { - return (this[SYM_PRIV_PEM] !== null); - }, - getPrivatePEM: function getPrivatePEM() { - return this[SYM_PRIV_PEM]; - }, - getPublicPEM: function getPublicPEM() { - return this[SYM_PUB_PEM]; - }, - getPublicSSH: function getPublicSSH() { - return this[SYM_PUB_SSH]; - }, - equals: function equals(key) { - const parsed = parseKey(key); - if (parsed instanceof Error) - return false; - return ( - this.type === parsed.type - && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] - && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] - && this[SYM_PUB_SSH] === parsed[SYM_PUB_SSH] - ); - }, -}; - - -function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -OpenSSH_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; - OpenSSH_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let ret; - const data = Buffer.from(m[1], 'base64'); - if (data.length < 31) // magic (+ magic null term.) + minimum field lengths - return new Error('Malformed OpenSSH private key'); - const magic = data.utf8Slice(0, 15); - if (magic !== 'openssh-key-v1\0') - return new Error(`Unsupported OpenSSH key magic: ${magic}`); - - const cipherName = readString(data, 15, true); - if (cipherName === undefined) - return new Error('Malformed OpenSSH private key'); - if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1) - return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); - - const kdfName = readString(data, data._pos, true); - if (kdfName === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'none') { - if (cipherName === 'none') - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'bcrypt') - return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); - if (!passphrase) { - return new Error( - 'Encrypted private OpenSSH key detected, but no passphrase given' - ); - } - } else if (cipherName !== 'none') { - return new Error('Malformed OpenSSH private key'); - } - - let encInfo; - let cipherKey; - let cipherIV; - if (cipherName !== 'none') - encInfo = CIPHER_INFO[cipherName]; - const kdfOptions = readString(data, data._pos); - if (kdfOptions === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfOptions.length) { - switch (kdfName) { - case 'none': - return new Error('Malformed OpenSSH private key'); - case 'bcrypt': - /* - string salt - uint32 rounds - */ - const salt = readString(kdfOptions, 0); - if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length) - return new Error('Malformed OpenSSH private key'); - const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); - const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); - const r = bcrypt_pbkdf(passphrase, - passphrase.length, - salt, - salt.length, - gen, - gen.length, - rounds); - if (r !== 0) - return new Error('Failed to generate information to decrypt key'); - cipherKey = bufferSlice(gen, 0, encInfo.keyLen); - cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); - break; - } - } else if (kdfName !== 'none') { - return new Error('Malformed OpenSSH private key'); - } - - if (data._pos + 3 >= data.length) - return new Error('Malformed OpenSSH private key'); - const keyCount = readUInt32BE(data, data._pos); - data._pos += 4; - - if (keyCount > 0) { - // TODO: place sensible limit on max `keyCount` - - // Read public keys first - for (let i = 0; i < keyCount; ++i) { - const pubData = readString(data, data._pos); - if (pubData === undefined) - return new Error('Malformed OpenSSH private key'); - const type = readString(pubData, 0, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); - } - - let privBlob = readString(data, data._pos); - if (privBlob === undefined) - return new Error('Malformed OpenSSH private key'); - - if (cipherKey !== undefined) { - // Encrypted private key(s) - if (privBlob.length < encInfo.blockLen - || (privBlob.length % encInfo.blockLen) !== 0) { - return new Error('Malformed OpenSSH private key'); - } - try { - const options = { authTagLength: encInfo.authLen }; - const decipher = createDecipheriv(encInfo.sslName, - cipherKey, - cipherIV, - options); - if (encInfo.authLen > 0) { - if (data.length - data._pos < encInfo.authLen) - return new Error('Malformed OpenSSH private key'); - decipher.setAuthTag( - bufferSlice(data, data._pos, data._pos += encInfo.authLen) - ); - } - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; - } - } - // Nothing should we follow the private key(s), except a possible - // authentication tag for relevant ciphers - if (data._pos !== data.length) - return new Error('Malformed OpenSSH private key'); - - ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined); - } else { - ret = []; - } - // This will need to change if/when OpenSSH ever starts storing multiple - // keys in their key files - return ret[0]; - }; - - function parseOpenSSHPrivKeys(data, nkeys, decrypted) { - const keys = []; - /* - uint32 checkint - uint32 checkint - string privatekey1 - string comment1 - string privatekey2 - string comment2 - ... - string privatekeyN - string commentN - char 1 - char 2 - char 3 - ... - char padlen % 255 - */ - if (data.length < 8) - return new Error('Malformed OpenSSH private key'); - const check1 = readUInt32BE(data, 0); - const check2 = readUInt32BE(data, 4); - if (check1 !== check2) { - if (decrypted) { - return new Error( - 'OpenSSH key integrity check failed -- bad passphrase?' - ); - } - return new Error('OpenSSH key integrity check failed'); - } - data._pos = 8; - let i; - let oid; - for (i = 0; i < nkeys; ++i) { - let algo; - let privPEM; - let pubPEM; - let pubSSH; - // The OpenSSH documentation for the key format actually lies, the - // entirety of the private key content is not contained with a string - // field, it's actually the literal contents of the private key, so to be - // able to find the end of the key data you need to know the layout/format - // of each key type ... - const type = readString(data, data._pos, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); - - switch (type) { - case 'ssh-rsa': { - /* - string n -- public - string e -- public - string d -- private - string iqmp -- private - string p -- private - string q -- private - */ - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH private key'); - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed OpenSSH private key'); - const d = readString(data, data._pos); - if (d === undefined) - return new Error('Malformed OpenSSH private key'); - const iqmp = readString(data, data._pos); - if (iqmp === undefined) - return new Error('Malformed OpenSSH private key'); - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - algo = 'sha1'; - break; - } - case 'ssh-dss': { - /* - string p -- public - string q -- public - string g -- public - string y -- public - string x -- private - */ - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH private key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH private key'); - const x = readString(data, data._pos); - if (x === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - algo = 'sha1'; - break; - } - case 'ssh-ed25519': { - if (!eddsaSupported) - return new Error(`Unsupported OpenSSH private key type: ${type}`); - /* - * string public key - * string private key + public key - */ - const edpub = readString(data, data._pos); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH private key'); - const edpriv = readString(data, data._pos); - if (edpriv === undefined || edpriv.length !== 64) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); - algo = null; - break; - } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; - } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; - } - /* - string curve name - string Q -- public - string d -- private - */ - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH private key'); - const ecpub = readString(data, data._pos); - if (ecpub === undefined) - return new Error('Malformed OpenSSH private key'); - const ecpriv = readString(data, data._pos); - if (ecpriv === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); - break; - } - default: - return new Error(`Unsupported OpenSSH private key type: ${type}`); - } - - const privComment = readString(data, data._pos, true); - if (privComment === undefined) - return new Error('Malformed OpenSSH private key'); - - keys.push( - new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo, - decrypted) - ); - } - let cnt = 0; - for (i = data._pos; i < data.length; ++i) { - if (data[i] !== (++cnt % 255)) - return new Error('Malformed OpenSSH private key'); - } - - return keys; - } -} - - -function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -OpenSSH_Old_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; - OpenSSH_Old_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let privBlob = Buffer.from(m[3], 'base64'); - let headers = m[2]; - let decrypted = false; - if (headers !== undefined) { - // encrypted key - headers = headers.split(/\r\n|\n/g); - for (let i = 0; i < headers.length; ++i) { - const header = headers[i]; - let sepIdx = header.indexOf(':'); - if (header.slice(0, sepIdx) === 'DEK-Info') { - const val = header.slice(sepIdx + 2); - sepIdx = val.indexOf(','); - if (sepIdx === -1) - continue; - const cipherName = val.slice(0, sepIdx).toLowerCase(); - if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); - } - const encInfo = CIPHER_INFO_OPENSSL[cipherName]; - if (!encInfo) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); - } - const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex'); - if (cipherIV.length !== encInfo.ivLen) - return new Error('Malformed encrypted OpenSSH private key'); - if (!passphrase) { - return new Error( - 'Encrypted OpenSSH private key detected, but no passphrase given' - ); - } - const ivSlice = bufferSlice(cipherIV, 0, 8); - let cipherKey = createHash('md5') - .update(passphrase) - .update(ivSlice) - .digest(); - while (cipherKey.length < encInfo.keyLen) { - cipherKey = combineBuffers( - cipherKey, - createHash('md5') - .update(cipherKey) - .update(passphrase) - .update(ivSlice) - .digest() - ); - } - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - decrypted = true; - } catch (ex) { - return ex; - } - } - } - } - - let type; - let privPEM; - let pubPEM; - let pubSSH; - let algo; - let reader; - let errMsg = 'Malformed OpenSSH private key'; - if (decrypted) - errMsg += '. Bad passphrase?'; - switch (m[1]) { - case 'RSA': - type = 'ssh-rsa'; - privPEM = makePEM('RSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const n = reader.readString(Ber.Integer, true); - if (n === null) - return new Error(errMsg); - const e = reader.readString(Ber.Integer, true); - if (e === null) - return new Error(errMsg); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'DSA': - type = 'ssh-dss'; - privPEM = makePEM('DSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const p = reader.readString(Ber.Integer, true); - if (p === null) - return new Error(errMsg); - const q = reader.readString(Ber.Integer, true); - if (q === null) - return new Error(errMsg); - const g = reader.readString(Ber.Integer, true); - if (g === null) - return new Error(errMsg); - const y = reader.readString(Ber.Integer, true); - if (y === null) - return new Error(errMsg); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'EC': - let ecSSLName; - let ecPriv; - let ecOID; - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - ecPriv = reader.readString(Ber.OctetString, true); - reader.readByte(); // Skip "complex" context type byte - const offset = reader.readLength(); // Skip context length - if (offset !== null) { - reader._offset = offset; - ecOID = reader.readOID(); - if (ecOID === null) - return new Error(errMsg); - switch (ecOID) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - ecSSLName = 'prime256v1'; - type = 'ecdsa-sha2-nistp256'; - algo = 'sha256'; - break; - case '1.3.132.0.34': - // secp384r1 - ecSSLName = 'secp384r1'; - type = 'ecdsa-sha2-nistp384'; - algo = 'sha384'; - break; - case '1.3.132.0.35': - // secp521r1 - ecSSLName = 'secp521r1'; - type = 'ecdsa-sha2-nistp521'; - algo = 'sha512'; - break; - default: - return new Error(`Unsupported private key EC OID: ${ecOID}`); - } - } else { - return new Error(errMsg); - } - } catch { - return new Error(errMsg); - } - privPEM = makePEM('EC PRIVATE', privBlob); - const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); - pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); - pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); - break; - } - - return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo, - decrypted); - }; -} - - -function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -PPK_Private.prototype = BaseKey; -{ - const EMPTY_PASSPHRASE = Buffer.alloc(0); - const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - const PPK_PP1 = Buffer.from([0, 0, 0, 0]); - const PPK_PP2 = Buffer.from([0, 0, 0, 1]); - const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; - PPK_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = key type - // m[2] = encryption type - // m[3] = comment - // m[4] = base64-encoded public key data: - // for "ssh-rsa": - // string "ssh-rsa" - // mpint e (public exponent) - // mpint n (modulus) - // for "ssh-dss": - // string "ssh-dss" - // mpint p (modulus) - // mpint q (prime) - // mpint g (base number) - // mpint y (public key parameter: g^x mod p) - // m[5] = base64-encoded private key data: - // for "ssh-rsa": - // mpint d (private exponent) - // mpint p (prime 1) - // mpint q (prime 2) - // mpint iqmp ([inverse of q] mod p) - // for "ssh-dss": - // mpint x (private key parameter) - // m[6] = SHA1 HMAC over: - // string name of algorithm ("ssh-dss", "ssh-rsa") - // string encryption type - // string comment - // string public key data - // string private-plaintext (including the final padding) - const cipherName = m[2]; - const encrypted = (cipherName !== 'none'); - if (encrypted && !passphrase) { - return new Error( - 'Encrypted PPK private key detected, but no passphrase given' - ); - } - - let privBlob = Buffer.from(m[5], 'base64'); - - if (encrypted) { - const encInfo = CIPHER_INFO[cipherName]; - let cipherKey = combineBuffers( - createHash('sha1').update(PPK_PP1).update(passphrase).digest(), - createHash('sha1').update(PPK_PP2).update(passphrase).digest() - ); - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(encInfo.sslName, - cipherKey, - PPK_IV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; - } - } - - const type = m[1]; - const comment = m[3]; - const pubBlob = Buffer.from(m[4], 'base64'); - - const mac = m[6]; - const typeLen = type.length; - const cipherNameLen = cipherName.length; - const commentLen = Buffer.byteLength(comment); - const pubLen = pubBlob.length; - const privLen = privBlob.length; - const macData = Buffer.allocUnsafe(4 + typeLen - + 4 + cipherNameLen - + 4 + commentLen - + 4 + pubLen - + 4 + privLen); - let p = 0; - - writeUInt32BE(macData, typeLen, p); - macData.utf8Write(type, p += 4, typeLen); - writeUInt32BE(macData, cipherNameLen, p += typeLen); - macData.utf8Write(cipherName, p += 4, cipherNameLen); - writeUInt32BE(macData, commentLen, p += cipherNameLen); - macData.utf8Write(comment, p += 4, commentLen); - writeUInt32BE(macData, pubLen, p += commentLen); - macData.set(pubBlob, p += 4); - writeUInt32BE(macData, privLen, p += pubLen); - macData.set(privBlob, p + 4); - - if (!passphrase) - passphrase = EMPTY_PASSPHRASE; - - const calcMAC = createHmac( - 'sha1', - createHash('sha1') - .update('putty-private-key-file-mac-key') - .update(passphrase) - .digest() - ).update(macData).digest('hex'); - - if (calcMAC !== mac) { - if (encrypted) { - return new Error( - 'PPK private key integrity check failed -- bad passphrase?' - ); - } - return new Error('PPK private key integrity check failed'); - } - - let pubPEM; - let pubSSH; - let privPEM; - pubBlob._pos = 0; - skipFields(pubBlob, 1); // skip (duplicate) key type - switch (type) { - case 'ssh-rsa': { - const e = readString(pubBlob, pubBlob._pos); - if (e === undefined) - return new Error('Malformed PPK public key'); - const n = readString(pubBlob, pubBlob._pos); - if (n === undefined) - return new Error('Malformed PPK public key'); - const d = readString(privBlob, 0); - if (d === undefined) - return new Error('Malformed PPK private key'); - const p = readString(privBlob, privBlob._pos); - if (p === undefined) - return new Error('Malformed PPK private key'); - const q = readString(privBlob, privBlob._pos); - if (q === undefined) - return new Error('Malformed PPK private key'); - const iqmp = readString(privBlob, privBlob._pos); - if (iqmp === undefined) - return new Error('Malformed PPK private key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - break; - } - case 'ssh-dss': { - const p = readString(pubBlob, pubBlob._pos); - if (p === undefined) - return new Error('Malformed PPK public key'); - const q = readString(pubBlob, pubBlob._pos); - if (q === undefined) - return new Error('Malformed PPK public key'); - const g = readString(pubBlob, pubBlob._pos); - if (g === undefined) - return new Error('Malformed PPK public key'); - const y = readString(pubBlob, pubBlob._pos); - if (y === undefined) - return new Error('Malformed PPK public key'); - const x = readString(privBlob, 0); - if (x === undefined) - return new Error('Malformed PPK private key'); - - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - break; - } - } - - return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1', - encrypted); - }; -} - - -function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; -} -OpenSSH_Public.prototype = BaseKey; -{ - let regexp; - if (eddsaSupported) - regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - else - regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - OpenSSH_Public.parse = (str) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = full type - // m[2] = base type - // m[3] = base64-encoded public key - // m[4] = comment - - const fullType = m[1]; - const baseType = m[2]; - const data = Buffer.from(m[3], 'base64'); - const comment = (m[4] || ''); - - const type = readString(data, data._pos, true); - if (type === undefined || type.indexOf(baseType) !== 0) - return new Error('Malformed OpenSSH public key'); - - return parseDER(data, baseType, comment, fullType); - }; -} - - -function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; -} -RFC4716_Public.prototype = BaseKey; -{ - const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; - const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; - const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; - const RE_HEADER_ENDS = /\\\r?\n/g; - RFC4716_Public.parse = (str) => { - let m = regexp.exec(str); - if (m === null) - return null; - - const body = m[1]; - let dataStart = 0; - let comment = ''; - - while (m = RE_HEADER.exec(body)) { - const headerName = m[1]; - const headerValue = m[2].replace(RE_HEADER_ENDS, ''); - if (headerValue.length > 1024) { - RE_HEADER.lastIndex = 0; - return new Error('Malformed RFC4716 public key'); - } - - dataStart = RE_HEADER.lastIndex; - - if (headerName.toLowerCase() === 'comment') { - comment = headerValue; - if (comment.length > 1 - && comment.charCodeAt(0) === 34/* '"' */ - && comment.charCodeAt(comment.length - 1) === 34/* '"' */) { - comment = comment.slice(1, -1); - } - } - } - - let data = body.slice(dataStart); - if (!RE_DATA.test(data)) - return new Error('Malformed RFC4716 public key'); - - data = Buffer.from(data, 'base64'); - - const type = readString(data, 0, true); - if (type === undefined) - return new Error('Malformed RFC4716 public key'); - - let pubPEM = null; - let pubSSH = null; - switch (type) { - case 'ssh-rsa': { - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed RFC4716 public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - break; - } - case 'ssh-dss': { - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed RFC4716 public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed RFC4716 public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed RFC4716 public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - break; - } - default: - return new Error('Malformed RFC4716 public key'); - } - - return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1'); - }; -} - - -function parseDER(data, baseType, comment, fullType) { - if (!isSupportedKeyType(baseType)) - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - - let algo; - let oid; - let pubPEM = null; - let pubSSH = null; - - switch (baseType) { - case 'ssh-rsa': { - const e = readString(data, data._pos || 0); - if (e === undefined) - return new Error('Malformed OpenSSH public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - algo = 'sha1'; - break; - } - case 'ssh-dss': { - const p = readString(data, data._pos || 0); - if (p === undefined) - return new Error('Malformed OpenSSH public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - algo = 'sha1'; - break; - } - case 'ssh-ed25519': { - const edpub = readString(data, data._pos || 0); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - algo = null; - break; - } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; - } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; - } - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH public key'); - const ecpub = readString(data, data._pos || 0); - if (ecpub === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - break; - } - default: - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - } - - return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); -} - -function isSupportedKeyType(type) { - switch (type) { - case 'ssh-rsa': - case 'ssh-dss': - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': - return true; - case 'ssh-ed25519': - if (eddsaSupported) - return true; - // FALLTHROUGH - default: - return false; - } -} - -function isParsedKey(val) { - if (!val) - return false; - return (typeof val[SYM_DECRYPTED] === 'boolean'); -} - -function parseKey(data, passphrase) { - if (isParsedKey(data)) - return data; - - let origBuffer; - if (Buffer.isBuffer(data)) { - origBuffer = data; - data = data.utf8Slice(0, data.length).trim(); - } else if (typeof data === 'string') { - data = data.trim(); - } else { - return new Error('Key data must be a Buffer or string'); - } - - // eslint-disable-next-line eqeqeq - if (passphrase != undefined) { - if (typeof passphrase === 'string') - passphrase = Buffer.from(passphrase); - else if (!Buffer.isBuffer(passphrase)) - return new Error('Passphrase must be a string or Buffer when supplied'); - } - - let ret; - - // First try as printable string format (e.g. PEM) - - // Private keys - if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = PPK_Private.parse(data, passphrase)) !== null) - return ret; - - // Public keys - if ((ret = OpenSSH_Public.parse(data)) !== null) - return ret; - if ((ret = RFC4716_Public.parse(data)) !== null) - return ret; - - // Finally try as a binary format if we were originally passed binary data - if (origBuffer) { - binaryKeyParser.init(origBuffer, 0); - const type = binaryKeyParser.readString(true); - if (type !== undefined) { - data = binaryKeyParser.readRaw(); - if (data !== undefined) { - ret = parseDER(data, type, '', type); - // Ignore potentially useless errors in case the data was not actually - // in the binary format - if (ret instanceof Error) - ret = null; - } - } - binaryKeyParser.clear(); - } - - if (ret) - return ret; - - return new Error('Unsupported key format'); -} - -module.exports = { - isParsedKey, - isSupportedKeyType, - parseDERKey: (data, type) => parseDER(data, type, '', type), - parseKey, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/node-fs-compat.js b/reverse_engineering/node_modules/ssh2/lib/protocol/node-fs-compat.js deleted file mode 100644 index 80ed71f..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/node-fs-compat.js +++ /dev/null @@ -1,115 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { inspect } = require('util'); - -// Only use this for integers! Decimal numbers do not work with this function. -function addNumericalSeparator(val) { - let res = ''; - let i = val.length; - const start = val[0] === '-' ? 1 : 0; - for (; i >= start + 4; i -= 3) - res = `_${val.slice(i - 3, i)}${res}`; - return `${val.slice(0, i)}${res}`; -} - -function oneOf(expected, thing) { - assert(typeof thing === 'string', '`thing` has to be of type string'); - if (Array.isArray(expected)) { - const len = expected.length; - assert(len > 0, 'At least one expected value needs to be specified'); - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` - + expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } - return `of ${thing} ${expected[0]}`; - } - return `of ${thing} ${String(expected)}`; -} - - -exports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { - constructor(message) { - super(); - Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); - - const suffix = 'This is caused by either a bug in ssh2 ' - + 'or incorrect usage of ssh2 internals.\n' - + 'Please open an issue with this stack trace at ' - + 'https://github.com/mscdex/ssh2/issues\n'; - - this.message = (message === undefined ? suffix : `${message}\n${suffix}`); - } -}; - -const MAX_32BIT_INT = 2 ** 32; -const MAX_32BIT_BIGINT = (() => { - try { - return new Function('return 2n ** 32n')(); - } catch {} -})(); -exports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { - constructor(str, range, input, replaceDefaultBoolean) { - super(); - Error.captureStackTrace(this, ERR_OUT_OF_RANGE); - - assert(range, 'Missing "range" argument'); - let msg = (replaceDefaultBoolean - ? str - : `The value of "${str}" is out of range.`); - let received; - if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === 'bigint') { - received = String(input); - if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) - received = addNumericalSeparator(received); - received += 'n'; - } else { - received = inspect(input); - } - msg += ` It must be ${range}. Received ${received}`; - - this.message = msg; - } -}; - -class ERR_INVALID_ARG_TYPE extends TypeError { - constructor(name, expected, actual) { - super(); - Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE); - - assert(typeof name === 'string', `'name' must be a string`); - - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && expected.startsWith('not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - let msg; - if (name.endsWith(' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = (name.includes('.') ? 'property' : 'argument'); - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; - } - - msg += `. Received type ${typeof actual}`; - - this.message = msg; - } -} -exports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; - -exports.validateNumber = function validateNumber(value, name) { - if (typeof value !== 'number') - throw new ERR_INVALID_ARG_TYPE(name, 'number', value); -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/utils.js b/reverse_engineering/node_modules/ssh2/lib/protocol/utils.js deleted file mode 100644 index 0dab875..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/utils.js +++ /dev/null @@ -1,356 +0,0 @@ -'use strict'; - -const Ber = require('asn1').Ber; - -let DISCONNECT_REASON; - -const FastBuffer = Buffer[Symbol.species]; -const TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; - -function readUInt32BE(buf, offset) { - return (buf[offset++] * 16777216) - + (buf[offset++] * 65536) - + (buf[offset++] * 256) - + buf[offset]; -} - -function bufferCopy(src, dest, srcStart, srcEnd, destStart) { - if (!destStart) - destStart = 0; - if (srcEnd > src.length) - srcEnd = src.length; - let nb = srcEnd - srcStart; - const destLeft = (dest.length - destStart); - if (nb > destLeft) - nb = destLeft; - dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), - destStart); - return nb; -} - -function bufferSlice(buf, start, end) { - if (end === undefined) - end = buf.length; - return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); -} - -function makeBufferParser() { - let pos = 0; - let buffer; - - const self = { - init: (buf, start) => { - buffer = buf; - pos = (typeof start === 'number' ? start : 0); - }, - pos: () => pos, - length: () => (buffer ? buffer.length : 0), - avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0), - clear: () => { - buffer = undefined; - }, - readUInt32BE: () => { - if (!buffer || pos + 3 >= buffer.length) - return; - return (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - }, - readUInt64BE: (behavior) => { - if (!buffer || pos + 7 >= buffer.length) - return; - switch (behavior) { - case 'always': - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - case 'maybe': - if (buffer[pos] > 0x1F) - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - // FALLTHROUGH - default: - return (buffer[pos++] * 72057594037927940) - + (buffer[pos++] * 281474976710656) - + (buffer[pos++] * 1099511627776) - + (buffer[pos++] * 4294967296) - + (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - } - }, - skip: (n) => { - if (buffer && n > 0) - pos += n; - }, - skipString: () => { - const len = self.readUInt32BE(); - if (len === undefined) - return; - pos += len; - return (pos <= buffer.length ? len : undefined); - }, - readByte: () => { - if (buffer && pos < buffer.length) - return buffer[pos++]; - }, - readBool: () => { - if (buffer && pos < buffer.length) - return !!buffer[pos++]; - }, - readList: () => { - const list = self.readString(true); - if (list === undefined) - return; - return (list ? list.split(',') : []); - }, - readString: (dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; - } - - const len = self.readUInt32BE(); - if (len === undefined) - return; - - if ((buffer.length - pos) < len - || (typeof maxLen === 'number' && len > maxLen)) { - return; - } - - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, pos, pos += len); - return buffer.utf8Slice(pos, pos += len); - } - return bufferSlice(buffer, pos, pos += len); - }, - readRaw: (len) => { - if (!buffer) - return; - if (typeof len !== 'number') - return bufferSlice(buffer, pos, pos += (buffer.length - pos)); - if ((buffer.length - pos) >= len) - return bufferSlice(buffer, pos, pos += len); - }, - }; - - return self; -} - -function makeError(msg, level, fatal) { - const err = new Error(msg); - if (typeof level === 'boolean') { - fatal = level; - err.level = 'protocol'; - } else { - err.level = level || 'protocol'; - } - err.fatal = !!fatal; - return err; -} - -function writeUInt32BE(buf, value, offset) { - buf[offset++] = (value >>> 24); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 8); - buf[offset++] = value; - return offset; -} - -const utilBufferParser = makeBufferParser(); - -module.exports = { - bufferCopy, - bufferSlice, - FastBuffer, - bufferFill: (buf, value, start, end) => { - return TypedArrayFill.call(buf, value, start, end); - }, - makeError, - doFatalError: (protocol, msg, level, reason) => { - let err; - if (DISCONNECT_REASON === undefined) - ({ DISCONNECT_REASON } = require('./utils.js')); - if (msg instanceof Error) { - // doFatalError(protocol, err[, reason]) - err = msg; - if (typeof level !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - else - reason = level; - } else { - // doFatalError(protocol, msg[, level[, reason]]) - err = makeError(msg, level, true); - } - if (typeof reason !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - protocol.disconnect(reason); - protocol._destruct(); - protocol._onError(err); - return Infinity; - }, - readUInt32BE, - writeUInt32BE, - writeUInt32LE: (buf, value, offset) => { - buf[offset++] = value; - buf[offset++] = (value >>> 8); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 24); - return offset; - }, - makeBufferParser, - bufferParser: makeBufferParser(), - readString: (buffer, start, dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; - } - - if (start === undefined) - start = 0; - - const left = (buffer.length - start); - if (start < 0 || start >= buffer.length || left < 4) - return; - - const len = readUInt32BE(buffer, start); - if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen)) - return; - - start += 4; - const end = start + len; - buffer._pos = end; - - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, start, end); - return buffer.utf8Slice(start, end); - } - return bufferSlice(buffer, start, end); - }, - sigSSHToASN1: (sig, type) => { - switch (type) { - case 'ssh-dss': { - if (sig.length > 40) - return sig; - // Change bare signature r and s values to ASN.1 BER values for OpenSSL - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - let r = sig.slice(0, 20); - let s = sig.slice(20); - if (r[0] & 0x80) { - const rNew = Buffer.allocUnsafe(21); - rNew[0] = 0x00; - r.copy(rNew, 1); - r = rNew; - } else if (r[0] === 0x00 && !(r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] & 0x80) { - const sNew = Buffer.allocUnsafe(21); - sNew[0] = 0x00; - s.copy(sNew, 1); - s = sNew; - } else if (s[0] === 0x00 && !(s[1] & 0x80)) { - s = s.slice(1); - } - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - utilBufferParser.init(sig, 0); - const r = utilBufferParser.readString(); - const s = utilBufferParser.readString(); - utilBufferParser.clear(); - if (r === undefined || s === undefined) - return; - - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - default: - return sig; - } - }, - convertSignature: (signature, keyType) => { - switch (keyType) { - case 'ssh-dss': { - if (signature.length <= 40) - return signature; - // This is a quick and dirty way to get from BER encoded r and s that - // OpenSSL gives us, to just the bare values back to back (40 bytes - // total) like OpenSSH (and possibly others) are expecting - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - let r = asnReader.readString(Ber.Integer, true); - let s = asnReader.readString(Ber.Integer, true); - let rOffset = 0; - let sOffset = 0; - if (r.length < 20) { - const rNew = Buffer.allocUnsafe(20); - rNew.set(r, 1); - r = rNew; - r[0] = 0; - } - if (s.length < 20) { - const sNew = Buffer.allocUnsafe(20); - sNew.set(s, 1); - s = sNew; - s[0] = 0; - } - if (r.length > 20 && r[0] === 0) - rOffset = 1; - if (s.length > 20 && s[0] === 0) - sOffset = 1; - const newSig = - Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset)); - bufferCopy(r, newSig, rOffset, r.length, 0); - bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); - return newSig; - } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - if (signature[0] === 0) - return signature; - // Convert SSH signature parameters to ASN.1 BER values for OpenSSL - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - const r = asnReader.readString(Ber.Integer, true); - const s = asnReader.readString(Ber.Integer, true); - if (r === null || s === null) - return; - const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); - writeUInt32BE(newSig, r.length, 0); - newSig.set(r, 4); - writeUInt32BE(newSig, s.length, 4 + r.length); - newSig.set(s, 4 + 4 + r.length); - return newSig; - } - } - - return signature; - }, - sendPacket: (proto, packet, bypass) => { - if (!bypass && proto._kexinit !== undefined) { - // We're currently in the middle of a handshake - - if (proto._queue === undefined) - proto._queue = []; - proto._queue.push(packet); - proto._debug && proto._debug('Outbound: ... packet queued'); - return false; - } - proto._cipher.encrypt(packet); - return true; - }, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/protocol/zlib.js b/reverse_engineering/node_modules/ssh2/lib/protocol/zlib.js deleted file mode 100644 index f68319a..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/protocol/zlib.js +++ /dev/null @@ -1,255 +0,0 @@ -'use strict'; - -const { kMaxLength } = require('buffer'); -const { - createInflate, - constants: { - DEFLATE, - INFLATE, - Z_DEFAULT_CHUNK, - Z_DEFAULT_COMPRESSION, - Z_DEFAULT_MEMLEVEL, - Z_DEFAULT_STRATEGY, - Z_DEFAULT_WINDOWBITS, - Z_PARTIAL_FLUSH, - } -} = require('zlib'); -const ZlibHandle = createInflate()._handle.constructor; - -function processCallback() { - throw new Error('Should not get here'); -} - -function zlibOnError(message, errno, code) { - const self = this._owner; - // There is no way to cleanly recover. - // Continuing only obscures problems. - - const error = new Error(message); - error.errno = errno; - error.code = code; - self._err = error; -} - -function _close(engine) { - // Caller may invoke .close after a zlib error (which will null _handle). - if (!engine._handle) - return; - - engine._handle.close(); - engine._handle = null; -} - -class Zlib { - constructor(mode) { - const windowBits = Z_DEFAULT_WINDOWBITS; - const level = Z_DEFAULT_COMPRESSION; - const memLevel = Z_DEFAULT_MEMLEVEL; - const strategy = Z_DEFAULT_STRATEGY; - const dictionary = undefined; - - this._err = undefined; - this._writeState = new Uint32Array(2); - this._chunkSize = Z_DEFAULT_CHUNK; - this._maxOutputLength = kMaxLength; - this._outBuffer = Buffer.allocUnsafe(this._chunkSize); - this._outOffset = 0; - - this._handle = new ZlibHandle(mode); - this._handle._owner = this; - this._handle.onerror = zlibOnError; - this._handle.init(windowBits, - level, - memLevel, - strategy, - this._writeState, - processCallback, - dictionary); - } - - writeSync(chunk, retChunks) { - const handle = this._handle; - if (!handle) - throw new Error('Invalid Zlib instance'); - - let availInBefore = chunk.length; - let availOutBefore = this._chunkSize - this._outOffset; - let inOff = 0; - let availOutAfter; - let availInAfter; - - let buffers; - let nread = 0; - const state = this._writeState; - let buffer = this._outBuffer; - let offset = this._outOffset; - const chunkSize = this._chunkSize; - - while (true) { - handle.writeSync(Z_PARTIAL_FLUSH, - chunk, // in - inOff, // in_off - availInBefore, // in_len - buffer, // out - offset, // out_off - availOutBefore); // out_len - if (this._err) - throw this._err; - - availOutAfter = state[0]; - availInAfter = state[1]; - - const inDelta = availInBefore - availInAfter; - const have = availOutBefore - availOutAfter; - - if (have > 0) { - const out = (offset === 0 && have === buffer.length - ? buffer - : buffer.slice(offset, offset + have)); - offset += have; - if (!buffers) - buffers = out; - else if (buffers.push === undefined) - buffers = [buffers, out]; - else - buffers.push(out); - nread += out.byteLength; - - if (nread > this._maxOutputLength) { - _close(this); - throw new Error( - `Output length exceeded maximum of ${this._maxOutputLength}` - ); - } - } else if (have !== 0) { - throw new Error('have should not go down'); - } - - // Exhausted the output buffer, or used all the input create a new one. - if (availOutAfter === 0 || offset >= chunkSize) { - availOutBefore = chunkSize; - offset = 0; - buffer = Buffer.allocUnsafe(chunkSize); - } - - if (availOutAfter === 0) { - // Not actually done. Need to reprocess. - // Also, update the availInBefore to the availInAfter value, - // so that if we have to hit it a third (fourth, etc.) time, - // it'll have the correct byte counts. - inOff += inDelta; - availInBefore = availInAfter; - } else { - break; - } - } - - this._outBuffer = buffer; - this._outOffset = offset; - - if (nread === 0) - buffers = Buffer.alloc(0); - - if (retChunks) { - buffers.totalLen = nread; - return buffers; - } - - if (buffers.push === undefined) - return buffers; - - const output = Buffer.allocUnsafe(nread); - for (let i = 0, p = 0; i < buffers.length; ++i) { - const buf = buffers[i]; - output.set(buf, p); - p += buf.length; - } - return output; - } -} - -class ZlibPacketWriter { - constructor(protocol) { - this.allocStart = 0; - this.allocStartKEX = 0; - this._protocol = protocol; - this._zlib = new Zlib(DEFLATE); - } - - cleanup() { - if (this._zlib) - _close(this._zlib); - } - - alloc(payloadSize, force) { - return Buffer.allocUnsafe(payloadSize); - } - - finalize(payload, force) { - if (this._protocol._kexinit === undefined || force) { - const output = this._zlib.writeSync(payload, true); - const packet = this._protocol._cipher.allocPacket(output.totalLen); - if (output.push === undefined) { - packet.set(output, 5); - } else { - for (let i = 0, p = 5; i < output.length; ++i) { - const chunk = output[i]; - packet.set(chunk, p); - p += chunk.length; - } - } - return packet; - } - return payload; - } -} - -class PacketWriter { - constructor(protocol) { - this.allocStart = 5; - this.allocStartKEX = 5; - this._protocol = protocol; - } - - cleanup() {} - - alloc(payloadSize, force) { - if (this._protocol._kexinit === undefined || force) - return this._protocol._cipher.allocPacket(payloadSize); - return Buffer.allocUnsafe(payloadSize); - } - - finalize(packet, force) { - return packet; - } -} - -class ZlibPacketReader { - constructor() { - this._zlib = new Zlib(INFLATE); - } - - cleanup() { - if (this._zlib) - _close(this._zlib); - } - - read(data) { - return this._zlib.writeSync(data, false); - } -} - -class PacketReader { - cleanup() {} - - read(data) { - return data; - } -} - -module.exports = { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -}; diff --git a/reverse_engineering/node_modules/ssh2/lib/server.js b/reverse_engineering/node_modules/ssh2/lib/server.js deleted file mode 100644 index 11c15a1..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/server.js +++ /dev/null @@ -1,1363 +0,0 @@ -// TODO: -// * convert listenerCount() usage to emit() return value checking? -// * emit error when connection severed early (e.g. before handshake) -// * add '.connected' or similar property to connection objects to allow -// immediate connection status checking -'use strict'; - -const { Server: netServer } = require('net'); -const EventEmitter = require('events'); -const { listenerCount } = EventEmitter; - -const { - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = require('./protocol/constants.js'); -const { init: cryptoInit } = require('./protocol/crypto.js'); -const { KexInit } = require('./protocol/kex.js'); -const { parseKey } = require('./protocol/keyParser.js'); -const Protocol = require('./protocol/Protocol.js'); -const { SFTP } = require('./protocol/SFTP.js'); -const { writeUInt32BE } = require('./protocol/utils.js'); - -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = require('./Channel.js'); - -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = require('./utils.js'); - -const MAX_PENDING_AUTHS = 10; - -class AuthContext extends EventEmitter { - constructor(protocol, username, service, method, cb) { - super(); - - this.username = this.user = username; - this.service = service; - this.method = method; - this._initialResponse = false; - this._finalResponse = false; - this._multistep = false; - this._cbfinal = (allowed, methodsLeft, isPartial) => { - if (!this._finalResponse) { - this._finalResponse = true; - cb(this, allowed, methodsLeft, isPartial); - } - }; - this._protocol = protocol; - } - - accept() { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(true); - } - reject(methodsLeft, isPartial) { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(false, methodsLeft, isPartial); - } -} - - -class KeyboardAuthContext extends AuthContext { - constructor(protocol, username, service, method, submethods, cb) { - super(protocol, username, service, method, cb); - - this._multistep = true; - - this._cb = undefined; - this._onInfoResponse = (responses) => { - const callback = this._cb; - if (callback) { - this._cb = undefined; - callback(responses); - } - }; - this.submethods = submethods; - this.on('abort', () => { - this._cb && this._cb(new Error('Authentication request aborted')); - }); - } - - prompt(prompts, title, instructions, cb) { - if (!Array.isArray(prompts)) - prompts = [ prompts ]; - - if (typeof title === 'function') { - cb = title; - title = instructions = undefined; - } else if (typeof instructions === 'function') { - cb = instructions; - instructions = undefined; - } else if (typeof cb !== 'function') { - cb = undefined; - } - - for (let i = 0; i < prompts.length; ++i) { - if (typeof prompts[i] === 'string') { - prompts[i] = { - prompt: prompts[i], - echo: true - }; - } - } - - this._cb = cb; - this._initialResponse = true; - - this._protocol.authInfoReq(title, instructions, prompts); - } -} - -class PKAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); - - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - } - - accept() { - if (!this.signature) { - this._initialResponse = true; - this._protocol.authPKOK(this.key.algo, this.key.data); - } else { - AuthContext.prototype.accept.call(this); - } - } -} - -class HostbasedAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); - - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - this.localHostname = pkInfo.localHostname; - this.localUsername = pkInfo.localUsername; - } -} - -class PwdAuthContext extends AuthContext { - constructor(protocol, username, service, method, password, cb) { - super(protocol, username, service, method, cb); - - this.password = password; - this._changeCb = undefined; - } - - requestChange(prompt, cb) { - if (this._changeCb) - throw new Error('Change request already in progress'); - if (typeof prompt !== 'string') - throw new Error('prompt argument must be a string'); - if (typeof cb !== 'function') - throw new Error('Callback argument must be a function'); - this._changeCb = cb; - this._protocol.authPasswdChg(prompt); - } -} - - -class Session extends EventEmitter { - constructor(client, info, localChan) { - super(); - - this.type = 'session'; - this.subtype = undefined; - this._ending = false; - this._channel = undefined; - this._chanInfo = { - type: 'session', - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - } -} - - -class Server extends EventEmitter { - constructor(cfg, listener) { - super(); - - if (typeof cfg !== 'object' || cfg === null) - throw new Error('Missing configuration object'); - - const hostKeys = Object.create(null); - const hostKeyAlgoOrder = []; - - const hostKeys_ = cfg.hostKeys; - if (!Array.isArray(hostKeys_)) - throw new Error('hostKeys must be an array'); - - const cfgAlgos = ( - typeof cfg.algorithms === 'object' && cfg.algorithms !== null - ? cfg.algorithms - : {} - ); - - const hostKeyAlgos = generateAlgorithmList( - cfgAlgos.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY - ); - for (let i = 0; i < hostKeys_.length; ++i) { - let privateKey; - if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string') - privateKey = parseKey(hostKeys_[i]); - else - privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); - - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } - - if (privateKey.getPrivatePEM() === null) - throw new Error('privateKey value contains an invalid private key'); - - // Discard key if we already found a key of the same type - if (hostKeyAlgoOrder.includes(privateKey.type)) - continue; - - if (privateKey.type === 'ssh-rsa') { - // SSH supports multiple signature hashing algorithms for RSA, so we add - // the algorithms in the desired order - let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa'); - const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256'); - const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512'); - if (sha1Pos === -1) { - // Fall back to giving SHA1 the lowest priority - sha1Pos = Infinity; - } - [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { - if (pos === -1) - return; - - let type; - switch (pos) { - case sha1Pos: type = 'ssh-rsa'; break; - case sha256Pos: type = 'rsa-sha2-256'; break; - case sha512Pos: type = 'rsa-sha2-512'; break; - default: return; - } - - // Store same RSA key under each hash algorithm name for convenience - hostKeys[type] = privateKey; - - hostKeyAlgoOrder.push(type); - }); - } else { - hostKeys[privateKey.type] = privateKey; - hostKeyAlgoOrder.push(privateKey.type); - } - } - - const algorithms = { - kex: generateAlgorithmList(cfgAlgos.kex, DEFAULT_KEX, SUPPORTED_KEX), - serverHostKey: hostKeyAlgoOrder, - cs: { - cipher: generateAlgorithmList( - cfgAlgos.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER - ), - mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), - compress: generateAlgorithmList( - cfgAlgos.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION - ), - lang: [], - }, - sc: undefined, - }; - algorithms.sc = algorithms.cs; - - if (typeof listener === 'function') - this.on('connection', listener); - - const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined); - const offer = new KexInit(algorithms); - - this._srv = new netServer((socket) => { - if (this._connections >= this.maxConnections) { - socket.destroy(); - return; - } - ++this._connections; - socket.once('close', () => { - --this._connections; - }); - - let debug; - if (origDebug) { - // Prepend debug output with a unique identifier in case there are - // multiple clients connected at the same time - const debugPrefix = `[${process.hrtime().join('.')}] `; - debug = (msg) => { - origDebug(`${debugPrefix}${msg}`); - }; - } - - // eslint-disable-next-line no-use-before-define - new Client(socket, hostKeys, ident, offer, debug, this, cfg); - }).on('error', (err) => { - this.emit('error', err); - }).on('listening', () => { - this.emit('listening'); - }).on('close', () => { - this.emit('close'); - }); - this._connections = 0; - this.maxConnections = Infinity; - } - - injectSocket(socket) { - this._srv.emit('connection', socket); - } - - listen(...args) { - this._srv.listen(...args); - return this; - } - - address() { - return this._srv.address(); - } - - getConnections(cb) { - this._srv.getConnections(cb); - return this; - } - - close(cb) { - this._srv.close(cb); - return this; - } - - ref() { - this._srv.ref(); - return this; - } - - unref() { - this._srv.unref(); - return this; - } -} -Server.KEEPALIVE_CLIENT_INTERVAL = 15000; -Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; - - -class Client extends EventEmitter { - constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) { - super(); - - let exchanges = 0; - let acceptedAuthSvc = false; - let pendingAuths = []; - let authCtx; - let kaTimer; - let onPacket; - const unsentGlobalRequestsReplies = []; - this._sock = socket; - this._chanMgr = new ChannelManager(this); - this._debug = debug; - this.noMoreSessions = false; - this.authenticated = false; - - // Silence pre-header errors - function onClientPreHeaderError(err) {} - this.on('error', onClientPreHeaderError); - - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from client: ${JSON.stringify(msg)}`); - }); - - const kaIntvl = ( - typeof srvCfg.keepaliveInterval === 'number' - && isFinite(srvCfg.keepaliveInterval) - && srvCfg.keepaliveInterval > 0 - ? srvCfg.keepaliveInterval - : ( - typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) - && Server.KEEPALIVE_CLIENT_INTERVAL > 0 - ? Server.KEEPALIVE_CLIENT_INTERVAL - : -1 - ) - ); - const kaCountMax = ( - typeof srvCfg.keepaliveCountMax === 'number' - && isFinite(srvCfg.keepaliveCountMax) - && srvCfg.keepaliveCountMax >= 0 - ? srvCfg.keepaliveCountMax - : ( - typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) - && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 - ? Server.KEEPALIVE_CLIENT_COUNT_MAX - : -1 - ) - ); - let kaCurCount = 0; - if (kaIntvl !== -1 && kaCountMax !== -1) { - this.once('ready', () => { - const onClose = () => { - clearInterval(kaTimer); - }; - this.on('close', onClose).on('end', onClose); - kaTimer = setInterval(() => { - if (++kaCurCount > kaCountMax) { - clearInterval(kaTimer); - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - this.end(); - } else { - // XXX: if the server ever starts sending real global requests to - // the client, we will need to add a dummy callback here to - // keep the correct reply order - proto.ping(); - } - }, kaIntvl); - }); - // TODO: re-verify keepalive behavior with OpenSSH - onPacket = () => { - kaTimer && kaTimer.refresh(); - kaCurCount = 0; - }; - } - - const proto = this._protocol = new Protocol({ - server: true, - hostKeys, - ident, - offer, - onPacket, - greeting: srvCfg.greeting, - banner: srvCfg.banner, - onWrite: (data) => { - if (isWritable(socket)) - socket.write(data); - }, - onError: (err) => { - if (!proto._destruct) - socket.removeAllListeners('data'); - this.emit('error', err); - try { - socket.end(); - } catch {} - }, - onHeader: (header) => { - this.removeListener('error', onClientPreHeaderError); - - const info = { - ip: socket.remoteAddress, - family: socket.remoteFamily, - port: socket.remotePort, - header, - }; - if (!server.emit('connection', this, info)) { - // auto reject - proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); - socket.end(); - return; - } - - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - if (++exchanges > 1) - this.emit('rekey'); - this.emit('handshake', negotiated); - }, - debug, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - socket.end(); - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from client - - // Do early reject in some cases to prevent wasteful channel - // allocation - if ((info.type === 'session' && this.noMoreSessions) - || !this.authenticated) { - const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - return proto.channelOpenFail(info.sender, reasonCode); - } - - let localChan = -1; - let reason; - let replied = false; - - let accept; - const reject = () => { - if (replied) - return; - replied = true; - - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } - - proto.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = this._chanMgr.add(); - - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (debug) { - debug('Automatic rejection of incoming channel open: ' - + 'no channels available'); - } - } - - return (localChan !== -1); - }; - - const data = info.data; - switch (info.type) { - case 'session': - if (listenerCount(this, 'session') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const instance = new Session(this, info, localChan); - this._chanMgr.update(localChan, instance); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return instance; - }; - - this.emit('session', accept, reject); - return; - } - break; - case 'direct-tcpip': - if (listenerCount(this, 'tcpip') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return stream; - }; - - this.emit('tcpip', accept, reject, data); - return; - } - break; - case 'direct-streamlocal@openssh.com': - if (listenerCount(this, 'openssh.streamlocal') - && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return stream; - }; - - this.emit('openssh.streamlocal', accept, reject, data); - return; - } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (debug) { - debug('Automatic rejection of unsupported incoming channel open' - + ` type: ${info.type}`); - } - } - - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (debug) { - debug('Automatic rejection of unexpected incoming channel open' - + ` for: ${info.type}`); - } - } - - reject(); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; - - const chanInfo = { - type: channel.type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - - const instance = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; - - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - // NOOP -- should not be sent by client - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; - - if (channel._waitWindow) { - channel._waitWindow = false; - - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); - } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const session = this._chanMgr.get(recipient); - if (typeof session !== 'object' || session === null) - return; - - let replied = false; - let accept; - let reject; - - if (session.constructor !== Session) { - // normal Channel instance - if (wantReply) - proto.channelFailure(session.outgoing.id); - return; - } - - if (wantReply) { - // "real session" requests will have custom accept behaviors - if (type !== 'shell' - && type !== 'exec' - && type !== 'subsystem') { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - proto.channelSuccess(session._chanInfo.outgoing.id); - }; - } - - reject = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - proto.channelFailure(session._chanInfo.outgoing.id); - }; - } - - if (session._ending) { - reject && reject(); - return; - } - - switch (type) { - // "pre-real session start" requests - case 'env': - if (listenerCount(session, 'env')) { - session.emit('env', accept, reject, { - key: data.name, - val: data.value - }); - return; - } - break; - case 'pty-req': - if (listenerCount(session, 'pty')) { - session.emit('pty', accept, reject, data); - return; - } - break; - case 'window-change': - if (listenerCount(session, 'window-change')) - session.emit('window-change', accept, reject, data); - else - reject && reject(); - break; - case 'x11-req': - if (listenerCount(session, 'x11')) { - session.emit('x11', accept, reject, data); - return; - } - break; - // "post-real session start" requests - case 'signal': - if (listenerCount(session, 'signal')) { - session.emit('signal', accept, reject, { - name: data - }); - return; - } - break; - // XXX: is `auth-agent-req@openssh.com` really "post-real session - // start"? - case 'auth-agent-req@openssh.com': - if (listenerCount(session, 'auth-agent')) { - session.emit('auth-agent', accept, reject); - return; - } - break; - // "real session start" requests - case 'shell': - if (listenerCount(session, 'shell')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - const channel = new Channel( - this, session._chanInfo, { server: true } - ); - - channel.subtype = session.subtype = type; - session._channel = channel; - - return channel; - }; - - session.emit('shell', accept, reject); - return; - } - break; - case 'exec': - if (listenerCount(session, 'exec')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - const channel = new Channel( - this, session._chanInfo, { server: true } - ); - - channel.subtype = session.subtype = type; - session._channel = channel; - - return channel; - }; - - session.emit('exec', accept, reject, { - command: data - }); - return; - } - break; - case 'subsystem': { - let useSFTP = (data === 'sftp'); - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - let instance; - if (useSFTP) { - instance = new SFTP(this, session._chanInfo, { - server: true, - debug, - }); - } else { - instance = new Channel( - this, session._chanInfo, { server: true } - ); - instance.subtype = - session.subtype = `${type}:${data}`; - } - session._channel = instance; - - return instance; - }; - - if (data === 'sftp') { - if (listenerCount(session, 'sftp')) { - session.emit('sftp', accept, reject); - return; - } - useSFTP = false; - } - if (listenerCount(session, 'subsystem')) { - session.emit('subsystem', accept, reject, { - name: data - }); - return; - } - break; - } - } - debug && debug( - `Automatic rejection of incoming channel request: ${type}` - ); - reject && reject(); - }, - CHANNEL_EOF: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - if (!channel._ending) { - channel._ending = true; - channel.emit('eof'); - channel.emit('end'); - } - channel = channel._channel; - if (!channel) - return; - } - - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; - - if (channel.readable) - channel.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel._ending = true; - channel.emit('close'); - channel = channel._channel; - if (!channel) - return; - } - - onCHANNEL_CLOSE(this, recipient, channel); - }, - // Begin service/auth-related ========================================== - SERVICE_REQUEST: (p, service) => { - if (exchanges === 0 - || acceptedAuthSvc - || this.authenticated - || service !== 'ssh-userauth') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } - - acceptedAuthSvc = true; - proto.serviceAccept(service); - }, - USERAUTH_REQUEST: (p, username, service, method, methodData) => { - if (exchanges === 0 - || this.authenticated - || (authCtx - && (authCtx.username !== username - || authCtx.service !== service)) - // TODO: support hostbased auth - || (method !== 'password' - && method !== 'publickey' - && method !== 'hostbased' - && method !== 'keyboard-interactive' - && method !== 'none') - || pendingAuths.length === MAX_PENDING_AUTHS) { - proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); - socket.end(); - return; - } else if (service !== 'ssh-connection') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } - - let ctx; - switch (method) { - case 'keyboard-interactive': - ctx = new KeyboardAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'publickey': - ctx = new PKAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'hostbased': - ctx = new HostbasedAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'password': - if (authCtx - && authCtx instanceof PwdAuthContext - && authCtx._changeCb) { - const cb = authCtx._changeCb; - authCtx._changeCb = undefined; - cb(methodData.newPassword); - return; - } - ctx = new PwdAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'none': - ctx = new AuthContext(proto, username, service, method, - onAuthDecide); - break; - } - - if (authCtx) { - if (!authCtx._initialResponse) { - return pendingAuths.push(ctx); - } else if (authCtx._multistep && !authCtx._finalResponse) { - // RFC 4252 says to silently abort the current auth request if a - // new auth request comes in before the final response from an - // auth method that requires additional request/response exchanges - // -- this means keyboard-interactive for now ... - authCtx._cleanup && authCtx._cleanup(); - authCtx.emit('abort'); - } - } - - authCtx = ctx; - - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - }, - USERAUTH_INFO_RESPONSE: (p, responses) => { - if (authCtx && authCtx instanceof KeyboardAuthContext) - authCtx._onInfoResponse(responses); - }, - // End service/auth-related ============================================ - GLOBAL_REQUEST: (p, name, wantReply, data) => { - const reply = { - type: null, - buf: null - }; - - function setReply(type, buf) { - reply.type = type; - reply.buf = buf; - sendReplies(); - } - - if (wantReply) - unsentGlobalRequestsReplies.push(reply); - - if ((name === 'tcpip-forward' - || name === 'cancel-tcpip-forward' - || name === 'no-more-sessions@openssh.com' - || name === 'streamlocal-forward@openssh.com' - || name === 'cancel-streamlocal-forward@openssh.com') - && listenerCount(this, 'request') - && this.authenticated) { - let accept; - let reject; - - if (wantReply) { - let replied = false; - accept = (chosenPort) => { - if (replied) - return; - replied = true; - let bufPort; - if (name === 'tcpip-forward' - && data.bindPort === 0 - && typeof chosenPort === 'number') { - bufPort = Buffer.allocUnsafe(4); - writeUInt32BE(bufPort, chosenPort, 0); - } - setReply('SUCCESS', bufPort); - }; - reject = () => { - if (replied) - return; - replied = true; - setReply('FAILURE'); - }; - } - - if (name === 'no-more-sessions@openssh.com') { - this.noMoreSessions = true; - accept && accept(); - return; - } - - this.emit('request', accept, reject, name, data); - } else if (wantReply) { - setReply('FAILURE'); - } - }, - }, - }); - - socket.pause(); - cryptoInit.then(() => { - socket.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(socket)) - socket.end(); - } catch {} - } - }); - socket.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(socket)) - socket.end(); - } catch {} - }); - socket.on('error', (err) => { - err.level = 'socket'; - this.emit('error', err); - }).once('end', () => { - debug && debug('Socket ended'); - proto.cleanup(); - this.emit('end'); - }).once('close', () => { - debug && debug('Socket closed'); - proto.cleanup(); - this.emit('close'); - - const err = new Error('No response from server'); - - // Simulate error for pending channels and close any open channels - this._chanMgr.cleanup(err); - }); - - const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { - if (authCtx === ctx && !this.authenticated) { - if (allowed) { - authCtx = undefined; - this.authenticated = true; - proto.authSuccess(); - pendingAuths = []; - this.emit('ready'); - } else { - proto.authFailure(methodsLeft, isPartial); - if (pendingAuths.length) { - authCtx = pendingAuths.pop(); - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - } - } - } - }; - - function sendReplies() { - while (unsentGlobalRequestsReplies.length > 0 - && unsentGlobalRequestsReplies[0].type) { - const reply = unsentGlobalRequestsReplies.shift(); - if (reply.type === 'SUCCESS') - proto.requestSuccess(reply.buf); - if (reply.type === 'FAILURE') - proto.requestFailure(); - } - } - } - - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); - } - return this; - } - - x11(originAddr, originPort, cb) { - const opts = { originAddr, originPort }; - openChannel(this, 'x11', opts, cb); - return this; - } - - forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { - const opts = { boundAddr, boundPort, remoteAddr, remotePort }; - openChannel(this, 'forwarded-tcpip', opts, cb); - return this; - } - - openssh_forwardOutStreamLocal(socketPath, cb) { - const opts = { socketPath }; - openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb); - return this; - } - - rekey(cb) { - let error; - - try { - this._protocol.rekey(); - } catch (ex) { - error = ex; - } - - // TODO: re-throw error if no callback? - - if (typeof cb === 'function') { - if (error) - process.nextTick(cb, error); - else - this.once('rekey', cb); - } - } -} - - -function openChannel(self, type, opts, cb) { - // Ask the client to open a channel for some purpose (e.g. a forwarded TCP - // connection) - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; - - const localChan = self._chanMgr.add(wrapper); - - if (localChan === -1) { - cb(new Error('No free channels available')); - return; - } - - switch (type) { - case 'forwarded-tcpip': - self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'x11': - self._protocol.x11(localChan, initWindow, maxPacket, opts); - break; - case 'forwarded-streamlocal@openssh.com': - self._protocol.openssh_forwardedStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } -} - -function compareNumbers(a, b) { - return a - b; -} - -module.exports = Server; -module.exports.IncomingClient = Client; diff --git a/reverse_engineering/node_modules/ssh2/lib/utils.js b/reverse_engineering/node_modules/ssh2/lib/utils.js deleted file mode 100644 index 04d4b96..0000000 --- a/reverse_engineering/node_modules/ssh2/lib/utils.js +++ /dev/null @@ -1,332 +0,0 @@ -'use strict'; - -const { SFTP } = require('./protocol/SFTP.js'); - -const MAX_CHANNEL = 2 ** 32 - 1; - -function onChannelOpenFailure(self, recipient, info, cb) { - self._chanMgr.remove(recipient); - if (typeof cb !== 'function') - return; - - let err; - if (info instanceof Error) { - err = info; - } else if (typeof info === 'object' && info !== null) { - err = new Error(`(SSH) Channel open failure: ${info.description}`); - err.reason = info.reason; - } else { - err = new Error( - '(SSH) Channel open failure: server closed channel unexpectedly' - ); - err.reason = ''; - } - - cb(err); -} - -function onCHANNEL_CLOSE(self, recipient, channel, err, dead) { - if (typeof channel === 'function') { - // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when - // requesting to open a channel - onChannelOpenFailure(self, recipient, err, channel); - return; - } - if (typeof channel !== 'object' - || channel === null - || channel.incoming.state === 'closed') { - return; - } - - channel.incoming.state = 'closed'; - - if (channel.readable) - channel.push(null); - if (channel.server) { - if (channel.stderr.writable) - channel.stderr.end(); - } else if (channel.stderr.readable) { - channel.stderr.push(null); - } - - if (channel.constructor !== SFTP - && (channel.outgoing.state === 'open' - || channel.outgoing.state === 'eof') - && !dead) { - channel.close(); - } - if (channel.outgoing.state === 'closing') - channel.outgoing.state = 'closed'; - - self._chanMgr.remove(recipient); - - const readState = channel._readableState; - const writeState = channel._writableState; - if (writeState && !writeState.ending && !writeState.finished && !dead) - channel.end(); - - // Take care of any outstanding channel requests - const chanCallbacks = channel._callbacks; - channel._callbacks = []; - for (let i = 0; i < chanCallbacks.length; ++i) - chanCallbacks[i](true); - - if (channel.server) { - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - channel.emit('close'); - } else { - channel.once('end', () => channel.emit('close')); - } - } else { - let doClose; - switch (channel.type) { - case 'direct-streamlocal@openssh.com': - case 'direct-tcpip': - doClose = () => channel.emit('close'); - break; - default: { - // Align more with node child processes, where the close event gets - // the same arguments as the exit event - const exit = channel._exit; - doClose = () => { - if (exit.code === null) - channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc); - else - channel.emit('close', exit.code); - }; - } - } - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - doClose(); - } else { - channel.once('end', doClose); - } - - const errReadState = channel.stderr._readableState; - if (!channel.stderr.readable - || channel.stderr.destroyed - || (errReadState && errReadState.endEmitted)) { - channel.stderr.emit('close'); - } else { - channel.stderr.once('end', () => channel.stderr.emit('close')); - } - } -} - -class ChannelManager { - constructor(client) { - this._client = client; - this._channels = {}; - this._cur = -1; - this._count = 0; - } - add(val) { - // Attempt to reserve an id - - let id; - // Optimized paths - if (this._cur < MAX_CHANNEL) { - id = ++this._cur; - } else if (this._count === 0) { - // Revert and reset back to fast path once we no longer have any channels - // open - this._cur = 0; - id = 0; - } else { - // Slower lookup path - - // This path is triggered we have opened at least MAX_CHANNEL channels - // while having at least one channel open at any given time, so we have - // to search for a free id. - const channels = this._channels; - for (let i = 0; i < MAX_CHANNEL; ++i) { - if (channels[i] === undefined) { - id = i; - break; - } - } - } - - if (id === undefined) - return -1; - - this._channels[id] = (val || true); - ++this._count; - - return id; - } - update(id, val) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - if (val && this._channels[id]) - this._channels[id] = val; - } - get(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - return this._channels[id]; - } - remove(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - if (this._channels[id]) { - delete this._channels[id]; - if (this._count) - --this._count; - } - } - cleanup(err) { - const channels = this._channels; - this._channels = {}; - this._cur = -1; - this._count = 0; - - const chanIDs = Object.keys(channels); - const client = this._client; - for (let i = 0; i < chanIDs.length; ++i) { - const id = +chanIDs[i]; - const channel = channels[id]; - onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); - } - } -} - -const isRegExp = (() => { - const toString = Object.prototype.toString; - return (val) => toString.call(val) === '[object RegExp]'; -})(); - -function generateAlgorithmList(algoList, defaultList, supportedList) { - if (Array.isArray(algoList) && algoList.length > 0) { - // Exact list - for (let i = 0; i < algoList.length; ++i) { - if (supportedList.indexOf(algoList[i]) === -1) - throw new Error(`Unsupported algorithm: ${algoList[i]}`); - } - return algoList; - } - - if (typeof algoList === 'object' && algoList !== null) { - // Operations based on the default list - const keys = Object.keys(algoList); - let list = defaultList; - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - let val = algoList[key]; - switch (key) { - case 'append': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const append = val[j]; - if (typeof append === 'string') { - if (!append || list.indexOf(append) !== -1) - continue; - if (supportedList.indexOf(append) === -1) - throw new Error(`Unsupported algorithm: ${append}`); - if (list === defaultList) - list = list.slice(); - list.push(append); - } else if (isRegExp(append)) { - for (let k = 0; k < supportedList.length; ++k) { - const algo = supportedList[k]; - if (append.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.push(algo); - } - } - } - } - } - break; - case 'prepend': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = val.length; j >= 0; --j) { - const prepend = val[j]; - if (typeof prepend === 'string') { - if (!prepend || list.indexOf(prepend) !== -1) - continue; - if (supportedList.indexOf(prepend) === -1) - throw new Error(`Unsupported algorithm: ${prepend}`); - if (list === defaultList) - list = list.slice(); - list.unshift(prepend); - } else if (isRegExp(prepend)) { - for (let k = supportedList.length; k >= 0; --k) { - const algo = supportedList[k]; - if (prepend.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.unshift(algo); - } - } - } - } - } - break; - case 'remove': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const search = val[j]; - if (typeof search === 'string') { - if (!search) - continue; - const idx = list.indexOf(search); - if (idx === -1) - continue; - if (list === defaultList) - list = list.slice(); - list.splice(idx, 1); - } else if (isRegExp(search)) { - for (let k = 0; k < list.length; ++k) { - if (search.test(list[k])) { - if (list === defaultList) - list = list.slice(); - list.splice(k, 1); - --k; - } - } - } - } - } - break; - } - } - - return list; - } - - return defaultList; -} - -module.exports = { - ChannelManager, - generateAlgorithmList, - onChannelOpenFailure, - onCHANNEL_CLOSE, - isWritable: (stream) => { - // XXX: hack to workaround regression in node - // See: https://github.com/nodejs/node/issues/36029 - return (stream - && stream.writable - && stream._readableState - && stream._readableState.ended === false); - }, -}; diff --git a/reverse_engineering/node_modules/ssh2/package.json b/reverse_engineering/node_modules/ssh2/package.json deleted file mode 100644 index 2d54f8f..0000000 --- a/reverse_engineering/node_modules/ssh2/package.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "_from": "ssh2@1.4.0", - "_id": "ssh2@1.4.0", - "_inBundle": false, - "_integrity": "sha512-XvXwcXKvS452DyQvCa6Ct+chpucwc/UyxgliYz+rWXJ3jDHdtBb9xgmxJdMmnIn5bpgGAEV3KaEsH98ZGPHqwg==", - "_location": "/ssh2", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "ssh2@1.4.0", - "name": "ssh2", - "escapedName": "ssh2", - "rawSpec": "1.4.0", - "saveSpec": null, - "fetchSpec": "1.4.0" - }, - "_requiredBy": [ - "/tunnel-ssh" - ], - "_resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.4.0.tgz", - "_shasum": "e32e8343394364c922bad915a5a7fecd67d0f5c5", - "_spec": "ssh2@1.4.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/tunnel-ssh", - "author": { - "name": "Brian White", - "email": "mscdex@mscdex.net" - }, - "bugs": { - "url": "https://github.com/mscdex/ssh2/issues" - }, - "bundleDependencies": false, - "dependencies": { - "asn1": "^0.2.4", - "bcrypt-pbkdf": "^1.0.2", - "cpu-features": "0.0.2", - "nan": "^2.15.0" - }, - "deprecated": false, - "description": "SSH2 client and server modules written in pure JavaScript for node.js", - "devDependencies": { - "@mscdex/eslint-config": "^1.0.0", - "eslint": "^7.0.0" - }, - "engines": { - "node": ">=10.16.0" - }, - "homepage": "https://github.com/mscdex/ssh2#readme", - "keywords": [ - "ssh", - "ssh2", - "sftp", - "secure", - "shell", - "exec", - "remote", - "client" - ], - "licenses": [ - { - "type": "MIT", - "url": "http://github.com/mscdex/ssh2/raw/master/LICENSE" - } - ], - "main": "./lib/index.js", - "name": "ssh2", - "optionalDependencies": { - "cpu-features": "0.0.2", - "nan": "^2.15.0" - }, - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/mscdex/ssh2.git" - }, - "scripts": { - "install": "node install.js", - "lint": "eslint --cache --report-unused-disable-directives --ext=.js .eslintrc.js examples lib test", - "lint:fix": "npm run lint -- --fix", - "rebuild": "node install.js", - "test": "node test/test.js" - }, - "version": "1.4.0" -} diff --git a/reverse_engineering/node_modules/ssh2/test/common.js b/reverse_engineering/node_modules/ssh2/test/common.js deleted file mode 100644 index a531924..0000000 --- a/reverse_engineering/node_modules/ssh2/test/common.js +++ /dev/null @@ -1,316 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { readFileSync } = require('fs'); -const { join } = require('path'); -const { inspect } = require('util'); - -const Client = require('../lib/client.js'); -const Server = require('../lib/server.js'); -const { parseKey } = require('../lib/protocol/keyParser.js'); - -const mustCallChecks = []; - -const DEFAULT_TEST_TIMEOUT = 30 * 1000; - -function noop() {} - -function runCallChecks(exitCode) { - if (exitCode !== 0) return; - - const failed = mustCallChecks.filter((context) => { - if ('minimum' in context) { - context.messageSegment = `at least ${context.minimum}`; - return context.actual < context.minimum; - } - context.messageSegment = `exactly ${context.exact}`; - return context.actual !== context.exact; - }); - - failed.forEach((context) => { - console.error('Mismatched %s function calls. Expected %s, actual %d.', - context.name, - context.messageSegment, - context.actual); - console.error(context.stack.split('\n').slice(2).join('\n')); - }); - - if (failed.length) - process.exit(1); -} - -function mustCall(fn, exact) { - return _mustCallInner(fn, exact, 'exact'); -} - -function mustCallAtLeast(fn, minimum) { - return _mustCallInner(fn, minimum, 'minimum'); -} - -function _mustCallInner(fn, criteria = 1, field) { - if (process._exiting) - throw new Error('Cannot use common.mustCall*() in process exit handler'); - - if (typeof fn === 'number') { - criteria = fn; - fn = noop; - } else if (fn === undefined) { - fn = noop; - } - - if (typeof criteria !== 'number') - throw new TypeError(`Invalid ${field} value: ${criteria}`); - - const context = { - [field]: criteria, - actual: 0, - stack: inspect(new Error()), - name: fn.name || '' - }; - - // Add the exit listener only once to avoid listener leak warnings - if (mustCallChecks.length === 0) - process.on('exit', runCallChecks); - - mustCallChecks.push(context); - - function wrapped(...args) { - ++context.actual; - return fn.call(this, ...args); - } - // TODO: remove origFn? - wrapped.origFn = fn; - - return wrapped; -} - -function getCallSite(top) { - const originalStackFormatter = Error.prepareStackTrace; - Error.prepareStackTrace = (err, stack) => - `${stack[0].getFileName()}:${stack[0].getLineNumber()}`; - const err = new Error(); - Error.captureStackTrace(err, top); - // With the V8 Error API, the stack is not formatted until it is accessed - // eslint-disable-next-line no-unused-expressions - err.stack; - Error.prepareStackTrace = originalStackFormatter; - return err.stack; -} - -function mustNotCall(msg) { - const callSite = getCallSite(mustNotCall); - return function mustNotCall(...args) { - args = args.map(inspect).join(', '); - const argsInfo = (args.length > 0 - ? `\ncalled with arguments: ${args}` - : ''); - assert.fail( - `${msg || 'function should not have been called'} at ${callSite}` - + argsInfo); - }; -} - -function setup(title, configs) { - const { - client: clientCfg_, - server: serverCfg_, - allReady: allReady_, - timeout: timeout_, - debug, - noForceClientReady, - noForceServerReady, - noClientError, - noServerError, - } = configs; - - // Make shallow copies of client/server configs to avoid mutating them when - // multiple tests share the same config object reference - let clientCfg; - if (clientCfg_) - clientCfg = { ...clientCfg_ }; - let serverCfg; - if (serverCfg_) - serverCfg = { ...serverCfg_ }; - - let clientClose = false; - let clientReady = false; - let serverClose = false; - let serverReady = false; - const msg = (text) => { - return `${title}: ${text}`; - }; - - const timeout = (typeof timeout_ === 'number' - ? timeout_ - : DEFAULT_TEST_TIMEOUT); - - const allReady = (typeof allReady_ === 'function' ? allReady_ : undefined); - - if (debug) { - if (clientCfg) { - clientCfg.debug = (...args) => { - console.log(`[${title}][CLIENT]`, ...args); - }; - } - if (serverCfg) { - serverCfg.debug = (...args) => { - console.log(`[${title}][SERVER]`, ...args); - }; - } - } - - let timer; - let client; - let clientReadyFn; - let server; - let serverReadyFn; - if (clientCfg) { - client = new Client(); - if (!noClientError) - client.on('error', onError); - clientReadyFn = (noForceClientReady ? onReady : mustCall(onReady)); - client.on('ready', clientReadyFn) - .on('close', mustCall(onClose)); - } else { - clientReady = clientClose = true; - } - - if (serverCfg) { - server = new Server(serverCfg); - if (!noServerError) - server.on('error', onError); - serverReadyFn = (noForceServerReady ? onReady : mustCall(onReady)); - server.on('connection', mustCall((conn) => { - if (!noServerError) - conn.on('error', onError); - conn.on('ready', serverReadyFn); - server.close(); - })).on('close', mustCall(onClose)); - } else { - serverReady = serverClose = true; - } - - function onError(err) { - const which = (this === client ? 'client' : 'server'); - assert(false, msg(`Unexpected ${which} error: ${err.stack}\n`)); - } - - function onReady() { - if (this === client) { - assert(!clientReady, - msg('Received multiple ready events for client')); - clientReady = true; - } else { - assert(!serverReady, - msg('Received multiple ready events for server')); - serverReady = true; - } - clientReady && serverReady && allReady && allReady(); - } - - function onClose() { - if (this === client) { - assert(!clientClose, - msg('Received multiple close events for client')); - clientClose = true; - } else { - assert(!serverClose, - msg('Received multiple close events for server')); - serverClose = true; - } - if (clientClose && serverClose) - clearTimeout(timer); - } - - process.nextTick(mustCall(() => { - function connectClient() { - if (clientCfg.sock) { - clientCfg.sock.connect(server.address().port, 'localhost'); - } else { - clientCfg.host = 'localhost'; - clientCfg.port = server.address().port; - } - try { - client.connect(clientCfg); - } catch (ex) { - ex.message = msg(ex.message); - throw ex; - } - } - - if (server) { - server.listen(0, 'localhost', mustCall(() => { - if (timeout >= 0) { - timer = setTimeout(() => { - assert(false, msg('Test timed out')); - }, timeout); - } - if (client) - connectClient(); - })); - } - })); - - return { client, server }; -} - -const FIXTURES_DIR = join(__dirname, 'fixtures'); -const fixture = (() => { - const cache = new Map(); - return (file) => { - const existing = cache.get(file); - if (existing !== undefined) - return existing; - - const result = readFileSync(join(FIXTURES_DIR, file)); - cache.set(file, result); - return result; - }; -})(); -const fixtureKey = (() => { - const cache = new Map(); - return (file, passphrase, bypass) => { - if (typeof passphrase === 'boolean') { - bypass = passphrase; - passphrase = undefined; - } - if (typeof bypass !== 'boolean' || !bypass) { - const existing = cache.get(file); - if (existing !== undefined) - return existing; - } - const fullPath = join(FIXTURES_DIR, file); - const raw = fixture(file); - let key = parseKey(raw, passphrase); - if (Array.isArray(key)) - key = key[0]; - const result = { key, raw, fullPath }; - cache.set(file, result); - return result; - }; -})(); - -function setupSimple(debug, title) { - const { client, server } = setup(title, { - client: { username: 'Password User', password: '12345' }, - server: { hostKeys: [ fixtureKey('ssh_host_rsa_key').raw ] }, - debug, - }); - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })); - })); - return { client, server }; -} - -module.exports = { - fixture, - fixtureKey, - FIXTURES_DIR, - mustCall, - mustCallAtLeast, - mustNotCall, - setup, - setupSimple, -}; diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/bad_rsa_private_key b/reverse_engineering/node_modules/ssh2/test/fixtures/bad_rsa_private_key deleted file mode 100644 index 80fdc87..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/bad_rsa_private_key +++ /dev/null @@ -1,26 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpQIBAAKCAQEAz7MF4vhgw6HxNf3KtVf3VULTYgrRSlv+cCZdB1xxI1p/nGyu -/eekUn5C+mGeDS488DX5ulzicxVpL7pamc/tFNcp91MrR7PiIMK2l+bwbZJubbLj -DHhNcBklnFOSKxtmQRfuorGakpy/kXmIxF5of0xXGns6DlHRq9dGCJIXvrkqhcEb -k4n2y4aV4VOiMHdo6FrFQVPzA8DlbJP2SjIFZ/0VdK7O7eiyiqV1p1xlbTQQ5rAX -LdsshBn/GvoBOTCVupMXurn2582vgGh26Mmovj2QGzScMGUVttkMlnxUmKT/aQka -mC0vR54QOW7lyWPjAitOV0qgmtGm3/cl7W7NjwIDAQABAoIBAFxH0C+951BEXWV9 -s1jLEqshG8YNxFtjcDLn+KFSoznv9Y7MgxtwlgPI8X1Jbe2xQ4X+lUwGBN7Y/nkk -NSjtxwphZtXqb+pVs/yWRoZLJzunucSnnFVoBg/uPFWuk9zvOYlmVrKWcnT9i+fY -tbl5sLgOdQzg/zRpidztssIQFti3o2jnpyrEGcepPWLkfCgqPfGmNv78BAIt/6iT -zYDB4GMSq/LnPTIOFsIOvlkZg3RCcLWeAPRC+lvFQVY+M/uJL5WIbA5il1IMMKH7 -MULWpRO3lnb1JVrkZlBldK5uew6AN3tHDQOmg+C2JuIbOZ35J9dcnwsE+IptWWBj -XiFRJCECgYEA8BeuufkslureqOycaPLMkqchMTue1OxbLJFvPN+dh/cW6Lng3b8+ -xAyzZrc0vccH/jl9WVHhIZ7TcKXDzSmmrtnZ/3m1c4gANGqIPwO+emL1ZzzkIKGd -FrLeBZKP4TWry9kjg4cG1SKGpcB5ngJMPXUxMZNe74tC4Hk820PkFjcCgYEA3XXn -ngRCgH9N1eKSD2daxxlBhTTSnTgjU+dDaDFQzPIhJCcS8HwyQBQmNTOSXXK9sShC -fdXAsmiBby5WEBq/K5+cXeDG2ZlFLyPovEgTUrLgraw42PYs0+A8Ls7dFk7PuMez -3G2gUPkY039JiyXKfcog9/dIRfbWCwzQ6s7TV2kCgYEArsme81cahhgg1zvCNokk -M1Omz2/HFt2nFpAeOmPVDGnu7Kh9sxGKgTF53bpclBh0kjiKL99zFYXKCoUzQYYk -CcEhemLBnYUSGRbBb5arMfAfFfR3Y+YkNaUsC0SCqILpOfMvbo57g+ipu7ufDlA/ -7rIFiUDvaVap7j909W+8egsCgYEAsuc/0DBixMmSyHl7QwRcmkC15HVSu32RVIOb -ub01KAtmaH1EWJAMTCW64/mggOtjgI0kgeE/BSFVhsqo7eOdkhEj0db27OxbroRU -zF1xdrpYtRRO7D6a4iLgm3OzuQS72+tASo8pFqDUxG6sq8NAvLOgRJE4ioSoT07w -KvAgXRkCgYEAmWgcsX/BdNcKOteSDtPkys5NRtWCBz7Coxb+xXXoXz1FVegBolpY -wXVePvXTIbU8VJOLunMyH5wpmMUiJbTX9v2o/yfpsH0ci4GaAeVtqpA= ------END RSA PRIVATE KEY----- \ No newline at end of file diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/https_cert.pem b/reverse_engineering/node_modules/ssh2/test/fixtures/https_cert.pem deleted file mode 100644 index 49e1045..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/https_cert.pem +++ /dev/null @@ -1,33 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIFuzCCA6OgAwIBAgIUPtNIRfp8v8RsObCr+9LVosWVD/QwDQYJKoZIhvcNAQEL -BQAwbTELMAkGA1UEBhMCVVMxEzARBgNVBAgMClNvbWUtU3RhdGUxEjAQBgNVBAcM -CVNvbWUtQ2l0eTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMRIw -EAYDVQQDDAlsb2NhbGhvc3QwHhcNMjAxMjIwMDQwNTM1WhcNMzAxMjE4MDQwNTM1 -WjBtMQswCQYDVQQGEwJVUzETMBEGA1UECAwKU29tZS1TdGF0ZTESMBAGA1UEBwwJ -U29tZS1DaXR5MSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxEjAQ -BgNVBAMMCWxvY2FsaG9zdDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB -AJ/m96/mBMFoUWUOFSvvmJjHj/XxnO89ClCcCIFA6bJNCJMFZV3m853HAhP9g3kF -M3hL0c96GKS5IsRJiNUMrIUYrWCPh1yUJCNfczyGbBJNcEoRhfqCuuzjA5U7jAil -jqLWBP+ZI0tKRuQXX4bDHp51qDESscxNHZQp0+Lho86y4XjZPnT1OYd5rl3D6D82 -AElOrGOtsj7KmHl3eYhQoKNDlCGa5ZK+L05rsClU5m/LXyGmf5QtOIF00JqJ7KS4 -mX3ZF+XE/+3gkXLJyOCOYFDLjGY7WjsJXz3Wm6pktW8NGqhMaaRfIINqtCQkDgMk -gTjF3TtEA/M2DsGU2edL3qm/ibQ4z88dMVkLGZ6DWZg5oGwZR0W8jRAauhWO01Qq -JSLF3Rhvj4VasF4Hj6sI2HQcgGlDFqPNs/ErTA91mN/+yzXzCYIGBUeF5cSbIsLL -TNo6fCHKRIYqpHYCQjwBYQh/2R4/o/BHHkePVWDN0dg2VAyrp/YhV3YTfs3M4ond -yx2CoW1FJHPlhsmGH3A6PlWe2dRgu9f0ZejOX+eefqkkJtrVbmxfVCB9KET7TrV1 -lBX/V6bnFwmT0fygeBHd0aR+h8dvIs3E/wovLp4MZjtT97p+IMcGUcH9AmbFlXgi -VOnYx4/3WLuqGpyurDaCWwJDmtdCDoclZeZ3ef+IEi3/AgMBAAGjUzBRMB0GA1Ud -DgQWBBTQsY4pBOEhu4+hJb5KqaxKNBMPLTAfBgNVHSMEGDAWgBTQsY4pBOEhu4+h -Jb5KqaxKNBMPLTAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4ICAQBf -+YfOSlOw79aCdtU40OH51QFJxuK54ryxpzRcpBeDE57HfnuNHAM+z+5xVu8+qaRn -jo27ylmLLmzlWV946Yb+fyxIZb37KNXiIYehPTYyiG9MYmE3kEH/kLEvU8SQ6zO5 -6CVP3RN+HP1ZdgHi4Zq6DLsngr/ma8nAXuRUgsvLogB2yrtTJTlMB5631ahdD3U8 -kInPa1FlWYjq0QvllzMJ2q/uUG8kMLZRArqKMxb6j5hqHZuA2PAhb1h2K54doOWt -26HdGPVBxZcnE7HUUqKMAxAf++vmYicDTSv6rsEONxmG9cn0SQWzUnr3G6zZ4uxF -9wlvl5/VN6jT9XtS9rpZfwOVLigmuhMFkUCxTTN0eHOh0u76QSk2nphxumIj1vc+ -I9G/KNk0R3G+7AyjDK2WIxaqUTChpBfytQoiiQCOYEL+KlJboWhYL7mfeBT2flzH -H3/LfF61Y8V2H5pjX1x+e/FghA5OFiHsrgoJVegVYu6v0JyCzNwGaSvnpu8QZcOZ -lT6d4UKS8JmIuq2w7iru6cURBRzMfBZ4qaX3Gm/NSDfi6q/8aL/mogzQHg91lrFz -AXZUkb+WGikJ6TEgL9M4qBHwgssk7ayEejBhIuLxQD654Py8P8diEt/77iY0qsS9 -EEw/onPXr9nLLeIcigQEa2+14msAb2I7a2/RhlUW+Q== ------END CERTIFICATE----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/https_key.pem b/reverse_engineering/node_modules/ssh2/test/fixtures/https_key.pem deleted file mode 100644 index 3be6a97..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/https_key.pem +++ /dev/null @@ -1,52 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQCf5vev5gTBaFFl -DhUr75iYx4/18ZzvPQpQnAiBQOmyTQiTBWVd5vOdxwIT/YN5BTN4S9HPehikuSLE -SYjVDKyFGK1gj4dclCQjX3M8hmwSTXBKEYX6grrs4wOVO4wIpY6i1gT/mSNLSkbk -F1+Gwx6edagxErHMTR2UKdPi4aPOsuF42T509TmHea5dw+g/NgBJTqxjrbI+yph5 -d3mIUKCjQ5QhmuWSvi9Oa7ApVOZvy18hpn+ULTiBdNCaieykuJl92RflxP/t4JFy -ycjgjmBQy4xmO1o7CV891puqZLVvDRqoTGmkXyCDarQkJA4DJIE4xd07RAPzNg7B -lNnnS96pv4m0OM/PHTFZCxmeg1mYOaBsGUdFvI0QGroVjtNUKiUixd0Yb4+FWrBe -B4+rCNh0HIBpQxajzbPxK0wPdZjf/ss18wmCBgVHheXEmyLCy0zaOnwhykSGKqR2 -AkI8AWEIf9keP6PwRx5Hj1VgzdHYNlQMq6f2IVd2E37NzOKJ3csdgqFtRSRz5YbJ -hh9wOj5VntnUYLvX9GXozl/nnn6pJCba1W5sX1QgfShE+061dZQV/1em5xcJk9H8 -oHgR3dGkfofHbyLNxP8KLy6eDGY7U/e6fiDHBlHB/QJmxZV4IlTp2MeP91i7qhqc -rqw2glsCQ5rXQg6HJWXmd3n/iBIt/wIDAQABAoICAQCb0z8o4WVc/UXkzvZ+3Hy+ -1itKp+whkECPEZ+QJiwXn85tR+LiwYBDD37M8E7BDvp7jpemMvv0+p4Q3wBDbphp -FAVRhk2JQKx+9DOelfiXVXPKGo2P9Poog4ooUeFDQ+NeeGZil1+3rWisOsLS1y7t -iQcg23D9AWGD08cy4GT7t4LWfA7Ld3ZauY/cvF+FyiA5UDva35hGbLRuGqoK11fU -ArVGkmaKvF/pcjQ38w6lf3DzoAfP5MmeDrKDB0nftC2QYJFTTsmBjUjwrgfeHaFq -2xG1Rr3FrnpsDsmgIYhV8lU6EU0Z68IJj2CBn8kv8tEi/F99s+iNiO6UY3R+XIdd -Jng5zPxHwprzKjvdfl6e4KhwkV8YJbPW0SFDj6Y0Ie0CdSysdJ8BhT7dk7LvJH1Q -DhQSAFftSna4MW5fzAogyQVL+KF3JnQ9BvFZX1swlIqBDHc6DeM+sFg0U++7qFyl -nZellskBgfLXlGCjgGEC/W5pUOaZzBk1BGa8x8Zm3vA//uaoOw/BKizfa+p0VqoU -bC4E8HEK+Rqj9oB07wVliqU9mCqrc5offhjeft9YbUAqx6GPG+1kPiKW1F4++iT2 -Yils/euv+gtK9d9JbMUCCH6mp1wIy40a14XisA8/O8NONjF63VTZX3try7rjOKxd -D0W68FGzACIkRkmTTc2NsQKCAQEAzKq7Lk/6cf2bzSQc0oH0XWxuA497czTQYj7l -k4UkGcUeEu9qOp3qU66KjmqLXLJnF233tQ2ArpiwX7tHNmhXZmIufNxa0Gue2VGx -eyRO/aTCnD1FsSayX1KcaLrwvg5gvwOPQLNCacMc47RCyI6/05irXfNtRlqKKm+R -ZgnhHxcwMzX5lLX9Rr54AWp0yuLEK+i0lcKsNnypAMl/C9GTqk3dEpao0y6SGHiW -Ih8Q2Cy4LbRD48PWuf9rBvb3iZyiLe0xemD8wuNN0j7/Xt9tcL4OuzkmkzWCyslM -Qi3yNw6eRziFhzdpDdHpJjFjEnGI94jgt1AYJtesFvSf8Tz7jQKCAQEAyAH7JQKx -mYvaRioAaUKQHiLImPxypt5cEGiyrPdiBBrU+3fBTC/EZJn/VK7ApM+7YRqvO/vz -d9orkvsWfzxpQM1xhBZ3bwTWXXWRz7g5vzKwJk4pZkXaUk+QAUwp79OrZFTcQokJ -d/l1wj5sUQCrs0l5gD5M3O6ZXPWLoSv1gBI7ktBxXY3VBrQ0uAwE9mQHjyrO+Utc -fcdFEtOqwOxyQQmcsj0vjGm385FmtuIG/pSzhvPXGyo3VYrQjTXT7pYnghu3LBgg -JJuE8kOAlSVTL0ccSO9GLqvj2bTyLlrFcKPBReXHNLwl5kij2w7WBTPGQn61u+ye -+bmSunIkjE2muwKCAQEAr/k4OcjAgJRbCpY7RfBAyLb7HIqYzWSiq2aDBEUc1h97 -DTLXNpEislLHhU4sh0ZJh4agzgZPF0/njlg7EZfDVh+i8u6QEtYF3br1C/kbBdFN -FwND0d6AzZ79JrtdVTyNiI8p86pttvvw8gPCzCiY3PlOltg/o5cjZvtIm+BwtMe+ -RLnq3ydfHx2TlzwOMYeqvko2QvIAGlUzBp85YlMPUQXjyCDMBc/sA6hjBfGKDSTe -M0XkfYicLo5jWrir+6E2fKCNwzhy+6pu9g/+iHc45RA1IFsyRK5kx7EupVRWB2rF -Ql1hyfIlnKFYguNB2NDPwG3rMRJnwbX8nDw27TfO3QKCAQEAlHAb82DnbFzGF3LO -sVBMY4FPPXOGp9+5lhgOG57SKNe9IBDF7gQ5jqxYOoIjyW2+1JeYXD1meZn64u/k -x3OPbh/LUsvVwhhl/CDoobBJc2RsJVG3GgdXu+T+rGfZa/u9ZQ4yFlNcKqWCxzHK -8+c6hypNuWcDZqjSO5KlGW3lmzJs8k4vBM7hvkL6KWoKOM8OaSvNRmmu8E53LjzX -qq0RMsGugP42DtDbTDKqd6qSpFi6ULsh9zBCtwL6OwMrEhRwp/hn3prdKC4f4ilF -Aewcq6bsEBk9DiBWT1oir1KA3FM8euLJEJNe0WUx7r85Cc1eJDWkLR+08QPQKP3T -sCllRwKCAQBQgSFFI65dlLJf/iJrZPuP3sCzZNABe4y7lxZK2Gij4FXzf2KA1SAl -dyxuUU+Hv98l52pJIWmoNYWKEXOorsu+TuadgiK11DSx/ajQ9y8OEbscOVTJwrv3 -aVbaz4f0z2AKRLrBLsln2aVLQVPF5dsPNmsYIUWOrvBJ+DFFeXQG+QWimS2VbS+P -wrDdpVej8sEaUVfCqvCAx8gWtrFtE401BmfNla1xFGHiHhcLrsqKj3uxIojQ0Met -fFCrKqxES0OQ6pY/9VlrBmfihw/Bt1LWMPUo90atFArbwGaUxXLwi4FwRafkW5Di -k77w3OGObcFv4zxCOoFxcXXc3MCyw3r8 ------END PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/id_dsa b/reverse_engineering/node_modules/ssh2/test/fixtures/id_dsa deleted file mode 100644 index d9c9b5b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/id_dsa +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN DSA PRIVATE KEY----- -MIIBuwIBAAKBgQC3/2VIGHgqHuxvhPa6rryqqLy6sQmjeSIwyrIW5F/o8W4sz/mE -0noDSW4PaoXjgPQv5egj1EByws6dMOUqLaZHNWNn+Lh/jkKlwKyhbSCAjqoWH3v3 -uI1j58GO/eZ2+REijfyA0XJxdm7kqEexxbg0UpFr1F/eLBUxpLIbhhS1cwIVAKcB -B9DnAObuPJGTwYTCaIIBQDy9AoGAJicW0pIFwgoTYsIeywmUQopJ3FQ4M3eDwQ0U -T33pzWvBZFN2OsUDTFg64PNm9ow09wk042qMg168eKCUTp2iR/Y9R4xTj8dls8iv -aMGMZ/B32eURIjUREGiXYTyG1pfuB2znSvr/5pavhuz5yG9M0AJCiYiexdaQKO3N -oJp6T3ACgYEAsep79p4WljnawrJc928zGq6dLYjs+5apYhqx4vf2l3Z2u26VqVNG -i5zZkUzhWQYV3/qtEOpO43dyZTHW+d9L8ni6HbXFWRVx60WE+5WKkzkimHJ6gox2 -kDvOqPudiS34KJOCEYYLEnJmK8aUZBZzWFORXkN8QgA/h9ts8AU785UCFAVXZMWq -CteWCH2HzcY2x/65dMwL ------END DSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/id_ecdsa b/reverse_engineering/node_modules/ssh2/test/fixtures/id_ecdsa deleted file mode 100644 index 036e3b6..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/id_ecdsa +++ /dev/null @@ -1,5 +0,0 @@ ------BEGIN EC PRIVATE KEY----- -MHcCAQEEIPMZuWP7fMsZeyC1XXVUALVebJOX7PTwmsPql9qG25SeoAoGCCqGSM49 -AwEHoUQDQgAEB/B6mC5lrekKPWfGEkKpnCk08+dRnzFUg2jUHpaIrOTt4jGdvq6T -yAN57asB+PYmFyVIpi35NcmicF18qX3ayg== ------END EC PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa b/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa deleted file mode 100644 index 90a6f72..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXQIBAAKBgQDL0yFO4W4xbdrJk/i+CW3itPATvhRkS+x+gKmkdH739AqWYP6r -kTFAmFTw9gLJ/c2tN7ow0T0QUR9iUsv/3QzTuwsjBu0feo3CVxwMkaJTo5ks9XBo -OW0R3tyCcOLlAcQ1WjC7cv5Ifn4gXLLM+k8/y/m3u8ERtidNxbRqpQ/gPQIDAQAB -AoGABirSRC/ABNDdIOJQUXe5knWFGiPTPCGr+zvrZiV8PgZtV5WBvzE6e0jgsRXQ -icobMhWQla+PGHJL786vi4NlwuhwKcF7Pd908ofej1eeBOd1u/HQ/qsfxPdxI0zF -dcWPYgAOo9ydOMGcSx4v1zDIgFInELJzKbv64LJQD0/xhoUCQQD7KhJ7M8Nkwsr2 -iKCyWTFM2M8/VKltgaiSmsNKZETashk5tKOrM3EWX4RcB/DnvHe8VNyYpC6Sd1uQ -AHwPDfxDAkEAz7+7hDybH6Cfvmr8kUOlDXiJJWXp5lP37FLzMDU6a9wTKZFnh57F -e91zRmKlQTegFet93MXaFYljRkI+4lMpfwJBAPPLbNEF973Qjq4rBMDZbs9HDDRO -+35+AqD7dGC7X1Jg2bd3rf66GiU7ZgDm/GIUQK0gOlg31bT6AniO39zFGH0CQFBh -Yd9HR8nT7xrQ8EoQPzNYGNBUf0xz3rAcZCWZ4rHK48sojEMoBkbnputrzX7PU+xH -QlqCXuAIWVXc2dHd1WcCQQDIUJHPOsgeAfTLoRRRURp/m8zZ9IpbaPTyDstPVNYe -zARW3Oa/tzPqdO6NWaetCp17u7Kb6X9np7Vz17i/4KED ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa.ppk b/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa.ppk deleted file mode 100644 index 4504f18..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa.ppk +++ /dev/null @@ -1,26 +0,0 @@ -PuTTY-User-Key-File-2: ssh-rsa -Encryption: none -Comment: rsa-key-20150522 -Public-Lines: 6 -AAAAB3NzaC1yc2EAAAABJQAAAQB1quqP0rhl78NOLD4lj+1x5FGAqZ3aqo6GiEPz -KOaQmy86FuJMK0nHj3gUKTa/Kvaa+8PZyeu+uVseHg47YrynCOcJEEnpqvbArc8M -xMWuUnTUMrjvokGDOBBiQu4UAE4bybpgXkNHJfbrcDVgivmv3Ikn8PVIZ1rLBMLZ -6Lzn0rjPjFD0X4WqsAJW2SFiZnsjMZtVL2TWadNTyyfjjm2NCRBvd32VLohkSe9Q -BZBD6MW8YQyBKUnEF/7WNY0eehDVrfx1YqPOV1bDwFUhRaAYpLDLDR0KCAPvx7qb -8G5Cq0TIBsEr3H8ztNRcOTQoaKgn0T18M7cyS4ykoNLYW4Zx -Private-Lines: 14 -AAABACyF3DZraF3sBLXLjSL4MFSblHXfUHxAiPSiQzlpa/9dUCPRTrUJddzOgHZU -yJtcXU9mLm4VDRe7wZyxbSs6Hd5WZUGzIuLLEUH8k4hKdE/MLDSdkhV7qhX5iaij -tAeRaammRoVUGXTd7rnzGx2cXnnkvkZ22VmqkQ6MLg1DTmWNfOO9cdwFGdQawf/n -yUV0nTkWsHXy5Qrozq9wRFk8eyw+pFllxqavsNftZX8VDiQt27JLZPTU4LGkH660 -3gq1KhNS/l05TlXnMZGjlcPN8UEaBzmCWRezhJSttjs5Kgp1K3yDf4ozMR/HWOCj -Jq8fd3VIgli6ML8yjr/c0A0T9MUAAACBAL1/byxHiCvY/2C+/L5T+ZZq13jdZuYK -MmOFaNITgEdNGWSIFYRzhLKGXj7awQWOIW6chj470GNOfQjFL1TvXhbwfqW6esDa -kETOYQPYQHZijABcn7uurMUm/bu5x/z9gYkAfniOCI5vmvMvJ09JcZ0iUmFWDZZY -fAutBvrt+n/vAAAAgQCe9jrA51wn1/wzKmWF+2+OWFUG9usheIcEbHB8mxLguLfU -+x4i+2vLo0FtXEPAw+Bt7Tge4t0m6USiVZXtW/QKsh0kMj4mNVHFz+XXw4l1QOYv -n5TjnLepiP7majXv4GHI2eOcHkyly4sIkj4jNLYqvT86hMxW4IC+jtJEWhn/nwAA -AIEAlJ8cExu2WrWukTDJQHrVegtvdJUhNjol2wLucPuWwSxKuB8FHYwaPRYRkf3d -DkZ53hhjJZ0BVkAaQ28uqM09xKD+q1H4/r0nnbtlV4uHLl3cCD5mGrH8I/iDPJX4 -fFIqCa0+n1D6RzvDqs1QIu+PGSp0K6vHOOS5fP0ZpuT025E= -Private-MAC: 4ca26008c85b901f4d2766b0924c25e527678d7e diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa_enc deleted file mode 100644 index 75a1e95..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/id_rsa_enc +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,CCE70744FB28F2EFB1D74377281A780C - -1WiGnqpSGXFIg+WYr7T2XN72C1YrNQ1jmRISb32TB/Rh2Zo47fjyQnv9impz8b6m -91R/qF7uCLI0fswvT5oqwn1L0vUAA0YtW/E2IQJEx5GPiaexoDJYYfu2yy036Kca -e9VtCajgrV+kycg1CknCxQKMcKXNq8Czvq66PM4Bzknek5hhdmxHxOl0QAE+8EXt -pnasOGz3szTUKkD6givwWgvDXY3BnVG46fXff99Xqgb6fx5IDbAkVKaxWIN/c81E -b0rcfyoLb7yjPgNYn9vUI6Z+24NMYUYARzb3dG5geaeX0BYb/VlCtJUsP0Rp2P2P -jl+cdvBKaeOvA9gPo/jAtSOFexQRs7AzKzoOLYU1fokd8HhqxOKAljn9ujmEqif7 -qcimk2s7ff6tSSlxtRzDP+Uq9d1u5tyaONRV2lwj+GdP1gRoOmdZL5chdvoAi0I8 -5eMf58hEuN2d4h4FryO6z7K+XQ9oo6/N/xHU0U/t2Pco9oY2L6oWMDxKwbfPhaD5 -CcoEElsK4XFArYDielEq9Y1sXaEuwR5I0ksDDsANp74r9Bhcqz60gJa6hVz0ouEU -QA67wV9+TRmulKRxwANvqxQwqPuxqcTPeJjXSUN/ZCaDwYmI+d1poxMx2fQzT82M -onlgOWq+3HbCotyoeFpCameymwDQzmrYdMBr7oWLgnOrxmJ89zDc6+jkHFgQJvnU -atyeVDqe866ZvvIGWS+r/EsDjV3cTW/cJvdsC+5BpnoXoVF4LqxE3LFbEbQBvqio -4enCZpspQSMOJra37vSofbD+DyI5Wd+y8SBmfDLjyDFhT0spW9aN99uFqSc3UElA -SAmnFmpYBFEQrRGpvpu5sC0c/YjZeRXr0/F1xPpIT1SWzpRsbcsWRBDzWjLOKWQx -8ytwc2QS7eKedfqkPWpYKW0Qtps+XgnGWA6PBX42IYhLsKANRfhFXQv5LPqLNNOn -3EsG9pd+0dBpfxFQfyyAKAUuvpJNgJ6kNx8VSj8Ppj8lyUdGa9YucgB02m7gHC9U -A4YyJsIcjo6IcrjM+ez1govRRS0nE8AUb8ups9tn8mdBwqcPCrgcJhV7JkOYNJYh -NAh0vgmneOq8LSVs2SRaL3uuLNbjh1LR9iViwbIY8kMQXkiXa2/V+PFwt5oqeX5f -2x3yzCeGBiQW10InyBBnKutbPD85R4YJhQ55bOMDSFfGGqwOU1QURiO1NUzf9n/2 -+E8VE7J/IQoO0TrJpC+EV0ROKME9W6+AvEFdmdIigbq3bkdEgSixyLnrhV8V8T4N -nbKlLoqfXt8DmT+h8XPzgsu0Fq/PNi6xBaiUsaN9tK6OP2ZVjr9ihbeLTI0rcKDr -XX2cWPvTcboRLt+S4wmqchMf7Kxa2PfX5Tf+KCcdZNQO4YqS23wQZgk61kuOQCsS -uOop+ICI7yWZkjqCOzGOeHLl/7FyFeprsFDIwD1g20y9bzibbJlbQPhwXSalqDQT -MWLH3rdFuvgLH7ujtjxSakES+VzkOhbnmb/Wypbl1D7P7GT2seau16EEGQDhDzcJ -Q4d/BjR2WqqxmC79MOAvUWAu6fZQjPD30/gYPGpMaEuiLrDlzDqvf+oi4A9+EtRL ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa deleted file mode 100644 index a8722ab..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa +++ /dev/null @@ -1,21 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABsgAAAAdzc2gtZH -NzAAAAgQDg+DsMAituSW/NJpWVy2w7xN6Uu/IfCqpy38CFBW+mBnOX7OzPulI+1uZxXRLy -UKiQDAegXCqSHMCo5ACZhw2BRwq74J4VA5fOFGdwcacTQo1zKDF64wvyVSgQE/E2PSFLKu -NHHtRFnjvq6WrgTQsL9aif2FBWS5q0MGahzXhNkQAAABUAn1ASRSRcIVsWqrrZubFQq4pU -OlMAAACBALcKIRLTtYG5+N/vzEULdsXSGToDRth6X5Yjb7c0UotAmy9VGrnmN5IO+//1em -2USHeSoO+5shRq92zdggdQwNaXXzU301huIETztfRwGHOfUGZbzJmIqdzLhdziFhneAzaN -zVeUFyIqvWL1Q89WgC2Uh3DY/lK/gIhRK7WD0cDAAAAAgC882WUEEig48DVyjbNi1xf8rG -svyypMHSs2rj6pja2Upfm+C5AKKU387x8Vj/Kz291ROIl7h/AhmKOlwdxwPZOG5ffDygaW -Tlo4/JagwP9HmTsK1Tyd1chuyMk9cNLdgWFsCGGHY2RcEwccq9panvvtKp57HqDaT1W7AS -g2spT9AAAB8G4oDW5uKA1uAAAAB3NzaC1kc3MAAACBAOD4OwwCK25Jb80mlZXLbDvE3pS7 -8h8KqnLfwIUFb6YGc5fs7M+6Uj7W5nFdEvJQqJAMB6BcKpIcwKjkAJmHDYFHCrvgnhUDl8 -4UZ3BxpxNCjXMoMXrjC/JVKBAT8TY9IUsq40ce1EWeO+rpauBNCwv1qJ/YUFZLmrQwZqHN -eE2RAAAAFQCfUBJFJFwhWxaqutm5sVCrilQ6UwAAAIEAtwohEtO1gbn43+/MRQt2xdIZOg -NG2HpfliNvtzRSi0CbL1UaueY3kg77//V6bZRId5Kg77myFGr3bN2CB1DA1pdfNTfTWG4g -RPO19HAYc59QZlvMmYip3MuF3OIWGd4DNo3NV5QXIiq9YvVDz1aALZSHcNj+Ur+AiFErtY -PRwMAAAACALzzZZQQSKDjwNXKNs2LXF/ysay/LKkwdKzauPqmNrZSl+b4LkAopTfzvHxWP -8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PKBpZOWjj8lqDA/0eZOwrVPJ3VyG7IyT1w0t2BYW -wIYYdjZFwTBxyr2lqe++0qnnseoNpPVbsBKDaylP0AAAAVAIoWASGAfFqckLwvtPRNCzow -TTl1AAAAEm5ldyBvcGVuc3NoIGZvcm1hdAECAwQFBgc= ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub deleted file mode 100644 index d5b662d..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-dss AAAAB3NzaC1kc3MAAACBAOD4OwwCK25Jb80mlZXLbDvE3pS78h8KqnLfwIUFb6YGc5fs7M+6Uj7W5nFdEvJQqJAMB6BcKpIcwKjkAJmHDYFHCrvgnhUDl84UZ3BxpxNCjXMoMXrjC/JVKBAT8TY9IUsq40ce1EWeO+rpauBNCwv1qJ/YUFZLmrQwZqHNeE2RAAAAFQCfUBJFJFwhWxaqutm5sVCrilQ6UwAAAIEAtwohEtO1gbn43+/MRQt2xdIZOgNG2HpfliNvtzRSi0CbL1UaueY3kg77//V6bZRId5Kg77myFGr3bN2CB1DA1pdfNTfTWG4gRPO19HAYc59QZlvMmYip3MuF3OIWGd4DNo3NV5QXIiq9YvVDz1aALZSHcNj+Ur+AiFErtYPRwMAAAACALzzZZQQSKDjwNXKNs2LXF/ysay/LKkwdKzauPqmNrZSl+b4LkAopTfzvHxWP8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PKBpZOWjj8lqDA/0eZOwrVPJ3VyG7IyT1w0t2BYWwIYYdjZFwTBxyr2lqe++0qnnseoNpPVbsBKDaylP0= new openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result deleted file mode 100644 index 7b8d66e..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtzCCASwGByqGSM44BAEwggEfAoGBAOD4OwwCK25Jb80mlZXLbDvE3pS78h8K\nqnLfwIUFb6YGc5fs7M+6Uj7W5nFdEvJQqJAMB6BcKpIcwKjkAJmHDYFHCrvgnhUD\nl84UZ3BxpxNCjXMoMXrjC/JVKBAT8TY9IUsq40ce1EWeO+rpauBNCwv1qJ/YUFZL\nmrQwZqHNeE2RAhUAn1ASRSRcIVsWqrrZubFQq4pUOlMCgYEAtwohEtO1gbn43+/M\nRQt2xdIZOgNG2HpfliNvtzRSi0CbL1UaueY3kg77//V6bZRId5Kg77myFGr3bN2C\nB1DA1pdfNTfTWG4gRPO19HAYc59QZlvMmYip3MuF3OIWGd4DNo3NV5QXIiq9YvVD\nz1aALZSHcNj+Ur+AiFErtYPRwMADgYQAAoGALzzZZQQSKDjwNXKNs2LXF/ysay/L\nKkwdKzauPqmNrZSl+b4LkAopTfzvHxWP8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PK\nBpZOWjj8lqDA/0eZOwrVPJ3VyG7IyT1w0t2BYWwIYYdjZFwTBxyr2lqe++0qnnse\noNpPVbsBKDaylP0=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAOD4OwwCK25Jb80mlZXLbDvE3pS78h8KqnLfwIUFb6YGc5fs7M+6Uj7W5nFdEvJQqJAMB6BcKpIcwKjkAJmHDYFHCrvgnhUDl84UZ3BxpxNCjXMoMXrjC/JVKBAT8TY9IUsq40ce1EWeO+rpauBNCwv1qJ/YUFZLmrQwZqHNeE2RAAAAFQCfUBJFJFwhWxaqutm5sVCrilQ6UwAAAIEAtwohEtO1gbn43+/MRQt2xdIZOgNG2HpfliNvtzRSi0CbL1UaueY3kg77//V6bZRId5Kg77myFGr3bN2CB1DA1pdfNTfTWG4gRPO19HAYc59QZlvMmYip3MuF3OIWGd4DNo3NV5QXIiq9YvVDz1aALZSHcNj+Ur+AiFErtYPRwMAAAACALzzZZQQSKDjwNXKNs2LXF/ysay/LKkwdKzauPqmNrZSl+b4LkAopTfzvHxWP8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PKBpZOWjj8lqDA/0eZOwrVPJ3VyG7IyT1w0t2BYWwIYYdjZFwTBxyr2lqe++0qnnseoNpPVbsBKDaylP0=", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result deleted file mode 100644 index 0d93248..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtzCCASwGByqGSM44BAEwggEfAoGBAOD4OwwCK25Jb80mlZXLbDvE3pS78h8K\nqnLfwIUFb6YGc5fs7M+6Uj7W5nFdEvJQqJAMB6BcKpIcwKjkAJmHDYFHCrvgnhUD\nl84UZ3BxpxNCjXMoMXrjC/JVKBAT8TY9IUsq40ce1EWeO+rpauBNCwv1qJ/YUFZL\nmrQwZqHNeE2RAhUAn1ASRSRcIVsWqrrZubFQq4pUOlMCgYEAtwohEtO1gbn43+/M\nRQt2xdIZOgNG2HpfliNvtzRSi0CbL1UaueY3kg77//V6bZRId5Kg77myFGr3bN2C\nB1DA1pdfNTfTWG4gRPO19HAYc59QZlvMmYip3MuF3OIWGd4DNo3NV5QXIiq9YvVD\nz1aALZSHcNj+Ur+AiFErtYPRwMADgYQAAoGALzzZZQQSKDjwNXKNs2LXF/ysay/L\nKkwdKzauPqmNrZSl+b4LkAopTfzvHxWP8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PK\nBpZOWjj8lqDA/0eZOwrVPJ3VyG7IyT1w0t2BYWwIYYdjZFwTBxyr2lqe++0qnnse\noNpPVbsBKDaylP0=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAOD4OwwCK25Jb80mlZXLbDvE3pS78h8KqnLfwIUFb6YGc5fs7M+6Uj7W5nFdEvJQqJAMB6BcKpIcwKjkAJmHDYFHCrvgnhUDl84UZ3BxpxNCjXMoMXrjC/JVKBAT8TY9IUsq40ce1EWeO+rpauBNCwv1qJ/YUFZLmrQwZqHNeE2RAAAAFQCfUBJFJFwhWxaqutm5sVCrilQ6UwAAAIEAtwohEtO1gbn43+/MRQt2xdIZOgNG2HpfliNvtzRSi0CbL1UaueY3kg77//V6bZRId5Kg77myFGr3bN2CB1DA1pdfNTfTWG4gRPO19HAYc59QZlvMmYip3MuF3OIWGd4DNo3NV5QXIiq9YvVDz1aALZSHcNj+Ur+AiFErtYPRwMAAAACALzzZZQQSKDjwNXKNs2LXF/ysay/LKkwdKzauPqmNrZSl+b4LkAopTfzvHxWP8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PKBpZOWjj8lqDA/0eZOwrVPJ3VyG7IyT1w0t2BYWwIYYdjZFwTBxyr2lqe++0qnnseoNpPVbsBKDaylP0=", - "private": "-----BEGIN DSA PRIVATE KEY-----\nMIIBvAIBAAKBgQDg+DsMAituSW/NJpWVy2w7xN6Uu/IfCqpy38CFBW+mBnOX7OzP\nulI+1uZxXRLyUKiQDAegXCqSHMCo5ACZhw2BRwq74J4VA5fOFGdwcacTQo1zKDF6\n4wvyVSgQE/E2PSFLKuNHHtRFnjvq6WrgTQsL9aif2FBWS5q0MGahzXhNkQIVAJ9Q\nEkUkXCFbFqq62bmxUKuKVDpTAoGBALcKIRLTtYG5+N/vzEULdsXSGToDRth6X5Yj\nb7c0UotAmy9VGrnmN5IO+//1em2USHeSoO+5shRq92zdggdQwNaXXzU301huIETz\ntfRwGHOfUGZbzJmIqdzLhdziFhneAzaNzVeUFyIqvWL1Q89WgC2Uh3DY/lK/gIhR\nK7WD0cDAAoGALzzZZQQSKDjwNXKNs2LXF/ysay/LKkwdKzauPqmNrZSl+b4LkAop\nTfzvHxWP8rPb3VE4iXuH8CGYo6XB3HA9k4bl98PKBpZOWjj8lqDA/0eZOwrVPJ3V\nyG7IyT1w0t2BYWwIYYdjZFwTBxyr2lqe++0qnnseoNpPVbsBKDaylP0CFQCKFgEh\ngHxanJC8L7T0TQs6ME05dQ==\n-----END DSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc deleted file mode 100644 index 392f214..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc +++ /dev/null @@ -1,22 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABBgJ5gXYn -/2IFE2+CrAxYR8AAAAEAAAAAEAAAGxAAAAB3NzaC1kc3MAAACBAPKhVnFGWb0KLibdYnJz -0RwFy/mt98KMIdByHKQWRm9UjoVJk1ypuQpnj+bqFnxCzCFSU9OUj0/Xe0Wuk+kF2BtMO0 -w+ZYfVHCqEaaIJ1D/iLqi8aBbYs552l9+P0DsFUlTE0D/AvKTQ2PsztFq7wHUTQVmnj4vy -k1bw7ske+ImLAAAAFQDnXsk6hdenasLyE8ylLHSE+0XR3QAAAIBsMerhmMT0/416hJV/pr -s7crOX0e0gF8C7kar/ILj5WULX7k143+4lgluoogrPXbd5fXgOnqdQawow8a/IjU62Sz6n -/qfHLJtQ2sJOK2Vkj5NF2UCcRHrewqJw9nDCS7yYh3c+gUfIBcIRkEJK6eRJfrZuaq0Yue -nUa9AuFwnjPAAAAIBwjDUjp9jaJu46eobNK8CWJL/Noi2fXTtFZFgUFRwkr/FXLLsOckQT -mYxaWcxP4NwuvMyI25tOueM0RvAIR7J3Afc5pbuCx6dIgiOf2gRClQU5OlqhrnMW2BQXlR -hBKBNMp5LjM5t46KTBkjh/30//s4Kimrp/C2XBGgEuRdgyqQAAAgDIGP0oYyi7sTk0HdU9 -uWZLaDhHpW4Z8xTzfgUDbxoTYQ2igO90O32vSqW/cC2QKWTFuPCFnsCerHAIGzX/eyxlCQ -VyNa7VrhbNjIKAHBF3XMcRVRbW2SdYq8tHSkeZHr5EuO5dRfJ7wsR8flkPb4O4viNlIbvF -Ake8dsZEOhcnVNiv+NMR9mTq8l91wR60tr3XiWzCMkEYrJiWOfQuZSvzYi7dUmFxQuEZfQ -vIPkZD3L6XdaAz/r6YAONFAbtUMAOaUxOGV9puSsunSosAvmi+NcJ9iUM2FpAu561gp+Tv -RRcgXHxLGuzTNASiMaTN3M+HenqUh3RWmWauL5wSR7DbrH7Vq47YTnVjtg8xcZnMCfOx2D -Wz775hD6uyLwbkxKMaNMf8p4sOcXsSpHNqKmfkUxQBpNRp6Vg5W+AVaAkyXQng2LRt6txJ -Xv5zBiSFdsobkrWko/ONfGKfG+zVP+LIVcghLpp71GZQX6Ci02vB55pvk8k0G91H3INn/c -t6Q5zY5pK9VZwxjZ29psm7V+FdeD1g8VQ1Rp9muq6zDXHKKyqkBK/oGCM9UhBHFjki0gBR -v6LY/iXsz/eG14svhLjM5zYFSX7jUOI9b/PnhhL7Mos4wguHN2EjfGWuC07PkkqDPoqSwn -cC91OKhub6yqZsqvBz9BcV+2FxVNPNKzRdzA== ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub deleted file mode 100644 index c2b1190..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-dss AAAAB3NzaC1kc3MAAACBAPKhVnFGWb0KLibdYnJz0RwFy/mt98KMIdByHKQWRm9UjoVJk1ypuQpnj+bqFnxCzCFSU9OUj0/Xe0Wuk+kF2BtMO0w+ZYfVHCqEaaIJ1D/iLqi8aBbYs552l9+P0DsFUlTE0D/AvKTQ2PsztFq7wHUTQVmnj4vyk1bw7ske+ImLAAAAFQDnXsk6hdenasLyE8ylLHSE+0XR3QAAAIBsMerhmMT0/416hJV/prs7crOX0e0gF8C7kar/ILj5WULX7k143+4lgluoogrPXbd5fXgOnqdQawow8a/IjU62Sz6n/qfHLJtQ2sJOK2Vkj5NF2UCcRHrewqJw9nDCS7yYh3c+gUfIBcIRkEJK6eRJfrZuaq0YuenUa9AuFwnjPAAAAIBwjDUjp9jaJu46eobNK8CWJL/Noi2fXTtFZFgUFRwkr/FXLLsOckQTmYxaWcxP4NwuvMyI25tOueM0RvAIR7J3Afc5pbuCx6dIgiOf2gRClQU5OlqhrnMW2BQXlRhBKBNMp5LjM5t46KTBkjh/30//s4Kimrp/C2XBGgEuRdgyqQ== diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result deleted file mode 100644 index d15133a..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtjCCASsGByqGSM44BAEwggEeAoGBAPKhVnFGWb0KLibdYnJz0RwFy/mt98KM\nIdByHKQWRm9UjoVJk1ypuQpnj+bqFnxCzCFSU9OUj0/Xe0Wuk+kF2BtMO0w+ZYfV\nHCqEaaIJ1D/iLqi8aBbYs552l9+P0DsFUlTE0D/AvKTQ2PsztFq7wHUTQVmnj4vy\nk1bw7ske+ImLAhUA517JOoXXp2rC8hPMpSx0hPtF0d0CgYBsMerhmMT0/416hJV/\nprs7crOX0e0gF8C7kar/ILj5WULX7k143+4lgluoogrPXbd5fXgOnqdQawow8a/I\njU62Sz6n/qfHLJtQ2sJOK2Vkj5NF2UCcRHrewqJw9nDCS7yYh3c+gUfIBcIRkEJK\n6eRJfrZuaq0YuenUa9AuFwnjPAOBhAACgYBwjDUjp9jaJu46eobNK8CWJL/Noi2f\nXTtFZFgUFRwkr/FXLLsOckQTmYxaWcxP4NwuvMyI25tOueM0RvAIR7J3Afc5pbuC\nx6dIgiOf2gRClQU5OlqhrnMW2BQXlRhBKBNMp5LjM5t46KTBkjh/30//s4Kimrp/\nC2XBGgEuRdgyqQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAPKhVnFGWb0KLibdYnJz0RwFy/mt98KMIdByHKQWRm9UjoVJk1ypuQpnj+bqFnxCzCFSU9OUj0/Xe0Wuk+kF2BtMO0w+ZYfVHCqEaaIJ1D/iLqi8aBbYs552l9+P0DsFUlTE0D/AvKTQ2PsztFq7wHUTQVmnj4vyk1bw7ske+ImLAAAAFQDnXsk6hdenasLyE8ylLHSE+0XR3QAAAIBsMerhmMT0/416hJV/prs7crOX0e0gF8C7kar/ILj5WULX7k143+4lgluoogrPXbd5fXgOnqdQawow8a/IjU62Sz6n/qfHLJtQ2sJOK2Vkj5NF2UCcRHrewqJw9nDCS7yYh3c+gUfIBcIRkEJK6eRJfrZuaq0YuenUa9AuFwnjPAAAAIBwjDUjp9jaJu46eobNK8CWJL/Noi2fXTtFZFgUFRwkr/FXLLsOckQTmYxaWcxP4NwuvMyI25tOueM0RvAIR7J3Afc5pbuCx6dIgiOf2gRClQU5OlqhrnMW2BQXlRhBKBNMp5LjM5t46KTBkjh/30//s4Kimrp/C2XBGgEuRdgyqQ==", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result deleted file mode 100644 index 2271c47..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "new openssh format encrypted", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtjCCASsGByqGSM44BAEwggEeAoGBAPKhVnFGWb0KLibdYnJz0RwFy/mt98KM\nIdByHKQWRm9UjoVJk1ypuQpnj+bqFnxCzCFSU9OUj0/Xe0Wuk+kF2BtMO0w+ZYfV\nHCqEaaIJ1D/iLqi8aBbYs552l9+P0DsFUlTE0D/AvKTQ2PsztFq7wHUTQVmnj4vy\nk1bw7ske+ImLAhUA517JOoXXp2rC8hPMpSx0hPtF0d0CgYBsMerhmMT0/416hJV/\nprs7crOX0e0gF8C7kar/ILj5WULX7k143+4lgluoogrPXbd5fXgOnqdQawow8a/I\njU62Sz6n/qfHLJtQ2sJOK2Vkj5NF2UCcRHrewqJw9nDCS7yYh3c+gUfIBcIRkEJK\n6eRJfrZuaq0YuenUa9AuFwnjPAOBhAACgYBwjDUjp9jaJu46eobNK8CWJL/Noi2f\nXTtFZFgUFRwkr/FXLLsOckQTmYxaWcxP4NwuvMyI25tOueM0RvAIR7J3Afc5pbuC\nx6dIgiOf2gRClQU5OlqhrnMW2BQXlRhBKBNMp5LjM5t46KTBkjh/30//s4Kimrp/\nC2XBGgEuRdgyqQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAPKhVnFGWb0KLibdYnJz0RwFy/mt98KMIdByHKQWRm9UjoVJk1ypuQpnj+bqFnxCzCFSU9OUj0/Xe0Wuk+kF2BtMO0w+ZYfVHCqEaaIJ1D/iLqi8aBbYs552l9+P0DsFUlTE0D/AvKTQ2PsztFq7wHUTQVmnj4vyk1bw7ske+ImLAAAAFQDnXsk6hdenasLyE8ylLHSE+0XR3QAAAIBsMerhmMT0/416hJV/prs7crOX0e0gF8C7kar/ILj5WULX7k143+4lgluoogrPXbd5fXgOnqdQawow8a/IjU62Sz6n/qfHLJtQ2sJOK2Vkj5NF2UCcRHrewqJw9nDCS7yYh3c+gUfIBcIRkEJK6eRJfrZuaq0YuenUa9AuFwnjPAAAAIBwjDUjp9jaJu46eobNK8CWJL/Noi2fXTtFZFgUFRwkr/FXLLsOckQTmYxaWcxP4NwuvMyI25tOueM0RvAIR7J3Afc5pbuCx6dIgiOf2gRClQU5OlqhrnMW2BQXlRhBKBNMp5LjM5t46KTBkjh/30//s4Kimrp/C2XBGgEuRdgyqQ==", - "private": "-----BEGIN DSA PRIVATE KEY-----\nMIIBugIBAAKBgQDyoVZxRlm9Ci4m3WJyc9EcBcv5rffCjCHQchykFkZvVI6FSZNc\nqbkKZ4/m6hZ8QswhUlPTlI9P13tFrpPpBdgbTDtMPmWH1RwqhGmiCdQ/4i6ovGgW\n2LOedpffj9A7BVJUxNA/wLyk0Nj7M7Rau8B1E0FZp4+L8pNW8O7JHviJiwIVAOde\nyTqF16dqwvITzKUsdIT7RdHdAoGAbDHq4ZjE9P+NeoSVf6a7O3Kzl9HtIBfAu5Gq\n/yC4+VlC1+5NeN/uJYJbqKIKz123eX14Dp6nUGsKMPGvyI1Otks+p/6nxyybUNrC\nTitlZI+TRdlAnER63sKicPZwwku8mId3PoFHyAXCEZBCSunkSX62bmqtGLnp1GvQ\nLhcJ4zwCgYBwjDUjp9jaJu46eobNK8CWJL/Noi2fXTtFZFgUFRwkr/FXLLsOckQT\nmYxaWcxP4NwuvMyI25tOueM0RvAIR7J3Afc5pbuCx6dIgiOf2gRClQU5OlqhrnMW\n2BQXlRhBKBNMp5LjM5t46KTBkjh/30//s4Kimrp/C2XBGgEuRdgyqQIUSNLlRVPv\nMC3Q3P3ajY1DdZvi9z8=\n-----END DSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm deleted file mode 100644 index 38566b4..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm +++ /dev/null @@ -1,23 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAAFmFlczEyOC1nY21Ab3BlbnNzaC5jb20AAAAGYmNyeXB0AA -AAGAAAABD01pNY1+DTCAHuI6mcjB0YAAAAEAAAAAEAAAGyAAAAB3NzaC1kc3MAAACBAPLA -N0jFExSJiCvw7p2W2v5tqvXIG4YwCglrl2wnGOMBGmfaeIcxZErzW00hOxq+NvDIlK43kJ -iP98Vz0XTHIW6DpkE9DcC5GGA6nDZn9L+BSrBL8NhuBlz2ekgWOTCqnDC7Il/iyUCMi79s -ZPOEg/bMExWJlB5AosJr7v5twVftAAAAFQC5AGsioHKAc2Cd2QwKLUZSmDZAVwAAAIBxYf -EThMIXPQkSer3snKJfDz0uvc1y/6htsjXLk93TAAi3LSD2dGqYs5s0WfzO4RnFso0EovrL -OnIbqU1XApr6CPKAVX2REsXFWWF3VixEHIEF1Q9gIvHdYgAxSxtwYvOPpAwDmaPxWeV5/q -MsMu2RSKkK6f08J0vsESnKU4nmnwAAAIEAxH8NZyntzihIAHnx1Lbo7h1sPi4RhcpKK5pS -UiaKoWxkjseqUsyWENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3qhq/B3bspx1GWjL -qLfKbeVi4un8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi7GdZG8Q0tuyfXxsAAAIA -PDupGK4wMtROtFZqo7vduzkHJuDrE/tAwGqiD2pKMova7WaKM0EUznwcl3gtmhHvFeY+NJ -3Uc9sQcX/9n3y6NAYsC+eZeqe7Sy2GWVyqxOUJHpZqfsKYJidG61TBgKgx+JXAeidYdz4L -4cEapwwocOptbY3ZRFmszekq5xPomnkP9DeSQG6l4eYSv7OpeAHlFj2KCmJMVEZDOl6RyJ -KCqOpfEJIIVoCmna/hQdd9ptLVFmbX/VShgLjvUwfBggJtZNPb5jx+PMy+I0ylywaCIG5K -JQAqust6dzFBx3mBoO4kZPBHlb8XwQ4HYLYph0Ur/lINsHrpLxgmtEw7zzs73Nshl6go2V -uvBtcZ5ywAMk+8CLP5ZgpiGBxlMtFGowp/5zuJxRpc9FgdfxnnVWDyzcQ/YvX9lwzb6cNz -bXeLPsKjOSLPV7G/RFIiuCAOa97ZCM8Ho4FhdNYOGilmjuxV7FJiTc7KP2r+Wh3oxsV7AB -Q6Thj06b2mX3iE4hqLaMKIVE1zs22nMlUtFJv8YY1ZWBihUVlnR9vWgIH7ODoZOwNWBlLd -Qfyfi8w3KgJWj5oVNAM7WniNFQjfNxEbrPklfYg93deVE/LhPghs9I7fsIeHY/p8GtsO/S -amTcjkYi6pUuT8m7IeFYQ8cWvGnbaYz6/9+ni+0aoUL93GKHQw1+mBUVuswVZXBF1WVCf+ -LMgZ ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub deleted file mode 100644 index d9eb1a5..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-dss AAAAB3NzaC1kc3MAAACBAPLAN0jFExSJiCvw7p2W2v5tqvXIG4YwCglrl2wnGOMBGmfaeIcxZErzW00hOxq+NvDIlK43kJiP98Vz0XTHIW6DpkE9DcC5GGA6nDZn9L+BSrBL8NhuBlz2ekgWOTCqnDC7Il/iyUCMi79sZPOEg/bMExWJlB5AosJr7v5twVftAAAAFQC5AGsioHKAc2Cd2QwKLUZSmDZAVwAAAIBxYfEThMIXPQkSer3snKJfDz0uvc1y/6htsjXLk93TAAi3LSD2dGqYs5s0WfzO4RnFso0EovrLOnIbqU1XApr6CPKAVX2REsXFWWF3VixEHIEF1Q9gIvHdYgAxSxtwYvOPpAwDmaPxWeV5/qMsMu2RSKkK6f08J0vsESnKU4nmnwAAAIEAxH8NZyntzihIAHnx1Lbo7h1sPi4RhcpKK5pSUiaKoWxkjseqUsyWENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3qhq/B3bspx1GWjLqLfKbeVi4un8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi7GdZG8Q0tuyfXxs= diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result deleted file mode 100644 index 6a918a8..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtzCCASsGByqGSM44BAEwggEeAoGBAPLAN0jFExSJiCvw7p2W2v5tqvXIG4Yw\nCglrl2wnGOMBGmfaeIcxZErzW00hOxq+NvDIlK43kJiP98Vz0XTHIW6DpkE9DcC5\nGGA6nDZn9L+BSrBL8NhuBlz2ekgWOTCqnDC7Il/iyUCMi79sZPOEg/bMExWJlB5A\nosJr7v5twVftAhUAuQBrIqBygHNgndkMCi1GUpg2QFcCgYBxYfEThMIXPQkSer3s\nnKJfDz0uvc1y/6htsjXLk93TAAi3LSD2dGqYs5s0WfzO4RnFso0EovrLOnIbqU1X\nApr6CPKAVX2REsXFWWF3VixEHIEF1Q9gIvHdYgAxSxtwYvOPpAwDmaPxWeV5/qMs\nMu2RSKkK6f08J0vsESnKU4nmnwOBhQACgYEAxH8NZyntzihIAHnx1Lbo7h1sPi4R\nhcpKK5pSUiaKoWxkjseqUsyWENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3q\nhq/B3bspx1GWjLqLfKbeVi4un8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi\n7GdZG8Q0tuyfXxs=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAPLAN0jFExSJiCvw7p2W2v5tqvXIG4YwCglrl2wnGOMBGmfaeIcxZErzW00hOxq+NvDIlK43kJiP98Vz0XTHIW6DpkE9DcC5GGA6nDZn9L+BSrBL8NhuBlz2ekgWOTCqnDC7Il/iyUCMi79sZPOEg/bMExWJlB5AosJr7v5twVftAAAAFQC5AGsioHKAc2Cd2QwKLUZSmDZAVwAAAIBxYfEThMIXPQkSer3snKJfDz0uvc1y/6htsjXLk93TAAi3LSD2dGqYs5s0WfzO4RnFso0EovrLOnIbqU1XApr6CPKAVX2REsXFWWF3VixEHIEF1Q9gIvHdYgAxSxtwYvOPpAwDmaPxWeV5/qMsMu2RSKkK6f08J0vsESnKU4nmnwAAAIEAxH8NZyntzihIAHnx1Lbo7h1sPi4RhcpKK5pSUiaKoWxkjseqUsyWENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3qhq/B3bspx1GWjLqLfKbeVi4un8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi7GdZG8Q0tuyfXxs=", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result deleted file mode 100644 index 27ae40b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "new openssh format encrypted gcm", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtzCCASsGByqGSM44BAEwggEeAoGBAPLAN0jFExSJiCvw7p2W2v5tqvXIG4Yw\nCglrl2wnGOMBGmfaeIcxZErzW00hOxq+NvDIlK43kJiP98Vz0XTHIW6DpkE9DcC5\nGGA6nDZn9L+BSrBL8NhuBlz2ekgWOTCqnDC7Il/iyUCMi79sZPOEg/bMExWJlB5A\nosJr7v5twVftAhUAuQBrIqBygHNgndkMCi1GUpg2QFcCgYBxYfEThMIXPQkSer3s\nnKJfDz0uvc1y/6htsjXLk93TAAi3LSD2dGqYs5s0WfzO4RnFso0EovrLOnIbqU1X\nApr6CPKAVX2REsXFWWF3VixEHIEF1Q9gIvHdYgAxSxtwYvOPpAwDmaPxWeV5/qMs\nMu2RSKkK6f08J0vsESnKU4nmnwOBhQACgYEAxH8NZyntzihIAHnx1Lbo7h1sPi4R\nhcpKK5pSUiaKoWxkjseqUsyWENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3q\nhq/B3bspx1GWjLqLfKbeVi4un8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi\n7GdZG8Q0tuyfXxs=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAPLAN0jFExSJiCvw7p2W2v5tqvXIG4YwCglrl2wnGOMBGmfaeIcxZErzW00hOxq+NvDIlK43kJiP98Vz0XTHIW6DpkE9DcC5GGA6nDZn9L+BSrBL8NhuBlz2ekgWOTCqnDC7Il/iyUCMi79sZPOEg/bMExWJlB5AosJr7v5twVftAAAAFQC5AGsioHKAc2Cd2QwKLUZSmDZAVwAAAIBxYfEThMIXPQkSer3snKJfDz0uvc1y/6htsjXLk93TAAi3LSD2dGqYs5s0WfzO4RnFso0EovrLOnIbqU1XApr6CPKAVX2REsXFWWF3VixEHIEF1Q9gIvHdYgAxSxtwYvOPpAwDmaPxWeV5/qMsMu2RSKkK6f08J0vsESnKU4nmnwAAAIEAxH8NZyntzihIAHnx1Lbo7h1sPi4RhcpKK5pSUiaKoWxkjseqUsyWENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3qhq/B3bspx1GWjLqLfKbeVi4un8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi7GdZG8Q0tuyfXxs=", - "private": "-----BEGIN DSA PRIVATE KEY-----\nMIIBuwIBAAKBgQDywDdIxRMUiYgr8O6dltr+bar1yBuGMAoJa5dsJxjjARpn2niH\nMWRK81tNITsavjbwyJSuN5CYj/fFc9F0xyFug6ZBPQ3AuRhgOpw2Z/S/gUqwS/DY\nbgZc9npIFjkwqpwwuyJf4slAjIu/bGTzhIP2zBMViZQeQKLCa+7+bcFX7QIVALkA\nayKgcoBzYJ3ZDAotRlKYNkBXAoGAcWHxE4TCFz0JEnq97JyiXw89Lr3Ncv+obbI1\ny5Pd0wAIty0g9nRqmLObNFn8zuEZxbKNBKL6yzpyG6lNVwKa+gjygFV9kRLFxVlh\nd1YsRByBBdUPYCLx3WIAMUsbcGLzj6QMA5mj8Vnlef6jLDLtkUipCun9PCdL7BEp\nylOJ5p8CgYEAxH8NZyntzihIAHnx1Lbo7h1sPi4RhcpKK5pSUiaKoWxkjseqUsyW\nENt6DTByIdGhBNrOp9/vw2R5CSUkxuI0TlI8bj3qhq/B3bspx1GWjLqLfKbeVi4u\nn8CrooRRq2g8+nYLu2EWbF/56pEEzws6DptlDJQi7GdZG8Q0tuyfXxsCFG8ERflm\nOIBFUymTHP8ZeVOgNm/1\n-----END DSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa deleted file mode 100644 index 114e078..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa +++ /dev/null @@ -1,9 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS -1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQTjIb0On/AzYDLFRi+g3fGdAIF72KFG -iZBpP8oKZ8bsncH9ULtVV9517cNcRNuDETQtvLqoCdIn7TipYo8Jv/lKAAAAsA6ULqEOlC -6hAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOMhvQ6f8DNgMsVG -L6Dd8Z0AgXvYoUaJkGk/ygpnxuydwf1Qu1VX3nXtw1xE24MRNC28uqgJ0iftOKlijwm/+U -oAAAAfVd3jjve28r7FhY6Uo//cKIM1rBeWZG16b8bjyVyFswAAABJuZXcgb3BlbnNzaCBm -b3JtYXQBAgMEBQYH ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub deleted file mode 100644 index 8ebee0f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub +++ /dev/null @@ -1 +0,0 @@ -ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOMhvQ6f8DNgMsVGL6Dd8Z0AgXvYoUaJkGk/ygpnxuydwf1Qu1VX3nXtw1xE24MRNC28uqgJ0iftOKlijwm/+Uo= new openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result deleted file mode 100644 index b430d73..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4yG9Dp/wM2AyxUYvoN3xnQCBe9ih\nRomQaT/KCmfG7J3B/VC7VVfede3DXETbgxE0Lby6qAnSJ+04qWKPCb/5Sg==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOMhvQ6f8DNgMsVGL6Dd8Z0AgXvYoUaJkGk/ygpnxuydwf1Qu1VX3nXtw1xE24MRNC28uqgJ0iftOKlijwm/+Uo=", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result deleted file mode 100644 index 4affa3e..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4yG9Dp/wM2AyxUYvoN3xnQCBe9ih\nRomQaT/KCmfG7J3B/VC7VVfede3DXETbgxE0Lby6qAnSJ+04qWKPCb/5Sg==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOMhvQ6f8DNgMsVGL6Dd8Z0AgXvYoUaJkGk/ygpnxuydwf1Qu1VX3nXtw1xE24MRNC28uqgJ0iftOKlijwm/+Uo=", - "private": "-----BEGIN EC PRIVATE KEY-----\nMHYCAQEEH1Xd4473tvK+xYWOlKP/3CiDNawXlmRtem/G48lchbOgCgYIKoZIzj0D\nAQehRANCAATjIb0On/AzYDLFRi+g3fGdAIF72KFGiZBpP8oKZ8bsncH9ULtVV951\n7cNcRNuDETQtvLqoCdIn7TipYo8Jv/lK\n-----END EC PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc deleted file mode 100644 index 08fe2d1..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc +++ /dev/null @@ -1,10 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABBqNbb13W -CKfO7B1vpwJDwbAAAAEAAAAAEAAABoAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlz -dHAyNTYAAABBBJibjz7zvP/EhMZrW/JDdKvYgiEATNUKMfg2NOVxKlf++eTRypLFc1doTp -r+04Ebm1fkyp8RgpFsmvLXLt/dKU0AAADA86k3lHnP6pfD977mwEtKxHOJm44wx8NsdBwN -mNLqxlxUE520nsXjDgpgNU0MF9JDnc1kdhSy8PcdTAAH5+k6bpf3gotPrltPUBMFQdPqst -5kVS7zOgaxv1qZnlyhOqEdNR3Hee09gJByRrAojtcs+sPI7Nba879NPMb5c5K+gKhONHsa -wLAnz66eFQH5iLjd2MwrV4gJe0x6NGCSI2kyzNlxFsoIl7IcHlJHyyuaSlEOFWQJB8cbB4 -BVZB+/8yAx ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub deleted file mode 100644 index 3d87cb2..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJibjz7zvP/EhMZrW/JDdKvYgiEATNUKMfg2NOVxKlf++eTRypLFc1doTpr+04Ebm1fkyp8RgpFsmvLXLt/dKU0= diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result deleted file mode 100644 index dcca403..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEmJuPPvO8/8SExmtb8kN0q9iCIQBM\n1Qox+DY05XEqV/755NHKksVzV2hOmv7TgRubV+TKnxGCkWya8tcu390pTQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJibjz7zvP/EhMZrW/JDdKvYgiEATNUKMfg2NOVxKlf++eTRypLFc1doTpr+04Ebm1fkyp8RgpFsmvLXLt/dKU0=", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result deleted file mode 100644 index 9fe2c73..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "new openssh format encrypted", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEmJuPPvO8/8SExmtb8kN0q9iCIQBM\n1Qox+DY05XEqV/755NHKksVzV2hOmv7TgRubV+TKnxGCkWya8tcu390pTQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJibjz7zvP/EhMZrW/JDdKvYgiEATNUKMfg2NOVxKlf++eTRypLFc1doTpr+04Ebm1fkyp8RgpFsmvLXLt/dKU0=", - "private": "-----BEGIN EC PRIVATE KEY-----\nMHgCAQEEIQDG2nALLBBmkBnw1QvdW4ClRfF3Zl3CcRHujsYz9CLvf6AKBggqhkjO\nPQMBB6FEA0IABJibjz7zvP/EhMZrW/JDdKvYgiEATNUKMfg2NOVxKlf++eTRypLF\nc1doTpr+04Ebm1fkyp8RgpFsmvLXLt/dKU0=\n-----END EC PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm deleted file mode 100644 index 84178ba..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm +++ /dev/null @@ -1,10 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAAFmFlczEyOC1nY21Ab3BlbnNzaC5jb20AAAAGYmNyeXB0AA -AAGAAAABAHURyWtYwqVbjholNpL6opAAAAEAAAAAEAAABoAAAAE2VjZHNhLXNoYTItbmlz -dHAyNTYAAAAIbmlzdHAyNTYAAABBBM+ppawNxvkdHbOaB3ygsRueTdIKiT+OQkAH/5LpDx -XcD6i5AR8T/vrCsZ9/y+8GxU8gmvg4Uszr6LDfaQBZnsUAAADAFqKM/ylVkJ/ZA40ZROrW -LNgrttf2+lpVkADwXWzhuESFPPzERKlbHVsVtbiiYmPkLnY1s5VM4zXIj7xyO9YNA9KcM5 -GHOKUL2/NmDaTyGgc9s3BGu/ibpjSeOd1rtGAB4cw1s9ifbXBQd3qDbqzaEmovs3MGaGHD -c3VagdxhsppjrPjZ+B40Pzs9QkSGutsSJDpH9wVIu4OLr89TquTU3PVACDRU03lPPENVbt -rh2IMJeEQyNINQHtfVwordj8LMOEsBjyQ1aqHNva/iKyTBiw== ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub deleted file mode 100644 index 61b0b99..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub +++ /dev/null @@ -1 +0,0 @@ -ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM+ppawNxvkdHbOaB3ygsRueTdIKiT+OQkAH/5LpDxXcD6i5AR8T/vrCsZ9/y+8GxU8gmvg4Uszr6LDfaQBZnsU= diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result deleted file mode 100644 index 1078648..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEz6mlrA3G+R0ds5oHfKCxG55N0gqJ\nP45CQAf/kukPFdwPqLkBHxP++sKxn3/L7wbFTyCa+DhSzOvosN9pAFmexQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM+ppawNxvkdHbOaB3ygsRueTdIKiT+OQkAH/5LpDxXcD6i5AR8T/vrCsZ9/y+8GxU8gmvg4Uszr6LDfaQBZnsU=", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result deleted file mode 100644 index 626aedf..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "new openssh format encrypted gcm", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEz6mlrA3G+R0ds5oHfKCxG55N0gqJ\nP45CQAf/kukPFdwPqLkBHxP++sKxn3/L7wbFTyCa+DhSzOvosN9pAFmexQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM+ppawNxvkdHbOaB3ygsRueTdIKiT+OQkAH/5LpDxXcD6i5AR8T/vrCsZ9/y+8GxU8gmvg4Uszr6LDfaQBZnsU=", - "private": "-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIHQfJ+4ZNcwSBaCR5kwrR6HjUsTF//R1F983RSTR8vbJoAoGCCqGSM49\nAwEHoUQDQgAEz6mlrA3G+R0ds5oHfKCxG55N0gqJP45CQAf/kukPFdwPqLkBHxP+\n+sKxn3/L7wbFTyCa+DhSzOvosN9pAFmexQ==\n-----END EC PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 deleted file mode 100644 index 7ae3165..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 +++ /dev/null @@ -1,7 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW -QyNTUxOQAAACCyOMGts0WaAdug9NeXbGn2Jrt4wwiO64dumxV2a1IgKQAAAJBOfs+eTn7P -ngAAAAtzc2gtZWQyNTUxOQAAACCyOMGts0WaAdug9NeXbGn2Jrt4wwiO64dumxV2a1IgKQ -AAAEBgQKxJoToGE/Xi4UkYR+FXfin4jG8NTcZ13rJ4CDnCfLI4wa2zRZoB26D015dsafYm -u3jDCI7rh26bFXZrUiApAAAAB3Rlc3RpbmcBAgMEBQY= ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub deleted file mode 100644 index c85c7d1..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILI4wa2zRZoB26D015dsafYmu3jDCI7rh26bFXZrUiAp testing diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result deleted file mode 100644 index 3c9ca29..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-ed25519", - "comment": "testing", - "public": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAsjjBrbNFmgHboPTXl2xp9ia7eMMIjuuHbpsVdmtSICk=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAC3NzaC1lZDI1NTE5AAAAILI4wa2zRZoB26D015dsafYmu3jDCI7rh26bFXZrUiAp", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result deleted file mode 100644 index 705fa99..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-ed25519", - "comment": "testing", - "public": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAsjjBrbNFmgHboPTXl2xp9ia7eMMIjuuHbpsVdmtSICk=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAC3NzaC1lZDI1NTE5AAAAILI4wa2zRZoB26D015dsafYmu3jDCI7rh26bFXZrUiAp", - "private": "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIGBArEmhOgYT9eLhSRhH4Vd+KfiMbw1NxnXesngIOcJ8\n-----END PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa deleted file mode 100644 index ccded2a..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn -NhAAAAAwEAAQAAAQEA4q6eZdx7LYh46PcZNcS3CnO7GuYsEJZeTj5LQSgp21IyTelaBPpr -ijnMwKa+pLQt5TEobpKFFNecPdT6oPoOKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHM -BNkoTFeGrursPkqYRJ0HL4CqYqRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKb -zibJc64JFM7tUoK6Vl64YiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs -8zjxsf6c6N2tKXkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38 -KvTx3wjNQwAAA8hLhVBxS4VQcQAAAAdzc2gtcnNhAAABAQDirp5l3HstiHjo9xk1xLcKc7 -sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+l -fQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg6 -4MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u -2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28 -uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1DAAAAAwEAAQAAAQAmShSbZBiyYkD6KPLr -MCUy8MWED6kVzDB1yvPvN5eKYmH44xe/i4UqvgSl7gR50a2G7zzDIKC2Go1brGQBWPuXRa -ZtOjQygeD4rMHBiH/b7zfy4pQyKDfITTHOFXWE8ERiyL00bAZt09icCy92rQaq8IY/+U56 -sPPJH9UAYG9nEev8opFjAWToFDu0U2+dC+lbqLlXDqDRo75NlnDFmgUoja3y2eFr9A0Cc+ -hjecrdxyJFsCJfEfaLWtBnZb886gqzzvfbHImSQtBAKERcSxuki7uxMoP67g3iQOXa65uz -8kFWRNmbQTGQttakoUaybh1t9eLpBqvVON/4Kg0THShRAAAAgFBTz2ajBK/R/crOSL9VK1 -f7oQv2iJTRVfnUs0r+qPGgf/a/5UwkGRj0KfEWBp3qYD+keShnPr6PDPFrm8UmIdUX8AY7 -3tWT2K/JQVlzJNuINsw+DNjn4M17Z25q0LPmReRWL0nRc2w6W/hmQ/Jmqz6w8Qc4+xpeqS -/HG5feliVnAAAAgQD90a+5Ky3o/2YtueqRf/3dKoiMgGB7JAOzye4dDKGABSlWuQ4N4xEI -CW5MSTp7i/uobTF/tyFO3tTSyb5b2Xwbn/kLO0vgvFCdUGR2BQfN3mcT92T0Gn3JDF3Wym -i2mgU6qnPf+eu+RKZQ9IiyNGny61ROUQa0R0z0pgiAfA89xwAAAIEA5KE9i6hHmigJwfD7 -/AGI4ujyWIVpNyrTdXG3HAPhsdoFuG5ggHggrPuuBF9wNcosrhL20VNOQGHg15gWZIVudu -0qxky4ivQs67Sk9XUjuvTnf+VubM51rIsmh4atKJFSSZo78DEcTRt8aXLrSNvGQ4WPRweM -2Z0YGfMMDM9KJKUAAAASbmV3IG9wZW5zc2ggZm9ybWF0AQ== ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub deleted file mode 100644 index 133afc9..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D new openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result deleted file mode 100644 index dd8a8b4..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result deleted file mode 100644 index d1ada9c..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "new openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEA4q6eZdx7LYh46PcZNcS3CnO7GuYsEJZeTj5LQSgp21IyTela\nBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoOKKMe6oH/pX0BNyAEB9KFZfZgh0v4\nJ4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYqRdINy1sgDU6jUIOuDD5XZzlpDXb1\nftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64YiPgxsNXOJYMTrelVJYebtsNrJFm\nh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKXkk9G4EDKKip4g0bzDmD/fREPQ9vL\ni59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjNQwIDAQABAoIBACZKFJtkGLJiQPoo\n8uswJTLwxYQPqRXMMHXK8+83l4piYfjjF7+LhSq+BKXuBHnRrYbvPMMgoLYajVus\nZAFY+5dFpm06NDKB4PiswcGIf9vvN/LilDIoN8hNMc4VdYTwRGLIvTRsBm3T2JwL\nL3atBqrwhj/5Tnqw88kf1QBgb2cR6/yikWMBZOgUO7RTb50L6VuouVcOoNGjvk2W\ncMWaBSiNrfLZ4Wv0DQJz6GN5yt3HIkWwIl8R9ota0GdlvzzqCrPO99sciZJC0EAo\nRFxLG6SLu7Eyg/ruDeJA5drrm7PyQVZE2ZtBMZC21qShRrJuHW314ukGq9U43/gq\nDRMdKFECgYEA/dGvuSst6P9mLbnqkX/93SqIjIBgeyQDs8nuHQyhgAUpVrkODeMR\nCAluTEk6e4v7qG0xf7chTt7U0sm+W9l8G5/5CztL4LxQnVBkdgUHzd5nE/dk9Bp9\nyQxd1spotpoFOqpz3/nrvkSmUPSIsjRp8utUTlEGtEdM9KYIgHwPPccCgYEA5KE9\ni6hHmigJwfD7/AGI4ujyWIVpNyrTdXG3HAPhsdoFuG5ggHggrPuuBF9wNcosrhL2\n0VNOQGHg15gWZIVudu0qxky4ivQs67Sk9XUjuvTnf+VubM51rIsmh4atKJFSSZo7\n8DEcTRt8aXLrSNvGQ4WPRweM2Z0YGfMMDM9KJKUCgYB7Yh0b1EOjCdQv0jqWtDNB\n+dUbB6Te92jdUwHvGR7AzsGDqL2OPp0e3QbDCq3lNO0GuN3hCbKlVmj6dpuUpqpP\n+3ni3dZKzwAZGOVdAaEDkGNnL1Hh36bZvqs3KHmymjiEhiuB60mP2mtG2zg/+H6w\nWXlIANdTd32PR87GNohqLQKBgA36ic/LJy2Wuxn/iPicg2kUQxUEey1jUfCBVmfB\nGQCNywG+xem07pKFBNvBlhPD27187VhZFpS7J0snQl89BUcCMzZSpIniagizT86u\nLdQVez4HohvG98zn6SAqLNYpJHXZl0aVShywzIeJ/jbDMTkZpmv6WzNG9p1HjfoO\nhoL9AoGAUFPPZqMEr9H9ys5Iv1UrV/uhC/aIlNFV+dSzSv6o8aB/9r/lTCQZGPQp\n8RYGnepgP6R5KGc+vo8M8WubxSYh1RfwBjve1ZPYr8lBWXMk24g2zD4M2OfgzXtn\nbmrQs+ZF5FYvSdFzbDpb+GZD8marPrDxBzj7Gl6pL8cbl96WJWc=\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc deleted file mode 100644 index 09aa65d..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAS8H9Cyk -rueA/Ue6tOb1MOAAAAEAAAAAEAAAEXAAAAB3NzaC1yc2EAAAADAQABAAABAQC8hCiCPnRs -0ucZeyn3pNYKN63dVoxbMB4Yzjs7gvo7XKDby/6GXoU/CFQ/Q9zXRxRZmFglMYh2pOD8iW -dwpLBdd+GmHb4a6xxKtoPpz1+yCPYvi6nXzKPO3B9Wbg8dtTpV23l8MZDxSRUQ9HIkYHQO -oOjJx/AaMdZyHZP+eYK7UqmX1+dtCzr5vvLyEABxrsoFxH/oW/iKO6cDmTxoMyFl9DfUhD -TS7cL1OVBulSBav3aJPxjsCEIs6OE94wLJfFtZAPe4GqWWcC7uG1uUL5Muy2N+SfXHOHLa -I5n1vozt7lIO5TqvykcqTxipKblMW4Y7Iwlhh0YKJxzH3KJ+Qkn7AAAD4GeinUMcN5H0RP -KnXzIsYGq4rG+pEYNL0WyXCOFnyHzr6cASFYa/ViRVRN5H2dDoc0i2tcQStvDt2AfBxP97 -xbTEmRhLkKW7Sxif+bRRpNt2sO1y7ThufOZ8ZSJdbUYf9nc++k5GMZZUTtkFGhFIyhdyl+ -ZReuQFrc1Fv0/JV0K72uLSMSSMvunFjnGchch98Z1t0jEuiym8AIAwFtlvRpbOOySJhHun -fClEOahNvgzkgpqvviged7Gl9Kh3Fpp57ke1087WUF4hdgG2wuLqRq3Jq2kNvTKVi6+PMv -Kz5cLl6beqAJpbkJCpujzrmffo5NHh94R/v8DbAWCyrkjB6NHjOPIVnKaDmXixkcJ489W3 -PQF0kZ9kLrNU2yP1hBLjikr1zollw6xXC5eEpUsIrNcAHrofTMCMsGKuZhlEgTNe0cEATp -ycxi4gHdA6kNSDnMPwOv9rLDZDkgqCqIzxjZCWabqRHwiyoN3CrdDsJNrk8jSqF5epuzXA -EjrPUvu+sgFHIWDJOij+HQCvCgmdO/W7NkL/xCEx6QagjoJhapGICnq6CXPO5vBQeK7AMV -KWUPB1jdxxlHdrSUYU9v11j0SPUM51AMpWA89GZmuQbe/tK14W35VjtL9aGKsz9Ubio029 -O23HJXMxM9Dd6EYXAR9xMLFDTcLT03kjRlL/4XFS4fJqbTGDtuQNqRO3QK/myVAYjgnXwz -X1s77WeIK3sOMwTIXaHReUiQ1Cw+WmkXOhefePT+HrkyDlJk3ikgPUy2s5QW5/d6Lmolwb -mcS9JUfaai0ysP3v1bew8go/IHiUD/X9AkjkKM2kfS1NcPSi18r2721e6RqZiIHxSoyKvq -yUmwiS1kUklSuhlTORBvbclbv4HTwp1iJfu/6zsMqVJc2E8H6WUw3kTeh9fhDMpTY5NArF -KD2aRIYHFvOKav+0vSbQ/KqmKeiTvyZaV7q6giRxVLxBddl4+ucD+FybPJZSebRQ+0QT1j -aUDSpp541zW0rX7sCiZ6sFUybCPVDM1uA5gTAP015OD/FS342gi+Y04K0jBSjlApuy6BQx -sMEQbR3weMmnodbhCtbcgDZDagSFNPlDud0GJl9IWV4hO/K1f9a+Ox3G27Jq4YC2PFgTDb -aYib4xAXPUHJpoWsstSjpMnfgKcS3AGRdJ/jxlKRWV/NXFf4DYIwpzITqFMF+4VqXCa2AS -JWOcSxOK92UqCcZEs8RED3x9dF9E2yBBwHeuwDvH3c9x/nsM/cjDY+EE9VcEUOxF6qMOhO -CiRtEihEAYM46XeFzcSOQrwWPcKu3WTv3IpnzTaofBxV065CUn ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub deleted file mode 100644 index 0e80f0f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC8hCiCPnRs0ucZeyn3pNYKN63dVoxbMB4Yzjs7gvo7XKDby/6GXoU/CFQ/Q9zXRxRZmFglMYh2pOD8iWdwpLBdd+GmHb4a6xxKtoPpz1+yCPYvi6nXzKPO3B9Wbg8dtTpV23l8MZDxSRUQ9HIkYHQOoOjJx/AaMdZyHZP+eYK7UqmX1+dtCzr5vvLyEABxrsoFxH/oW/iKO6cDmTxoMyFl9DfUhDTS7cL1OVBulSBav3aJPxjsCEIs6OE94wLJfFtZAPe4GqWWcC7uG1uUL5Muy2N+SfXHOHLaI5n1vozt7lIO5TqvykcqTxipKblMW4Y7Iwlhh0YKJxzH3KJ+Qkn7 diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result deleted file mode 100644 index ee0fd94..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvIQogj50bNLnGXsp96TW\nCjet3VaMWzAeGM47O4L6O1yg28v+hl6FPwhUP0Pc10cUWZhYJTGIdqTg/IlncKSw\nXXfhph2+GuscSraD6c9fsgj2L4up18yjztwfVm4PHbU6Vdt5fDGQ8UkVEPRyJGB0\nDqDoycfwGjHWch2T/nmCu1Kpl9fnbQs6+b7y8hAAca7KBcR/6Fv4ijunA5k8aDMh\nZfQ31IQ00u3C9TlQbpUgWr92iT8Y7AhCLOjhPeMCyXxbWQD3uBqllnAu7htblC+T\nLstjfkn1xzhy2iOZ9b6M7e5SDuU6r8pHKk8YqSm5TFuGOyMJYYdGCiccx9yifkJJ\n+wIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQC8hCiCPnRs0ucZeyn3pNYKN63dVoxbMB4Yzjs7gvo7XKDby/6GXoU/CFQ/Q9zXRxRZmFglMYh2pOD8iWdwpLBdd+GmHb4a6xxKtoPpz1+yCPYvi6nXzKPO3B9Wbg8dtTpV23l8MZDxSRUQ9HIkYHQOoOjJx/AaMdZyHZP+eYK7UqmX1+dtCzr5vvLyEABxrsoFxH/oW/iKO6cDmTxoMyFl9DfUhDTS7cL1OVBulSBav3aJPxjsCEIs6OE94wLJfFtZAPe4GqWWcC7uG1uUL5Muy2N+SfXHOHLaI5n1vozt7lIO5TqvykcqTxipKblMW4Y7Iwlhh0YKJxzH3KJ+Qkn7", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result deleted file mode 100644 index a0f0fed..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "new openssh format encrypted", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvIQogj50bNLnGXsp96TW\nCjet3VaMWzAeGM47O4L6O1yg28v+hl6FPwhUP0Pc10cUWZhYJTGIdqTg/IlncKSw\nXXfhph2+GuscSraD6c9fsgj2L4up18yjztwfVm4PHbU6Vdt5fDGQ8UkVEPRyJGB0\nDqDoycfwGjHWch2T/nmCu1Kpl9fnbQs6+b7y8hAAca7KBcR/6Fv4ijunA5k8aDMh\nZfQ31IQ00u3C9TlQbpUgWr92iT8Y7AhCLOjhPeMCyXxbWQD3uBqllnAu7htblC+T\nLstjfkn1xzhy2iOZ9b6M7e5SDuU6r8pHKk8YqSm5TFuGOyMJYYdGCiccx9yifkJJ\n+wIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQC8hCiCPnRs0ucZeyn3pNYKN63dVoxbMB4Yzjs7gvo7XKDby/6GXoU/CFQ/Q9zXRxRZmFglMYh2pOD8iWdwpLBdd+GmHb4a6xxKtoPpz1+yCPYvi6nXzKPO3B9Wbg8dtTpV23l8MZDxSRUQ9HIkYHQOoOjJx/AaMdZyHZP+eYK7UqmX1+dtCzr5vvLyEABxrsoFxH/oW/iKO6cDmTxoMyFl9DfUhDTS7cL1OVBulSBav3aJPxjsCEIs6OE94wLJfFtZAPe4GqWWcC7uG1uUL5Muy2N+SfXHOHLaI5n1vozt7lIO5TqvykcqTxipKblMW4Y7Iwlhh0YKJxzH3KJ+Qkn7", - "private": "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAvIQogj50bNLnGXsp96TWCjet3VaMWzAeGM47O4L6O1yg28v+\nhl6FPwhUP0Pc10cUWZhYJTGIdqTg/IlncKSwXXfhph2+GuscSraD6c9fsgj2L4up\n18yjztwfVm4PHbU6Vdt5fDGQ8UkVEPRyJGB0DqDoycfwGjHWch2T/nmCu1Kpl9fn\nbQs6+b7y8hAAca7KBcR/6Fv4ijunA5k8aDMhZfQ31IQ00u3C9TlQbpUgWr92iT8Y\n7AhCLOjhPeMCyXxbWQD3uBqllnAu7htblC+TLstjfkn1xzhy2iOZ9b6M7e5SDuU6\nr8pHKk8YqSm5TFuGOyMJYYdGCiccx9yifkJJ+wIDAQABAoIBAD1UXX1p5iSVRHvk\nttWLOdsfHCA7DPSJpfD5/wkwZkozq112czqxu3WzNv1SDaG3zSYMyvhmsfevUka2\nSQG7gmkWHEIXwQYu4Qhpcmb5gS+BfN4g+MNtHwmoUUWkDqTilbTi7xX5ZicpWIIo\nlI3DF16++JzUwAc1mYeMmd4bF+3quh93xW7hhrcQ31+D9kzqt6nLG1d9+IVpMbhD\nnNB9zapkZHwnz6YYhb5waMOHr6U902TyGgKyjq3Z/PkMJ0zKg01roUtQs9oQOIZF\nvueF2hwyzHqeIgpqhWJl9HMpfdym6Lh2lwguK3KYwNIMFQg+gNBWruYlH6SGfylq\n0wB5xIECgYEA8FdyEDd4TbVBKIXzzmY6zYmN/Q9uiz0IjbeYYzuRxZ4a7stE/t8n\nM5UxxkqeD8rtRAQJyFDGPAhFeeOpIfzEVPG+5s72pI69+9aE/gCGA91+sOSnLoiJ\nPW1I7SouZfCeaaRQxSSIMjsCea2s6yraujGZJyPEWSkG5TijY8+vzDsCgYEAyMxX\nCYvqlRTaT5lAkRTFLqf0/NSpRoCnG7qSPUyJjxJsVfYFLv1FZCyyrA+SaIyufjoT\nKutKE31r7wre5bkjRRenIcTkR/tdNRdkWsB/ysZ9Cp43FIPTXS5gxTQxOaJyRGvJ\n9MW0m8N1pMvPIsagzoxxvzgU9ZOejs2NQ69qXUECgYBq7DxOgp7+0zhdsto4ZLqc\nXinQ/2CKiWiYw6kD3KiJZkFNIxla2iQyiplOQjv3gqvzqmg/uc+3PWbLR0EjYbRm\npfXr8P9BTk+vDky0Q79bUNrgD5lg1lVYApqDCFUD/Pw8u2FDk3EUB7SeNWnMZZBR\nbWdZRkw/7kSnDX+DFA59qQKBgG9v0AHxT4/LEdlJEOczYrcg6TqDfyosbhFaepxg\nZJstO0h9j6TjVGZi1AnfXn59TL2q10ZjbCni2krAerF9DNDkbpG0Joi4PKMhR0WC\nPam4fF6vLZxKCLxW58epzoPQ3p+QPnWEX1ZupFR/84W2PDpFAT+BDUi40y8nbnWY\n3WvBAoGADjh0hEkq3sy6oWt0m1NjGU1yxKV+geg48BFnu2LVSFv1rw1V7X8XFEYl\nP1B3sEpOOpPGuoz+r2E9PrsdMuYNOmVlRFRpe7pm7zyhzdFYBvLE2btJqv1PmxFu\ncEkrXJS/ETxkKdMaoUbYHcKiTIMi2pDrdJtg6oHcipm0yTBZkKs=\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm deleted file mode 100644 index 442a4f5..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm +++ /dev/null @@ -1,29 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAAFmFlczEyOC1nY21Ab3BlbnNzaC5jb20AAAAGYmNyeXB0AA -AAGAAAABBJL2YVn88iqv/H9bFiyW2PAAAAEAAAAAEAAAEXAAAAB3NzaC1yc2EAAAADAQAB -AAABAQDMemjkha1c+2s58qzx4968svvvpbxt6EiLlyRHuqXCouTdBZeXGtVRlxpkqnnOE0 -ETMSQSqm1d5k1EMa7VVcTeXFQaBIc2XF0S1uIoEvNV0JXpDjiIdPmjUFuUf9oGGLKKQQMf -zpymqoiHYQNhuarYd1mSb0+a+UwKxAxGeCPd95o/JfWjKO0JTr3nnEj1eTjtu0pofmchab -9HC9YbJ3JsvbdRq7Z2ZHp8uu16SflPpP2A9l+F4HN+gPOLcGxbVkVZHsLI07OpkWdxMPBU -rzPF9OnCntRWoBhQ4LFHYHllTtd+/E90QXXhe1pxj8FktJiaitiz09GU5h4IWi3isNr/AA -AD4Ktd9gUs9KHBmWTVFnDofcB6P1dZJsYHAapQgNXZtx5SjwgfBpP5aBLtSjN1iHFE+3XC -Cofc9UJ8fbytwT7LCEQIzo3KJaOhVzgJN+lrjtFouWsw0Y1q2JONHvvNJ5A9nGjIGbp3du -4TAMSgVAvxZBEYez4ajhb2NL7TE56AjOxW4n/M2ZDJLCo11F3ON3Eq6MirHZMgGKo/lbOc -SaBld7tzqknye+1fKVlnCLyu+v0KCbATBypRsMeX1+E/D8L5cMIgRSe97swqiWeG9yBhQi -xahbWDpmU34nz1cxc9H7KnL1rbbOxrr4OEdMOHNBQjbLlpJpnSJ3XvEGP74zjfd5zMocgx -rnqreMmY+eDEObkw33+XD5ROYJT+SW/zI+r3SeIjS3UPh0ucU5nipBvXfkUezek9i/FN1X -CY7xJnAZGGKU0JSqiVW3JWXp18v8lmo3ACvXeotJfUGkwvJOeO2N4Qb7RTIzivLV5Q5Plf -zHWqHE57UqDL/Ya7SrX1FaqqhOHOlS1mqPQ+/VdsOSP5fJcXN+oKoL7jPr2WlmtFjo8PKc -rpgKC3DhUzvRXnNYotG7trbPOGJbBRgoxTQ06rlChoaBp7kUKqNNBxXhFQCeN0sCb90fHV -c+X3Yy8oUsAIxxmCymuVV8gRzLD6OdqQRBthEUQktNJLhv4mSufwSfsLDluEc7YEOrsJhx -jk57TmkFFyLj++IAKi80FnSkRfSBQF3dTSrBZ4BIHWnek8V6goxhy6lRMaFoTow2foknvr -VHgiNGvimOM3ESYVcOwt3YQqbUG/7b4jRlY3nNBJcsbxGe54B8zaoLt5pQNRxUuHc3fR4R -haWHR6IWsfey7jAlRzrJAVVEEj4d6yvJ4bLqWGmoim5QlrePRuRFyV4FNb8N6hJ9gvWY9f -HUT9TwxArDIMzu4T1khwRoFU45XN0U6xHEPcT/pZ2C5jJSSQ5W/SyBudexjMMPRKf2EIeD -gjv8vIhdtkmxHv7bapaaYeYX5gtKYl+McRollDxVC8Kr48RmOVJnK4aFBQ99Wu7SXDbwas -vcvVHI+zUiRGjU01/CU/Tf4GTodAlmZIuqKmBTX/KvVj6ZiK0BsZuEl9qom+l4rlazaahY -FdL5M4u0qt7rVirWJWgWzmPXZ+MCK0Fs70ORvqRGxVMilhQcWsng3ZXnHaYiBRhk31KqF+ -BEPEh79OknD0okKed2YYfg8vdUR+noENybrsIleP1aKBBmQCNbKU04N/9Su+wxX8YfGhYU -kPST35Wg45zER9gZGsREnON4sQTng9LHB5CrJCo/MowcZG/ycqL1mxemApZ9nYUrjA8HJi -zDwRHHUtkkLNG8Cmyg== ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub deleted file mode 100644 index d5c7685..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDMemjkha1c+2s58qzx4968svvvpbxt6EiLlyRHuqXCouTdBZeXGtVRlxpkqnnOE0ETMSQSqm1d5k1EMa7VVcTeXFQaBIc2XF0S1uIoEvNV0JXpDjiIdPmjUFuUf9oGGLKKQQMfzpymqoiHYQNhuarYd1mSb0+a+UwKxAxGeCPd95o/JfWjKO0JTr3nnEj1eTjtu0pofmchab9HC9YbJ3JsvbdRq7Z2ZHp8uu16SflPpP2A9l+F4HN+gPOLcGxbVkVZHsLI07OpkWdxMPBUrzPF9OnCntRWoBhQ4LFHYHllTtd+/E90QXXhe1pxj8FktJiaitiz09GU5h4IWi3isNr/ diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result deleted file mode 100644 index 0f00545..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzHpo5IWtXPtrOfKs8ePe\nvLL776W8behIi5ckR7qlwqLk3QWXlxrVUZcaZKp5zhNBEzEkEqptXeZNRDGu1VXE\n3lxUGgSHNlxdEtbiKBLzVdCV6Q44iHT5o1BblH/aBhiyikEDH86cpqqIh2EDYbmq\n2HdZkm9PmvlMCsQMRngj3feaPyX1oyjtCU6955xI9Xk47btKaH5nIWm/RwvWGydy\nbL23Uau2dmR6fLrtekn5T6T9gPZfheBzfoDzi3BsW1ZFWR7CyNOzqZFncTDwVK8z\nxfTpwp7UVqAYUOCxR2B5ZU7XfvxPdEF14XtacY/BZLSYmorYs9PRlOYeCFot4rDa\n/wIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMemjkha1c+2s58qzx4968svvvpbxt6EiLlyRHuqXCouTdBZeXGtVRlxpkqnnOE0ETMSQSqm1d5k1EMa7VVcTeXFQaBIc2XF0S1uIoEvNV0JXpDjiIdPmjUFuUf9oGGLKKQQMfzpymqoiHYQNhuarYd1mSb0+a+UwKxAxGeCPd95o/JfWjKO0JTr3nnEj1eTjtu0pofmchab9HC9YbJ3JsvbdRq7Z2ZHp8uu16SflPpP2A9l+F4HN+gPOLcGxbVkVZHsLI07OpkWdxMPBUrzPF9OnCntRWoBhQ4LFHYHllTtd+/E90QXXhe1pxj8FktJiaitiz09GU5h4IWi3isNr/", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result deleted file mode 100644 index 127ce3d..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "new openssh format encrypted gcm", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzHpo5IWtXPtrOfKs8ePe\nvLL776W8behIi5ckR7qlwqLk3QWXlxrVUZcaZKp5zhNBEzEkEqptXeZNRDGu1VXE\n3lxUGgSHNlxdEtbiKBLzVdCV6Q44iHT5o1BblH/aBhiyikEDH86cpqqIh2EDYbmq\n2HdZkm9PmvlMCsQMRngj3feaPyX1oyjtCU6955xI9Xk47btKaH5nIWm/RwvWGydy\nbL23Uau2dmR6fLrtekn5T6T9gPZfheBzfoDzi3BsW1ZFWR7CyNOzqZFncTDwVK8z\nxfTpwp7UVqAYUOCxR2B5ZU7XfvxPdEF14XtacY/BZLSYmorYs9PRlOYeCFot4rDa\n/wIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMemjkha1c+2s58qzx4968svvvpbxt6EiLlyRHuqXCouTdBZeXGtVRlxpkqnnOE0ETMSQSqm1d5k1EMa7VVcTeXFQaBIc2XF0S1uIoEvNV0JXpDjiIdPmjUFuUf9oGGLKKQQMfzpymqoiHYQNhuarYd1mSb0+a+UwKxAxGeCPd95o/JfWjKO0JTr3nnEj1eTjtu0pofmchab9HC9YbJ3JsvbdRq7Z2ZHp8uu16SflPpP2A9l+F4HN+gPOLcGxbVkVZHsLI07OpkWdxMPBUrzPF9OnCntRWoBhQ4LFHYHllTtd+/E90QXXhe1pxj8FktJiaitiz09GU5h4IWi3isNr/", - "private": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEAzHpo5IWtXPtrOfKs8ePevLL776W8behIi5ckR7qlwqLk3QWX\nlxrVUZcaZKp5zhNBEzEkEqptXeZNRDGu1VXE3lxUGgSHNlxdEtbiKBLzVdCV6Q44\niHT5o1BblH/aBhiyikEDH86cpqqIh2EDYbmq2HdZkm9PmvlMCsQMRngj3feaPyX1\noyjtCU6955xI9Xk47btKaH5nIWm/RwvWGydybL23Uau2dmR6fLrtekn5T6T9gPZf\nheBzfoDzi3BsW1ZFWR7CyNOzqZFncTDwVK8zxfTpwp7UVqAYUOCxR2B5ZU7XfvxP\ndEF14XtacY/BZLSYmorYs9PRlOYeCFot4rDa/wIDAQABAoIBAQCCb7uluxhh7gfy\niTmFfETDvrEzqFfRDJHqadm83/WJeXvg+gY/X+CgEXHGsXDN4j5qzbgjKBBoC9dS\nHxdWA0Z4ShFkH2tZZAYDVIwj4CLVpR9b8bRiZ6wvX71rtzsPFIYf52Tkz1nif3pk\nUaBkoJm5SDkdTmBLjafSXkkuUskeeAV7gx+fzWqSpcKmhTqjnQfdlmD8OSIq4jjD\nagiHmmfBhZ4NOvF/E9UBydqFV8GNyfSFC6kC2LYmiQD1hvqNhMdYVjh99V1L3ZPq\nHMSQVAOv5WgpLTLKY8MFNBbqqp0eKhatRNA8q9O23jADDp3fubKV0aUQSrRZz0y9\nPmmEJnTRAoGBAPZoL+p+AbI5yTg01LdsaQL2f3Ieb3CGudesmjAVnI3QEoC6gxGX\n4cbmBSCY+vBzh2RJNJcS+Rq6VmJZA930Tb0npHiQYOohB7BFOCbBJ2L18g/JdNpi\nVb3wqFs9NG1GFOOV6iGtV/6t4CRTKtAbd695YZAJ5S6DDvMrH9pTnAKrAoGBANRw\nVuLfBTFhSKvFz+0W0yy6Sn0koXjpp1ifC0BWLwHiA/IZjAY7qmsNQZxWdleWLP28\nRNaac3vMJO/HFD4IyL59Zli+kREGKazvZM1dvOs0mgdVMTPMsT57wcJr5OSxqCvJ\nD3NkcgFuA1e3jVC5p/wUJCi/lhyFPx3z1C5vRqj9AoGBANeyYmd5wFBcp1ktXhvm\nqZIvZ2blX5X4ScyTSjHXaUD2qIvJORz4gGqVRl2/rMM5zoYqUwAAWtFb1mynEWyF\nBFwVzLLBaCTrnwhdv4alRK4rL6dEKadVt0ra1PVxgWg6leSXgenTDRli6bfCmdKs\niLuxnIbzMozhqv+Qe4Sp9gKbAoGBALWBThsEpXEtR2PL3P0atU7P0/jcJUIjkCF9\nsaVEfWFEdE6TWTmyHMbeSqKClRX8b3BTPRWGXQj2wNBE7Zya8LkgdyN3noZHF7Bz\n0VJNtq3XAYsmVKWHTCCwqDmu6aAj0iWm4ZabyXRDRIPbhdfk6AvOQZ63IlA34Fd9\nDlqmJF8ZAoGAIJzfMDT2LvlMOHqpKgelS4ZTHEmqqJZM5rXdsZwYqcyekjz25COE\nTJwme3xIt3kSZEcOauGHCgUVeBcE6GwZbQ1WoNIvazhnUXeErOeoxQ+ZqdfC8iyT\nUn/P27yx/FcwDdubQhbgxZ5M+pu+0OQ1WPu02LQZQrX7x4a6isYtTDo=\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa deleted file mode 100644 index f2ae4d4..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN DSA PRIVATE KEY----- -MIIBvQIBAAKBgQDs+n9ZKhwYNr1V2uGn0C/2MSTM4KB4puy4jR5ubRTT1yq5SbzK -RQlCjfplDN//Eqa6aiFmvGKA3RKUtPtBmD96EHW1mvr7O+Pc8z8L/4zg9tkVQR6V -WBKgBhVwZHDzzs5+Ag2j54BZfcaGMcNGhTE9DcZYeI/t6FhOxgpID3EA/QIVAMyI -czBU74xB48IMoamlEhc5Lh+3AoGBAMuy2h9K9+oQIPcTcsD/mtmhOYlw2ZPCJV2b -WFeZ3QxAujenBzEp0oqht8tdj+BE7Er+CWT2Ab/A92MrjYUaGaPjdF5+K6CSPMUX -rK8nBabSBJ+ELqTo/8vHJ2eVWIUJBwCzbw3ryitH7LD3gyEr2NuQQJE++wyWPBHK -M3SFOft6AoGBAOdrYUJ38yjc9tnrvLWsB1KlkYhc+UbTMSRKfA8Yo/Xs5QldFycz -bUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMnOzRVQXpUI7z2W3/Ie4/i2Lu/ -xXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5ciuO0ltu90L9+2YvWAhUAr/vy -ahuEz4UFGhB8IIeLWQUO5FA= ------END DSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub deleted file mode 100644 index a7fd375..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-dss AAAAB3NzaC1kc3MAAACBAOz6f1kqHBg2vVXa4afQL/YxJMzgoHim7LiNHm5tFNPXKrlJvMpFCUKN+mUM3/8SprpqIWa8YoDdEpS0+0GYP3oQdbWa+vs749zzPwv/jOD22RVBHpVYEqAGFXBkcPPOzn4CDaPngFl9xoYxw0aFMT0Nxlh4j+3oWE7GCkgPcQD9AAAAFQDMiHMwVO+MQePCDKGppRIXOS4ftwAAAIEAy7LaH0r36hAg9xNywP+a2aE5iXDZk8IlXZtYV5ndDEC6N6cHMSnSiqG3y12P4ETsSv4JZPYBv8D3YyuNhRoZo+N0Xn4roJI8xResrycFptIEn4QupOj/y8cnZ5VYhQkHALNvDevKK0fssPeDISvY25BAkT77DJY8EcozdIU5+3oAAACBAOdrYUJ38yjc9tnrvLWsB1KlkYhc+UbTMSRKfA8Yo/Xs5QldFyczbUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMnOzRVQXpUI7z2W3/Ie4/i2Lu/xXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5ciuO0ltu90L9+2YvW old openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result deleted file mode 100644 index 05f8140..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "old openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBuDCCASwGByqGSM44BAEwggEfAoGBAOz6f1kqHBg2vVXa4afQL/YxJMzgoHim\n7LiNHm5tFNPXKrlJvMpFCUKN+mUM3/8SprpqIWa8YoDdEpS0+0GYP3oQdbWa+vs7\n49zzPwv/jOD22RVBHpVYEqAGFXBkcPPOzn4CDaPngFl9xoYxw0aFMT0Nxlh4j+3o\nWE7GCkgPcQD9AhUAzIhzMFTvjEHjwgyhqaUSFzkuH7cCgYEAy7LaH0r36hAg9xNy\nwP+a2aE5iXDZk8IlXZtYV5ndDEC6N6cHMSnSiqG3y12P4ETsSv4JZPYBv8D3YyuN\nhRoZo+N0Xn4roJI8xResrycFptIEn4QupOj/y8cnZ5VYhQkHALNvDevKK0fssPeD\nISvY25BAkT77DJY8EcozdIU5+3oDgYUAAoGBAOdrYUJ38yjc9tnrvLWsB1KlkYhc\n+UbTMSRKfA8Yo/Xs5QldFyczbUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMn\nOzRVQXpUI7z2W3/Ie4/i2Lu/xXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5c\niuO0ltu90L9+2YvW\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAOz6f1kqHBg2vVXa4afQL/YxJMzgoHim7LiNHm5tFNPXKrlJvMpFCUKN+mUM3/8SprpqIWa8YoDdEpS0+0GYP3oQdbWa+vs749zzPwv/jOD22RVBHpVYEqAGFXBkcPPOzn4CDaPngFl9xoYxw0aFMT0Nxlh4j+3oWE7GCkgPcQD9AAAAFQDMiHMwVO+MQePCDKGppRIXOS4ftwAAAIEAy7LaH0r36hAg9xNywP+a2aE5iXDZk8IlXZtYV5ndDEC6N6cHMSnSiqG3y12P4ETsSv4JZPYBv8D3YyuNhRoZo+N0Xn4roJI8xResrycFptIEn4QupOj/y8cnZ5VYhQkHALNvDevKK0fssPeDISvY25BAkT77DJY8EcozdIU5+3oAAACBAOdrYUJ38yjc9tnrvLWsB1KlkYhc+UbTMSRKfA8Yo/Xs5QldFyczbUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMnOzRVQXpUI7z2W3/Ie4/i2Lu/xXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5ciuO0ltu90L9+2YvW", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result deleted file mode 100644 index d21d1cb..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBuDCCASwGByqGSM44BAEwggEfAoGBAOz6f1kqHBg2vVXa4afQL/YxJMzgoHim\n7LiNHm5tFNPXKrlJvMpFCUKN+mUM3/8SprpqIWa8YoDdEpS0+0GYP3oQdbWa+vs7\n49zzPwv/jOD22RVBHpVYEqAGFXBkcPPOzn4CDaPngFl9xoYxw0aFMT0Nxlh4j+3o\nWE7GCkgPcQD9AhUAzIhzMFTvjEHjwgyhqaUSFzkuH7cCgYEAy7LaH0r36hAg9xNy\nwP+a2aE5iXDZk8IlXZtYV5ndDEC6N6cHMSnSiqG3y12P4ETsSv4JZPYBv8D3YyuN\nhRoZo+N0Xn4roJI8xResrycFptIEn4QupOj/y8cnZ5VYhQkHALNvDevKK0fssPeD\nISvY25BAkT77DJY8EcozdIU5+3oDgYUAAoGBAOdrYUJ38yjc9tnrvLWsB1KlkYhc\n+UbTMSRKfA8Yo/Xs5QldFyczbUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMn\nOzRVQXpUI7z2W3/Ie4/i2Lu/xXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5c\niuO0ltu90L9+2YvW\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAOz6f1kqHBg2vVXa4afQL/YxJMzgoHim7LiNHm5tFNPXKrlJvMpFCUKN+mUM3/8SprpqIWa8YoDdEpS0+0GYP3oQdbWa+vs749zzPwv/jOD22RVBHpVYEqAGFXBkcPPOzn4CDaPngFl9xoYxw0aFMT0Nxlh4j+3oWE7GCkgPcQD9AAAAFQDMiHMwVO+MQePCDKGppRIXOS4ftwAAAIEAy7LaH0r36hAg9xNywP+a2aE5iXDZk8IlXZtYV5ndDEC6N6cHMSnSiqG3y12P4ETsSv4JZPYBv8D3YyuNhRoZo+N0Xn4roJI8xResrycFptIEn4QupOj/y8cnZ5VYhQkHALNvDevKK0fssPeDISvY25BAkT77DJY8EcozdIU5+3oAAACBAOdrYUJ38yjc9tnrvLWsB1KlkYhc+UbTMSRKfA8Yo/Xs5QldFyczbUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMnOzRVQXpUI7z2W3/Ie4/i2Lu/xXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5ciuO0ltu90L9+2YvW", - "private": "-----BEGIN DSA PRIVATE KEY-----\nMIIBvQIBAAKBgQDs+n9ZKhwYNr1V2uGn0C/2MSTM4KB4puy4jR5ubRTT1yq5SbzK\nRQlCjfplDN//Eqa6aiFmvGKA3RKUtPtBmD96EHW1mvr7O+Pc8z8L/4zg9tkVQR6V\nWBKgBhVwZHDzzs5+Ag2j54BZfcaGMcNGhTE9DcZYeI/t6FhOxgpID3EA/QIVAMyI\nczBU74xB48IMoamlEhc5Lh+3AoGBAMuy2h9K9+oQIPcTcsD/mtmhOYlw2ZPCJV2b\nWFeZ3QxAujenBzEp0oqht8tdj+BE7Er+CWT2Ab/A92MrjYUaGaPjdF5+K6CSPMUX\nrK8nBabSBJ+ELqTo/8vHJ2eVWIUJBwCzbw3ryitH7LD3gyEr2NuQQJE++wyWPBHK\nM3SFOft6AoGBAOdrYUJ38yjc9tnrvLWsB1KlkYhc+UbTMSRKfA8Yo/Xs5QldFycz\nbUtsFGdLvqPol0pww2LqeKUQ8zVIF56Aw3SxmPMnOzRVQXpUI7z2W3/Ie4/i2Lu/\nxXos8ZHnIu+e7SLJRHe+RGNvISbsQhk+vnpNQP5ciuO0ltu90L9+2YvWAhUAr/vy\nahuEz4UFGhB8IIeLWQUO5FA=\n-----END DSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc deleted file mode 100644 index 57064cd..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN DSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,3239878D1E2D496289CE9CD2CB639BE8 - -k8/4Ax6UcnImNvEuybHwa9OHZHeCpKmq3Cu/q29a9AkTnktAWVmU9rQFch5CweDH -TEuRN+ZHecHrrMPR0fTpjXzZTxmU3549BQ2DfMSAdikPNKtBvhJwpT2se0rJ9M98 -p2xJQNhpxXT6f4Hy8m6QvjP5iTmlnQrrVBjV05ih9TLLQb4Y4NlydC08OyEcEoJV -w43G69sv2ws/tUVr7XSUtv8l+51ywSm42Pw6YOVlMZ7y+XB/uWmFNMz5gLN17tkc -wikhgvNnMWGLqb/AruuKPp5FrGRIC19DKRzDSPF5WlzLBdd2TQKDltknDj08AQMJ -bDsImbePteqhU+D7GiN2pVAD2b5kCZlFzYG43/Q8R3+O2l0Lvq5VBIqNB7LyJfTy -DL8XX0gzHk7FgG5MfLYin/qp7upnDXeSnIm8A2tlBYh9YzG3q/a53c5V2NomWjX0 -zvS+C7+w5NDwDRT5t+kecMhmHWNBuE/Pbvy0DaZQ/nnsC6TlkcaROJ0fiY3Da8E6 -EYvM4uKaZudsOOapwx0ZXHu2GZgLnly0p2Cd0Yf9t2UX9uySfwdL2TNw8nLVNVkh -aBE/x9LkKPWqOBV8tg/9ITGys/qgZh0A1r+RGmj/tII= ------END DSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub deleted file mode 100644 index 18f5804..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-dss AAAAB3NzaC1kc3MAAACBAP25RC69mW4t09jpaine5ZRHmOtqNJa2nbsRrSsZkvGXxbJ7ojxsybWf4kAAI4GpsGMzlrFrlMEpHQfebJAn+zJwGS+loR7T+gNz8JoVIgPF9dabXVymcygl4FB/sNAmV4XK3OjvSW1NCKdSkwZZr/gz5JBo1qAiQDKMD/ikWqq/AAAAFQC/rPmzFozpCeLbFQykOaDGFZaqaQAAAIEAw1hJAYQzn/ZboF/xXDHzP49uRpIIoyaSfUz5W3+Lpi/CBkOIGaGOuitwcpTfzBSZIDZ9ORs9fq5oBh29JJcAdBNgVXfzThSiGvBgU4UIj41MlG4PG6St88VXCy0niEXWmjSkdcW3hZ0ai0SOlVxxEkYneg7RH9Seh+U3rRacrh4AAACAOX41OCxx8mTuxpON/uZn6GwvK/m0K9fr/UmIX8D4Mp8PgnPLC71AOwLy1HrCVi3ohCqeSY2C1uf1VWUVlSqMH85Pxc7pLtuULoQdCgiYt1agVrioFSP6bEyFdV8vGxA4YGh6cUSkeFZBJBrdNM4VmYBeT+3n/IO5uUbWoPK5iAo= diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result deleted file mode 100644 index ad14260..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtzCCASwGByqGSM44BAEwggEfAoGBAP25RC69mW4t09jpaine5ZRHmOtqNJa2\nnbsRrSsZkvGXxbJ7ojxsybWf4kAAI4GpsGMzlrFrlMEpHQfebJAn+zJwGS+loR7T\n+gNz8JoVIgPF9dabXVymcygl4FB/sNAmV4XK3OjvSW1NCKdSkwZZr/gz5JBo1qAi\nQDKMD/ikWqq/AhUAv6z5sxaM6Qni2xUMpDmgxhWWqmkCgYEAw1hJAYQzn/ZboF/x\nXDHzP49uRpIIoyaSfUz5W3+Lpi/CBkOIGaGOuitwcpTfzBSZIDZ9ORs9fq5oBh29\nJJcAdBNgVXfzThSiGvBgU4UIj41MlG4PG6St88VXCy0niEXWmjSkdcW3hZ0ai0SO\nlVxxEkYneg7RH9Seh+U3rRacrh4DgYQAAoGAOX41OCxx8mTuxpON/uZn6GwvK/m0\nK9fr/UmIX8D4Mp8PgnPLC71AOwLy1HrCVi3ohCqeSY2C1uf1VWUVlSqMH85Pxc7p\nLtuULoQdCgiYt1agVrioFSP6bEyFdV8vGxA4YGh6cUSkeFZBJBrdNM4VmYBeT+3n\n/IO5uUbWoPK5iAo=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAP25RC69mW4t09jpaine5ZRHmOtqNJa2nbsRrSsZkvGXxbJ7ojxsybWf4kAAI4GpsGMzlrFrlMEpHQfebJAn+zJwGS+loR7T+gNz8JoVIgPF9dabXVymcygl4FB/sNAmV4XK3OjvSW1NCKdSkwZZr/gz5JBo1qAiQDKMD/ikWqq/AAAAFQC/rPmzFozpCeLbFQykOaDGFZaqaQAAAIEAw1hJAYQzn/ZboF/xXDHzP49uRpIIoyaSfUz5W3+Lpi/CBkOIGaGOuitwcpTfzBSZIDZ9ORs9fq5oBh29JJcAdBNgVXfzThSiGvBgU4UIj41MlG4PG6St88VXCy0niEXWmjSkdcW3hZ0ai0SOlVxxEkYneg7RH9Seh+U3rRacrh4AAACAOX41OCxx8mTuxpON/uZn6GwvK/m0K9fr/UmIX8D4Mp8PgnPLC71AOwLy1HrCVi3ohCqeSY2C1uf1VWUVlSqMH85Pxc7pLtuULoQdCgiYt1agVrioFSP6bEyFdV8vGxA4YGh6cUSkeFZBJBrdNM4VmYBeT+3n/IO5uUbWoPK5iAo=", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result deleted file mode 100644 index 18c5271..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtzCCASwGByqGSM44BAEwggEfAoGBAP25RC69mW4t09jpaine5ZRHmOtqNJa2\nnbsRrSsZkvGXxbJ7ojxsybWf4kAAI4GpsGMzlrFrlMEpHQfebJAn+zJwGS+loR7T\n+gNz8JoVIgPF9dabXVymcygl4FB/sNAmV4XK3OjvSW1NCKdSkwZZr/gz5JBo1qAi\nQDKMD/ikWqq/AhUAv6z5sxaM6Qni2xUMpDmgxhWWqmkCgYEAw1hJAYQzn/ZboF/x\nXDHzP49uRpIIoyaSfUz5W3+Lpi/CBkOIGaGOuitwcpTfzBSZIDZ9ORs9fq5oBh29\nJJcAdBNgVXfzThSiGvBgU4UIj41MlG4PG6St88VXCy0niEXWmjSkdcW3hZ0ai0SO\nlVxxEkYneg7RH9Seh+U3rRacrh4DgYQAAoGAOX41OCxx8mTuxpON/uZn6GwvK/m0\nK9fr/UmIX8D4Mp8PgnPLC71AOwLy1HrCVi3ohCqeSY2C1uf1VWUVlSqMH85Pxc7p\nLtuULoQdCgiYt1agVrioFSP6bEyFdV8vGxA4YGh6cUSkeFZBJBrdNM4VmYBeT+3n\n/IO5uUbWoPK5iAo=\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAP25RC69mW4t09jpaine5ZRHmOtqNJa2nbsRrSsZkvGXxbJ7ojxsybWf4kAAI4GpsGMzlrFrlMEpHQfebJAn+zJwGS+loR7T+gNz8JoVIgPF9dabXVymcygl4FB/sNAmV4XK3OjvSW1NCKdSkwZZr/gz5JBo1qAiQDKMD/ikWqq/AAAAFQC/rPmzFozpCeLbFQykOaDGFZaqaQAAAIEAw1hJAYQzn/ZboF/xXDHzP49uRpIIoyaSfUz5W3+Lpi/CBkOIGaGOuitwcpTfzBSZIDZ9ORs9fq5oBh29JJcAdBNgVXfzThSiGvBgU4UIj41MlG4PG6St88VXCy0niEXWmjSkdcW3hZ0ai0SOlVxxEkYneg7RH9Seh+U3rRacrh4AAACAOX41OCxx8mTuxpON/uZn6GwvK/m0K9fr/UmIX8D4Mp8PgnPLC71AOwLy1HrCVi3ohCqeSY2C1uf1VWUVlSqMH85Pxc7pLtuULoQdCgiYt1agVrioFSP6bEyFdV8vGxA4YGh6cUSkeFZBJBrdNM4VmYBeT+3n/IO5uUbWoPK5iAo=", - "private": "-----BEGIN DSA PRIVATE KEY-----\nMIIBvAIBAAKBgQD9uUQuvZluLdPY6Wop3uWUR5jrajSWtp27Ea0rGZLxl8Wye6I8\nbMm1n+JAACOBqbBjM5axa5TBKR0H3myQJ/sycBkvpaEe0/oDc/CaFSIDxfXWm11c\npnMoJeBQf7DQJleFytzo70ltTQinUpMGWa/4M+SQaNagIkAyjA/4pFqqvwIVAL+s\n+bMWjOkJ4tsVDKQ5oMYVlqppAoGBAMNYSQGEM5/2W6Bf8Vwx8z+PbkaSCKMmkn1M\n+Vt/i6YvwgZDiBmhjrorcHKU38wUmSA2fTkbPX6uaAYdvSSXAHQTYFV3804Uohrw\nYFOFCI+NTJRuDxukrfPFVwstJ4hF1po0pHXFt4WdGotEjpVccRJGJ3oO0R/Unofl\nN60WnK4eAoGAOX41OCxx8mTuxpON/uZn6GwvK/m0K9fr/UmIX8D4Mp8PgnPLC71A\nOwLy1HrCVi3ohCqeSY2C1uf1VWUVlSqMH85Pxc7pLtuULoQdCgiYt1agVrioFSP6\nbEyFdV8vGxA4YGh6cUSkeFZBJBrdNM4VmYBeT+3n/IO5uUbWoPK5iAoCFQCdYU1l\nO1pCZ3Jhf/YDAAnfQHAtMxAQEBAQEBAQEBAQEBAQEBA=\n-----END DSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa deleted file mode 100644 index f4170ac..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa +++ /dev/null @@ -1,5 +0,0 @@ ------BEGIN EC PRIVATE KEY----- -MHcCAQEEIJx7zPcbJg1zUAsBhKbmN0eOjbr+/W2qGSZTCP/c0mz4oAoGCCqGSM49 -AwEHoUQDQgAELN85t86lbEONGsyPNDxD/P2f9D9/ePBT3ZpAeVYUdyrVO00jO4JE -FPfKlVc4htC9oZbDaNeW1ssAIbn4uzigMQ== ------END EC PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub deleted file mode 100644 index 8f39dd6..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub +++ /dev/null @@ -1 +0,0 @@ -ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCzfObfOpWxDjRrMjzQ8Q/z9n/Q/f3jwU92aQHlWFHcq1TtNIzuCRBT3ypVXOIbQvaGWw2jXltbLACG5+Ls4oDE= old openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result deleted file mode 100644 index 68f3c14..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "old openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELN85t86lbEONGsyPNDxD/P2f9D9/\nePBT3ZpAeVYUdyrVO00jO4JEFPfKlVc4htC9oZbDaNeW1ssAIbn4uzigMQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCzfObfOpWxDjRrMjzQ8Q/z9n/Q/f3jwU92aQHlWFHcq1TtNIzuCRBT3ypVXOIbQvaGWw2jXltbLACG5+Ls4oDE=", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result deleted file mode 100644 index cfabd13..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELN85t86lbEONGsyPNDxD/P2f9D9/\nePBT3ZpAeVYUdyrVO00jO4JEFPfKlVc4htC9oZbDaNeW1ssAIbn4uzigMQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCzfObfOpWxDjRrMjzQ8Q/z9n/Q/f3jwU92aQHlWFHcq1TtNIzuCRBT3ypVXOIbQvaGWw2jXltbLACG5+Ls4oDE=", - "private": "-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIJx7zPcbJg1zUAsBhKbmN0eOjbr+/W2qGSZTCP/c0mz4oAoGCCqGSM49\nAwEHoUQDQgAELN85t86lbEONGsyPNDxD/P2f9D9/ePBT3ZpAeVYUdyrVO00jO4JE\nFPfKlVc4htC9oZbDaNeW1ssAIbn4uzigMQ==\n-----END EC PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc deleted file mode 100644 index 7e118d8..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc +++ /dev/null @@ -1,8 +0,0 @@ ------BEGIN EC PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,4BE217089AE8B7311672C159E0690AB4 - -AkqjOP53cDHrdkJFRVLHYS7fSPVcIa4BgKegLwqRUqJOvEOnn5j6RYCh2CMdPjwN -rdw26Gc0V++xeMISAbrX4TGAQPWyDyiuoCffTIAfbkNq8YQR/sNJjNmZEgtCs6+O -4iBQ8TMXO+7oWRC221FDbTIhB6k4lXXph/HzdW0/Y2A= ------END EC PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub deleted file mode 100644 index 8efc1fe..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBA4KgjqWJj9PR55PeF7t7PTXdx7cvMDqNkq4UTMjoXA5WtQYdoC2sxJnI5Psqvtrfa13C31gY8TlFAZ1cClnoBk= diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result deleted file mode 100644 index 3b3064f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDgqCOpYmP09Hnk94Xu3s9Nd3Hty8\nwOo2SrhRMyOhcDla1Bh2gLazEmcjk+yq+2t9rXcLfWBjxOUUBnVwKWegGQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBA4KgjqWJj9PR55PeF7t7PTXdx7cvMDqNkq4UTMjoXA5WtQYdoC2sxJnI5Psqvtrfa13C31gY8TlFAZ1cClnoBk=", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result deleted file mode 100644 index 423f6e2..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ecdsa-sha2-nistp256", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDgqCOpYmP09Hnk94Xu3s9Nd3Hty8\nwOo2SrhRMyOhcDla1Bh2gLazEmcjk+yq+2t9rXcLfWBjxOUUBnVwKWegGQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBA4KgjqWJj9PR55PeF7t7PTXdx7cvMDqNkq4UTMjoXA5WtQYdoC2sxJnI5Psqvtrfa13C31gY8TlFAZ1cClnoBk=", - "private": "-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIA7fGKE3wZkXb6jMcMriZujktUQ6FTC0SoTAa6fKDXY8oAoGCCqGSM49\nAwEHoUQDQgAEDgqCOpYmP09Hnk94Xu3s9Nd3Hty8wOo2SrhRMyOhcDla1Bh2gLaz\nEmcjk+yq+2t9rXcLfWBjxOUUBnVwKWegGQcHBwcHBwc=\n-----END EC PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa deleted file mode 100644 index 2eadbb0..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEA8wISnx2xWoeZur8yn/8NPykUY2mYyxn1n0mE5WJSo+mclFFS -mnN08WCt856AO8PMPuAn9cw0j3qJe0SKTnoMYSp+4fBsq6YHOGJvlRATF9SJkSIx -wBCYsMT+cf78vzhKRJrXAfJ/LWzV7b5gThHxj+Jby+fE/yePi8+Mb39UwYWGEFf+ -uRxcQIeuDX/VjPNtNKQPuO+HRi67WNXPFoUNmFXv1Ymn61S5duvVCxL8XdHXHdnZ -gIJ87CTlLBGPV/U9HrGJfl0AQ/jvMsvAV4IhMZMlV5QS2QigK7rkfBVe7k0NIWQ7 -Vwk5iunUpmUNVhKARdznvb8CJJm0ZEx4F2n8cQIDAQABAoIBAQCtZR46cSp6qWU1 -DnamGYyvM7W7lb6TtYtAxGnSb0z+bpPudPSXBqk8DrswqTlg674SY0nAJpyegFYX -Ifn6MzYgIv10ZGR2OjrOrdZmq5ikGWCrsZWEMZNyFq5kUwivvQ+pUj72wbyjghRH -1t7K9hzCiUbtAQzc77KKlWbkrBujFSp5EPNT67j5vV29WnZFbkPdUmfkM/ca/CZc -CWwvyAx19aFGyw3BsFhWQP5C9waT+QI9QZrVOA+8wTT11OcR6PT0oKdEmSYCKgHJ -JuYDWZ2XX2R2d5YNoxiqIZbCqQ/ayJuLOjLgQ1mx17pUyMNP3PoZCQXOi4jZWHZZ -+3/jqvJNAoGBAPmoL03KPvLVtHByEdxzPPfnonpYjfjlD4FvXgSQjdAcrTy4O06t -bDf4hMgUHQmDCyUakO45wyYwP0ISapQSBWniryjR/7U7/G/dX45fKRUeNoMvpmSC -qSEMAbd31Inpzuu5k0Y8p3hvoexeYlhbRkBL1ryx1LgIvC0TkWR+e6EvAoGBAPku -pHcpi3t2wewmP6f1krxtOLyvVt5RKaRjZ/2gNtzLPXL6ulQR5hufYlLKgyyyf2gJ -HxVFhCkfRjwVHV8qdIJc+Q4mjnjOeNfvqnzWOlSfZFegyWvOPW7hTX0/jZYGOb4I -7fzYyUPHnlu73twmshJMTzE1Ju7RdJXyLtg8xpRfAoGBAKjlyELXTWjZfP4Jnd3H -NHr+gSRGHp5A0RGe9zsdVGNz0xteA/mBR9JB1grJ2K8jsXmDlIMmHskKIPGhJetQ -mcr9qcRy9Yx1rZ08ZbYa2N9JllV/+hDLeII77jlh3y8CN5Ov81u0ExReaWxQmjXu -YgODix4TLLboae4Q6+7Rxu/PAoGAOZ04N7kqX/ygb+qUE1Crgde7I51i93pKp5C4 -baMKrFhtt9UTGfcdfkuG31+lnsMSxEo/npp5KUzq319+cA+P6sh2aXguvu32cO8g -O0cJK6HDAKPTjpKcD7QWR5xXL1X3KeJErI6vUnWoPsuchsiHqcVtFhKVEujpDPZ3 -MFY1D/8CgYBvv5mBb2kBf2/2JHp3lP/Q6LepEBkZk9dvoEU6/5xLvA5gEXR0MUj8 -g97Z1duGdXD/uEVRuRuOJkk4p8YmSM7t34st3lF06wdJUGcKvmZpp2ee+CdLwESi -GDCwcP5pcii56TVr09uHITWei4jFm+3Ye3h092dvPyNoEiJOgk2lsg== ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub deleted file mode 100644 index 1eaa7e0..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDzAhKfHbFah5m6vzKf/w0/KRRjaZjLGfWfSYTlYlKj6ZyUUVKac3TxYK3znoA7w8w+4Cf1zDSPeol7RIpOegxhKn7h8Gyrpgc4Ym+VEBMX1ImRIjHAEJiwxP5x/vy/OEpEmtcB8n8tbNXtvmBOEfGP4lvL58T/J4+Lz4xvf1TBhYYQV/65HFxAh64Nf9WM8200pA+474dGLrtY1c8WhQ2YVe/ViafrVLl269ULEvxd0dcd2dmAgnzsJOUsEY9X9T0esYl+XQBD+O8yy8BXgiExkyVXlBLZCKAruuR8FV7uTQ0hZDtXCTmK6dSmZQ1WEoBF3Oe9vwIkmbRkTHgXafxx old openssh format diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result deleted file mode 100644 index 720438a..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "old openssh format", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8wISnx2xWoeZur8yn/8N\nPykUY2mYyxn1n0mE5WJSo+mclFFSmnN08WCt856AO8PMPuAn9cw0j3qJe0SKTnoM\nYSp+4fBsq6YHOGJvlRATF9SJkSIxwBCYsMT+cf78vzhKRJrXAfJ/LWzV7b5gThHx\nj+Jby+fE/yePi8+Mb39UwYWGEFf+uRxcQIeuDX/VjPNtNKQPuO+HRi67WNXPFoUN\nmFXv1Ymn61S5duvVCxL8XdHXHdnZgIJ87CTlLBGPV/U9HrGJfl0AQ/jvMsvAV4Ih\nMZMlV5QS2QigK7rkfBVe7k0NIWQ7Vwk5iunUpmUNVhKARdznvb8CJJm0ZEx4F2n8\ncQIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDzAhKfHbFah5m6vzKf/w0/KRRjaZjLGfWfSYTlYlKj6ZyUUVKac3TxYK3znoA7w8w+4Cf1zDSPeol7RIpOegxhKn7h8Gyrpgc4Ym+VEBMX1ImRIjHAEJiwxP5x/vy/OEpEmtcB8n8tbNXtvmBOEfGP4lvL58T/J4+Lz4xvf1TBhYYQV/65HFxAh64Nf9WM8200pA+474dGLrtY1c8WhQ2YVe/ViafrVLl269ULEvxd0dcd2dmAgnzsJOUsEY9X9T0esYl+XQBD+O8yy8BXgiExkyVXlBLZCKAruuR8FV7uTQ0hZDtXCTmK6dSmZQ1WEoBF3Oe9vwIkmbRkTHgXafxx", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result deleted file mode 100644 index affc996..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8wISnx2xWoeZur8yn/8N\nPykUY2mYyxn1n0mE5WJSo+mclFFSmnN08WCt856AO8PMPuAn9cw0j3qJe0SKTnoM\nYSp+4fBsq6YHOGJvlRATF9SJkSIxwBCYsMT+cf78vzhKRJrXAfJ/LWzV7b5gThHx\nj+Jby+fE/yePi8+Mb39UwYWGEFf+uRxcQIeuDX/VjPNtNKQPuO+HRi67WNXPFoUN\nmFXv1Ymn61S5duvVCxL8XdHXHdnZgIJ87CTlLBGPV/U9HrGJfl0AQ/jvMsvAV4Ih\nMZMlV5QS2QigK7rkfBVe7k0NIWQ7Vwk5iunUpmUNVhKARdznvb8CJJm0ZEx4F2n8\ncQIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDzAhKfHbFah5m6vzKf/w0/KRRjaZjLGfWfSYTlYlKj6ZyUUVKac3TxYK3znoA7w8w+4Cf1zDSPeol7RIpOegxhKn7h8Gyrpgc4Ym+VEBMX1ImRIjHAEJiwxP5x/vy/OEpEmtcB8n8tbNXtvmBOEfGP4lvL58T/J4+Lz4xvf1TBhYYQV/65HFxAh64Nf9WM8200pA+474dGLrtY1c8WhQ2YVe/ViafrVLl269ULEvxd0dcd2dmAgnzsJOUsEY9X9T0esYl+XQBD+O8yy8BXgiExkyVXlBLZCKAruuR8FV7uTQ0hZDtXCTmK6dSmZQ1WEoBF3Oe9vwIkmbRkTHgXafxx", - "private": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA8wISnx2xWoeZur8yn/8NPykUY2mYyxn1n0mE5WJSo+mclFFS\nmnN08WCt856AO8PMPuAn9cw0j3qJe0SKTnoMYSp+4fBsq6YHOGJvlRATF9SJkSIx\nwBCYsMT+cf78vzhKRJrXAfJ/LWzV7b5gThHxj+Jby+fE/yePi8+Mb39UwYWGEFf+\nuRxcQIeuDX/VjPNtNKQPuO+HRi67WNXPFoUNmFXv1Ymn61S5duvVCxL8XdHXHdnZ\ngIJ87CTlLBGPV/U9HrGJfl0AQ/jvMsvAV4IhMZMlV5QS2QigK7rkfBVe7k0NIWQ7\nVwk5iunUpmUNVhKARdznvb8CJJm0ZEx4F2n8cQIDAQABAoIBAQCtZR46cSp6qWU1\nDnamGYyvM7W7lb6TtYtAxGnSb0z+bpPudPSXBqk8DrswqTlg674SY0nAJpyegFYX\nIfn6MzYgIv10ZGR2OjrOrdZmq5ikGWCrsZWEMZNyFq5kUwivvQ+pUj72wbyjghRH\n1t7K9hzCiUbtAQzc77KKlWbkrBujFSp5EPNT67j5vV29WnZFbkPdUmfkM/ca/CZc\nCWwvyAx19aFGyw3BsFhWQP5C9waT+QI9QZrVOA+8wTT11OcR6PT0oKdEmSYCKgHJ\nJuYDWZ2XX2R2d5YNoxiqIZbCqQ/ayJuLOjLgQ1mx17pUyMNP3PoZCQXOi4jZWHZZ\n+3/jqvJNAoGBAPmoL03KPvLVtHByEdxzPPfnonpYjfjlD4FvXgSQjdAcrTy4O06t\nbDf4hMgUHQmDCyUakO45wyYwP0ISapQSBWniryjR/7U7/G/dX45fKRUeNoMvpmSC\nqSEMAbd31Inpzuu5k0Y8p3hvoexeYlhbRkBL1ryx1LgIvC0TkWR+e6EvAoGBAPku\npHcpi3t2wewmP6f1krxtOLyvVt5RKaRjZ/2gNtzLPXL6ulQR5hufYlLKgyyyf2gJ\nHxVFhCkfRjwVHV8qdIJc+Q4mjnjOeNfvqnzWOlSfZFegyWvOPW7hTX0/jZYGOb4I\n7fzYyUPHnlu73twmshJMTzE1Ju7RdJXyLtg8xpRfAoGBAKjlyELXTWjZfP4Jnd3H\nNHr+gSRGHp5A0RGe9zsdVGNz0xteA/mBR9JB1grJ2K8jsXmDlIMmHskKIPGhJetQ\nmcr9qcRy9Yx1rZ08ZbYa2N9JllV/+hDLeII77jlh3y8CN5Ov81u0ExReaWxQmjXu\nYgODix4TLLboae4Q6+7Rxu/PAoGAOZ04N7kqX/ygb+qUE1Crgde7I51i93pKp5C4\nbaMKrFhtt9UTGfcdfkuG31+lnsMSxEo/npp5KUzq319+cA+P6sh2aXguvu32cO8g\nO0cJK6HDAKPTjpKcD7QWR5xXL1X3KeJErI6vUnWoPsuchsiHqcVtFhKVEujpDPZ3\nMFY1D/8CgYBvv5mBb2kBf2/2JHp3lP/Q6LepEBkZk9dvoEU6/5xLvA5gEXR0MUj8\ng97Z1duGdXD/uEVRuRuOJkk4p8YmSM7t34st3lF06wdJUGcKvmZpp2ee+CdLwESi\nGDCwcP5pcii56TVr09uHITWei4jFm+3Ye3h092dvPyNoEiJOgk2lsg==\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc deleted file mode 100644 index e5b6398..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,1380F5ADA0E0B636860A6BF78D47D6B2 - -ICLCebZN4+91mTQwByj210FD3D7kCxFA6kZ5fZ1TG34RzGynOSgUSdxPaXBHO4hC -DjS7lv6vrtaXPxlz5MVAhb6n0+X1pZDu5Wh5xjtkOt9yt4YPNKkvDPazSFBTHDth -jURe/aCLwXa+N5g5v1G/asb5dufA96tiPD8jjsBPm6RPq/444jAnLkid6YwTRLCk -a+IZZ+sX8onOq2xJM5NhsJxCEp5yquQCdyjvBBEBk5PExvWDHz4BIkK0WDR86IX/ -j4baAbTREiwP+EmVw1uogijvS+9nWPv3dQrtWwNQQNdWE2jJnsuDv44VAh1QQD7A -Txz2Y2A6IyzQsDxr6fL4JidVZOeeOXagYOBceZMs4IdNVJ52LJ9fqWtH1Eavj0za -c9zLgFN547l/Uqc334BQTkWhA9zGNkYJo4GCl/zjL2C6ce9gp0l6aBwSRyBmfH21 -pxFYqO/LQOSTbupeGzkNOpeNm/XtdOHe2N+2fiMO8hqEr6tOR4dsEUVBLCWt3tpD -C4jT3TtXKvx4qPV5N0w/umgXDd01Npk02k+wiQRnPBczFYLfRpceV/7MGtttV86/ -Ldl2p00q+JB6TzkHfOa4dA8oZJAwz3RPwmGYt/riJS4JOIpQGCs9lU3zgi7NTt4L -T9YAlAP3fjG1n3vy1uktKfRa+AoSqgS/pTJgB2srs6vxw3kt/V825cVyzSfGdQM/ -2oinmrbMAs0tRpTiHyqc/FjVRTW/8+LoSv/o6ZpN2x4jxkW/7cBH0Pcytvw8svd2 -Q+h92cfHuiNWi5tuiUkeDfjWEXo6ssVFA2t1ebTOk5y2wwPVAURf/jVxhEpFm4iY -PCIqwCwNSs1S05zAaIQ39ltBETj4Y46715GuYKsqLDYhv2lAIAlWXWgQ/N0tYVS6 -Oi/Qp9XFSEeyym5vzX/2ck1SJePvHvHewiABJjYzq3wlvIdWE6V3tJ3MRXRhlKNf -4bG8caItSG1n/QIeguNZI+A2Pu8AIdKjjKsnVcn3mikuKfcCAICZwf6m3Bd+Al7G -lrsJxyPqhhbPN1/t0w30tu8QuTSV+uMx4ZCKoUc6yJMQRmoM0RJ626re51IT2ikk -gB4f3Ms1VbB176it2L/zbXUAaxeE7Cbdcp/5058ksbuE0yA7JB+a2vQHFqw8Xxsb -qdKc4m4jkCdvaA5oNnGoG4milYukp1WVCGJeLD7gspTHR5dDYsOQgHvkxu+Ukor+ -0+1yvf8R6pRJWMoV0VvNkuSBUqcx94A+xLaEYCkB78Koum8xlPA1OA7VVkMVjQSk -r6c/iANbNV20IVz1TBpg9J1rQOGisbE43yRkH+aMgHnAnhk+UgK584QOH6eJpGZT -yBwes57P1kgT5VubavoJbeZLL6B70Sn/sKoLzxxruzPKmsmufJNK9klB7lu5f4gj -lvKtuNaiWbux1+fQmU+05nM1WW7s5Nm9MVUCfS5RxUq8SRqC7W17ouHEssW6mJT1 -jHK1xhoxX05X/T0NfdPzbG7S7+DG18Q6jnyHb28LeKLXv33sEUrT5z7+Nx4JS4XM -ZeMzPdRgYJw9vLQSYdksj0cNBb8UpAiG410lICrbPGWJh9d2KzhNKlfk/vLHia1V ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub deleted file mode 100644 index 806ab91..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDHLfm98g0aHjbQJcjbamutwkWTMY426a4IdwGrpAOv806h6wBXNcOj2VJbgeQ2/XkQ0RY78fGrHSacaadGsT9E5sRGyvkr/WtDpBokXrgpP15OvhfTaSMVTcty6qknndpu7P5nmSipdn9fQR9TyNRyAajhn+UINuquGfxyLL30W4IBqSISOcXKc0pScTdMOIOmkxxY+vQFydQpWF0a3TopKKa4b3sQJgqc0MJkREllT6U+0U4+YufoW6zZyMNIS2gxWUlGUiA5XveWSaYIXCaPQmps4WoO9AlrM7z1sTcG5yXn0kEUvTmBYUOUlffiBgXzArt4Pmm8gVklR5UH98y5 diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result deleted file mode 100644 index b4aad7b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result +++ /dev/null @@ -1,8 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxy35vfINGh420CXI22pr\nrcJFkzGONumuCHcBq6QDr/NOoesAVzXDo9lSW4HkNv15ENEWO/Hxqx0mnGmnRrE/\nRObERsr5K/1rQ6QaJF64KT9eTr4X02kjFU3LcuqpJ53abuz+Z5koqXZ/X0EfU8jU\ncgGo4Z/lCDbqrhn8ciy99FuCAakiEjnFynNKUnE3TDiDppMcWPr0BcnUKVhdGt06\nKSimuG97ECYKnNDCZERJZU+lPtFOPmLn6Fus2cjDSEtoMVlJRlIgOV73lkmmCFwm\nj0JqbOFqDvQJazO89bE3Bucl59JBFL05gWFDlJX34gYF8wK7eD5pvIFZJUeVB/fM\nuQIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDHLfm98g0aHjbQJcjbamutwkWTMY426a4IdwGrpAOv806h6wBXNcOj2VJbgeQ2/XkQ0RY78fGrHSacaadGsT9E5sRGyvkr/WtDpBokXrgpP15OvhfTaSMVTcty6qknndpu7P5nmSipdn9fQR9TyNRyAajhn+UINuquGfxyLL30W4IBqSISOcXKc0pScTdMOIOmkxxY+vQFydQpWF0a3TopKKa4b3sQJgqc0MJkREllT6U+0U4+YufoW6zZyMNIS2gxWUlGUiA5XveWSaYIXCaPQmps4WoO9AlrM7z1sTcG5yXn0kEUvTmBYUOUlffiBgXzArt4Pmm8gVklR5UH98y5", - "private": null -} - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result deleted file mode 100644 index fddff0f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxy35vfINGh420CXI22pr\nrcJFkzGONumuCHcBq6QDr/NOoesAVzXDo9lSW4HkNv15ENEWO/Hxqx0mnGmnRrE/\nRObERsr5K/1rQ6QaJF64KT9eTr4X02kjFU3LcuqpJ53abuz+Z5koqXZ/X0EfU8jU\ncgGo4Z/lCDbqrhn8ciy99FuCAakiEjnFynNKUnE3TDiDppMcWPr0BcnUKVhdGt06\nKSimuG97ECYKnNDCZERJZU+lPtFOPmLn6Fus2cjDSEtoMVlJRlIgOV73lkmmCFwm\nj0JqbOFqDvQJazO89bE3Bucl59JBFL05gWFDlJX34gYF8wK7eD5pvIFZJUeVB/fM\nuQIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDHLfm98g0aHjbQJcjbamutwkWTMY426a4IdwGrpAOv806h6wBXNcOj2VJbgeQ2/XkQ0RY78fGrHSacaadGsT9E5sRGyvkr/WtDpBokXrgpP15OvhfTaSMVTcty6qknndpu7P5nmSipdn9fQR9TyNRyAajhn+UINuquGfxyLL30W4IBqSISOcXKc0pScTdMOIOmkxxY+vQFydQpWF0a3TopKKa4b3sQJgqc0MJkREllT6U+0U4+YufoW6zZyMNIS2gxWUlGUiA5XveWSaYIXCaPQmps4WoO9AlrM7z1sTcG5yXn0kEUvTmBYUOUlffiBgXzArt4Pmm8gVklR5UH98y5", - "private": "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAxy35vfINGh420CXI22prrcJFkzGONumuCHcBq6QDr/NOoesA\nVzXDo9lSW4HkNv15ENEWO/Hxqx0mnGmnRrE/RObERsr5K/1rQ6QaJF64KT9eTr4X\n02kjFU3LcuqpJ53abuz+Z5koqXZ/X0EfU8jUcgGo4Z/lCDbqrhn8ciy99FuCAaki\nEjnFynNKUnE3TDiDppMcWPr0BcnUKVhdGt06KSimuG97ECYKnNDCZERJZU+lPtFO\nPmLn6Fus2cjDSEtoMVlJRlIgOV73lkmmCFwmj0JqbOFqDvQJazO89bE3Bucl59JB\nFL05gWFDlJX34gYF8wK7eD5pvIFZJUeVB/fMuQIDAQABAoIBAGuSfhZDGyZm+Q2T\nypYONNekW7Uyh29K5640r9dGfqNRkb9LT2TKab4dSiiXz2yPmwolEpAPjIjw9oB1\nY11/rv8Eby8YwlgqxvrCL0hDS80jJ0j5y55nYwZHfMC00eTOkUFlh8Tl6BsWH5aP\ncl7q0So9kTtCAw1bs4WSDVCQr4q/x7fZRQWeWudi4IjnCv5vn1Pgot7XxDwdFNQG\nDrkUHvYXv0M2OCdl7YN0D/bHQon5ney0YU10mtqGbkcEmu0woykW1Bc539b9AoD3\nxI6LVyY6/OEwGu5ctKolIVJjsguwfLJ9WR7SenR5nTzjJyxMdSfXtXkKPX2NZxpO\nziNYnm0CgYEA/afEFBu5Ld/TjYatdf7ezZe9iDx6vBzWmMtwkhr3OHCzVP1OIaB0\nSTsCWrTdoLFTMOizUHjj71vX5v5G4aCgaMXQnSDf13mxrFzR36w5oyJOBLjkHhol\nf0ROO7QCXK1hjBAUvnKwLPQvx1CAkDB9z+cT/BJwRCarfeLhrd/sGEMCgYEAyQVN\nOGIdRVBs3Q/8dbtaz+7LOv6IBZm2y9TKHKmfBm1txAsgkqRl7cfVTyczgAZfS/RB\nzrAje5UA+phCSPtyb5B+K1i/eHw7xDZrw8wauAKY8ILSadS9ZA0mU+7XCqsWhNqN\nrvuB5dttsTDgyXnMxCbYqCWAcyKn8jBh1cDo5VMCgYBe3iMQnjnI9YCK2wb/LZ6o\n6Aqj7HK+7k44gUYN7vXtbwEzVTWmj/tN9DryL9kAI7IIhc+i1kPxnrkGFK3v7wJv\njSRzz/rH/SS9YU3BSQmZgNgLHhd7Rq4lhid4Xt/PR61HFDCd9gj8FyvTcMFUrD4x\nxqwLx92jL49OGs/rFueXPwKBgBi46jJQ/sCTj4/wc2AXVqfT+nKa8yedK/oNhX3Y\n7pHfy2wc4jimt1JzDSza6V6JahbxR1agGv0L6j7nkt9e7UgDQUEbfRDYVpFfEAnY\nhEC1MRIDRNV3MIOpilkwOoo5WF+mcV5f2C3ouqjcFgkxTZmiHWswkYeXb4g9owqi\n2wG5AoGAb6/btpj3Ql+qYXRUH/cWPlLeFbKiGaAJ+Kn5RwlEW8D//FjKuV7fL7BN\nhvaDJUpwP9klNRny3IK6FWuFI0KDup0nyrIbS07h2rOCl/+g2erDuS5sofpu2zWU\nZDArpSmpU9EF6S8CvbbZmYvWzYUhYD/sEqIR+KSowNM4PA7g7fwKCgoKCgoKCgoK\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 deleted file mode 100644 index ceed070..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 +++ /dev/null @@ -1,54 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-256-CBC,5C3291414FA514EE9647898A2D5315FD - -PaIGvR7qnyhxjz7RI4YEeua59B0XJm6cTW6xv2tbSVIC/njwljgo+UzXJLPUH1gv -suhNs8X+U9n0aCME6vFQvSJcloo6B1NLhGL1DVNhMAiGu+byCSJtq4cTFR5+7YUQ -HGB0a5vGBtHhL86TBeaBcKYfgCE4jo6/FAvzfk/eyy3S/oHXjMMUfCqo3WrBcgLu -SwhOEGd2k7vRp4gZzsCZy9xMM4Gykrgxc/hLzyvGQF8isF5Nz6xtPLNlW9xPdD48 -Fq5CTfljR4+7mM/kruJRysnbXEoYAaA8oZhZsRD5cw2tMOartA4qUieR9sKfrMo0 -Ci7OXNkdDK83OWGZs3NUYT/BzMmIPf982Ws46RHZLQOad3qTHvFdCUeQKwPJtQZM -D40xdbw462KQi+yr8+dPs9q3yxS5lr1rG+SmCAe/s+5Ta6E6VMb30Jb9FBP+91Z8 -6XxrF9jl67xaOwz/8rqUfiYm0C31YHiSsGlewe7lmvr4W+f47kn+lxEVXJD6UG+M -l/iJMZR39nr305K4GHG29NVS/9h1XC63/FZbL+50YCfavBikvEEDZoBKSKzs3Rlh -LZOTt6netyFuJtW0Z2CsYnvyyBioztD2yVGStS1MX652uDutFuqcBgm5FCdC1XDD -c5y83mH6ZWAjJSai8ap80XATO+xImb86paJ7u96mSAq7t+ziTCjlFTl3Mmtfoyrr -yy4IWSFIZ7BGdk2yeOR+kW+UNij5tS0J8s+Ug8hIh0ax9pvIB9opB0HmCVRg8reY -KUZNUwPlBtP2Y9dU63fKf0LNkzzMZduiqN8iD/lC771TxEU/tvl9cwr0rP3Shqm7 -UYkhPG+l0iXmX9fJwfJ+sfnT6zRfUKqeuN58YpoJ1zliv+4g9wDZWDzPlcktW3RU -CcZ9nKxRzQ9WppZzPoN0OMr+POt+S9hKufGfKP0D4pvIJ3KOGvk0A31iyQ5Ua6mI -emC67kES+3djSaLBeYax0AOzxnuHc/9dcC4meGzPy3RWRknxYxt0KMlo4zR42ZTR -Qh3eA1h6POEtrwsCMUD+tI3W6QwcCCmaJW6gfwZPSqPqbLwI21NVfUS++0V8qB1X -ugRUwN7gvX9rf+2jp+IjTVXai6xPkN4LqIX8jULYihKdR+tMm/sKTEGfc+peMrN9 -iljwsPztLzAIEjr4UppaLyhJJCp4BHdveVg0/uhgBqQTuMHZtKX31IHdDjeJc2n+ -iITqdh20lwLl6fwKsAl1oBf1GaRSOsd+oi2IyXqpfMpoXlo2q/r7ExPAzDXXg0bb -tA5Awa6Fndu5BR4e4UUDDVnj3AU175D4Nz6ZyXmCBC9nB6rvXXAa/gdh8+/HL1nS -7gDU9rws6dDRP3BAE7xM8QQ4VNaPikPPlikKNTY9rom32kKMmGD64dEPuZHl/i1i -gNcQfQoLDdwQJzqYcn9ZtcsE3hPJgqwO+wvK4MhnKlYXsRnGIQVNgEt9ler98Wap -eFKgl+Jf9z+T4uJka7yFzni1HQ1kvanYpI0w5ili46te/yPE96uzhRGqn1bu+/QI -e1rC5IMHu8cYV1a/baX8r9iwIXislq6fia5ivj0fmFTYbBJZ/M4LlY3zVXlJnIQj -iykB31s5faMTUE8CDdj+fr1Dc5ERPWgiI4PxXTquPUHq7B6dhsJ6RbYkgIoBhuam -Ok39LZ/R4nTiJY9VaJwQPvdrNnQEZ9lmMnh7d8jcsja4SVNFObC2ONQ2MVbr+dXd -jTHIlOF3aqWM0ZP4dh/Zg0rIy4koL1G88/vOpKAoVPZVmftqww63TPao3uny9nTK -BjwqzalPZwt0KFSoAGr3e8psQpCXwHoP98/GyE9NVBhR4X/I2IST4Sk0x62Gz1pg -ZrGpz7VDEySYAd8GBvdOuAawjmE41YwEofRrBb7ZPbwIxrO3ei/G8f5LBABRCmjO -ikzAk9mADCnfY08nfQ8mjZAIiTth6MuFG92TeJSi1W56p+krikVh0SUxEfXeR1CR -XOyshItaWQNx7OojB3P7JG7nrY046144oQuUb7mVUi4oQE+TxKLRvc0jLkWyKmjf -Ii+BZFHuU3lQiAarQ+mZEA0pXCGCT+NDZK5Eo4LBCrYBfaviWcWB6LQoovAF2T42 -zzx5qZP4ANS7l4SUCd5qS7/h3/ftCkLHTEcV0KBJ2n3blF6wdP/7C3wQD6AcRHWQ -132dnFlD/agQ6VOFjTg4hnw7BrUtIHATKlmMg36CtXtqJYnb9DQEQDo24dBNVNjM -W1Tpgw8xkyVb9kICiZoy+kXnqqkGOnLHT12h+/pgkJqZO61kfvwUeNAK0USG/h/L -TRop17tZjsg2O6R9/aS0SnyANBJ8xgxRAneWuX6ry7t9IDYOH1Ybcn4riLe+tgCM -YPpxTOCUw49dqdkTU6/n2vEXXIRPXIefxBhIk1bKelX/owIwe+3kNSL96HzEDvI9 -GwaLRxNgMLi5diI3yJmevantJJWIKUFhz3ud2viaSWNWdAvfVmEcb7APs67cJAr9 -4oKnhF4TuD2oowFnH3nykczXRqAqHn+N/XynH0QJrQDJYwnYWH/+5YFWaYwHACSK -ppOnWNqQ28zjA7w5GLI//rHRT0NBbFbVF7s0TQlBu0Rukc042eW692BX/2qVSCpZ -8aVjhBFFbnt4YmRSYlj/X7ICnddWqHSiRNy5RMokdMlZD1ELxYf2XkkZionTlT/E -hHSsA2c4HgP5Ep9svM7EWtFO7Melk2vjgXZxyELbLPZUQuYImuK2ziKqL05YH/lc -/yfAdXOKLWjrUgVBk8r6QqoAWP0iCTZDOmB7IwVu9nLClpnJDfT3kRrai2GIpg/D -1+eBAcr6aoRfpLTduW3EAit7SNzLZSkcBvaLkkqJ3tCPTq9GR05DzOaTGCf+vyve -kRNdTMSX5E6IH3xomKTIPZrEgOMEJpdsJ4wBCt2ginYZvHOFsn+YiLL212+rLOTH -qqSKZb0O5lxgQNjl62PJ9bzDEJkiuUinz83OlLAe7fSZiT3wwKG2x8PsZugRSk6K -txDqENJGzcDsX/MLNYdy6y2MnAWRYKNsmp0luX5Exw7L8ls8jUAMnd0DS0RFB0gN -14UzNa+ZO35Xr4vj8n2URnX9O2vs+A9jcDQU7TOp1/ejq3ISATrIAjeyqUHNZ+Xq ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub deleted file mode 100644 index 0df674a..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDOHBVYZ041e+MqbjY+oSRiNNO1nDK1l0P6blyAyi4gwWfEOGSkqBZr+vCGnSj3/BNWsCcECbsG2TBMkoxCmXLc32rgQRz76/vON0gRaAzm+oi4N1hSSN7S/xX3XEwkH5OM/g9WKJvzerGejIExT9C6jzCvznlRdSTnntJrgwuf8ubyOfffXht66X/klC5+XeDI8SORiIr/E7q8QUpjcYYjgRgJHTjjh47xDGQOkcL+ceZb1/ufbU+4r7m8Ume/+fQuOTXcD13yKd1Na7auXMHL8Orh8YHvgwbFCVPOFDDEyReNgLLEaGGHJOuWaf55N+7J4CSDRkRqjz1tFqdqqHwdRr0/pJP77mjEe89Cx4iu+BDrT72/SPKo5bwDoXBa2TxSdoVHT9idjsUPDfwshD4eHtwyhrZkEiNY8Qp+F57I9MSgRT62zdO/vZ5wzEYDJC3DBXPw3owvpGdJEjSOhTD0rOFctNs/dKlwAXnU6QUAE1qgd9P+O3GIhYiPkrw3XsbF39VeouroYIbljv4KyDb+wQMk2U2wzUE/ZV/AVjV0OK/3colr43uxEhl6D48pWejzpQ6DMFKuL5pcxzZzIlBVmwwNsNb3DoWQ+a1gepyimp1ocUlv28JPqMMiarm/Kka86KY+fzcHUUPQXpz8R4edOLA2hQSudYdTcNmcAOpwMw== diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result deleted file mode 100644 index 3f23304..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result +++ /dev/null @@ -1,6 +0,0 @@ -{ "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAzhwVWGdONXvjKm42PqEk\nYjTTtZwytZdD+m5cgMouIMFnxDhkpKgWa/rwhp0o9/wTVrAnBAm7BtkwTJKMQply\n3N9q4EEc++v7zjdIEWgM5vqIuDdYUkje0v8V91xMJB+TjP4PViib83qxnoyBMU/Q\nuo8wr855UXUk557Sa4MLn/Lm8jn3314beul/5JQufl3gyPEjkYiK/xO6vEFKY3GG\nI4EYCR0444eO8QxkDpHC/nHmW9f7n21PuK+5vFJnv/n0Ljk13A9d8indTWu2rlzB\ny/Dq4fGB74MGxQlTzhQwxMkXjYCyxGhhhyTrlmn+eTfuyeAkg0ZEao89bRanaqh8\nHUa9P6ST++5oxHvPQseIrvgQ60+9v0jyqOW8A6FwWtk8UnaFR0/YnY7FDw38LIQ+\nHh7cMoa2ZBIjWPEKfheeyPTEoEU+ts3Tv72ecMxGAyQtwwVz8N6ML6RnSRI0joUw\n9KzhXLTbP3SpcAF51OkFABNaoHfT/jtxiIWIj5K8N17Gxd/VXqLq6GCG5Y7+Csg2\n/sEDJNlNsM1BP2VfwFY1dDiv93KJa+N7sRIZeg+PKVno86UOgzBSri+aXMc2cyJQ\nVZsMDbDW9w6FkPmtYHqcopqdaHFJb9vCT6jDImq5vypGvOimPn83B1FD0F6c/EeH\nnTiwNoUErnWHU3DZnADqcDMCAwEAAQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAACAQDOHBVYZ041e+MqbjY+oSRiNNO1nDK1l0P6blyAyi4gwWfEOGSkqBZr+vCGnSj3/BNWsCcECbsG2TBMkoxCmXLc32rgQRz76/vON0gRaAzm+oi4N1hSSN7S/xX3XEwkH5OM/g9WKJvzerGejIExT9C6jzCvznlRdSTnntJrgwuf8ubyOfffXht66X/klC5+XeDI8SORiIr/E7q8QUpjcYYjgRgJHTjjh47xDGQOkcL+ceZb1/ufbU+4r7m8Ume/+fQuOTXcD13yKd1Na7auXMHL8Orh8YHvgwbFCVPOFDDEyReNgLLEaGGHJOuWaf55N+7J4CSDRkRqjz1tFqdqqHwdRr0/pJP77mjEe89Cx4iu+BDrT72/SPKo5bwDoXBa2TxSdoVHT9idjsUPDfwshD4eHtwyhrZkEiNY8Qp+F57I9MSgRT62zdO/vZ5wzEYDJC3DBXPw3owvpGdJEjSOhTD0rOFctNs/dKlwAXnU6QUAE1qgd9P+O3GIhYiPkrw3XsbF39VeouroYIbljv4KyDb+wQMk2U2wzUE/ZV/AVjV0OK/3colr43uxEhl6D48pWejzpQ6DMFKuL5pcxzZzIlBVmwwNsNb3DoWQ+a1gepyimp1ocUlv28JPqMMiarm/Kka86KY+fzcHUUPQXpz8R4edOLA2hQSudYdTcNmcAOpwMw==", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result deleted file mode 100644 index 8cf3c91..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result +++ /dev/null @@ -1,6 +0,0 @@ -{ "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAzhwVWGdONXvjKm42PqEk\nYjTTtZwytZdD+m5cgMouIMFnxDhkpKgWa/rwhp0o9/wTVrAnBAm7BtkwTJKMQply\n3N9q4EEc++v7zjdIEWgM5vqIuDdYUkje0v8V91xMJB+TjP4PViib83qxnoyBMU/Q\nuo8wr855UXUk557Sa4MLn/Lm8jn3314beul/5JQufl3gyPEjkYiK/xO6vEFKY3GG\nI4EYCR0444eO8QxkDpHC/nHmW9f7n21PuK+5vFJnv/n0Ljk13A9d8indTWu2rlzB\ny/Dq4fGB74MGxQlTzhQwxMkXjYCyxGhhhyTrlmn+eTfuyeAkg0ZEao89bRanaqh8\nHUa9P6ST++5oxHvPQseIrvgQ60+9v0jyqOW8A6FwWtk8UnaFR0/YnY7FDw38LIQ+\nHh7cMoa2ZBIjWPEKfheeyPTEoEU+ts3Tv72ecMxGAyQtwwVz8N6ML6RnSRI0joUw\n9KzhXLTbP3SpcAF51OkFABNaoHfT/jtxiIWIj5K8N17Gxd/VXqLq6GCG5Y7+Csg2\n/sEDJNlNsM1BP2VfwFY1dDiv93KJa+N7sRIZeg+PKVno86UOgzBSri+aXMc2cyJQ\nVZsMDbDW9w6FkPmtYHqcopqdaHFJb9vCT6jDImq5vypGvOimPn83B1FD0F6c/EeH\nnTiwNoUErnWHU3DZnADqcDMCAwEAAQ==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAACAQDOHBVYZ041e+MqbjY+oSRiNNO1nDK1l0P6blyAyi4gwWfEOGSkqBZr+vCGnSj3/BNWsCcECbsG2TBMkoxCmXLc32rgQRz76/vON0gRaAzm+oi4N1hSSN7S/xX3XEwkH5OM/g9WKJvzerGejIExT9C6jzCvznlRdSTnntJrgwuf8ubyOfffXht66X/klC5+XeDI8SORiIr/E7q8QUpjcYYjgRgJHTjjh47xDGQOkcL+ceZb1/ufbU+4r7m8Ume/+fQuOTXcD13yKd1Na7auXMHL8Orh8YHvgwbFCVPOFDDEyReNgLLEaGGHJOuWaf55N+7J4CSDRkRqjz1tFqdqqHwdRr0/pJP77mjEe89Cx4iu+BDrT72/SPKo5bwDoXBa2TxSdoVHT9idjsUPDfwshD4eHtwyhrZkEiNY8Qp+F57I9MSgRT62zdO/vZ5wzEYDJC3DBXPw3owvpGdJEjSOhTD0rOFctNs/dKlwAXnU6QUAE1qgd9P+O3GIhYiPkrw3XsbF39VeouroYIbljv4KyDb+wQMk2U2wzUE/ZV/AVjV0OK/3colr43uxEhl6D48pWejzpQ6DMFKuL5pcxzZzIlBVmwwNsNb3DoWQ+a1gepyimp1ocUlv28JPqMMiarm/Kka86KY+fzcHUUPQXpz8R4edOLA2hQSudYdTcNmcAOpwMw==", - "private": "-----BEGIN RSA PRIVATE KEY-----\nMIIJKgIBAAKCAgEAzhwVWGdONXvjKm42PqEkYjTTtZwytZdD+m5cgMouIMFnxDhk\npKgWa/rwhp0o9/wTVrAnBAm7BtkwTJKMQply3N9q4EEc++v7zjdIEWgM5vqIuDdY\nUkje0v8V91xMJB+TjP4PViib83qxnoyBMU/Quo8wr855UXUk557Sa4MLn/Lm8jn3\n314beul/5JQufl3gyPEjkYiK/xO6vEFKY3GGI4EYCR0444eO8QxkDpHC/nHmW9f7\nn21PuK+5vFJnv/n0Ljk13A9d8indTWu2rlzBy/Dq4fGB74MGxQlTzhQwxMkXjYCy\nxGhhhyTrlmn+eTfuyeAkg0ZEao89bRanaqh8HUa9P6ST++5oxHvPQseIrvgQ60+9\nv0jyqOW8A6FwWtk8UnaFR0/YnY7FDw38LIQ+Hh7cMoa2ZBIjWPEKfheeyPTEoEU+\nts3Tv72ecMxGAyQtwwVz8N6ML6RnSRI0joUw9KzhXLTbP3SpcAF51OkFABNaoHfT\n/jtxiIWIj5K8N17Gxd/VXqLq6GCG5Y7+Csg2/sEDJNlNsM1BP2VfwFY1dDiv93KJ\na+N7sRIZeg+PKVno86UOgzBSri+aXMc2cyJQVZsMDbDW9w6FkPmtYHqcopqdaHFJ\nb9vCT6jDImq5vypGvOimPn83B1FD0F6c/EeHnTiwNoUErnWHU3DZnADqcDMCAwEA\nAQKCAgEAtDuwmr6zkGeGbYs02i2VoF8rpssxOMRPCIZLU7/4+GHH+LmLoMTv3nrw\nq/ZwZfJDgvHFHG3Z45I2/y7DglWnMOgaEII/8zgX2OtUlQwVBEKfHeAf1sysNXwk\n3EsUth36rDdad/BI93AaNFgPfWybTRh77bCzO/0hSX4D6UoN90+0jqsMS4KCq0fW\ns660vYIgV/cuMExjp8y75XV+tFkIgLGZsBaisazP3ZAFSwxBpLk7RKMpAO/Y39qi\no8C3wxOzaFxU8dtqPqJHSDVh6TVproo9C1liU2yTleejJjlXsC1c8DtTmBbi+gfa\nD40enye/Iz9jDnx6xWf+wg8mVUmCRZGxRvjvS/CjIEwNB6EX5vSCe4oM8lOg2V7f\nFynGpRYlP3vkcelNly5qf7mlb/Wkd7F8PnJ8JTHdTcGSalMJ3DKn063jn5eYFUQm\na40NkVAlDYOdeQZumCY7+v9Vontx4+0IrXlZJWr9EYyAEm80LlwenJ2s/YoTRwqV\nTfpWPaEcrNlZUq/2A9JM0m91gLktQaRLRyNnBvFap9504aWnLrD8m7tCWkzFf4wJ\nA+v9yN+lCveJPmNi5nW3Pzd1Xy3n126BN+yH7VUWVARKs8ZOUdOUMAg6ZVM0GnKe\nOt7AEAG5jsmGA5UQywtbGYOMonKBQqsqoWNKWTbbqbNbe4FyEqkCggEBAOzuRMHh\nI58/iv/TjG/t32CLdWRDM6cVvycoZL37zqObpzXo1LJHr1iCqxrEZnSzX5DCW3e5\nMbr3dq2GL02RfDb9Nta16dy/V6VzwK9bdavk9+CzJFoIvMVDqEZ6mVtTwvGrd6Aa\nnrTJjZjDG0dwfNe9LuNLmLSVE8p7WSWjU0E5XB45y1m53pIoQbqsR6cJPkiUGO2S\nUaR+xzxHeHv82zTavpf3T5+O+6UX6SRG5lx5Tk4ucUPzzwrry0PVdRERyZhJTjC3\nlG449RSrr1UOdwGE3Kkz4zEL14L661nDWogf9Yc6xsatSHSzVVdN9UY63e1pb8DN\ndEaNu0qddORTsD0CggEBAN6yxtydA+YMJ02C70PJZId3BeTLOzyk5ZCHU8kEEIFl\nRK4jW1kTXpxito2sSwDLYWnjHExnQiLFaYsVAhaxEFhS9bXrm9SWCjk7pD8XwdQ5\nBsi8uNz62W9cTNCHszwLCZ0HWKfsoQjodEbbAs3XS+F60i/e1RKAMsDm38tmO6rU\nSE1+81fgPpLTdT3cnAtwF51rxlgVQWFiohLxrSFvWS0X5eEvnoXZhqLMwdwQgUob\nuKuFDhMMleP17wbmA0QGdSWmUEgshx8g0Fx++BLqAcvSveQCkRGSn4RAfLq6I38S\n8ERJbbW9c2LjBKU2YyiuqdLcw0hVUJf0bGrOqHIFuS8CggEBAN4Z4bSJk3YGAAwf\nSGfoady7/pi1cmcvuJhBgmah9SxjjlS35SMWleX33+Pgtlaxi2VM/Kd3oImuzr6N\nqiwhtHpr1gtiTk8Tw1qi7r6zktRHeKJX7DzGMgcNjGI9LSNymq0nWqVoLtw0kJri\nUuEeLrmia6DAze6CTSIjjQb+Wt4qohLnhJug5GbIfA080JJh1NP+mHukDQqRmb0F\nFonMF8UtRTt5p1dglr9FcdUC7ZFEWcZqPN1BYRXQwiPdprcQoJU0Kqr6fJbyp7Pv\n2RV30NFItf2bWV8xxZ3QD+1+dpBivSw+SfYWnHRhZB/KQaHLLx0OGKd5MYWt+SNS\nBTDAztUCggEAEGOJvPyVJ93nGo4zO4LbshhxR5gpQNpFxrAe22FAMbWZK1OQymph\ngRLGqoBueJ1/CsLa90h2Fob+sGyYXcEkGcvpJz0yl59/Gx0nhjkiW5Liy+0Pkbuo\nOsjJImOKLjYFvBepT5pbc4Nf40ME3s8kV3CpfTph5d2nXojfGWHprDW5KHLaR7JK\nCJYlP6s3lKPoKP6gdyUBTcBrewdsHVTLdEUY9syBVwpeHScCcUaJrUGDAqRlF8PK\nWB9mOtS8ksoC3wVxTQ5x1zmb++KgMQwlm7Fjph8GPAvVT29LfpZqPFTRd8ULnN9X\nWYSpd9sbywenmcwDVxRoPPaQ7/9LaDDBowKCAQEAsoY/cxW+RrzavJYUZW8Zcdq5\n1/JHEGzr08FMRR+3UbeH8kpFQkc4/e/pobz/6ZRQkCasYGYc+5wZquYanbVsyJME\nkWBVREJ22kr3vjyueqgk1KQqYmOToOYNLYYS4TB0io84+HZTqsUKWXzJETc1TI6b\nMqslgSqd/jpK/BMTUUT9IrbAP7oGQcdcQ48R95LbjWlx/Mqe5mwmsSCex6b6ZKyk\nMGQJ7BG2Fjljs1NiHB3rwc50/wvUBsZmqMNQm/1/t3Nc9LQzJkUVe4IUSlQ56eBZ\n8k0JExiCAooRJNwUPAb8+GU+adYN7b4oPDCmAEgICojoX2PNLjAj9T1v4xPPcAIC\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc deleted file mode 100644 index 915508b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc +++ /dev/null @@ -1,17 +0,0 @@ -PuTTY-User-Key-File-2: ssh-dss -Encryption: aes256-cbc -Comment: dsa-key-20141202 -Public-Lines: 10 -AAAAB3NzaC1kc3MAAACBAJn2I8YefRo3BsEeinQt8KQ4cEyArAs7Y/W733oRSYOI -zWF1Ju124ysKrmg2okv+05CYcjV3Yp4AzQeomYAlgmB/7xCEnWaEnxCwAxmrrJMm -PrkwNjHOIi7yM5QOE90IM/Q+IJA4EPBfSb+Xr8fYhrp53KNHVSnc2KkOqpo2FsIj -AAAAFQC4NlP50GqyUqq2B82Vh/w5j3TzwQAAAIAeSGom9LLNdzcwCHnGfxKNnEz3 -55KITADTxiIpBvnQW+eDHwQvIw6V2Oc73bKCu5ZirZmIMW5w6KjQVwkuQBoF9Koq -/2u6VeevtL9pD6TBzSLMVw5pV3PmE4/C/eLiaUxZLIHdbzpqPkAvAUBrXKkj0ijz -cNzCp1fuF8H0pvR8yQAAAIAmvV+kqWhUgDYwNNz1qDaoS8XdsOponutZ/0stRQ66 -mKAy8kNVNNQ6oUx1XFl1WUt4iyFY/2Rz2fZhLz5/TbZRK5ygo666WgnxB/Ud4GAx -/BPQTghOJJOL00vJk+8jVCGNDc942V6nFXznDMXwqxhRCW6dm+2lTh7ntrli8mCk -5g== -Private-Lines: 1 -BytvbK+jNyMjiVxCO5lcE4YbW7q293oC+LZjkZ8Ajlw= -Private-MAC: c3da536ea28851fc32d5d1ff01498c8fcebc1170 diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result deleted file mode 100644 index 68edda7..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-dss", - "comment": "dsa-key-20141202", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBtjCCASsGByqGSM44BAEwggEeAoGBAJn2I8YefRo3BsEeinQt8KQ4cEyArAs7\nY/W733oRSYOIzWF1Ju124ysKrmg2okv+05CYcjV3Yp4AzQeomYAlgmB/7xCEnWaE\nnxCwAxmrrJMmPrkwNjHOIi7yM5QOE90IM/Q+IJA4EPBfSb+Xr8fYhrp53KNHVSnc\n2KkOqpo2FsIjAhUAuDZT+dBqslKqtgfNlYf8OY9088ECgYAeSGom9LLNdzcwCHnG\nfxKNnEz355KITADTxiIpBvnQW+eDHwQvIw6V2Oc73bKCu5ZirZmIMW5w6KjQVwku\nQBoF9Koq/2u6VeevtL9pD6TBzSLMVw5pV3PmE4/C/eLiaUxZLIHdbzpqPkAvAUBr\nXKkj0ijzcNzCp1fuF8H0pvR8yQOBhAACgYAmvV+kqWhUgDYwNNz1qDaoS8XdsOpo\nnutZ/0stRQ66mKAy8kNVNNQ6oUx1XFl1WUt4iyFY/2Rz2fZhLz5/TbZRK5ygo666\nWgnxB/Ud4GAx/BPQTghOJJOL00vJk+8jVCGNDc942V6nFXznDMXwqxhRCW6dm+2l\nTh7ntrli8mCk5g==\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1kc3MAAACBAJn2I8YefRo3BsEeinQt8KQ4cEyArAs7Y/W733oRSYOIzWF1Ju124ysKrmg2okv+05CYcjV3Yp4AzQeomYAlgmB/7xCEnWaEnxCwAxmrrJMmPrkwNjHOIi7yM5QOE90IM/Q+IJA4EPBfSb+Xr8fYhrp53KNHVSnc2KkOqpo2FsIjAAAAFQC4NlP50GqyUqq2B82Vh/w5j3TzwQAAAIAeSGom9LLNdzcwCHnGfxKNnEz355KITADTxiIpBvnQW+eDHwQvIw6V2Oc73bKCu5ZirZmIMW5w6KjQVwkuQBoF9Koq/2u6VeevtL9pD6TBzSLMVw5pV3PmE4/C/eLiaUxZLIHdbzpqPkAvAUBrXKkj0ijzcNzCp1fuF8H0pvR8yQAAAIAmvV+kqWhUgDYwNNz1qDaoS8XdsOponutZ/0stRQ66mKAy8kNVNNQ6oUx1XFl1WUt4iyFY/2Rz2fZhLz5/TbZRK5ygo666WgnxB/Ud4GAx/BPQTghOJJOL00vJk+8jVCGNDc942V6nFXznDMXwqxhRCW6dm+2lTh7ntrli8mCk5g==", - "private": "-----BEGIN DSA PRIVATE KEY-----\nMIIBugIBAAKBgQCZ9iPGHn0aNwbBHop0LfCkOHBMgKwLO2P1u996EUmDiM1hdSbt\nduMrCq5oNqJL/tOQmHI1d2KeAM0HqJmAJYJgf+8QhJ1mhJ8QsAMZq6yTJj65MDYx\nziIu8jOUDhPdCDP0PiCQOBDwX0m/l6/H2Ia6edyjR1Up3NipDqqaNhbCIwIVALg2\nU/nQarJSqrYHzZWH/DmPdPPBAoGAHkhqJvSyzXc3MAh5xn8SjZxM9+eSiEwA08Yi\nKQb50Fvngx8ELyMOldjnO92ygruWYq2ZiDFucOio0FcJLkAaBfSqKv9rulXnr7S/\naQ+kwc0izFcOaVdz5hOPwv3i4mlMWSyB3W86aj5ALwFAa1ypI9Io83DcwqdX7hfB\n9Kb0fMkCgYAmvV+kqWhUgDYwNNz1qDaoS8XdsOponutZ/0stRQ66mKAy8kNVNNQ6\noUx1XFl1WUt4iyFY/2Rz2fZhLz5/TbZRK5ygo666WgnxB/Ud4GAx/BPQTghOJJOL\n00vJk+8jVCGNDc942V6nFXznDMXwqxhRCW6dm+2lTh7ntrli8mCk5gIUCJZKAMAz\nkyr2vl2Pe48adi8Vs9s=\n-----END DSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa deleted file mode 100644 index 4504f18..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa +++ /dev/null @@ -1,26 +0,0 @@ -PuTTY-User-Key-File-2: ssh-rsa -Encryption: none -Comment: rsa-key-20150522 -Public-Lines: 6 -AAAAB3NzaC1yc2EAAAABJQAAAQB1quqP0rhl78NOLD4lj+1x5FGAqZ3aqo6GiEPz -KOaQmy86FuJMK0nHj3gUKTa/Kvaa+8PZyeu+uVseHg47YrynCOcJEEnpqvbArc8M -xMWuUnTUMrjvokGDOBBiQu4UAE4bybpgXkNHJfbrcDVgivmv3Ikn8PVIZ1rLBMLZ -6Lzn0rjPjFD0X4WqsAJW2SFiZnsjMZtVL2TWadNTyyfjjm2NCRBvd32VLohkSe9Q -BZBD6MW8YQyBKUnEF/7WNY0eehDVrfx1YqPOV1bDwFUhRaAYpLDLDR0KCAPvx7qb -8G5Cq0TIBsEr3H8ztNRcOTQoaKgn0T18M7cyS4ykoNLYW4Zx -Private-Lines: 14 -AAABACyF3DZraF3sBLXLjSL4MFSblHXfUHxAiPSiQzlpa/9dUCPRTrUJddzOgHZU -yJtcXU9mLm4VDRe7wZyxbSs6Hd5WZUGzIuLLEUH8k4hKdE/MLDSdkhV7qhX5iaij -tAeRaammRoVUGXTd7rnzGx2cXnnkvkZ22VmqkQ6MLg1DTmWNfOO9cdwFGdQawf/n -yUV0nTkWsHXy5Qrozq9wRFk8eyw+pFllxqavsNftZX8VDiQt27JLZPTU4LGkH660 -3gq1KhNS/l05TlXnMZGjlcPN8UEaBzmCWRezhJSttjs5Kgp1K3yDf4ozMR/HWOCj -Jq8fd3VIgli6ML8yjr/c0A0T9MUAAACBAL1/byxHiCvY/2C+/L5T+ZZq13jdZuYK -MmOFaNITgEdNGWSIFYRzhLKGXj7awQWOIW6chj470GNOfQjFL1TvXhbwfqW6esDa -kETOYQPYQHZijABcn7uurMUm/bu5x/z9gYkAfniOCI5vmvMvJ09JcZ0iUmFWDZZY -fAutBvrt+n/vAAAAgQCe9jrA51wn1/wzKmWF+2+OWFUG9usheIcEbHB8mxLguLfU -+x4i+2vLo0FtXEPAw+Bt7Tge4t0m6USiVZXtW/QKsh0kMj4mNVHFz+XXw4l1QOYv -n5TjnLepiP7majXv4GHI2eOcHkyly4sIkj4jNLYqvT86hMxW4IC+jtJEWhn/nwAA -AIEAlJ8cExu2WrWukTDJQHrVegtvdJUhNjol2wLucPuWwSxKuB8FHYwaPRYRkf3d -DkZ53hhjJZ0BVkAaQ28uqM09xKD+q1H4/r0nnbtlV4uHLl3cCD5mGrH8I/iDPJX4 -fFIqCa0+n1D6RzvDqs1QIu+PGSp0K6vHOOS5fP0ZpuT025E= -Private-MAC: 4ca26008c85b901f4d2766b0924c25e527678d7e diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result deleted file mode 100644 index 9ac4d2f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "rsa-key-20150522", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBHzANBgkqhkiG9w0BAQEFAAOCAQwAMIIBBwKCAQB1quqP0rhl78NOLD4lj+1x\n5FGAqZ3aqo6GiEPzKOaQmy86FuJMK0nHj3gUKTa/Kvaa+8PZyeu+uVseHg47Yryn\nCOcJEEnpqvbArc8MxMWuUnTUMrjvokGDOBBiQu4UAE4bybpgXkNHJfbrcDVgivmv\n3Ikn8PVIZ1rLBMLZ6Lzn0rjPjFD0X4WqsAJW2SFiZnsjMZtVL2TWadNTyyfjjm2N\nCRBvd32VLohkSe9QBZBD6MW8YQyBKUnEF/7WNY0eehDVrfx1YqPOV1bDwFUhRaAY\npLDLDR0KCAPvx7qb8G5Cq0TIBsEr3H8ztNRcOTQoaKgn0T18M7cyS4ykoNLYW4Zx\nAgEl\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAABJQAAAQB1quqP0rhl78NOLD4lj+1x5FGAqZ3aqo6GiEPzKOaQmy86FuJMK0nHj3gUKTa/Kvaa+8PZyeu+uVseHg47YrynCOcJEEnpqvbArc8MxMWuUnTUMrjvokGDOBBiQu4UAE4bybpgXkNHJfbrcDVgivmv3Ikn8PVIZ1rLBMLZ6Lzn0rjPjFD0X4WqsAJW2SFiZnsjMZtVL2TWadNTyyfjjm2NCRBvd32VLohkSe9QBZBD6MW8YQyBKUnEF/7WNY0eehDVrfx1YqPOV1bDwFUhRaAYpLDLDR0KCAPvx7qb8G5Cq0TIBsEr3H8ztNRcOTQoaKgn0T18M7cyS4ykoNLYW4Zx", - "private": "-----BEGIN RSA PRIVATE KEY-----\nMIIEoAIBAAKCAQB1quqP0rhl78NOLD4lj+1x5FGAqZ3aqo6GiEPzKOaQmy86FuJM\nK0nHj3gUKTa/Kvaa+8PZyeu+uVseHg47YrynCOcJEEnpqvbArc8MxMWuUnTUMrjv\nokGDOBBiQu4UAE4bybpgXkNHJfbrcDVgivmv3Ikn8PVIZ1rLBMLZ6Lzn0rjPjFD0\nX4WqsAJW2SFiZnsjMZtVL2TWadNTyyfjjm2NCRBvd32VLohkSe9QBZBD6MW8YQyB\nKUnEF/7WNY0eehDVrfx1YqPOV1bDwFUhRaAYpLDLDR0KCAPvx7qb8G5Cq0TIBsEr\n3H8ztNRcOTQoaKgn0T18M7cyS4ykoNLYW4ZxAgElAoIBACyF3DZraF3sBLXLjSL4\nMFSblHXfUHxAiPSiQzlpa/9dUCPRTrUJddzOgHZUyJtcXU9mLm4VDRe7wZyxbSs6\nHd5WZUGzIuLLEUH8k4hKdE/MLDSdkhV7qhX5iaijtAeRaammRoVUGXTd7rnzGx2c\nXnnkvkZ22VmqkQ6MLg1DTmWNfOO9cdwFGdQawf/nyUV0nTkWsHXy5Qrozq9wRFk8\neyw+pFllxqavsNftZX8VDiQt27JLZPTU4LGkH6603gq1KhNS/l05TlXnMZGjlcPN\n8UEaBzmCWRezhJSttjs5Kgp1K3yDf4ozMR/HWOCjJq8fd3VIgli6ML8yjr/c0A0T\n9MUCgYEAvX9vLEeIK9j/YL78vlP5lmrXeN1m5goyY4Vo0hOAR00ZZIgVhHOEsoZe\nPtrBBY4hbpyGPjvQY059CMUvVO9eFvB+pbp6wNqQRM5hA9hAdmKMAFyfu66sxSb9\nu7nH/P2BiQB+eI4Ijm+a8y8nT0lxnSJSYVYNllh8C60G+u36f+8CgYEAnvY6wOdc\nJ9f8MyplhftvjlhVBvbrIXiHBGxwfJsS4Li31PseIvtry6NBbVxDwMPgbe04HuLd\nJulEolWV7Vv0CrIdJDI+JjVRxc/l18OJdUDmL5+U45y3qYj+5mo17+BhyNnjnB5M\npcuLCJI+IzS2Kr0/OoTMVuCAvo7SRFoZ/58CgYBM0sw0i7O+v8F6P5blYFBtaZWf\ns7QYEfjAkAfmdpvJ4Px03Tkn284DL439zk5AhbqGydWO2fqJH9HTH4HkKbCF1x6W\nNtfRpLcHIzwWUMAv/nAb0oXyJDg0QD1Z8V7qBehn+UgHXCz7eVp+Q4x6FtsIWgW4\nwgWCI99DAPT98cZrNwKBgBEvYEw0sAROs3snLZHxqzH7tipENRhgDpixxvi20ZvA\n8Ud1GAPIJ1RJACd/mJ83xTxQ/yXvAybNHC05r1fuQ+V7ChHAPhH37SokUDMAYeMp\nnFgs7YBj+C4A+PZQq+KUzE0Qovwe84eLoFP0ImSrwKqsrOO7VFxrTDBGyp+bCbrF\nAoGBAJSfHBMbtlq1rpEwyUB61XoLb3SVITY6JdsC7nD7lsEsSrgfBR2MGj0WEZH9\n3Q5Ged4YYyWdAVZAGkNvLqjNPcSg/qtR+P69J527ZVeLhy5d3Ag+Zhqx/CP4gzyV\n+HxSKgmtPp9Q+kc7w6rNUCLvjxkqdCurxzjkuXz9Gabk9NuR\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc deleted file mode 100644 index 6f2f7f7..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc +++ /dev/null @@ -1,18 +0,0 @@ -PuTTY-User-Key-File-2: ssh-rsa -Encryption: aes256-cbc -Comment: rsa-key-20141119 -Public-Lines: 4 -AAAAB3NzaC1yc2EAAAABJQAAAIBrBWETAVAyJmuNG53jwTNDlbIcH5lrEvcx6lx5 -bM6EKg0XmOIH96VqUjS7eRRTTD9lpBA8hYhkrOjOx93/JWB/pcVN8/B3DYHshT9O -BW1DCkrNwut2pbJ2oZOBirhhAr+xqWFr3551FqbzaCIXpOKubr4EcIwCipBl6PxL -USfHgw== -Private-Lines: 8 -8O3NrBePR4+4RHHys8wrRKCmgx3Gsdz1cKoRJJDgnnrQxuAxBTVUlVTC2vzSOXrP -jlKdRP9DbtrL5YF8g9HkMPpzzTdgpiEAGikpIc+L0sJhN+S9VvMoXRRKqyuB7o1C -xZhAeRaZ68izdUUbFd7ajUwBNpGoFppOznGXyf/3/Ao9FfoTKReZzeBd/e2/JFhc -nsYkSbtWfKQBVXF1Fhr10UwRWSMaVJSDkcSuk8ghICoKBBCgRBnZFap0SR77oIJh -DKgmNFktoKzEqh111vYPhQyEEyGNxpD0aEPaGUJEjPEd3C5a46n7mIiqrNX7QJoo -xxZtkueGdXWaoe5mBf1tFc+nCA1l72nUlghJZooQhnO9NPpieu6NNZ8X+tFQ1Rq/ -xvOZHzpDOOeOgWdV7oAmRDbDjYPh0H67z2OKCFaP0Z9kgmnwqV2IJvTDrexj1VwY -6kFaPldnK+ohXl37oVIlWA== -Private-MAC: 9d09a15a122e48955682ba969d33c75ba8e4be2c diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result deleted file mode 100644 index f9ff958..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "rsa-key-20141119", - "public": "-----BEGIN PUBLIC KEY-----\nMIGcMA0GCSqGSIb3DQEBAQUAA4GKADCBhgKBgGsFYRMBUDIma40bnePBM0OVshwf\nmWsS9zHqXHlszoQqDReY4gf3pWpSNLt5FFNMP2WkEDyFiGSs6M7H3f8lYH+lxU3z\n8HcNgeyFP04FbUMKSs3C63alsnahk4GKuGECv7GpYWvfnnUWpvNoIhek4q5uvgRw\njAKKkGXo/EtRJ8eDAgEl\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAABJQAAAIBrBWETAVAyJmuNG53jwTNDlbIcH5lrEvcx6lx5bM6EKg0XmOIH96VqUjS7eRRTTD9lpBA8hYhkrOjOx93/JWB/pcVN8/B3DYHshT9OBW1DCkrNwut2pbJ2oZOBirhhAr+xqWFr3551FqbzaCIXpOKubr4EcIwCipBl6PxLUSfHgw==", - "private": "-----BEGIN RSA PRIVATE KEY-----\nMIICWQIBAAKBgGsFYRMBUDIma40bnePBM0OVshwfmWsS9zHqXHlszoQqDReY4gf3\npWpSNLt5FFNMP2WkEDyFiGSs6M7H3f8lYH+lxU3z8HcNgeyFP04FbUMKSs3C63al\nsnahk4GKuGECv7GpYWvfnnUWpvNoIhek4q5uvgRwjAKKkGXo/EtRJ8eDAgElAoGA\nU+GfHLvXEozQ1mHA8MfcEmCShL7SMVQN2wPL8HfgImYl7+aHpWE8de1nmdtwy6p2\n4PY2PUYQ9PY57i3zL8NZd8WQ7Rg0RBHDlndaFeF4Ef0uLboqYd/xN0rzfy55z7hW\nOL+8VhoxTrBUvveOhZwBPkOeHfxmkVz3xbbrg3kNlo0CQQDJYPKtCs/l46KJmN3l\nUANdI4QIuWQ+Zllz7p94FfdotnkvqG++Bp1wOqJSCih6UViwLfvpNZtGMCtk46WN\nhc0zAkEAiAyN4WUs/0x4WovG956J1A+uSEKeWzuqfpGGbWgZ9XfnPnk+1Al8FOW1\ntu9WWrMPIavQnZW/dXxhkeNWTH78cQJBALkM+qzZgMVpZO0ksDqA4H8Zt5lQafQm\nsxCWFf+le5CnraFqWNghwRsFcpCTtn486bamy89hsUdqiL2S6ygaFoECQFDk3r1e\nwM8mjMA3b2LM+AGMyH3+GPf59qwfLVXPMgeTZubgTt7w4f6WbAvoQS8Crw0aDVbH\nvfLUVbCwr9p1BM0CQFSBjCa/fzeICVkPFBaKQUmXjQ3IcPTOr90mSAiPnAAppSwT\nj5SYSfE9rSVb+EhQ0hk2VKWIfocNHBD1MAN9zb4=\n-----END RSA PRIVATE KEY-----" -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub deleted file mode 100644 index 3bfd6e8..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub +++ /dev/null @@ -1,9 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -Comment: "2048-bit RSA" -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result deleted file mode 100644 index fcc0553..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "2048-bit RSA", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub deleted file mode 100644 index e42f5c1..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub +++ /dev/null @@ -1,10 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -Comment: 2048-bit RSA -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- - diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result deleted file mode 100644 index fcc0553..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "2048-bit RSA", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub deleted file mode 100644 index 24a107b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub +++ /dev/null @@ -1,11 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -Comment: this is a special \ -multi-line comment\ - how cool is that not? -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result deleted file mode 100644 index 25dae67..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "this is a special multi-line comment how cool is that not?", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub deleted file mode 100644 index 0454a85..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub +++ /dev/null @@ -1,11 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -Comment: "this is a special \ -multi-line comment\ - how cool is that not?" -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result deleted file mode 100644 index 25dae67..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "this is a special multi-line comment how cool is that not?", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub deleted file mode 100644 index 14608c1..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub +++ /dev/null @@ -1,8 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result deleted file mode 100644 index a61d779..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub deleted file mode 100644 index 24a2261..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub +++ /dev/null @@ -1,13 +0,0 @@ ----- BEGIN SSH2 PUBLIC KEY ---- -Subject: "nodejs" -x-foo: something\ -completely\ -different -Comment: "Foo bar baz" -AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKC -nbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCH -S/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1m -gJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW -61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc -9lK/C2jItA3fwq9PHfCM1D ----- END SSH2 PUBLIC KEY ---- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result b/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result deleted file mode 100644 index ed7a4f5..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "ssh-rsa", - "comment": "Foo bar baz", - "public": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4q6eZdx7LYh46PcZNcS3\nCnO7GuYsEJZeTj5LQSgp21IyTelaBPprijnMwKa+pLQt5TEobpKFFNecPdT6oPoO\nKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHMBNkoTFeGrursPkqYRJ0HL4CqYq\nRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKbzibJc64JFM7tUoK6Vl64\nYiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs8zjxsf6c6N2tKX\nkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38KvTx3wjN\nQwIDAQAB\n-----END PUBLIC KEY-----", - "publicSSH": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDirp5l3HstiHjo9xk1xLcKc7sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+lfQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg64MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1D", - "private": null -} diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/openssh_new_rsa b/reverse_engineering/node_modules/ssh2/test/fixtures/openssh_new_rsa deleted file mode 100644 index ccded2a..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/openssh_new_rsa +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn -NhAAAAAwEAAQAAAQEA4q6eZdx7LYh46PcZNcS3CnO7GuYsEJZeTj5LQSgp21IyTelaBPpr -ijnMwKa+pLQt5TEobpKFFNecPdT6oPoOKKMe6oH/pX0BNyAEB9KFZfZgh0v4J4IOiO0KHM -BNkoTFeGrursPkqYRJ0HL4CqYqRdINy1sgDU6jUIOuDD5XZzlpDXb1ftZoCei9OHSWrMKb -zibJc64JFM7tUoK6Vl64YiPgxsNXOJYMTrelVJYebtsNrJFmh3XXQABDVutWMYb8I6IrNs -8zjxsf6c6N2tKXkk9G4EDKKip4g0bzDmD/fREPQ9vLi59N+ZsyjWCKKE3PZSvwtoyLQN38 -KvTx3wjNQwAAA8hLhVBxS4VQcQAAAAdzc2gtcnNhAAABAQDirp5l3HstiHjo9xk1xLcKc7 -sa5iwQll5OPktBKCnbUjJN6VoE+muKOczApr6ktC3lMShukoUU15w91Pqg+g4oox7qgf+l -fQE3IAQH0oVl9mCHS/gngg6I7QocwE2ShMV4au6uw+SphEnQcvgKpipF0g3LWyANTqNQg6 -4MPldnOWkNdvV+1mgJ6L04dJaswpvOJslzrgkUzu1SgrpWXrhiI+DGw1c4lgxOt6VUlh5u -2w2skWaHdddAAENW61Yxhvwjois2zzOPGx/pzo3a0peST0bgQMoqKniDRvMOYP99EQ9D28 -uLn035mzKNYIooTc9lK/C2jItA3fwq9PHfCM1DAAAAAwEAAQAAAQAmShSbZBiyYkD6KPLr -MCUy8MWED6kVzDB1yvPvN5eKYmH44xe/i4UqvgSl7gR50a2G7zzDIKC2Go1brGQBWPuXRa -ZtOjQygeD4rMHBiH/b7zfy4pQyKDfITTHOFXWE8ERiyL00bAZt09icCy92rQaq8IY/+U56 -sPPJH9UAYG9nEev8opFjAWToFDu0U2+dC+lbqLlXDqDRo75NlnDFmgUoja3y2eFr9A0Cc+ -hjecrdxyJFsCJfEfaLWtBnZb886gqzzvfbHImSQtBAKERcSxuki7uxMoP67g3iQOXa65uz -8kFWRNmbQTGQttakoUaybh1t9eLpBqvVON/4Kg0THShRAAAAgFBTz2ajBK/R/crOSL9VK1 -f7oQv2iJTRVfnUs0r+qPGgf/a/5UwkGRj0KfEWBp3qYD+keShnPr6PDPFrm8UmIdUX8AY7 -3tWT2K/JQVlzJNuINsw+DNjn4M17Z25q0LPmReRWL0nRc2w6W/hmQ/Jmqz6w8Qc4+xpeqS -/HG5feliVnAAAAgQD90a+5Ky3o/2YtueqRf/3dKoiMgGB7JAOzye4dDKGABSlWuQ4N4xEI -CW5MSTp7i/uobTF/tyFO3tTSyb5b2Xwbn/kLO0vgvFCdUGR2BQfN3mcT92T0Gn3JDF3Wym -i2mgU6qnPf+eu+RKZQ9IiyNGny61ROUQa0R0z0pgiAfA89xwAAAIEA5KE9i6hHmigJwfD7 -/AGI4ujyWIVpNyrTdXG3HAPhsdoFuG5ggHggrPuuBF9wNcosrhL20VNOQGHg15gWZIVudu -0qxky4ivQs67Sk9XUjuvTnf+VubM51rIsmh4atKJFSSZo78DEcTRt8aXLrSNvGQ4WPRweM -2Z0YGfMMDM9KJKUAAAASbmV3IG9wZW5zc2ggZm9ybWF0AQ== ------END OPENSSH PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_dsa_key b/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_dsa_key deleted file mode 100644 index 5448947..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_dsa_key +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN DSA PRIVATE KEY----- -MIIBuwIBAAKBgQDEK+daQ7RuajwxkmBmogb0iUSi/w2RYKuvC2EiviBu3S2s9Bfq -gROKscAnURrxpTOa+iYeI7hRzfuX0qFmnFwXIjKJBjqBdg9r76UR5UNytnWQkJ5x -lxsZThMeAMw38SvmRMw15kkgxycKGqu4yvNLGyVwN02bPVjLcEVLWLCM1wIVAK50 -5JqF0nmGXFkcmNtxR24/mNXTAoGBAIc2p8C8b08OTQPmfZI+Wq8a+CuEr5R36bMW -TAs5etqmO2aVo5zvR0MnTjoS2ZDbuznDG9RiSuIB+ivr/daEwi+K+Ha8pZfYjXCG -ldzvmr5I4x8rkH3zyn7BADnc+/q3pa8AnZvTme5eNsxn1Pu/rmC/8KKnhmzRggqP -N8ORhoQQAoGAMCvoMcsDAui2d/WVpgHZZEFlxfbf4dPUPYb5zf2xOiMG9OK+Cbv3 -NaLZwk/Hd2g4L3nwTKDASxfmRcrbuaOg/d7aDjQ2mJz18Js4IjY34QpgLspGCNX/ -6rJSQ+ov1Z2Etr95N4Tzm3qpxW5BH9TTgaC/ntb9NRqIzNPCvAHXmlcCFBxgZpyb -4GUgmqhTOMtmBkJ7QpL9 ------END DSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key b/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key deleted file mode 100644 index 0476442..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key +++ /dev/null @@ -1,5 +0,0 @@ ------BEGIN EC PRIVATE KEY----- -MHcCAQEEICrdbIIYmW/XTK9hxaQZZ56IGwG0NhqD2eppYUJNZsECoAoGCCqGSM49 -AwEHoUQDQgAEa+MuLv++3ft5HPFIsM2hQnmHPF12q08/MaHoGud4yqp3evyomjZN -xbsSb39fv8t6XX1u1rm5oHQcBV5Mqomaeg== ------END EC PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_rsa_key b/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_rsa_key deleted file mode 100644 index 9c2cc6f..0000000 --- a/reverse_engineering/node_modules/ssh2/test/fixtures/ssh_host_rsa_key +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXAIBAAKBgQC57UB/5H0M+t+mopksrltCCIXghryzofJjau+8tuMT9CG6ta3S -O9aKApJUUG/xtc88giVhB7HFABX/oob+jrkSthR8s/whULC8E+GhvOBjHydRUZIs -aPYOMBb42HcbOsgq3li/hwOcDk0vY00hZDKCum9BgvRAb7dPEkw2dmiCQQIDAQAB -AoGAMG+HOwoaLbR5aR64yrQNYBF6Vvii1iUdURr9o2r9kygpVUuZIcim5kMvPbnK -v+w+NaQt+q4XeJvCH1uG0W/69FwnphfaOVmCCUtsoJ6sU3fWr9x59MtKL2Llh8xR -50lz6R+eDXoYRDq245hG9BFn/bu0vtqQqx06mlZJcjaRocECQQDjdYFmr+DSww3x -VNx0G0DUkaQZZ+iqZiT3Zund2pcBB4aLiewOrqj0GFct4+YNzgxIXPejmS0eSokN -N2lC3NxZAkEA0UGjN5TG5/LEK3zcYtx2kpXryenrYORo1n2L/WPMZ0mjLQyd4LJr -ibfgVUfwX/kV3vgGYLwjpgcaTiMsecv4KQJAYMmMgZSPdz+WvD1e/WznXkyG5mSn -xXJngnrhQw0TulVodBIBR5IcxJli510VdIRcB6K/oXa5ky0mOmB8wv3WKQJBAKEF -PxE//KbzWhyUogm4180IbD4dMDCI0ltqlFRRfTJlqZi6wqnq4XFB+u/kwYU4aKoA -dPfvDgduI8HIsyqt17ECQDI/HC8PiYsDIOyVpQuQdIAsbGmoavK7X1MVEWR2nj9t -7BbUVFSnVKynL4TWIJZ6xP8WQwkDBQc5WjognHDaUTQ= ------END RSA PRIVATE KEY----- diff --git a/reverse_engineering/node_modules/ssh2/test/test-exec.js b/reverse_engineering/node_modules/ssh2/test/test-exec.js deleted file mode 100644 index 86b2e31..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-exec.js +++ /dev/null @@ -1,578 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { inspect } = require('util'); - -const { - mustCall, - mustCallAtLeast, - setupSimple, -} = require('./common.js'); - -const DEBUG = false; - -const setup = setupSimple.bind(undefined, DEBUG); - -{ - const { client, server } = setup('Simple exec()'); - - const COMMAND = 'foo --bar'; - const STDOUT_DATA = 'stdout data!\n'; - const STDERR_DATA = 'stderr data!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === COMMAND, - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.stderr.write(STDERR_DATA); - stream.write(STDOUT_DATA); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let out = ''; - let outErr = ''; - const events = []; - const EXPECTED_EVENTS = [ 'exit', 'close' ]; - const EXPECTED_EXIT_CLOSE_ARGS = [ 100 ]; - client.on('close', mustCall(() => { - assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); - assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); - assert.deepStrictEqual( - events, - EXPECTED_EVENTS, - `Wrong command event order: ${events}` - ); - })).exec(COMMAND, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.on('data', mustCallAtLeast((d) => { - out += d; - })).on('exit', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong exit args: ${inspect(args)}`); - events.push('exit'); - })).on('close', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong close args: ${inspect(args)}`); - events.push('close'); - })).stderr.on('data', mustCallAtLeast((d) => { - outErr += d; - })); - })); - })); -} - -{ - const { client, server } = setup('Simple exec() (exit signal)'); - - const COMMAND = 'foo --bar'; - const STDOUT_DATA = 'stdout data!\n'; - const STDERR_DATA = 'stderr data!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === COMMAND, - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.stderr.write(STDERR_DATA); - stream.write(STDOUT_DATA); - assert.throws(() => stream.exit('SIGFAKE')); - stream.exit('SIGKILL'); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let out = ''; - let outErr = ''; - const events = []; - const EXPECTED_EVENTS = [ 'exit', 'close' ]; - const EXPECTED_EXIT_CLOSE_ARGS = [ null, 'SIGKILL', false, '' ]; - client.on('close', mustCall(() => { - assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); - assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); - assert.deepStrictEqual( - events, - EXPECTED_EVENTS, - `Wrong command event order: ${events}` - ); - })).exec(COMMAND, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.on('data', mustCallAtLeast((d) => { - out += d; - })).on('exit', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong exit args: ${inspect(args)}`); - events.push('exit'); - })).on('close', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong close args: ${inspect(args)}`); - events.push('close'); - })).stderr.on('data', mustCallAtLeast((d) => { - outErr += d; - })); - })); - })); -} - -{ - const { client, server } = setup('Simple exec() (exit signal -- no "SIG")'); - - const COMMAND = 'foo --bar'; - const STDOUT_DATA = 'stdout data!\n'; - const STDERR_DATA = 'stderr data!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === COMMAND, - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.stderr.write(STDERR_DATA); - stream.write(STDOUT_DATA); - assert.throws(() => stream.exit('FAKE')); - stream.exit('KILL'); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let out = ''; - let outErr = ''; - const events = []; - const EXPECTED_EVENTS = [ 'exit', 'close' ]; - const EXPECTED_EXIT_CLOSE_ARGS = [ null, 'SIGKILL', false, '' ]; - client.on('close', mustCall(() => { - assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); - assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); - assert.deepStrictEqual( - events, - EXPECTED_EVENTS, - `Wrong command event order: ${events}` - ); - })).exec(COMMAND, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.on('data', mustCallAtLeast((d) => { - out += d; - })).on('exit', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong exit args: ${inspect(args)}`); - events.push('exit'); - })).on('close', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong close args: ${inspect(args)}`); - events.push('close'); - })).stderr.on('data', mustCallAtLeast((d) => { - outErr += d; - })); - })); - })); -} - -{ - const { client, server } = setup('Exec with signal()'); - - const COMMAND = 'foo --bar'; - const STDOUT_DATA = 'stdout data!\n'; - const STDERR_DATA = 'stderr data!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let stream; - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === COMMAND, - `Wrong exec command: ${info.command}`); - stream = accept(); - stream.stderr.write(STDERR_DATA); - stream.write(STDOUT_DATA); - })).on('signal', mustCall((accept, reject, info) => { - assert(info.name === 'INT', `Wrong client signal name: ${info.name}`); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let out = ''; - let outErr = ''; - const events = []; - const EXPECTED_EVENTS = [ 'exit', 'close' ]; - const EXPECTED_EXIT_CLOSE_ARGS = [ 100 ]; - client.on('close', mustCall(() => { - assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); - assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); - assert.deepStrictEqual( - events, - EXPECTED_EVENTS, - `Wrong command event order: ${events}` - ); - })).exec(COMMAND, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - const sendSignal = (() => { - let sent = false; - return () => { - if (sent) - return; - sent = true; - assert.throws(() => stream.signal('FAKE')); - assert.throws(() => stream.signal('SIGFAKE')); - stream.signal('SIGINT'); - }; - })(); - stream.on('data', mustCallAtLeast((d) => { - out += d; - sendSignal(); - })).on('exit', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong exit args: ${inspect(args)}`); - events.push('exit'); - })).on('close', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong close args: ${inspect(args)}`); - events.push('close'); - })).stderr.on('data', mustCallAtLeast((d) => { - outErr += d; - })); - })); - })); -} - -{ - const { client, server } = setup('Exec with signal() -- no "SIG"'); - - const COMMAND = 'foo --bar'; - const STDOUT_DATA = 'stdout data!\n'; - const STDERR_DATA = 'stderr data!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let stream; - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === COMMAND, - `Wrong exec command: ${info.command}`); - stream = accept(); - stream.stderr.write(STDERR_DATA); - stream.write(STDOUT_DATA); - })).on('signal', mustCall((accept, reject, info) => { - assert(info.name === 'INT', `Wrong client signal name: ${info.name}`); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let out = ''; - let outErr = ''; - const events = []; - const EXPECTED_EVENTS = [ 'exit', 'close' ]; - const EXPECTED_EXIT_CLOSE_ARGS = [ 100 ]; - client.on('close', mustCall(() => { - assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); - assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); - assert.deepStrictEqual( - events, - EXPECTED_EVENTS, - `Wrong command event order: ${events}` - ); - })).exec(COMMAND, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - const sendSignal = (() => { - let sent = false; - return () => { - if (sent) - return; - sent = true; - stream.signal('INT'); - }; - })(); - stream.on('data', mustCallAtLeast((d) => { - out += d; - sendSignal(); - })).on('exit', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong exit args: ${inspect(args)}`); - events.push('exit'); - })).on('close', mustCall((...args) => { - assert.deepStrictEqual(args, - EXPECTED_EXIT_CLOSE_ARGS, - `Wrong close args: ${inspect(args)}`); - events.push('close'); - })).stderr.on('data', mustCallAtLeast((d) => { - outErr += d; - })); - })); - })); -} - -{ - const { client, server } = setup('Exec with environment set'); - - const env = { SSH2NODETEST: 'foo' }; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('env', mustCall((accept, reject, info) => { - accept && accept(); - assert(info.key === Object.keys(env)[0], - 'Wrong env key'); - assert(info.val === Object.values(env)[0], - 'Wrong env value'); - })).on('exec', mustCall((accept, reject, info) => { - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo --bar', { env }, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} - -{ - const { client, server } = setup('Exec with setWindow()'); - - const dimensions = { - rows: 60, - cols: 115, - height: 480, - width: 640, - }; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('window-change', mustCall((accept, reject, info) => { - accept && accept(); - assert.deepStrictEqual(info, dimensions, 'Wrong dimensions'); - })).on('exec', mustCall((accept, reject, info) => { - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo --bar', mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.setWindow(...Object.values(dimensions)); - stream.resume(); - })); - })); -} - -{ - const { client, server } = setup('Exec with pty set'); - - const pty = { - rows: 2, - cols: 4, - width: 0, - height: 0, - term: 'vt220', - modes: {}, - }; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let sawPty = false; - accept().on('pty', mustCall((accept, reject, info) => { - assert.deepStrictEqual(info, pty, 'Wrong pty info'); - sawPty = true; - accept && accept(); - })).on('exec', mustCall((accept, reject, info) => { - assert(sawPty, 'Expected pty to be set up'); - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo --bar', { pty }, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} - -{ - const { client, server } = setup('Exec with X11 forwarding'); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let sawX11 = false; - accept().on('x11', mustCall((accept, reject, info) => { - assert.strictEqual(info.single, - false, - `Wrong x11 single: ${info.single}`); - assert.strictEqual(info.screen, - 0, - `Wrong x11 screen: ${info.screen}`); - assert.strictEqual(info.protocol, - 'MIT-MAGIC-COOKIE-1', - `Wrong x11 protocol: ${info.protocol}`); - assert(Buffer.isBuffer(info.cookie), 'Expected cookie Buffer'); - assert.strictEqual( - info.cookie.length, - 32, - `Invalid x11 cookie length: ${info.cookie.length}` - ); - sawX11 = true; - accept && accept(); - })).on('exec', mustCall((accept, reject, info) => { - assert(sawX11, 'Expected x11 before exec'); - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - conn.x11('127.0.0.1', 4321, mustCall((err, xstream) => { - assert(!err, `Unexpected x11() error: ${err}`); - xstream.resume(); - xstream.on('end', mustCall(() => { - stream.exit(100); - stream.end(); - conn.end(); - })).end(); - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.on('x11', mustCall((info, accept, reject) => { - assert.strictEqual(info.srcIP, - '127.0.0.1', - `Invalid x11 srcIP: ${info.srcIP}`); - assert.strictEqual(info.srcPort, - 4321, - `Invalid x11 srcPort: ${info.srcPort}`); - accept(); - })).exec('foo --bar', { x11: true }, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} - -{ - const { client, server } = setup( - 'Exec with X11 forwarding (custom X11 settings)' - ); - - const x11 = { - single: true, - screen: 1234, - protocol: 'YUMMY-MAGIC-COOKIE-1', - cookie: '00112233445566778899001122334455', - }; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let sawX11 = false; - accept().on('x11', mustCall((accept, reject, info) => { - assert.strictEqual(info.single, - x11.single, - `Wrong x11 single: ${info.single}`); - assert.strictEqual(info.screen, - x11.screen, - `Wrong x11 screen: ${info.screen}`); - assert.strictEqual(info.protocol, - x11.protocol, - `Wrong x11 protocol: ${info.protocol}`); - assert(Buffer.isBuffer(info.cookie), 'Expected cookie Buffer'); - assert.strictEqual(info.cookie.toString(), - x11.cookie, - `Wrong x11 cookie: ${info.cookie}`); - sawX11 = true; - accept && accept(); - })).on('exec', mustCall((accept, reject, info) => { - assert(sawX11, 'Expected x11 before exec'); - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - conn.x11('127.0.0.1', 4321, mustCall((err, xstream) => { - assert(!err, `Unexpected x11() error: ${err}`); - xstream.resume(); - xstream.on('end', mustCall(() => { - stream.exit(100); - stream.end(); - conn.end(); - })).end(); - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.on('x11', mustCall((info, accept, reject) => { - assert.strictEqual(info.srcIP, - '127.0.0.1', - `Invalid x11 srcIP: ${info.srcIP}`); - assert.strictEqual(info.srcPort, - 4321, - `Invalid x11 srcPort: ${info.srcPort}`); - accept(); - })).exec('foo --bar', { x11 }, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-integration-openssh.js b/reverse_engineering/node_modules/ssh2/test/test-integration-openssh.js deleted file mode 100644 index 2baf682..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-integration-openssh.js +++ /dev/null @@ -1,481 +0,0 @@ -// TODO: add more rekey tests that at least include switching from no -// compression to compression and vice versa -'use strict'; - -const assert = require('assert'); -const { spawn, spawnSync } = require('child_process'); -const { chmodSync, readdirSync } = require('fs'); -const { join } = require('path'); -const readline = require('readline'); - -const Server = require('../lib/server.js'); - -const { - fixture, - fixtureKey, - FIXTURES_DIR, - mustCall, - mustCallAtLeast, -} = require('./common.js'); - -const SPAWN_OPTS = { windowsHide: true }; -const CLIENT_TIMEOUT = 5000; - -const debug = false; -const opensshPath = 'ssh'; -let opensshVer; - -// TODO: figure out why this test is failing on Windows -if (process.platform === 'win32') { - console.log('Skipping OpenSSH integration tests on Windows'); - process.exit(0); -} - -// Fix file modes to avoid OpenSSH client complaints about keys' permissions -for (const file of readdirSync(FIXTURES_DIR, { withFileTypes: true })) { - if (file.isFile()) - chmodSync(join(FIXTURES_DIR, file.name), 0o600); -} - -{ - // Get OpenSSH client version first - const { - error, stderr, stdout - } = spawnSync(opensshPath, ['-V'], SPAWN_OPTS); - - if (error) { - console.error('OpenSSH client is required for these tests'); - process.exitCode = 5; - return; - } - - const re = /^OpenSSH_([\d.]+)/; - let m = re.exec(stdout.toString()); - if (!m || !m[1]) { - m = re.exec(stderr.toString()); - if (!m || !m[1]) { - console.error('OpenSSH client is required for these tests'); - process.exitCode = 5; - return; - } - } - - opensshVer = m[1]; - console.log(`Testing with OpenSSH version: ${opensshVer}`); -} - - -// Key-based authentication -[ - { desc: 'RSA user key (old OpenSSH)', - clientKey: fixtureKey('id_rsa') }, - { desc: 'RSA user key (new OpenSSH)', - clientKey: fixtureKey('openssh_new_rsa') }, - { desc: 'DSA user key', - clientKey: fixtureKey('id_dsa') }, - { desc: 'ECDSA user key', - clientKey: fixtureKey('id_ecdsa') }, -].forEach((test) => { - const { desc, clientKey } = test; - const username = 'KeyUser'; - const { server } = setup( - desc, - { - client: { - username, - privateKeyPath: clientKey.fullPath, - }, - server: { hostKeys: [ fixture('ssh_host_rsa_key') ] }, - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCallAtLeast((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - case 3: - if (authAttempt === 3) - assert(ctx.signature, 'Missing publickey signature'); - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - default: - assert(false, 'Unexpected number of auth attempts'); - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - // We should not expect any further auth attempts after we verify a - // signature - authAttempt = Infinity; - } - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - })); - })); - })); -}); - - -// Different host key types -[ - { desc: 'RSA host key (old OpenSSH)', - hostKey: fixture('id_rsa') }, - { desc: 'RSA host key (new OpenSSH)', - hostKey: fixture('openssh_new_rsa') }, - { desc: 'DSA host key', - hostKey: fixture('ssh_host_dsa_key') }, - { desc: 'ECDSA host key', - hostKey: fixture('ssh_host_ecdsa_key') }, - { desc: 'PPK', - hostKey: fixture('id_rsa.ppk') }, -].forEach((test) => { - const { desc, hostKey } = test; - const clientKey = fixtureKey('openssh_new_rsa'); - const username = 'KeyUser'; - const { server } = setup( - desc, - { - client: { - username, - privateKeyPath: clientKey.fullPath, - }, - server: { hostKeys: [ hostKey ] }, - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCallAtLeast((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - case 3: - if (authAttempt === 3) - assert(ctx.signature, 'Missing publickey signature'); - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - default: - assert(false, 'Unexpected number of auth attempts'); - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - // We should not expect any further auth attempts after we verify a - // signature - authAttempt = Infinity; - } - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - })); - })); - })); -}); - - -// Various edge cases -{ - const clientKey = fixtureKey('openssh_new_rsa'); - const username = 'KeyUser'; - const { server } = setup( - 'Server closes stdin too early', - { - client: { - username, - privateKeyPath: clientKey.fullPath, - }, - server: { hostKeys: [ fixture('ssh_host_rsa_key') ] }, - debug, - } - ); - - server.on('_child', mustCall((childProc) => { - childProc.stderr.once('data', mustCall((data) => { - childProc.stdin.end(); - })); - childProc.stdin.write('ping'); - })).on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCallAtLeast((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - case 3: - if (authAttempt === 3) - assert(ctx.signature, 'Missing publickey signature'); - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - default: - assert(false, 'Unexpected number of auth attempts'); - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - // We should not expect any further auth attempts after we verify a - // signature - authAttempt = Infinity; - } - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject) => { - const stream = accept(); - stream.stdin.on('data', mustCallAtLeast((data) => { - stream.stdout.write('pong on stdout'); - stream.stderr.write('pong on stderr'); - })).on('end', mustCall(() => { - stream.stdout.write('pong on stdout'); - stream.stderr.write('pong on stderr'); - stream.exit(0); - stream.close(); - })); - })); - })); - })); - })); -} -{ - const clientKey = fixtureKey('openssh_new_rsa'); - const username = 'KeyUser'; - const { server } = setup( - 'Rekey', - { - client: { - username, - privateKeyPath: clientKey.fullPath, - }, - server: { hostKeys: [ fixture('ssh_host_rsa_key') ] }, - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCallAtLeast((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - case 3: - if (authAttempt === 3) - assert(ctx.signature, 'Missing publickey signature'); - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - default: - assert(false, 'Unexpected number of auth attempts'); - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - // We should not expect any further auth attempts after we verify a - // signature - authAttempt = Infinity; - } - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - const session = accept(); - conn.rekey(); - session.on('exec', mustCall((accept, reject) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - })); - })); - })); -} - - -function setup(title, configs) { - const { - client: clientCfg, - server: serverCfg, - allReady: allReady_, - timeout: timeout_, - debug, - noForceServerReady, - } = configs; - let clientClose = false; - let serverClose = false; - let serverReady = false; - let client; - const msg = (text) => { - return `${title}: ${text}`; - }; - - const timeout = (typeof timeout_ === 'number' - ? timeout_ - : CLIENT_TIMEOUT); - - const allReady = (typeof allReady_ === 'function' ? allReady_ : undefined); - - if (debug) { - serverCfg.debug = (...args) => { - console.log(`[${title}][SERVER]`, ...args); - }; - } - - const serverReadyFn = (noForceServerReady ? onReady : mustCall(onReady)); - const server = new Server(serverCfg); - - server.on('error', onError) - .on('connection', mustCall((conn) => { - conn.on('error', onError) - .on('ready', serverReadyFn); - server.close(); - })) - .on('close', mustCall(onClose)); - - function onError(err) { - const which = (arguments.length >= 3 ? 'client' : 'server'); - assert(false, msg(`Unexpected ${which} error: ${err}`)); - } - - function onReady() { - assert(!serverReady, msg('Received multiple ready events for server')); - serverReady = true; - allReady && allReady(); - } - - function onClose() { - if (arguments.length >= 3) { - assert(!clientClose, msg('Received multiple close events for client')); - clientClose = true; - } else { - assert(!serverClose, msg('Received multiple close events for server')); - serverClose = true; - } - } - - process.nextTick(mustCall(() => { - server.listen(0, 'localhost', mustCall(() => { - const args = [ - '-o', 'UserKnownHostsFile=/dev/null', - '-o', 'StrictHostKeyChecking=no', - '-o', 'CheckHostIP=no', - '-o', 'ConnectTimeout=3', - '-o', 'GlobalKnownHostsFile=/dev/null', - '-o', 'GSSAPIAuthentication=no', - '-o', 'IdentitiesOnly=yes', - '-o', 'BatchMode=yes', - '-o', 'VerifyHostKeyDNS=no', - - '-vvvvvv', - '-T', - '-o', 'KbdInteractiveAuthentication=no', - '-o', 'HostbasedAuthentication=no', - '-o', 'PasswordAuthentication=no', - '-o', 'PubkeyAuthentication=yes', - '-o', 'PreferredAuthentications=publickey' - ]; - - if (clientCfg.privateKeyPath) - args.push('-o', `IdentityFile=${clientCfg.privateKeyPath}`); - - if (!/^[0-6]\./.test(opensshVer)) { - // OpenSSH 7.0+ disables DSS/DSA host (and user) key support by - // default, so we explicitly enable it here - args.push('-o', 'HostKeyAlgorithms=+ssh-dss'); - args.push('-o', 'PubkeyAcceptedKeyTypes=+ssh-dss'); - } - - args.push('-p', server.address().port.toString(), - '-l', clientCfg.username, - 'localhost', - 'uptime'); - - client = spawn(opensshPath, args, SPAWN_OPTS); - server.emit('_child', client); - - if (debug) { - readline.createInterface({ - input: client.stdout - }).on('line', (line) => { - console.log(`[${title}][CLIENT][STDOUT]`, line); - }); - readline.createInterface({ - input: client.stderr - }).on('line', (line) => { - console.error(`[${title}][CLIENT][STDERR]`, line); - }); - } else { - client.stdout.resume(); - client.stderr.resume(); - } - - client.on('error', (err) => { - onError(err, null, null); - }).on('exit', (code) => { - clearTimeout(client.timer); - if (code !== 0) - return onError(new Error(`Non-zero exit code ${code}`), null, null); - onClose(null, null, null); - }); - - client.timer = setTimeout(() => { - assert(false, msg('Client timeout')); - }, timeout); - })); - })); - - return { server }; -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-misc-client-server.js b/reverse_engineering/node_modules/ssh2/test/test-misc-client-server.js deleted file mode 100644 index f875a7d..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-misc-client-server.js +++ /dev/null @@ -1,1428 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { createHash } = require('crypto'); -const http = require('http'); -const https = require('https'); -const net = require('net'); -const { Transform } = require('stream'); -const { inspect } = require('util'); - -const Client = require('../lib/client.js'); -const { - SSHTTPAgent: HTTPAgent, - SSHTTPSAgent: HTTPSAgent, -} = require('../lib/http-agents.js'); -const Server = require('../lib/server.js'); -const { KexInit } = require('../lib/protocol/kex.js'); - -const { - fixture, - mustCall, - mustCallAtLeast, - mustNotCall, - setup: setup_, - setupSimple, -} = require('./common.js'); - -const KEY_RSA_BAD = fixture('bad_rsa_private_key'); -const HOST_RSA_MD5 = '64254520742d3d0792e918f3ce945a64'; -const clientCfg = { username: 'foo', password: 'bar' }; -const serverCfg = { hostKeys: [ fixture('ssh_host_rsa_key') ] }; - -const debug = false; - -const setup = setupSimple.bind(undefined, debug); - - -{ - const { server } = setup_( - 'Verify host fingerprint (sync success, hostHash set)', - { - client: { - ...clientCfg, - hostHash: 'md5', - hostVerifier: mustCall((hash) => { - assert(hash === HOST_RSA_MD5, 'Host fingerprint mismatch'); - return true; - }), - }, - server: serverCfg, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} - -{ - const { server } = setup_( - 'Verify host fingerprint (sync success, hostHash not set)', - { - client: { - ...clientCfg, - hostVerifier: mustCall((key) => { - assert(Buffer.isBuffer(key), 'Expected buffer'); - let hash = createHash('md5'); - hash.update(key); - hash = hash.digest('hex'); - assert(hash === HOST_RSA_MD5, 'Host fingerprint mismatch'); - return true; - }), - }, - server: serverCfg, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} - -{ - const { server } = setup_( - 'Verify host fingerprint (async success)', - { - client: { - ...clientCfg, - hostVerifier: mustCall((key, cb) => { - assert(Buffer.isBuffer(key), 'Expected buffer'); - let hash = createHash('md5'); - hash.update(key); - hash = hash.digest('hex'); - assert(hash === HOST_RSA_MD5, 'Host fingerprint mismatch'); - process.nextTick(cb, true); - }), - }, - server: serverCfg, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} - -{ - const { client, server } = setup_( - 'Verify host fingerprint (sync failure)', - { - client: { - ...clientCfg, - hostVerifier: mustCall((key) => { - return false; - }), - }, - server: serverCfg, - - noForceClientReady: true, - noForceServerReady: true, - }, - ); - - client.removeAllListeners('error'); - client.on('ready', mustNotCall()) - .on('error', mustCall((err) => { - assert(/verification failed/.test(err.message), - 'Wrong client error message'); - })); - - server.on('connection', mustCall((conn) => { - conn.removeAllListeners('error'); - - conn.on('authentication', mustNotCall()) - .on('ready', mustNotCall()) - .on('error', mustCall((err) => { - assert(/KEY_EXCHANGE_FAILED/.test(err.message), - 'Wrong server error message'); - })); - })); -} - -{ - // connect() on connected client - - const clientCfg_ = { ...clientCfg }; - const client = new Client(); - const server = new Server(serverCfg); - - server.listen(0, 'localhost', mustCall(() => { - clientCfg_.host = 'localhost'; - clientCfg_.port = server.address().port; - client.connect(clientCfg_); - })); - - let connections = 0; - server.on('connection', mustCall((conn) => { - if (++connections === 2) - server.close(); - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => {})); - }, 2)).on('close', mustCall(() => {})); - - let reconnect = false; - client.on('ready', mustCall(() => { - if (reconnect) { - client.end(); - } else { - reconnect = true; - client.connect(clientCfg_); - } - }, 2)).on('close', mustCall(() => {}, 2)); -} - -{ - // Throw when not connected - - const client = new Client({ - username: 'foo', - password: 'bar', - }); - - assert.throws(mustCall(() => { - client.exec('uptime', mustNotCall()); - })); -} - -{ - const { client, server } = setup( - 'Outstanding callbacks called on disconnect' - ); - - server.on('connection', mustCall((conn) => { - conn.on('session', mustCall(() => {}, 3)); - })); - - client.on('ready', mustCall(() => { - function callback(err, stream) { - assert(err, 'Expected error'); - assert(err.message === 'No response from server', - `Wrong error message: ${err.message}`); - } - client.exec('uptime', mustCall(callback)); - client.shell(mustCall(callback)); - client.sftp(mustCall(callback)); - client.end(); - })); -} - -{ - const { client, server } = setup('Pipelined requests'); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - }, 3)); - })); - })); - - client.on('ready', mustCall(() => { - let calledBack = 0; - function callback(err, stream) { - assert(!err, `Unexpected error: ${err}`); - stream.resume(); - if (++calledBack === 3) - client.end(); - } - client.exec('foo', mustCall(callback)); - client.exec('bar', mustCall(callback)); - client.exec('baz', mustCall(callback)); - })); -} - -{ - const { client, server } = setup( - 'Pipelined requests with intermediate rekeying' - ); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - const reqs = []; - conn.on('session', mustCall((accept, reject) => { - if (reqs.length === 0) { - conn.rekey(mustCall((err) => { - assert(!err, `Unexpected rekey error: ${err}`); - reqs.forEach((accept) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - }); - })); - } - reqs.push(accept); - }, 3)); - })); - })); - - client.on('ready', mustCall(() => { - let calledBack = 0; - function callback(err, stream) { - assert(!err, `Unexpected error: ${err}`); - stream.resume(); - if (++calledBack === 3) - client.end(); - } - client.exec('foo', mustCall(callback)); - client.exec('bar', mustCall(callback)); - client.exec('baz', mustCall(callback)); - })); -} - -{ - const { client, server } = setup('Ignore outgoing after stream close'); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo', mustCall((err, stream) => { - assert(!err, `Unexpected error: ${err}`); - stream.on('exit', mustCall((code, signal) => { - client.end(); - })); - })); - })); -} - -{ - const { client, server } = setup_( - 'Double pipe on unconnected, passed in net.Socket', - { - client: { - ...clientCfg, - sock: new net.Socket(), - }, - server: serverCfg, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => {})); - })); - client.on('ready', mustCall(() => { - client.end(); - })); -} - -{ - const { client, server } = setup( - 'Client auto-rejects inbound connections to unknown bound address' - ); - - const assignedPort = 31337; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('request', mustCall((accept, reject, name, info) => { - assert(name === 'tcpip-forward', 'Wrong request name'); - assert.deepStrictEqual( - info, - { bindAddr: 'good', bindPort: 0 }, - 'Wrong request info' - ); - accept(assignedPort); - conn.forwardOut(info.bindAddr, - assignedPort, - 'remote', - 12345, - mustCall((err, ch) => { - assert(!err, `Unexpected error: ${err}`); - conn.forwardOut('bad', - assignedPort, - 'remote', - 12345, - mustCall((err, ch) => { - assert(err, 'Should receive error'); - client.end(); - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - // request forwarding - client.forwardIn('good', 0, mustCall((err, port) => { - assert(!err, `Unexpected error: ${err}`); - assert(port === assignedPort, 'Wrong assigned port'); - })); - })).on('tcp connection', mustCall((details, accept, reject) => { - assert.deepStrictEqual( - details, - { destIP: 'good', - destPort: assignedPort, - srcIP: 'remote', - srcPort: 12345 - }, - 'Wrong connection details' - ); - accept(); - })); -} - -{ - const { client, server } = setup( - 'Client auto-rejects inbound connections to unknown bound port' - ); - - const assignedPort = 31337; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('request', mustCall((accept, reject, name, info) => { - assert(name === 'tcpip-forward', 'Wrong request name'); - assert.deepStrictEqual( - info, - { bindAddr: 'good', bindPort: 0 }, - 'Wrong request info' - ); - accept(assignedPort); - conn.forwardOut(info.bindAddr, - assignedPort, - 'remote', - 12345, - mustCall((err, ch) => { - assert(!err, `Unexpected error: ${err}`); - conn.forwardOut(info.bindAddr, - 99999, - 'remote', - 12345, - mustCall((err, ch) => { - assert(err, 'Should receive error'); - client.end(); - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - // request forwarding - client.forwardIn('good', 0, mustCall((err, port) => { - assert(!err, `Unexpected error: ${err}`); - assert(port === assignedPort, 'Wrong assigned port'); - })); - })).on('tcp connection', mustCall((details, accept, reject) => { - assert.deepStrictEqual( - details, - { destIP: 'good', - destPort: assignedPort, - srcIP: 'remote', - srcPort: 12345 - }, - 'Wrong connection details' - ); - accept(); - })); -} - -{ - const GREETING = 'Hello world!'; - - const { client, server } = setup_( - 'Server greeting', - { - client: { - ...clientCfg, - ident: 'node.js rules', - }, - server: { - ...serverCfg, - greeting: GREETING, - } - }, - ); - - let sawGreeting = false; - - server.on('connection', mustCall((conn, info) => { - assert.deepStrictEqual(info.header, { - identRaw: 'SSH-2.0-node.js rules', - greeting: '', - versions: { - protocol: '2.0', - software: 'node.js' - }, - comments: 'rules' - }); - conn.on('handshake', mustCall((details) => { - assert(sawGreeting, 'Client did not see greeting before handshake'); - })).on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); - - client.on('greeting', mustCall((greeting) => { - assert.strictEqual(greeting, `${GREETING}\r\n`); - sawGreeting = true; - })).on('banner', mustNotCall()); -} - -{ - const { client, server } = setup_( - 'Correct ident parsing', - { - client: { - ...clientCfg, - ident: 'node.js rules\n', - }, - server: serverCfg, - - noServerError: true, - noClientError: true, - noForceServerReady: true, - noForceClientReady: true, - }, - ); - - server.on('connection', mustCall((conn, info) => { - assert.deepStrictEqual(info.header, { - identRaw: 'SSH-2.0-node.js rules', - greeting: '', - versions: { - protocol: '2.0', - software: 'node.js' - }, - comments: 'rules' - }); - conn.once('error', mustCall((err) => { - assert(/bad packet length/i.test(err.message), 'Wrong error message'); - })); - conn.on('handshake', mustNotCall()) - .on('authentication', mustNotCall()) - .on('ready', mustNotCall()); - })); - - client.on('greeting', mustNotCall()) - .on('banner', mustNotCall()) - .on('ready', mustNotCall()); -} - -{ - const BANNER = 'Hello world!'; - - const { client, server } = setup_( - 'Server banner', - { - client: clientCfg, - server: { - ...serverCfg, - banner: BANNER, - } - }, - ); - - let sawBanner = false; - - server.on('connection', mustCall((conn) => { - conn.on('handshake', mustCall((details) => { - assert(!sawBanner, 'Client saw banner too early'); - })).on('authentication', mustCall((ctx) => { - assert(sawBanner, 'Client did not see banner before auth'); - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); - - client.on('greeting', mustNotCall()) - .on('banner', mustCall((message) => { - assert.strictEqual(message, 'Hello world!\r\n'); - sawBanner = true; - })); -} - -{ - const { client, server } = setup( - 'Server responds to global requests in the right order' - ); - - function sendAcceptLater(accept) { - if (fastRejectSent) - accept(); - else - setImmediate(sendAcceptLater, accept); - } - - let fastRejectSent = false; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('request', mustCall((accept, reject, name, info) => { - if (info.bindAddr === 'fastReject') { - // Will call reject on 'fastReject' soon ... - reject(); - fastRejectSent = true; - } else { - // ... but accept on 'slowAccept' later - sendAcceptLater(accept); - } - }, 2)); - })); - })); - - client.on('ready', mustCall(() => { - let replyCnt = 0; - - client.forwardIn('slowAccept', 0, mustCall((err) => { - assert(!err, `Unexpected error: ${err}`); - if (++replyCnt === 2) - client.end(); - })); - - client.forwardIn('fastReject', 0, mustCall((err) => { - assert(err, 'Expected error'); - if (++replyCnt === 2) - client.end(); - })); - })); -} - -{ - const { client, server } = setup( - 'Cleanup outstanding channel requests on channel close' - ); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - const session = accept(); - session.on('subsystem', mustCall((accept, reject, info) => { - assert(info.name === 'netconf', `Wrong subsystem name: ${info.name}`); - - // XXX: hack to prevent success reply from being sent - conn._protocol.channelSuccess = () => {}; - - accept().close(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.subsys('netconf', mustCall((err, stream) => { - assert(err, 'Expected error'); - client.end(); - })); - })); -} - -{ - const { client, server } = setup_( - 'Handshake errors are emitted', - { - client: { - ...clientCfg, - algorithms: { cipher: [ 'aes128-cbc' ] }, - }, - server: { - ...serverCfg, - algorithms: { cipher: [ 'aes128-ctr' ] }, - }, - - noForceClientReady: true, - noForceServerReady: true, - }, - ); - - client.removeAllListeners('error'); - - function onError(err) { - assert.strictEqual(err.level, 'handshake'); - assert(/handshake failed/i.test(err.message), 'Wrong error message'); - } - - server.on('connection', mustCall((conn) => { - conn.removeAllListeners('error'); - - conn.on('authentication', mustNotCall()) - .on('ready', mustNotCall()) - .on('handshake', mustNotCall()) - .on('error', mustCall(onError)) - .on('close', mustCall(() => {})); - })); - - client.on('ready', mustNotCall()) - .on('error', mustCall(onError)) - .on('close', mustCall(() => {})); -} - -{ - const { client, server } = setup_( - 'Client signing errors are caught and emitted', - { - client: { - username: 'foo', - privateKey: KEY_RSA_BAD, - }, - server: serverCfg, - - noForceClientReady: true, - noForceServerReady: true, - }, - ); - - client.removeAllListeners('error'); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(!ctx.signature, 'Unexpected signature'); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - ctx.accept(); - break; - } - }, 2)).on('ready', mustNotCall()).on('close', mustCall(() => {})); - })); - - let cliError; - client.on('ready', mustNotCall()).on('error', mustCall((err) => { - if (cliError) { - assert(/all configured/i.test(err.message), 'Wrong error message'); - } else { - cliError = err; - assert(/signing/i.test(err.message), 'Wrong error message'); - } - }, 2)).on('close', mustCall(() => {})); -} - -{ - const { client, server } = setup_( - 'Server signing errors are caught and emitted', - { - client: clientCfg, - server: { hostKeys: [KEY_RSA_BAD] }, - - noForceClientReady: true, - noForceServerReady: true, - }, - ); - - client.removeAllListeners('error'); - - server.on('connection', mustCall((conn) => { - conn.removeAllListeners('error'); - - conn.on('error', mustCall((err) => { - assert(/signature generation failed/i.test(err.message), - 'Wrong error message'); - })).on('authentication', mustNotCall()) - .on('ready', mustNotCall()) - .on('close', mustCall(() => {})); - })); - - client.on('ready', mustNotCall()).on('error', mustCall((err) => { - assert(/KEY_EXCHANGE_FAILED/.test(err.message), 'Wrong error message'); - })).on('close', mustCall(() => {})); -} - -{ - const { client, server } = setup_( - 'Rekeying with AES-GCM', - { - client: { - ...clientCfg, - algorithms: { cipher: [ 'aes128-gcm@openssh.com' ] }, - }, - server: { - ...serverCfg, - algorithms: { cipher: [ 'aes128-gcm@openssh.com' ] }, - }, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - const reqs = []; - conn.on('session', mustCall((accept, reject) => { - if (reqs.length === 0) { - conn.rekey(mustCall((err) => { - assert(!err, `Unexpected rekey error: ${err}`); - reqs.forEach((accept) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - }); - })); - } - reqs.push(accept); - }, 3)); - })); - })); - - client.on('ready', mustCall(() => { - let calledBack = 0; - function callback(err, stream) { - assert(!err, `Unexpected error: ${err}`); - stream.resume(); - if (++calledBack === 3) - client.end(); - } - client.exec('foo', mustCall(callback)); - client.exec('bar', mustCall(callback)); - client.exec('baz', mustCall(callback)); - })); -} - -{ - const { client, server } = setup_( - 'Switch from no compression to compression', - { - client: { - ...clientCfg, - algorithms: { compress: [ 'none' ] }, - }, - server: { - ...serverCfg, - algorithms: { compress: [ 'none', 'zlib@openssh.com' ] }, - }, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - const reqs = []; - conn.on('session', mustCall((accept, reject) => { - if (reqs.length === 0) { - // XXX: hack to change algorithms after initial handshake - client._protocol._offer = new KexInit({ - kex: [ 'ecdh-sha2-nistp256' ], - serverHostKey: [ 'rsa-sha2-256' ], - cs: { - cipher: [ 'aes128-gcm@openssh.com' ], - mac: [], - compress: [ 'zlib@openssh.com' ], - lang: [], - }, - sc: { - cipher: [ 'aes128-gcm@openssh.com' ], - mac: [], - compress: [ 'zlib@openssh.com' ], - lang: [], - }, - }); - - conn.rekey(mustCall((err) => { - assert(!err, `Unexpected rekey error: ${err}`); - reqs.forEach((accept) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - }); - })); - } - reqs.push(accept); - }, 3)); - })); - })); - - let handshakes = 0; - client.on('handshake', mustCall((info) => { - switch (++handshakes) { - case 1: - assert(info.cs.compress === 'none', 'wrong compress value'); - assert(info.sc.compress === 'none', 'wrong compress value'); - break; - case 2: - assert(info.cs.compress === 'zlib@openssh.com', - 'wrong compress value'); - assert(info.sc.compress === 'zlib@openssh.com', - 'wrong compress value'); - break; - } - }, 2)).on('ready', mustCall(() => { - let calledBack = 0; - function callback(err, stream) { - assert(!err, `Unexpected error: ${err}`); - stream.resume(); - if (++calledBack === 3) - client.end(); - } - client.exec('foo', mustCall(callback)); - client.exec('bar', mustCall(callback)); - client.exec('baz', mustCall(callback)); - })); -} - -{ - const { client, server } = setup_( - 'Switch from compression to no compression', - { - client: { - ...clientCfg, - algorithms: { compress: [ 'zlib' ] }, - }, - server: { - ...serverCfg, - algorithms: { compress: [ 'zlib', 'none' ] }, - } - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - const reqs = []; - conn.on('session', mustCall((accept, reject) => { - if (reqs.length === 0) { - // XXX: hack to change algorithms after initial handshake - client._protocol._offer = new KexInit({ - kex: [ 'ecdh-sha2-nistp256' ], - serverHostKey: [ 'rsa-sha2-256' ], - cs: { - cipher: [ 'aes128-gcm@openssh.com' ], - mac: [], - compress: [ 'none' ], - lang: [], - }, - sc: { - cipher: [ 'aes128-gcm@openssh.com' ], - mac: [], - compress: [ 'none' ], - lang: [], - }, - }); - - conn.rekey(mustCall((err) => { - assert(!err, `Unexpected rekey error: ${err}`); - reqs.forEach((accept) => { - const session = accept(); - session.on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - stream.exit(0); - stream.end(); - })); - }); - })); - } - reqs.push(accept); - }, 3)); - })); - })); - - let handshakes = 0; - client.on('handshake', mustCall((info) => { - switch (++handshakes) { - case 1: - assert(info.cs.compress === 'zlib', 'wrong compress value'); - assert(info.sc.compress === 'zlib', 'wrong compress value'); - break; - case 2: - assert(info.cs.compress === 'none', 'wrong compress value'); - assert(info.sc.compress === 'none', 'wrong compress value'); - break; - } - }, 2)).on('ready', mustCall(() => { - let calledBack = 0; - function callback(err, stream) { - assert(!err, `Unexpected error: ${err}`); - stream.resume(); - if (++calledBack === 3) - client.end(); - } - client.exec('foo', mustCall(callback)); - client.exec('bar', mustCall(callback)); - client.exec('baz', mustCall(callback)); - })); -} - -{ - const { client, server } = setup_( - 'Large data compression', - { - client: { - ...clientCfg, - algorithms: { compress: [ 'zlib' ] }, - }, - server: { - ...serverCfg, - algorithms: { compress: [ 'zlib' ] }, - } - }, - ); - - const chunk = Buffer.alloc(1024 * 1024, 'a'); - const chunkCount = 10; - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject, info) => { - const stream = accept(); - for (let i = 0; i < chunkCount; ++i) - stream.write(chunk); - stream.exit(0); - stream.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo', mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - let nb = 0; - stream.on('data', mustCallAtLeast((data) => { - nb += data.length; - })).on('end', mustCall(() => { - assert(nb === (chunkCount * chunk.length), - `Wrong stream byte count: ${nb}`); - client.end(); - })); - })); - })); -} - -{ - const { client, server } = setup_( - 'Debug output', - { - client: { - ...clientCfg, - debug: mustCallAtLeast((msg) => { - assert(typeof msg === 'string', - `Wrong debug argument type: ${typeof msg}`); - assert(msg.length > 0, 'Unexpected empty debug message'); - }), - }, - server: { - ...serverCfg, - debug: mustCallAtLeast((msg) => { - assert(typeof msg === 'string', - `Wrong debug argument type: ${typeof msg}`); - assert(msg.length > 0, 'Unexpected empty debug message'); - }), - }, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('exec', mustCall((accept, reject, info) => { - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo --bar', mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} - -{ - const { server } = setup_( - 'HTTP agent', - { - // No automatic client, the agent will create one - - server: serverCfg, - - debug, - }, - ); - - let httpServer; - server.on('listening', () => { - httpServer = http.createServer((req, res) => { - httpServer.close(); - res.end('hello world!'); - }); - httpServer.listen(0, 'localhost', () => { - const agent = new HTTPAgent({ - host: 'localhost', - port: server.address().port, - username: 'foo', - password: 'bar', - }); - http.get({ - host: 'localhost', - port: httpServer.address().port, - agent, - headers: { Connection: 'close' }, - }, (res) => { - assert(res.statusCode === 200, - `Wrong http status code: ${res.statusCode}`); - let buf = ''; - res.on('data', mustCallAtLeast((chunk) => { - buf += chunk; - })).on('end', mustCall(() => { - assert(buf === 'hello world!', - `Wrong http response body: ${inspect(buf)}`); - })); - }); - }); - }); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('tcpip', mustCall((accept, reject, info) => { - assert(info.destIP === 'localhost', `Wrong destIP: ${info.destIP}`); - assert(info.destPort === httpServer.address().port, - `Wrong destPort: ${info.destPort}`); - assert(info.srcIP === 'localhost', `Wrong srcIP: ${info.srcIP}`); - - const stream = accept(); - const tcp = new net.Socket(); - tcp.pipe(stream).pipe(tcp); - tcp.connect(httpServer.address().port, 'localhost'); - })); - })); - })); -} - -{ - const { server } = setup_( - 'HTTPS agent', - { - // No automatic client, the agent will create one - - server: serverCfg, - - debug, - }, - ); - - let httpsServer; - server.on('listening', () => { - httpsServer = https.createServer({ - key: fixture('https_key.pem'), - cert: fixture('https_cert.pem'), - }, (req, res) => { - httpsServer.close(); - res.end('hello world!'); - }); - httpsServer.listen(0, 'localhost', () => { - const agent = new HTTPSAgent({ - host: 'localhost', - port: server.address().port, - username: 'foo', - password: 'bar', - }); - https.get({ - host: 'localhost', - port: httpsServer.address().port, - agent, - headers: { Connection: 'close' }, - ca: fixture('https_cert.pem'), - }, (res) => { - assert(res.statusCode === 200, - `Wrong http status code: ${res.statusCode}`); - let buf = ''; - res.on('data', mustCallAtLeast((chunk) => { - buf += chunk; - })).on('end', mustCall(() => { - assert(buf === 'hello world!', - `Wrong http response body: ${inspect(buf)}`); - })); - }).on('error', (err) => { - // This workaround is necessary for some reason on node < v14.x - if (!/write after end/i.test(err.message)) - throw err; - }); - }); - }); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('tcpip', mustCall((accept, reject, info) => { - assert(info.destIP === 'localhost', `Wrong destIP: ${info.destIP}`); - assert(info.destPort === httpsServer.address().port, - `Wrong destPort: ${info.destPort}`); - assert(info.srcIP === 'localhost', `Wrong srcIP: ${info.srcIP}`); - - const stream = accept(); - const tcp = new net.Socket(); - tcp.pipe(stream).pipe(tcp); - tcp.connect(httpsServer.address().port, 'localhost'); - })); - })); - })); -} - -[ - { desc: 'remove/append/prepend (regexps)', - config: { - remove: /.*/, - append: /gcm/, - prepend: /ctr/, - }, - expected: [ - 'aes128-ctr', - 'aes192-ctr', - 'aes256-ctr', - 'aes128-gcm', - 'aes128-gcm@openssh.com', - 'aes256-gcm', - 'aes256-gcm@openssh.com', - ], - }, - { desc: 'remove/append/prepend (strings)', - config: { - remove: /.*/, - append: 'aes256-ctr', - prepend: [ 'aes256-gcm', 'aes128-gcm' ], - }, - expected: [ - 'aes256-gcm', - 'aes128-gcm', - 'aes256-ctr', - ], - }, -].forEach((info) => { - const { client, server } = setup_( - `Client algorithms option (${info.desc})`, - { - client: { - ...clientCfg, - algorithms: { cipher: info.config }, - }, - server: serverCfg, - - debug, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); - client.on('ready', mustCall(() => { - // XXX: hack to easily verify computed offer - const offer = client._protocol._offer.lists; - assert.deepStrictEqual( - offer.cs.cipher.array, - info.expected, - `Wrong algorithm list: ${offer.cs.cipher.array}` - ); - })); -}); - -{ - const { client } = setup_( - `Safely end() from Client 'error' event handler`, - { - client: clientCfg, - noClientError: true, - noForceClientReady: true, - }, - ); - - const badServer = net.createServer((s) => {}); - badServer.listen(0, 'localhost', mustCall(() => { - badServer.unref(); - - client.on('error', mustCallAtLeast((err) => { - client.end(); - })).on('ready', mustNotCall()).on('close', mustCall(() => {})); - client.connect({ - host: 'localhost', - port: badServer.address().port, - user: 'foo', - password: 'bar', - readyTimeout: 1, - }); - })); -} - -{ - const { client } = setup_( - 'Client error should be emitted on bad/nonexistent greeting', - { - client: clientCfg, - noClientError: true, - noForceClientReady: true, - }, - ); - - const badServer = net.createServer(mustCall((s) => { - badServer.close(); - s.end(); - })).listen(0, 'localhost', mustCall(() => { - client.on('error', mustCall((err) => { - client.end(); - })).on('ready', mustNotCall()).on('close', mustCall(() => {})); - client.connect({ - host: 'localhost', - port: badServer.address().port, - user: 'foo', - password: 'bar', - }); - })); -} - -{ - const { client } = setup_( - 'Only one client error on connection failure', - { - client: clientCfg, - noClientError: true, - noForceClientReady: true, - }, - ); - - client.on('error', mustCall((err) => { - assert.strictEqual(err.syscall, 'getaddrinfo'); - })); - client.connect({ - host: 'blerbblubblubblerb', - port: 9999, - user: 'foo', - password: 'bar' - }); -} - -{ - const { client, server } = setup( - 'Client should remove reserved channels on incoming channel rejection' - ); - - const assignedPort = 31337; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('request', mustCall((accept, reject, name, info) => { - assert(name === 'tcpip-forward', 'Wrong request name'); - assert.deepStrictEqual( - info, - { bindAddr: 'good', bindPort: 0 }, - 'Wrong request info' - ); - accept(assignedPort); - conn.forwardOut(info.bindAddr, - assignedPort, - 'remote', - 12345, - mustCall((err, ch) => { - assert(err, 'Should receive error'); - client.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - // request forwarding - client.forwardIn('good', 0, mustCall((err, port) => { - assert(!err, `Unexpected error: ${err}`); - assert(port === assignedPort, 'Wrong assigned port'); - })); - })).on('tcp connection', mustCall((details, accept, reject) => { - assert.deepStrictEqual( - details, - { destIP: 'good', - destPort: assignedPort, - srcIP: 'remote', - srcPort: 12345 - }, - 'Wrong connection details' - ); - assert.strictEqual(Object.keys(client._chanMgr._channels).length, 1); - assert.strictEqual(client._chanMgr._count, 1); - reject(); - assert.strictEqual(Object.keys(client._chanMgr._channels).length, 0); - assert.strictEqual(client._chanMgr._count, 0); - })); -} - -{ - // Allow injected sockets - - const socket = new Transform({ - emitClose: true, - autoDestroy: true, - transform: (chunk, encoding, cb) => { - cb(); - }, - }); - socket.remoteAddress = '127.0.0.1'; - socket.remotePort = '12345'; - socket.remoteFamily = 'IPv4'; - socket.push(Buffer.from('SSH-2.0-foo\r\n')); - - const server = new Server(serverCfg); - server.on('connection', mustCall((conn, info) => { - assert.strictEqual(info.header.versions.software, 'foo'); - assert.strictEqual(info.ip, '127.0.0.1'); - assert.strictEqual(info.port, '12345'); - assert.strictEqual(info.family, 'IPv4'); - conn.on('ready', mustNotCall()); - conn.on('close', mustCall()); - socket.end(); - })); - server.injectSocket(socket); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-openssh.js b/reverse_engineering/node_modules/ssh2/test/test-openssh.js deleted file mode 100644 index 67e1b86..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-openssh.js +++ /dev/null @@ -1,261 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { inspect } = require('util'); - -const { - fixture, - mustCall, - mustCallAtLeast, - setup: setup_, -} = require('./common.js'); - -const debug = false; - -const clientCfg = { username: 'foo', password: 'bar' }; -const serverCfg = { hostKeys: [ fixture('ssh_host_rsa_key') ] }; - -{ - const { client, server } = setup_( - 'Exec with OpenSSH agent forwarding', - { - client: { - ...clientCfg, - agent: '/path/to/agent', - }, - server: serverCfg, - - debug, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let sawAuthAgent = false; - accept().on('auth-agent', mustCall((accept, reject) => { - sawAuthAgent = true; - accept && accept(); - })).on('exec', mustCall((accept, reject, info) => { - assert(sawAuthAgent, 'Expected auth-agent before exec'); - assert(info.command === 'foo --bar', - `Wrong exec command: ${info.command}`); - const stream = accept(); - stream.exit(100); - stream.end(); - conn.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.exec('foo --bar', { agentForward: true }, mustCall((err, stream) => { - assert(!err, `Unexpected exec error: ${err}`); - stream.resume(); - })); - })); -} - -{ - const { client, server } = setup_( - 'OpenSSH forwarded UNIX socket connection', - { - client: clientCfg, - server: { - ...serverCfg, - ident: 'OpenSSH_7.1', - }, - - debug, - }, - ); - - const socketPath = '/foo'; - const events = []; - const expected = [ - ['client', 'openssh_forwardInStreamLocal'], - ['server', 'streamlocal-forward@openssh.com', { socketPath }], - ['client', 'forward callback'], - ['client', 'unix connection', { socketPath }], - ['client', 'socket data', '1'], - ['server', 'socket data', '2'], - ['client', 'socket end'], - ['server', 'cancel-streamlocal-forward@openssh.com', { socketPath }], - ['client', 'cancel callback'] - ]; - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.once('request', mustCall((accept, reject, name, info) => { - events.push(['server', name, info]); - assert(name === 'streamlocal-forward@openssh.com', - `Wrong request name: ${name}`); - accept(); - conn.openssh_forwardOutStreamLocal(socketPath, - mustCall((err, ch) => { - assert(!err, `Unexpected error: ${err}`); - ch.write('1'); - ch.on('data', mustCallAtLeast((data) => { - events.push(['server', 'socket data', data.toString()]); - ch.close(); - })); - })); - - conn.on('request', mustCall((accept, reject, name, info) => { - events.push(['server', name, info]); - assert(name === 'cancel-streamlocal-forward@openssh.com', - `Wrong request name: ${name}`); - accept(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - // request forwarding - events.push(['client', 'openssh_forwardInStreamLocal']); - client.openssh_forwardInStreamLocal(socketPath, mustCall((err) => { - assert(!err, `Unexpected error: ${err}`); - events.push(['client', 'forward callback']); - })); - client.on('unix connection', mustCall((info, accept, reject) => { - events.push(['client', 'unix connection', info]); - const stream = accept(); - stream.on('data', mustCallAtLeast((data) => { - events.push(['client', 'socket data', data.toString()]); - stream.write('2'); - })).on('end', mustCall(() => { - events.push(['client', 'socket end']); - client.openssh_unforwardInStreamLocal(socketPath, - mustCall((err) => { - assert(!err, `Unexpected error: ${err}`); - events.push(['client', 'cancel callback']); - client.end(); - })); - })); - })); - })).on('close', mustCall(() => { - assert.deepStrictEqual( - events, - expected, - 'Events mismatch\n' - + `Actual:\n${inspect(events)}\n` - + `Expected:\n${inspect(expected)}` - ); - })); -} - -{ - const { client, server } = setup_( - 'OpenSSH UNIX socket connection', - { - client: clientCfg, - server: { - ...serverCfg, - ident: 'OpenSSH_8.0', - }, - - debug, - }, - ); - - const socketPath = '/foo/bar/baz'; - const response = 'Hello World'; - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('openssh.streamlocal', mustCall((accept, reject, info) => { - assert.deepStrictEqual( - info, - { socketPath }, - `Wrong info: ${inspect(info)}` - ); - - const stream = accept(); - stream.on('close', mustCall(() => { - client.end(); - })).end(response); - stream.resume(); - })); - })); - })); - - client.on('ready', mustCall(() => { - client.openssh_forwardOutStreamLocal(socketPath, mustCall((err, stream) => { - assert(!err, `Unexpected error: ${err}`); - let buf = ''; - stream.on('data', mustCallAtLeast((data) => { - buf += data; - })).on('close', mustCall(() => { - assert(buf === response, `Wrong response: ${inspect(buf)}`); - })); - })); - })); -} - -{ - const { client, server } = setup_( - 'OpenSSH 5.x workaround for binding on port 0', - { - client: clientCfg, - server: { - ...serverCfg, - ident: 'OpenSSH_5.3', - }, - - debug, - }, - ); - - const boundAddr = 'good'; - const boundPort = 1337; - const tcpInfo = { - destIP: boundAddr, - destPort: boundPort, - srcIP: 'remote', - srcPort: 12345, - }; - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('request', mustCall((accept, reject, name, info) => { - assert(name === 'tcpip-forward', `Unexpected request: ${name}`); - assert(info.bindAddr === boundAddr, `Wrong addr: ${info.bindAddr}`); - assert(info.bindPort === 0, `Wrong port: ${info.bindPort}`); - accept(boundPort); - conn.forwardOut(boundAddr, - 0, - tcpInfo.srcIP, - tcpInfo.srcPort, - mustCall((err, ch) => { - assert(!err, `Unexpected error: ${err}`); - client.end(); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - // request forwarding - client.forwardIn(boundAddr, 0, mustCall((err, port) => { - assert(!err, `Unexpected error: ${err}`); - assert(port === boundPort, `Bad bound port: ${port}`); - })); - })).on('tcp connection', mustCall((details, accept, reject) => { - assert.deepStrictEqual( - details, - tcpInfo, - `Wrong tcp details: ${inspect(details)}` - ); - accept(); - })); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-protocol-crypto.js b/reverse_engineering/node_modules/ssh2/test/test-protocol-crypto.js deleted file mode 100644 index 8cae94c..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-protocol-crypto.js +++ /dev/null @@ -1,609 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { randomBytes } = require('crypto'); - -const { - CIPHER_INFO, - MAC_INFO, - bindingAvailable, - NullCipher, - createCipher, - NullDecipher, - createDecipher, - init: cryptoInit, -} = require('../lib/protocol/crypto.js'); - -(async () => { - await cryptoInit; - - console.log(`Crypto binding ${bindingAvailable ? '' : 'not '}available`); - { - const PAIRS = [ - // cipher, decipher - ['native', 'native'], - ['binding', 'native'], - ['native', 'binding'], - ['binding', 'binding'], - ].slice(0, bindingAvailable ? 4 : 1); - - [ - { cipher: null }, - { cipher: 'chacha20-poly1305@openssh.com' }, - { cipher: 'aes128-gcm@openssh.com' }, - { cipher: 'aes128-cbc', mac: 'hmac-sha1-etm@openssh.com' }, - { cipher: 'aes128-ctr', mac: 'hmac-sha1' }, - { cipher: 'arcfour', mac: 'hmac-sha2-256-96' }, - ].forEach((testConfig) => { - for (const pair of PAIRS) { - function onCipherData(data) { - ciphered = Buffer.concat([ciphered, data]); - } - - function onDecipherPayload(payload) { - deciphered.push(payload); - } - - function reset() { - ciphered = Buffer.alloc(0); - deciphered = []; - } - - function reinit() { - if (testConfig.cipher === null) { - cipher = new NullCipher(1, onCipherData); - decipher = new NullDecipher(1, onDecipherPayload); - } else { - cipher = createCipher(config); - decipher = createDecipher(config); - } - } - - let ciphered; - let deciphered; - let cipher; - let decipher; - let macSize; - let packet; - let payload; - let cipherInfo; - let config; - - console.log('Testing cipher: %s, mac: %s (%s encrypt, %s decrypt) ...', - testConfig.cipher, - testConfig.mac - || (testConfig.cipher === null ? '' : ''), - pair[0], - pair[1]); - - if (testConfig.cipher === null) { - cipher = new NullCipher(1, onCipherData); - decipher = new NullDecipher(1, onDecipherPayload); - macSize = 0; - } else { - cipherInfo = CIPHER_INFO[testConfig.cipher]; - let macInfo; - let macKey; - if (testConfig.mac) { - macInfo = MAC_INFO[testConfig.mac]; - macKey = randomBytes(macInfo.len); - macSize = macInfo.actualLen; - } else if (cipherInfo.authLen) { - macSize = cipherInfo.authLen; - } else { - throw new Error('Missing MAC for cipher'); - } - const key = randomBytes(cipherInfo.keyLen); - const iv = (cipherInfo.ivLen - ? randomBytes(cipherInfo.ivLen) - : Buffer.alloc(0)); - config = { - outbound: { - onWrite: onCipherData, - cipherInfo, - cipherKey: Buffer.from(key), - cipherIV: Buffer.from(iv), - seqno: 1, - macInfo, - macKey: (macKey && Buffer.from(macKey)), - forceNative: (pair[0] === 'native'), - }, - inbound: { - onPayload: onDecipherPayload, - decipherInfo: cipherInfo, - decipherKey: Buffer.from(key), - decipherIV: Buffer.from(iv), - seqno: 1, - macInfo, - macKey: (macKey && Buffer.from(macKey)), - forceNative: (pair[1] === 'native'), - }, - }; - cipher = createCipher(config); - decipher = createDecipher(config); - - if (pair[0] === 'binding') - assert(/binding/i.test(cipher.constructor.name)); - else - assert(/native/i.test(cipher.constructor.name)); - if (pair[1] === 'binding') - assert(/binding/i.test(decipher.constructor.name)); - else - assert(/native/i.test(decipher.constructor.name)); - } - - let expectedSeqno; - // Test zero-length payload ============================================ - payload = Buffer.alloc(0); - expectedSeqno = 2; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test single byte payload ============================================ - payload = Buffer.from([ 0xEF ]); - expectedSeqno = 3; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, 3); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test large payload ================================================== - payload = randomBytes(32 * 1024); - expectedSeqno = 4; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test sequnce number rollover ======================================== - payload = randomBytes(4); - expectedSeqno = 0; - cipher.outSeqno = decipher.inSeqno = (2 ** 32) - 1; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test chunked input -- split length bytes ============================ - payload = randomBytes(32 * 768); - expectedSeqno = 1; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, 2), undefined); - assert.strictEqual(decipher.decrypt(ciphered, 2, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test chunked input -- split length from payload ===================== - payload = randomBytes(32 * 768); - expectedSeqno = 2; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual(decipher.decrypt(ciphered, 0, 4), undefined); - assert.strictEqual(decipher.decrypt(ciphered, 4, ciphered.length), - undefined); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test chunked input -- split length and payload from MAC ============= - payload = randomBytes(32 * 768); - expectedSeqno = 3; - - reset(); - packet = cipher.allocPacket(payload.length); - payload.copy(packet, 5); - cipher.encrypt(packet); - assert.strictEqual( - decipher.decrypt(ciphered, 0, ciphered.length - macSize), - undefined - ); - assert.strictEqual( - decipher.decrypt(ciphered, - ciphered.length - macSize, - ciphered.length), - undefined - ); - - assert.strictEqual(cipher.outSeqno, expectedSeqno); - assert(ciphered.length >= 9 + macSize); - assert.strictEqual(decipher.inSeqno, cipher.outSeqno); - assert.strictEqual(deciphered.length, 1); - assert.deepStrictEqual(deciphered[0], payload); - - // Test packet length checks =========================================== - [0, 2 ** 32 - 1].forEach((n) => { - reset(); - packet = cipher.allocPacket(0); - packet.writeUInt32BE(n, 0); // Overwrite packet length field - cipher.encrypt(packet); - let threw = false; - try { - decipher.decrypt(ciphered, 0, ciphered.length); - } catch (ex) { - threw = true; - assert(ex instanceof Error); - assert(/packet length/i.test(ex.message)); - } - if (!threw) - throw new Error('Expected error'); - - // Recreate deciphers since errors leave them in an unusable state. - // We recreate the ciphers as well so that internal states of both - // ends match again. - reinit(); - }); - - // Test minimum padding length check =================================== - if (testConfig.cipher !== null) { - let payloadLen; - const blockLen = cipherInfo.blockLen; - if (/chacha|gcm/i.test(testConfig.cipher) - || /etm/i.test(testConfig.mac)) { - payloadLen = blockLen - 2; - } else { - payloadLen = blockLen - 6; - } - const minLen = 4 + 1 + payloadLen + (blockLen + 1); - // We don't do strict equality checks here since the length of the - // returned Buffer can vary due to implementation details. - assert(cipher.allocPacket(payloadLen).length >= minLen); - } - - // ===================================================================== - cipher.free(); - decipher.free(); - if (testConfig.cipher === null) - break; - } - }); - } - - // Test createCipher()/createDecipher() exceptions - { - [ - [ - [true, null], - /invalid config/i - ], - [ - [{}], - [/invalid outbound/i, /invalid inbound/i] - ], - [ - [{ outbound: {}, inbound: {} }], - [/invalid outbound\.onWrite/i, /invalid inbound\.onPayload/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: true - }, - inbound: { - onPayload: () => {}, - decipherInfo: true - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: null - }, - inbound: { - onPayload: () => {}, - decipherInfo: null - }, - }, - ], - [/invalid outbound\.cipherInfo/i, /invalid inbound\.decipherInfo/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: {}, - cipherKey: {}, - }, - inbound: { - onPayload: () => {}, - decipherInfo: {}, - decipherKey: {}, - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 32 }, - cipherKey: Buffer.alloc(8), - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 32 }, - decipherKey: Buffer.alloc(8), - }, - }, - ], - [/invalid outbound\.cipherKey/i, /invalid inbound\.decipherKey/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 12 }, - cipherKey: Buffer.alloc(1), - cipherIV: true - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 12 }, - decipherKey: Buffer.alloc(1), - cipherIV: true - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 12 }, - cipherKey: Buffer.alloc(1), - cipherIV: null - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 12 }, - decipherKey: Buffer.alloc(1), - cipherIV: null - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 12 }, - cipherKey: Buffer.alloc(1), - cipherIV: {} - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 12 }, - decipherKey: Buffer.alloc(1), - cipherIV: {} - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 12 }, - cipherKey: Buffer.alloc(1), - cipherIV: Buffer.alloc(1) - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 12 }, - decipherKey: Buffer.alloc(1), - cipherIV: Buffer.alloc(1) - }, - }, - ], - [/invalid outbound\.cipherIV/i, /invalid inbound\.decipherIV/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0 }, - cipherKey: Buffer.alloc(1), - seqno: true - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0 }, - decipherKey: Buffer.alloc(1), - seqno: true - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0 }, - cipherKey: Buffer.alloc(1), - seqno: -1 - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0 }, - decipherKey: Buffer.alloc(1), - seqno: -1 - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0 }, - cipherKey: Buffer.alloc(1), - seqno: 2 ** 32 - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0 }, - decipherKey: Buffer.alloc(1), - seqno: 2 ** 32 - }, - }, - ], - [/invalid outbound\.seqno/i, /invalid inbound\.seqno/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0 - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0 - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: true - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: true - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: null - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: null - }, - }, - ], - [/invalid outbound\.macInfo/i, /invalid inbound\.macInfo/i] - ], - [ - [ - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 } - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 } - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: true - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: true - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: null - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: null - }, - }, - { outbound: { - onWrite: () => {}, - cipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - cipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: Buffer.alloc(1) - }, - inbound: { - onPayload: () => {}, - decipherInfo: { keyLen: 1, ivLen: 0, sslName: 'foo' }, - decipherKey: Buffer.alloc(1), - seqno: 0, - macInfo: { keyLen: 16 }, - macKey: Buffer.alloc(1) - }, - }, - ], - [/invalid outbound\.macKey/i, /invalid inbound\.macKey/i] - ], - ].forEach((testCase) => { - let errorChecks = testCase[1]; - if (!Array.isArray(errorChecks)) - errorChecks = [errorChecks[0], errorChecks[0]]; - for (const input of testCase[0]) { - assert.throws(() => createCipher(input), errorChecks[0]); - assert.throws(() => createDecipher(input), errorChecks[1]); - } - }); - } -})(); diff --git a/reverse_engineering/node_modules/ssh2/test/test-protocol-keyparser.js b/reverse_engineering/node_modules/ssh2/test/test-protocol-keyparser.js deleted file mode 100644 index 850d405..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-protocol-keyparser.js +++ /dev/null @@ -1,145 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { readdirSync, readFileSync } = require('fs'); -const { inspect } = require('util'); - -const { parseKey } = require('../lib/protocol/keyParser.js'); - -const { EDDSA_SUPPORTED } = require('../lib/protocol/constants.js'); - -const BASE_PATH = `${__dirname}/fixtures/keyParser`; - -function failMsg(name, message, exit) { - const msg = `[${name}] ${message}`; - if (!exit) - return msg; - console.error(msg); - process.exit(1); -} - -readdirSync(BASE_PATH).forEach((name) => { - if (/\.result$/i.test(name)) - return; - if (/ed25519/i.test(name) && !EDDSA_SUPPORTED) - return; - - const isPublic = /\.pub$/i.test(name); - const isEncrypted = /_enc/i.test(name); - const isPPK = /^ppk_/i.test(name); - const key = readFileSync(`${BASE_PATH}/${name}`); - let res; - if (isEncrypted) - res = parseKey(key, (isPPK ? 'node.js' : 'password')); - else - res = parseKey(key); - let expected = JSON.parse( - readFileSync(`${BASE_PATH}/${name}.result`, 'utf8') - ); - if (typeof expected === 'string') { - if (!(res instanceof Error)) - failMsg(name, `Expected error: ${expected}`, true); - assert.strictEqual( - expected, - res.message, - failMsg(name, - 'Error message mismatch.\n' - + `Expected: ${inspect(expected)}\n` - + `Received: ${inspect(res.message)}`) - ); - } else if (res instanceof Error) { - failMsg(name, `Unexpected error: ${res.stack}`, true); - } else { - if (Array.isArray(expected) && !Array.isArray(res)) - failMsg(name, 'Expected array but did not receive one', true); - if (!Array.isArray(expected) && Array.isArray(res)) - failMsg(name, 'Received array but did not expect one', true); - - if (!Array.isArray(res)) { - res = [res]; - expected = [expected]; - } else if (res.length !== expected.length) { - failMsg(name, - `Expected ${expected.length} keys, but received ${res.length}`, - true); - } - - res.forEach((curKey, i) => { - const details = { - type: curKey.type, - comment: curKey.comment, - public: curKey.getPublicPEM(), - publicSSH: curKey.getPublicSSH() - && curKey.getPublicSSH().toString('base64'), - private: curKey.getPrivatePEM() - }; - assert.deepStrictEqual( - details, - expected[i], - failMsg(name, - 'Parser output mismatch.\n' - + `Expected: ${inspect(expected[i])}\n\n` - + `Received: ${inspect(details)}`) - ); - }); - } - - if (isEncrypted && !isPublic) { - // Make sure parsing encrypted keys without a passhprase or incorrect - // passphrase results in an appropriate error - const err = parseKey(key); - if (!(err instanceof Error)) - failMsg(name, 'Expected error during parse without passphrase', true); - if (!/no passphrase/i.test(err.message)) { - failMsg(name, - `Error during parse without passphrase: ${err.message}`, - true); - } - } - - if (!isPublic) { - // Try signing and verifying to make sure the private/public key PEMs are - // correct - const data = Buffer.from('hello world'); - res.forEach((curKey) => { - let result = curKey.sign(data); - if (result instanceof Error) { - failMsg(name, - `Error while signing data with key: ${result.message}`, - true); - } - result = curKey.verify(data, result); - if (result instanceof Error) { - failMsg(name, - `Error while verifying signed data with key: ${result.message}`, - true); - } - if (!result) - failMsg(name, 'Failed to verify signed data with key', true); - }); - if (res.length === 1 && !isPPK) { - const pubFile = readFileSync(`${BASE_PATH}/${name}.pub`); - const pubParsed = parseKey(pubFile); - if (!(pubParsed instanceof Error)) { - let result = res[0].sign(data); - if (result instanceof Error) { - failMsg(name, - `Error while signing data with key: ${result.message}`, - true); - } - result = pubParsed.verify(data, result); - if (result instanceof Error) { - failMsg(name, - 'Error while verifying signed data with separate public key: ' - + result.message, - true); - } - if (!result) { - failMsg(name, - 'Failed to verify signed data with separate public key', - true); - } - } - } - } -}); diff --git a/reverse_engineering/node_modules/ssh2/test/test-server-hostkeys.js b/reverse_engineering/node_modules/ssh2/test/test-server-hostkeys.js deleted file mode 100644 index 3093864..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-server-hostkeys.js +++ /dev/null @@ -1,136 +0,0 @@ -'use strict'; - -const assert = require('assert'); - -const { - fixtureKey, - mustCall, - setup, -} = require('./common.js'); - -const debug = false; - -[ - { desc: 'RSA user key (old OpenSSH)', - hostKey: fixtureKey('id_rsa') }, - { desc: 'RSA user key (new OpenSSH)', - hostKey: fixtureKey('openssh_new_rsa') }, - { desc: 'DSA host key', - hostKey: fixtureKey('ssh_host_dsa_key') }, - { desc: 'ECDSA host key', - hostKey: fixtureKey('ssh_host_ecdsa_key') }, - { desc: 'PPK', - hostKey: fixtureKey('id_rsa.ppk') }, -].forEach((test) => { - const { desc, hostKey } = test; - const clientKey = fixtureKey('openssh_new_rsa'); - const username = 'KeyUser'; - const { server } = setup( - desc, - { - client: { - username, - privateKey: clientKey.raw, - algorithms: { - serverHostKey: [ hostKey.key.type ], - } - }, - server: { hostKeys: [ hostKey.raw ] }, - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.signature, 'Missing publickey signature'); - // FALLTHROUGH - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - conn.end(); - })); - })); -}); - - -{ - const RSA_KEY = fixtureKey('ssh_host_rsa_key'); - const ECDSA_KEY = fixtureKey('ssh_host_ecdsa_key'); - [ RSA_KEY, ECDSA_KEY ].forEach((key) => { - const selKeyType = key.key.type; - const clientKey = fixtureKey('openssh_new_rsa'); - const username = 'KeyUser'; - const { client, server } = setup( - `Multiple host key types (${key.type} selected)`, - { - client: { - username, - privateKey: clientKey.raw, - algorithms: { - serverHostKey: [ selKeyType ], - } - }, - server: { hostKeys: [ RSA_KEY.raw, ECDSA_KEY.raw ] }, - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.signature, 'Missing publickey signature'); - // FALLTHROUGH - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - conn.end(); - })); - })); - client.on('handshake', mustCall((info) => { - assert(info.serverHostKey === selKeyType, 'Wrong host key selected'); - })); - }); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-sftp.js b/reverse_engineering/node_modules/ssh2/test/test-sftp.js deleted file mode 100644 index 50e56f5..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-sftp.js +++ /dev/null @@ -1,782 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { constants } = require('fs'); - -const { - fixture, - mustCall, - mustCallAtLeast, - mustNotCall, - setup: setup_, - setupSimple -} = require('./common.js'); - -const { OPEN_MODE, Stats, STATUS_CODE } = require('../lib/protocol/SFTP.js'); - -const DEBUG = false; - -setup('open', mustCall((client, server) => { - const path_ = '/tmp/foo.txt'; - const handle_ = Buffer.from('node.js'); - const pflags_ = (OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE); - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === pflags_, `Wrong flags: ${flagsToHuman(pflags)}`); - server.handle(id, handle_); - server.end(); - })); - client.open(path_, 'w', mustCall((err, handle) => { - assert(!err, `Unexpected open() error: ${err}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - })); -})); - -setup('close', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - server.on('CLOSE', mustCall((id, handle) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.close(handle_, mustCall((err) => { - assert(!err, `Unexpected close() error: ${err}`); - })); -})); - -setup('read', mustCall((client, server) => { - const expected = Buffer.from('node.jsnode.jsnode.jsnode.jsnode.jsnode.js'); - const handle_ = Buffer.from('node.js'); - const buf = Buffer.alloc(expected.length); - server.on('READ', mustCall((id, handle, offset, len) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert(offset === 5, `Wrong read offset: ${offset}`); - assert(len === buf.length, `Wrong read len: ${len}`); - server.data(id, expected); - server.end(); - })); - client.read(handle_, buf, 0, buf.length, 5, mustCall((err, nb) => { - assert(!err, `Unexpected read() error: ${err}`); - assert.deepStrictEqual(buf, expected, 'read data mismatch'); - })); -})); - -setup('read (overflow)', mustCall((client, server) => { - const maxChunk = client._maxReadLen; - const expected = Buffer.alloc(3 * maxChunk, 'Q'); - const handle_ = Buffer.from('node.js'); - const buf = Buffer.alloc(expected.length, 0); - let reqs = 0; - server.on('READ', mustCall((id, handle, offset, len) => { - ++reqs; - assert.strictEqual(id, reqs - 1, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert.strictEqual(offset, - (reqs - 1) * maxChunk, - `Wrong read offset: ${offset}`); - server.data(id, expected.slice(offset, offset + len)); - if (reqs === 3) - server.end(); - }, 3)); - client.read(handle_, buf, 0, buf.length, 0, mustCall((err, nb) => { - assert(!err, `Unexpected read() error: ${err}`); - assert.deepStrictEqual(buf, expected); - assert.strictEqual(nb, buf.length, 'read nb mismatch'); - })); -})); - -setup('write', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const buf = Buffer.from('node.jsnode.jsnode.jsnode.jsnode.jsnode.js'); - server.on('WRITE', mustCall((id, handle, offset, data) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert(offset === 5, `Wrong write offset: ${offset}`); - assert.deepStrictEqual(data, buf, 'write data mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.write(handle_, buf, 0, buf.length, 5, mustCall((err, nb) => { - assert(!err, `Unexpected write() error: ${err}`); - assert.strictEqual(nb, buf.length, 'wrong bytes written'); - })); -})); - -setup('write (overflow)', mustCall((client, server) => { - const maxChunk = client._maxWriteLen; - const handle_ = Buffer.from('node.js'); - const buf = Buffer.allocUnsafe(3 * maxChunk); - let reqs = 0; - server.on('WRITE', mustCall((id, handle, offset, data) => { - ++reqs; - assert.strictEqual(id, reqs - 1, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert.strictEqual(offset, - (reqs - 1) * maxChunk, - `Wrong write offset: ${offset}`); - assert((offset + data.length) <= buf.length, 'bad offset'); - assert.deepStrictEqual(data, - buf.slice(offset, offset + data.length), - 'write data mismatch'); - server.status(id, STATUS_CODE.OK); - if (reqs === 3) - server.end(); - }, 3)); - client.write(handle_, buf, 0, buf.length, 0, mustCall((err, nb) => { - assert(!err, `Unexpected write() error: ${err}`); - assert.strictEqual(nb, buf.length, 'wrote bytes written'); - })); -})); - -setup('lstat', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const attrs_ = new Stats({ - size: 10 * 1024, - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.on('LSTAT', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.attrs(id, attrs_); - server.end(); - })); - client.lstat(path_, mustCall((err, attrs) => { - assert(!err, `Unexpected lstat() error: ${err}`); - assert.deepStrictEqual(attrs, attrs_, 'attrs mismatch'); - })); -})); - -setup('fstat', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const attrs_ = new Stats({ - size: 10 * 1024, - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.on('FSTAT', mustCall((id, handle) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.attrs(id, attrs_); - server.end(); - })); - client.fstat(handle_, mustCall((err, attrs) => { - assert(!err, `Unexpected fstat() error: ${err}`); - assert.deepStrictEqual(attrs, attrs_, 'attrs mismatch'); - })); -})); - -setup('setstat', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const attrs_ = new Stats({ - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.on('SETSTAT', mustCall((id, path, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert.deepStrictEqual(attrs, attrs_, 'attrs mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.setstat(path_, attrs_, mustCall((err) => { - assert(!err, `Unexpected setstat() error: ${err}`); - })); -})); - -setup('fsetstat', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const attrs_ = new Stats({ - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.on('FSETSTAT', mustCall((id, handle, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert.deepStrictEqual(attrs, attrs_, 'attrs mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.fsetstat(handle_, attrs_, mustCall((err) => { - assert(!err, `Unexpected fsetstat() error: ${err}`); - })); -})); - -setup('opendir', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const path_ = '/tmp'; - server.on('OPENDIR', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.handle(id, handle_); - server.end(); - })); - client.opendir(path_, mustCall((err, handle) => { - assert(!err, `Unexpected opendir() error: ${err}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - })); -})); - -setup('readdir', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const list_ = [ - { filename: '.', - longname: 'drwxr-xr-x 56 nodejs nodejs 4096 Nov 10 01:05 .', - attrs: new Stats({ - mode: 0o755 | constants.S_IFDIR, - size: 4096, - uid: 9001, - gid: 8001, - atime: 1415599549, - mtime: 1415599590 - }) - }, - { filename: '..', - longname: 'drwxr-xr-x 4 root root 4096 May 16 2013 ..', - attrs: new Stats({ - mode: 0o755 | constants.S_IFDIR, - size: 4096, - uid: 0, - gid: 0, - atime: 1368729954, - mtime: 1368729999 - }) - }, - { filename: 'foo', - longname: 'drwxrwxrwx 2 nodejs nodejs 4096 Mar 8 2009 foo', - attrs: new Stats({ - mode: 0o777 | constants.S_IFDIR, - size: 4096, - uid: 9001, - gid: 8001, - atime: 1368729954, - mtime: 1368729999 - }) - }, - { filename: 'bar', - longname: '-rw-r--r-- 1 nodejs nodejs 513901992 Dec 4 2009 bar', - attrs: new Stats({ - mode: 0o644 | constants.S_IFREG, - size: 513901992, - uid: 9001, - gid: 8001, - atime: 1259972199, - mtime: 1259972199 - }) - } - ]; - server.on('READDIR', mustCall((id, handle) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.name(id, list_); - server.end(); - })); - client.readdir(handle_, mustCall((err, list) => { - assert(!err, `Unexpected readdir() error: ${err}`); - assert.deepStrictEqual(list, - list_.slice(2), - 'dir list mismatch'); - })); -})); - -setup('readdir (full)', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - const list_ = [ - { filename: '.', - longname: 'drwxr-xr-x 56 nodejs nodejs 4096 Nov 10 01:05 .', - attrs: new Stats({ - mode: 0o755 | constants.S_IFDIR, - size: 4096, - uid: 9001, - gid: 8001, - atime: 1415599549, - mtime: 1415599590 - }) - }, - { filename: '..', - longname: 'drwxr-xr-x 4 root root 4096 May 16 2013 ..', - attrs: new Stats({ - mode: 0o755 | constants.S_IFDIR, - size: 4096, - uid: 0, - gid: 0, - atime: 1368729954, - mtime: 1368729999 - }) - }, - { filename: 'foo', - longname: 'drwxrwxrwx 2 nodejs nodejs 4096 Mar 8 2009 foo', - attrs: new Stats({ - mode: 0o777 | constants.S_IFDIR, - size: 4096, - uid: 9001, - gid: 8001, - atime: 1368729954, - mtime: 1368729999 - }) - }, - { filename: 'bar', - longname: '-rw-r--r-- 1 nodejs nodejs 513901992 Dec 4 2009 bar', - attrs: new Stats({ - mode: 0o644 | constants.S_IFREG, - size: 513901992, - uid: 9001, - gid: 8001, - atime: 1259972199, - mtime: 1259972199 - }) - } - ]; - server.on('READDIR', mustCall((id, handle) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.name(id, list_); - server.end(); - })); - client.readdir(handle_, { full: true }, mustCall((err, list) => { - assert(!err, `Unexpected readdir() error: ${err}`); - assert.deepStrictEqual(list, list_, 'dir list mismatch'); - })); -})); - -setup('readdir (EOF)', mustCall((client, server) => { - const handle_ = Buffer.from('node.js'); - server.on('READDIR', mustCall((id, handle) => { - assert(id === 0, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.EOF); - server.end(); - })); - client.readdir(handle_, mustCall((err, list) => { - assert(err && err.code === STATUS_CODE.EOF, - `Expected EOF, got: ${err}`); - })); -})); - -setup('unlink', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - server.on('REMOVE', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.unlink(path_, mustCall((err) => { - assert(!err, `Unexpected unlink() error: ${err}`); - })); -})); - -setup('mkdir', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - server.on('MKDIR', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.mkdir(path_, mustCall((err) => { - assert(!err, `Unexpected mkdir() error: ${err}`); - })); -})); - -setup('rmdir', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - server.on('RMDIR', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.rmdir(path_, mustCall((err) => { - assert(!err, `Unexpected rmdir() error: ${err}`); - })); -})); - -setup('realpath', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const name_ = { filename: '/tmp/foo' }; - server.on('REALPATH', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.name(id, name_); - server.end(); - })); - client.realpath(path_, mustCall((err, name) => { - assert(!err, `Unexpected realpath() error: ${err}`); - assert.deepStrictEqual(name, name_.filename, 'name mismatch'); - })); -})); - -setup('stat', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const attrs_ = new Stats({ - mode: 0o644 | constants.S_IFREG, - size: 10 * 1024, - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.on('STAT', mustCall((id, path) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - server.attrs(id, attrs_); - server.end(); - })); - client.stat(path_, mustCall((err, attrs) => { - assert(!err, `Unexpected stat() error: ${err}`); - assert.deepStrictEqual(attrs, attrs_, 'attrs mismatch'); - const expectedTypes = { - isDirectory: false, - isFile: true, - isBlockDevice: false, - isCharacterDevice: false, - isSymbolicLink: false, - isFIFO: false, - isSocket: false - }; - for (const [fn, expect] of Object.entries(expectedTypes)) - assert(attrs[fn]() === expect, `attrs.${fn}() failed`); - })); -})); - -setup('rename', mustCall((client, server) => { - const oldPath_ = '/foo/bar/baz'; - const newPath_ = '/tmp/foo'; - server.on('RENAME', mustCall((id, oldPath, newPath) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(oldPath === oldPath_, `Wrong old path: ${oldPath}`); - assert(newPath === newPath_, `Wrong new path: ${newPath}`); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.rename(oldPath_, newPath_, mustCall((err) => { - assert(!err, `Unexpected rename() error: ${err}`); - })); -})); - -setup('readlink', mustCall((client, server) => { - const linkPath_ = '/foo/bar/baz'; - const name = { filename: '/tmp/foo' }; - server.on('READLINK', mustCall((id, linkPath) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(linkPath === linkPath_, `Wrong link path: ${linkPath}`); - server.name(id, name); - server.end(); - })); - client.readlink(linkPath_, mustCall((err, targetPath) => { - assert(!err, `Unexpected readlink() error: ${err}`); - assert(targetPath === name.filename, - `Wrong target path: ${targetPath}`); - })); -})); - -setup('symlink', mustCall((client, server) => { - const linkPath_ = '/foo/bar/baz'; - const targetPath_ = '/tmp/foo'; - server.on('SYMLINK', mustCall((id, linkPath, targetPath) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(linkPath === linkPath_, `Wrong link path: ${linkPath}`); - assert(targetPath === targetPath_, `Wrong target path: ${targetPath}`); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.symlink(targetPath_, linkPath_, mustCall((err) => { - assert(!err, `Unexpected symlink() error: ${err}`); - })); -})); - -setup('readFile', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const handle_ = Buffer.from('hi mom!'); - const data_ = Buffer.from('hello world'); - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === OPEN_MODE.READ, `Wrong flags: ${flagsToHuman(pflags)}`); - server.handle(id, handle_); - })).on('FSTAT', mustCall((id, handle) => { - assert(id === 1, `Wrong request id: ${id}`); - const attrs = new Stats({ - size: data_.length, - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.attrs(id, attrs); - })).on('READ', mustCall((id, handle, offset, len) => { - assert(id === 2, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert(offset === 0, `Wrong read offset: ${offset}`); - server.data(id, data_); - })).on('CLOSE', mustCall((id, handle) => { - assert(id === 3, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.readFile(path_, mustCall((err, buf) => { - assert(!err, `Unexpected error: ${err}`); - assert.deepStrictEqual(buf, data_, 'data mismatch'); - })); -})); - -setup('readFile (no size from fstat)', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const handle_ = Buffer.from('hi mom!'); - const data_ = Buffer.from('hello world'); - let reads = 0; - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === OPEN_MODE.READ, `Wrong flags: ${flagsToHuman(pflags)}`); - server.handle(id, handle_); - })).on('FSTAT', mustCall((id, handle) => { - assert(id === 1, `Wrong request id: ${id}`); - const attrs = new Stats({ - uid: 9001, - gid: 9001, - atime: (Date.now() / 1000) | 0, - mtime: (Date.now() / 1000) | 0 - }); - server.attrs(id, attrs); - })).on('READ', mustCall((id, handle, offset, len) => { - assert(++reads + 1 === id, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - switch (id) { - case 2: - assert(offset === 0, `Wrong read offset for first read: ${offset}`); - server.data(id, data_); - break; - case 3: - assert(offset === data_.length, - `Wrong read offset for second read: ${offset}`); - server.status(id, STATUS_CODE.EOF); - break; - } - }, 2)).on('CLOSE', mustCall((id, handle) => { - assert(id === 4, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - client.readFile(path_, mustCall((err, buf) => { - assert(!err, `Unexpected error: ${err}`); - assert.deepStrictEqual(buf, data_, 'data mismatch'); - })); -})); - -setup('ReadStream', mustCall((client, server) => { - let reads = 0; - const path_ = '/foo/bar/baz'; - const handle_ = Buffer.from('hi mom!'); - const data_ = Buffer.from('hello world'); - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === OPEN_MODE.READ, `Wrong flags: ${flagsToHuman(pflags)}`); - server.handle(id, handle_); - })).on('READ', mustCall((id, handle, offset, len) => { - assert(id === ++reads, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - if (reads === 1) { - assert(offset === 0, `Wrong read offset: ${offset}`); - server.data(id, data_); - } else { - server.status(id, STATUS_CODE.EOF); - } - }, 2)).on('CLOSE', mustCall((id, handle) => { - assert(id === 3, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - let buf = []; - client.createReadStream(path_).on('readable', mustCallAtLeast(function() { - let chunk; - while ((chunk = this.read()) !== null) - buf.push(chunk); - })).on('end', mustCall(() => { - buf = Buffer.concat(buf); - assert.deepStrictEqual(buf, data_, 'data mismatch'); - })); -})); - -setup('ReadStream (fewer bytes than requested)', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - const handle_ = Buffer.from('hi mom!'); - const data_ = Buffer.from('hello world'); - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - server.handle(id, handle_); - })).on('READ', mustCallAtLeast((id, handle, offset, len) => { - if (offset > data_.length) { - server.status(id, STATUS_CODE.EOF); - } else { - // Only read 4 bytes at a time - server.data(id, data_.slice(offset, offset + 4)); - } - })).on('CLOSE', mustCall((id, handle) => { - server.status(id, STATUS_CODE.OK); - server.end(); - })); - let buf = []; - client.createReadStream(path_).on('readable', mustCallAtLeast(function() { - let chunk; - while ((chunk = this.read()) !== null) - buf.push(chunk); - })).on('end', mustCall(() => { - buf = Buffer.concat(buf); - assert.deepStrictEqual(buf, data_, 'data mismatch'); - })); -})); - -setup('ReadStream (error)', mustCall((client, server) => { - const path_ = '/foo/bar/baz'; - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === OPEN_MODE.READ, `Wrong flags: ${flagsToHuman(pflags)}`); - server.status(id, STATUS_CODE.NO_SUCH_FILE); - server.end(); - })); - client.createReadStream(path_).on('error', mustCall((err) => { - assert(err.code === STATUS_CODE.NO_SUCH_FILE); - })); -})); - -setup('WriteStream', mustCall((client, server) => { - let writes = 0; - const path_ = '/foo/bar/baz'; - const handle_ = Buffer.from('hi mom!'); - const data_ = Buffer.from('hello world'); - const pflags_ = OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE; - server.on('OPEN', mustCall((id, path, pflags, attrs) => { - assert(id === 0, `Wrong request id: ${id}`); - assert(path === path_, `Wrong path: ${path}`); - assert(pflags === pflags_, `Wrong flags: ${flagsToHuman(pflags)}`); - server.handle(id, handle_); - })).on('FSETSTAT', mustCall((id, handle, attrs) => { - assert(id === 1, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert.strictEqual(attrs.mode, 0o666, 'Wrong file mode'); - server.status(id, STATUS_CODE.OK); - })).on('WRITE', mustCall((id, handle, offset, data) => { - assert(id === ++writes + 1, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - assert(offset === ((writes - 1) * data_.length), - `Wrong write offset: ${offset}`); - assert.deepStrictEqual(data, data_, 'Wrong data'); - server.status(id, STATUS_CODE.OK); - }, 3)).on('CLOSE', mustCall((id, handle) => { - assert(id === 5, `Wrong request id: ${id}`); - assert.deepStrictEqual(handle, handle_, 'handle mismatch'); - server.status(id, STATUS_CODE.OK); - server.end(); - })); - - const writer = client.createWriteStream(path_); - writer.cork && writer.cork(); - writer.write(data_); - writer.write(data_); - writer.write(data_); - writer.uncork && writer.uncork(); - writer.end(); -})); - -{ - const { client, server } = setup_( - 'SFTP server aborts with exit-status', - { - client: { username: 'foo', password: 'bar' }, - server: { hostKeys: [ fixture('ssh_host_rsa_key') ] }, - }, - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - ctx.accept(); - })).on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('sftp', mustCall((accept, reject) => { - const sftp = accept(); - - // XXX: hack - sftp._protocol.exitStatus(sftp.outgoing.id, 127); - sftp._protocol.channelClose(sftp.outgoing.id); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - const timeout = setTimeout(mustNotCall(), 1000); - client.sftp(mustCall((err, sftp) => { - clearTimeout(timeout); - assert(err, 'Expected error'); - assert(err.code === 127, `Expected exit code 127, saw: ${err.code}`); - client.end(); - })); - })); -} - - -// ============================================================================= -function setup(title, cb) { - const { client, server } = setupSimple(DEBUG, title); - let clientSFTP; - let serverSFTP; - - const onSFTP = mustCall(() => { - if (clientSFTP && serverSFTP) - cb(clientSFTP, serverSFTP); - }, 2); - - client.on('ready', mustCall(() => { - client.sftp(mustCall((err, sftp) => { - assert(!err, `[${title}] Unexpected client sftp start error: ${err}`); - sftp.on('close', mustCall(() => { - client.end(); - })); - clientSFTP = sftp; - onSFTP(); - })); - })); - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - accept().on('sftp', mustCall((accept, reject) => { - const sftp = accept(); - sftp.on('close', mustCall(() => { - conn.end(); - })); - serverSFTP = sftp; - onSFTP(); - })); - })); - })); - })); -} - -function flagsToHuman(flags) { - const ret = []; - - for (const [name, value] of Object.entries(OPEN_MODE)) { - if (flags & value) - ret.push(name); - } - - return ret.join(' | '); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-shell.js b/reverse_engineering/node_modules/ssh2/test/test-shell.js deleted file mode 100644 index debba11..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-shell.js +++ /dev/null @@ -1,109 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { inspect } = require('util'); - -const { - mustCall, - mustCallAtLeast, - setupSimple, -} = require('./common.js'); - -const DEBUG = false; - -const setup = setupSimple.bind(undefined, DEBUG); - -{ - const { client, server } = setup('Simple shell()'); - - const OUTPUT = 'shell output!\n'; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - const session = accept(); - session.on('pty', mustCall((accept, reject, info) => { - accept(); - session.on('shell', mustCall((accept, reject) => { - let input = ''; - const stream = accept(); - stream.write(OUTPUT); - stream.on('data', mustCallAtLeast((data) => { - input += data; - if (input === 'exit\n') { - stream.end(); - conn.end(); - } - })); - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let output = ''; - client.on('close', mustCall(() => { - assert(output === OUTPUT, `Wrong shell output: ${inspect(output)}`); - })).shell(mustCall((err, stream) => { - assert(!err, `Unexpected shell error: ${err}`); - stream.write('exit\n'); - stream.on('data', mustCallAtLeast((d) => { - output += d; - })).on('close', mustCall(() => {})); - })); - })); -} - -{ - const { client, server } = setup('Shell with environment set'); - - const OUTPUT = 'shell output!\n'; - const clientEnv = { SSH2NODETEST: 'foo' }; - - server.on('connection', mustCall((conn) => { - conn.on('ready', mustCall(() => { - conn.on('session', mustCall((accept, reject) => { - let pty = false; - let env = false; - accept().on('pty', mustCall((accept, reject, info) => { - accept(); - pty = true; - })).on('env', mustCall((accept, reject, info) => { - accept && accept(); - env = true; - assert(info.key === Object.keys(clientEnv)[0], - `Wrong env key: ${inspect(info.key)}`); - assert(info.val === Object.values(clientEnv)[0], - `Wrong env value: ${inspect(info.val)}`); - })).on('shell', mustCall((accept, reject) => { - assert(pty, 'Expected pty before shell'); - assert(env, 'Expected env before shell'); - let input = ''; - const stream = accept(); - stream.write(OUTPUT); - stream.on('data', mustCallAtLeast((data) => { - input += data; - if (input === 'exit\n') { - stream.end(); - conn.end(); - } - })); - })); - })); - })); - })); - - client.on('ready', mustCall(() => { - let output = ''; - client.on('close', mustCall(() => { - assert(output === OUTPUT, `Wrong shell output: ${inspect(output)}`); - })).shell({ env: clientEnv }, mustCall((err, stream) => { - assert(!err, `Unexpected shell error: ${err}`); - stream.write('exit\n'); - stream.on('data', mustCallAtLeast((d) => { - output += d; - })).on('close', mustCall(() => {})); - })); - })); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-userauth-agent-openssh.js b/reverse_engineering/node_modules/ssh2/test/test-userauth-agent-openssh.js deleted file mode 100644 index 55d1a25..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-userauth-agent-openssh.js +++ /dev/null @@ -1,109 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { spawnSync } = require('child_process'); - -const debug = false; -const SPAWN_OPTS = { windowsHide: true }; - -// TODO: figure out why this test is failing on Windows -if (process.platform === 'win32') { - console.log('Skipping ssh-agent test on Windows'); - process.exit(0); -} - -if (process.argv[2] === 'child') { - const { - fixtureKey, - mustCall, - setup, - } = require('./common.js'); - - const serverCfg = { hostKeys: [ fixtureKey('ssh_host_rsa_key').raw ] }; - - const clientKey = fixtureKey('openssh_new_rsa'); - - // Add key to the agent first - { - const { - error, status - } = spawnSync('ssh-add', [ clientKey.fullPath ], SPAWN_OPTS); - if (error || status !== 0) { - console.error('Failed to add key to agent'); - process.exit(1); - } - } - - const username = 'Agent User'; - const { server } = setup( - 'Agent authentication', - { - client: { username, agent: process.env.SSH_AUTH_SOCK }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.signature, 'Missing publickey signature'); - // FALLTHROUGH - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - conn.end(); - })); - })); -} else { - { - const { - error, status - } = spawnSync('which', ['ssh-agent'], SPAWN_OPTS); - - if (error || status !== 0) { - console.log('No ssh-agent available, skipping agent test ...'); - process.exit(0); - } - } - - { - const { - error, status - } = spawnSync('which', ['ssh-add'], SPAWN_OPTS); - - if (error || status !== 0) { - console.log('No ssh-add available, skipping agent test ...'); - process.exit(0); - } - } - - const { - error, status - } = spawnSync('ssh-agent', - [ process.execPath, __filename, 'child' ], - { ...SPAWN_OPTS, stdio: 'inherit' }); - if (error || status !== 0) - throw new Error('Agent test failed'); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-userauth-agent.js b/reverse_engineering/node_modules/ssh2/test/test-userauth-agent.js deleted file mode 100644 index a28ad0b..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-userauth-agent.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict'; - -const assert = require('assert'); - -const debug = false; - -const { - fixtureKey, - mustCall, - setup, -} = require('./common.js'); -const { - AgentProtocol, - BaseAgent, - utils: { parseKey }, -} = require('../lib/index.js'); - -const serverCfg = { hostKeys: [ fixtureKey('ssh_host_rsa_key').raw ] }; - -const clientKey = fixtureKey('openssh_new_rsa'); - -{ - let getIdentitiesCount = 0; - let signCount = 0; - class MyAgent extends BaseAgent { - getIdentities(cb) { - assert.strictEqual(++getIdentitiesCount, 1); - // Ensure that no private portion of the key is used by re-parsing the - // public version of the key - cb(null, [ parseKey(clientKey.key.getPublicSSH()) ]); - } - sign(pubKey, data, options, cb) { - assert.strictEqual(++signCount, 1); - assert.strictEqual(pubKey.getPublicPEM(), clientKey.key.getPublicPEM()); - const sig = clientKey.key.sign(data, options.hash); - cb(null, sig); - } - } - - const username = 'Agent User'; - const { server } = setup( - 'Custom agent authentication', - { - client: { username, agent: new MyAgent() }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.signature, 'Missing publickey signature'); - // FALLTHROUGH - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - assert.strictEqual(getIdentitiesCount, 1); - assert.strictEqual(signCount, 1); - conn.end(); - })); - })); -} -{ - const client = new AgentProtocol(true); - const server = new AgentProtocol(false); - - server.on('identities', mustCall((req) => { - setImmediate(() => server.failureReply(req)); - })); - client.getIdentities(mustCall((err, keys) => { - assert(err, 'Missing expected error'); - })); - - client.pipe(server).pipe(client); -} -{ - const client = new AgentProtocol(true); - const server = new AgentProtocol(false); - - server.on('identities', mustCall((req) => { - const keys = [ clientKey.key ]; - server.getIdentitiesReply(req, keys); - })); - client.getIdentities(mustCall((err, keys) => { - assert(!err, 'Unexpected error'); - assert.strictEqual(keys.length, 1); - assert.strictEqual(keys[0].isPrivateKey(), false); - assert.strictEqual(keys[0].getPublicPEM(), clientKey.key.getPublicPEM()); - })); - - client.pipe(server).pipe(client); -} -{ - const client = new AgentProtocol(true); - const server = new AgentProtocol(false); - const buf = Buffer.from('data to sign'); - - server.on('sign', mustCall((req, pubKey, data, options) => { - assert.strictEqual(pubKey.getPublicPEM(), clientKey.key.getPublicPEM()); - assert.deepStrictEqual(data, buf); - assert.strictEqual(options.hash, undefined); - server.failureReply(req); - })); - client.sign(clientKey.key.getPublicSSH(), - buf, - mustCall((err, signature) => { - assert(err, 'Missing expected error'); - })); - - client.pipe(server).pipe(client); -} -{ - const client = new AgentProtocol(true); - const server = new AgentProtocol(false); - const buf = Buffer.from('data to sign'); - - server.on('sign', mustCall((req, pubKey, data, options) => { - assert.strictEqual(pubKey.getPublicPEM(), clientKey.key.getPublicPEM()); - assert.deepStrictEqual(data, buf); - assert.strictEqual(options.hash, undefined); - server.signReply(req, clientKey.key.sign(data)); - })); - client.sign(clientKey.key.getPublicSSH(), - buf, - mustCall((err, signature) => { - assert(!err, 'Unexpected error'); - const pubKey = parseKey(clientKey.key.getPublicSSH()); - assert.strictEqual(pubKey.verify(buf, signature), true); - })); - - client.pipe(server).pipe(client); -} -{ - // Test that outstanding requests are handled upon unexpected closure of the - // protocol stream - - const client = new AgentProtocol(true); - const server = new AgentProtocol(false); - - server.on('identities', mustCall((req) => { - server.destroy(); - })); - client.getIdentities(mustCall((err) => { - assert(err, 'Missing expected error'); - })); - - client.pipe(server).pipe(client); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test-userauth.js b/reverse_engineering/node_modules/ssh2/test/test-userauth.js deleted file mode 100644 index fb2fe9e..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test-userauth.js +++ /dev/null @@ -1,608 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const { inspect } = require('util'); - -const { - fixtureKey, - mustCall, - mustNotCall, - setup, -} = require('./common.js'); - -const serverCfg = { hostKeys: [ fixtureKey('ssh_host_rsa_key').raw ] }; - -const debug = false; - -// Keys ======================================================================== -[ - { desc: 'RSA (old OpenSSH)', - clientKey: fixtureKey('id_rsa') }, - { desc: 'RSA (new OpenSSH)', - clientKey: fixtureKey('openssh_new_rsa') }, - { desc: 'RSA (encrypted)', - clientKey: fixtureKey('id_rsa_enc', 'foobarbaz'), - passphrase: 'foobarbaz' }, - { desc: 'DSA', - clientKey: fixtureKey('id_dsa') }, - { desc: 'ECDSA', - clientKey: fixtureKey('id_ecdsa') }, - { desc: 'PPK', - clientKey: fixtureKey('id_rsa.ppk') }, -].forEach((test) => { - const { desc, clientKey, passphrase } = test; - const username = 'Key User'; - const { server } = setup( - desc, - { - client: { username, privateKey: clientKey.raw, passphrase }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.signature, 'Missing publickey signature'); - // FALLTHROUGH - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - break; - } - if (ctx.signature) { - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify publickey signature'); - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - conn.end(); - })); - })); -}); - - -// Password ==================================================================== -{ - const username = 'Password User'; - const password = 'hi mom'; - const { server } = setup( - 'Password', - { - client: { username, password }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - if (++authAttempt === 1) { - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - } - assert(ctx.method === 'password', - `Wrong auth method: ${ctx.method}`); - assert(ctx.password === password, - `Wrong password: ${ctx.password}`); - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.end(); - })); - })); -} -{ - const username = ''; - const password = 'hi mom'; - const { server } = setup( - 'Password (empty username)', - { - client: { username, password }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - if (++authAttempt === 1) { - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - } - assert(ctx.method === 'password', - `Wrong auth method: ${ctx.method}`); - assert(ctx.password === password, - `Wrong password: ${ctx.password}`); - ctx.accept(); - }, 2)).on('ready', mustCall(() => { - conn.end(); - })); - })); -} -{ - const username = 'foo'; - const oldPassword = 'bar'; - const newPassword = 'baz'; - const changePrompt = 'Prithee changeth thy password'; - const { client, server } = setup( - 'Password (change requested)', - { - client: { username, password: oldPassword }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - if (++authAttempt === 1) { - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - } - assert(ctx.method === 'password', - `Wrong auth method: ${ctx.method}`); - assert(ctx.password === oldPassword, - `Wrong old password: ${ctx.password}`); - ctx.requestChange(changePrompt, mustCall((newPassword_) => { - assert(newPassword_ === newPassword, - `Wrong new password: ${newPassword_}`); - ctx.accept(); - })); - }, 2)).on('ready', mustCall(() => { - conn.end(); - })); - })); - - client.on('change password', mustCall((prompt, done) => { - assert(prompt === changePrompt, `Wrong password change prompt: ${prompt}`); - process.nextTick(done, newPassword); - })); -} - - -// Hostbased =================================================================== -{ - const localUsername = 'Local User Foo'; - const localHostname = 'Local Host Bar'; - const username = 'Hostbased User'; - const clientKey = fixtureKey('id_rsa'); - const { server } = setup( - 'Hostbased', - { - client: { - username, - privateKey: clientKey.raw, - localUsername, - localHostname, - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - switch (++authAttempt) { - case 1: - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 2: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - case 3: - assert(ctx.method === 'hostbased', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Wrong key algo: ${ctx.key.algo}`); - assert.deepStrictEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - assert(ctx.signature, 'Expected signature'); - assert(ctx.localHostname === localHostname, 'Wrong local hostname'); - assert(ctx.localUsername === localUsername, 'Wrong local username'); - assert(clientKey.key.verify(ctx.blob, ctx.signature) === true, - 'Could not verify hostbased signature'); - - break; - } - ctx.accept(); - }, 3)).on('ready', mustCall(() => { - conn.end(); - })); - })); -} - - -// keyboard-interactive ======================================================== -{ - const username = 'Keyboard-Interactive User'; - const request = { - name: 'SSH2 Authentication', - instructions: 'These are instructions', - prompts: [ - { prompt: 'Password: ', echo: false }, - { prompt: 'Is the cake a lie? ', echo: true }, - ], - }; - const responses = [ - 'foobarbaz', - 'yes', - ]; - const { client, server } = setup( - 'Password (empty username)', - { - client: { - username, - tryKeyboard: true, - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let authAttempt = 0; - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, - `Wrong username: ${ctx.username}`); - if (++authAttempt === 1) { - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - return ctx.reject(); - } - assert(ctx.method === 'keyboard-interactive', - `Wrong auth method: ${ctx.method}`); - ctx.prompt(request.prompts, - request.name, - request.instructions, - mustCall((responses_) => { - assert.deepStrictEqual(responses_, responses); - ctx.accept(); - })); - }, 2)).on('ready', mustCall(() => { - conn.end(); - })); - })); - - client.on('keyboard-interactive', - mustCall((name, instructions, lang, prompts, finish) => { - assert(name === request.name, `Wrong prompt name: ${name}`); - assert(instructions === request.instructions, - `Wrong prompt instructions: ${instructions}`); - assert.deepStrictEqual( - prompts, - request.prompts, - `Wrong prompts: ${inspect(prompts)}` - ); - process.nextTick(finish, responses); - })); -} - -// authHandler() tests ========================================================= -{ - const username = 'foo'; - const password = '1234'; - const clientKey = fixtureKey('id_rsa'); - const { server } = setup( - 'authHandler() (sync)', - { - client: { - username, - password, - privateKey: clientKey.raw, - - authHandler: mustCall((methodsLeft, partial, cb) => { - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - return 'none'; - }), - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, `Wrong username: ${ctx.username}`); - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const clientKey = fixtureKey('id_rsa'); - const { server } = setup( - 'authHandler() (async)', - { - client: { - username, - password, - privateKey: clientKey.raw, - - authHandler: mustCall((methodsLeft, partial, cb) => { - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - process.nextTick(mustCall(cb), 'none'); - }), - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, `Wrong username: ${ctx.username}`); - assert(ctx.method === 'none', `Wrong auth method: ${ctx.method}`); - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const clientKey = fixtureKey('id_rsa'); - const { client, server } = setup( - 'authHandler() (no methods left -- sync)', - { - client: { - username, - password, - privateKey: clientKey.raw, - - authHandler: mustCall((methodsLeft, partial, cb) => { - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - return false; - }), - }, - server: serverCfg, - - debug, - noForceClientReady: true, - noForceServerReady: true, - } - ); - - // Remove default client error handler added by `setup()` since we are - // expecting an error in this case - client.removeAllListeners('error'); - - client.on('error', mustCall((err) => { - assert.strictEqual(err.level, 'client-authentication'); - assert(/configured authentication methods failed/i.test(err.message), - 'Wrong error message'); - })); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustNotCall()) - .on('ready', mustNotCall()); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const clientKey = fixtureKey('id_rsa'); - const { client, server } = setup( - 'authHandler() (no methods left -- async)', - { - client: { - username, - password, - privateKey: clientKey.raw, - - authHandler: mustCall((methodsLeft, partial, cb) => { - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - process.nextTick(mustCall(cb), false); - }), - }, - server: serverCfg, - - debug, - noForceClientReady: true, - noForceServerReady: true, - } - ); - - // Remove default client error handler added by `setup()` since we are - // expecting an error in this case - client.removeAllListeners('error'); - - client.on('error', mustCall((err) => { - assert.strictEqual(err.level, 'client-authentication'); - assert(/configured authentication methods failed/i.test(err.message), - 'Wrong error message'); - })); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustNotCall()) - .on('ready', mustNotCall()); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const clientKey = fixtureKey('id_rsa'); - const events = []; - const expectedEvents = [ - 'client', 'server', 'client', 'server' - ]; - let clientCalls = 0; - const { client, server } = setup( - 'authHandler() (multi-step)', - { - client: { - username, - password, - privateKey: clientKey.raw, - - authHandler: mustCall((methodsLeft, partial, cb) => { - events.push('client'); - switch (++clientCalls) { - case 1: - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - return 'publickey'; - case 2: - assert.deepStrictEqual( - methodsLeft, - ['password'], - `expected 'password' method left, saw: ${methodsLeft}` - ); - assert(partial === true, 'expected partial success'); - return 'password'; - } - }, 2), - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - let attempts = 0; - conn.on('authentication', mustCall((ctx) => { - assert(++attempts === clientCalls, 'server<->client state mismatch'); - assert(ctx.username === username, - `Unexpected username: ${ctx.username}`); - events.push('server'); - switch (attempts) { - case 1: - assert(ctx.method === 'publickey', - `Wrong auth method: ${ctx.method}`); - assert(ctx.key.algo === clientKey.key.type, - `Unexpected key algo: ${ctx.key.algo}`); - assert.deepEqual(clientKey.key.getPublicSSH(), - ctx.key.data, - 'Public key mismatch'); - ctx.reject(['password'], true); - break; - case 2: - assert(ctx.method === 'password', - `Wrong auth method: ${ctx.method}`); - assert(ctx.password === password, - `Unexpected password: ${ctx.password}`); - ctx.accept(); - break; - } - }, 2)).on('ready', mustCall(() => { - conn.end(); - })); - })); - - client.on('close', mustCall(() => { - assert.deepStrictEqual(events, expectedEvents); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const { server } = setup( - 'authHandler() (custom auth configuration)', - { - client: { - username: 'bar', - password: '5678', - - authHandler: mustCall((methodsLeft, partial, cb) => { - assert(methodsLeft === null, 'expected null methodsLeft'); - assert(partial === null, 'expected null partial'); - return { - type: 'password', - username, - password, - }; - }), - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, `Wrong username: ${ctx.username}`); - assert(ctx.method === 'password', `Wrong auth method: ${ctx.method}`); - assert(ctx.password === password, `Unexpected password: ${ctx.password}`); - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} -{ - const username = 'foo'; - const password = '1234'; - const { server } = setup( - 'authHandler() (simple construction with custom auth configuration)', - { - client: { - username: 'bar', - password: '5678', - - authHandler: [{ - type: 'password', - username, - password, - }], - }, - server: serverCfg, - - debug, - } - ); - - server.on('connection', mustCall((conn) => { - conn.on('authentication', mustCall((ctx) => { - assert(ctx.username === username, `Wrong username: ${ctx.username}`); - assert(ctx.method === 'password', `Wrong auth method: ${ctx.method}`); - assert(ctx.password === password, `Unexpected password: ${ctx.password}`); - ctx.accept(); - })).on('ready', mustCall(() => { - conn.end(); - })); - })); -} diff --git a/reverse_engineering/node_modules/ssh2/test/test.js b/reverse_engineering/node_modules/ssh2/test/test.js deleted file mode 100644 index d0380f2..0000000 --- a/reverse_engineering/node_modules/ssh2/test/test.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -const { spawnSync } = require('child_process'); -const { readdirSync } = require('fs'); -const { join } = require('path'); - -const files = readdirSync(__dirname).sort(); -for (const filename of files) { - if (filename.startsWith('test-')) { - const path = join(__dirname, filename); - console.log(`> Running ${filename} ...`); - const result = spawnSync(`${process.argv0} ${path}`, { - shell: true, - stdio: 'inherit', - windowsHide: true - }); - if (result.status !== 0) - process.exitCode = 1; - } -} diff --git a/reverse_engineering/node_modules/ssh2/util/build_pagent.bat b/reverse_engineering/node_modules/ssh2/util/build_pagent.bat deleted file mode 100644 index 9f5aaf8..0000000 --- a/reverse_engineering/node_modules/ssh2/util/build_pagent.bat +++ /dev/null @@ -1,2 +0,0 @@ -@cl /Ox pagent.c User32.lib -@del /Q *.obj \ No newline at end of file diff --git a/reverse_engineering/node_modules/ssh2/util/pagent.c b/reverse_engineering/node_modules/ssh2/util/pagent.c deleted file mode 100644 index e900491..0000000 --- a/reverse_engineering/node_modules/ssh2/util/pagent.c +++ /dev/null @@ -1,88 +0,0 @@ -#include -#include -#include - -#define AGENT_COPYDATA_ID 0x804e50ba -#define AGENT_MAX_MSGLEN 8192 - -#define GET_32BIT_MSB_FIRST(cp) \ - (((unsigned long)(unsigned char)(cp)[0] << 24) | \ - ((unsigned long)(unsigned char)(cp)[1] << 16) | \ - ((unsigned long)(unsigned char)(cp)[2] << 8) | \ - ((unsigned long)(unsigned char)(cp)[3])) - -#define GET_32BIT(cp) GET_32BIT_MSB_FIRST(cp) - -#define RET_ERR_BADARGS 10 -#define RET_ERR_UNAVAILABLE 11 -#define RET_ERR_NOMAP 12 -#define RET_ERR_BINSTDIN 13 -#define RET_ERR_BINSTDOUT 14 -#define RET_ERR_BADLEN 15 - -#define RET_NORESPONSE 1 -#define RET_RESPONSE 0 - -int main (int argc, const char* argv[]) { - HWND hwnd; - char *mapname; - HANDLE filemap; - unsigned char *p, *ret; - int id, retlen, inlen, n, rmode, r = RET_NORESPONSE; - COPYDATASTRUCT cds; - void *in; - - if (argc < 2) - return RET_ERR_BADARGS; - - hwnd = FindWindow("Pageant", "Pageant"); - if (!hwnd) - return RET_ERR_UNAVAILABLE; - - rmode = _setmode(_fileno(stdin), _O_BINARY); - if (rmode == -1) - return RET_ERR_BINSTDIN; - - rmode = _setmode(_fileno(stdout), _O_BINARY); - if (rmode == -1) - return RET_ERR_BINSTDOUT; - - inlen = atoi(argv[1]); - in = malloc(inlen); - n = fread(in, 1, inlen, stdin); - if (n != inlen) { - free(in); - return RET_ERR_BADLEN; - } - - mapname = malloc(32); - n = sprintf(mapname, "PageantRequest%08x", (unsigned)GetCurrentThreadId()); - - filemap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, - 0, AGENT_MAX_MSGLEN, mapname); - if (filemap == NULL || filemap == INVALID_HANDLE_VALUE) { - free(in); - free(mapname); - return RET_ERR_NOMAP; - } - - p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0); - memcpy(p, in, inlen); - cds.dwData = AGENT_COPYDATA_ID; - cds.cbData = 1 + n; - cds.lpData = mapname; - - id = SendMessage(hwnd, WM_COPYDATA, (WPARAM) NULL, (LPARAM) &cds); - if (id > 0) { - r = RET_RESPONSE; - retlen = 4 + GET_32BIT(p); - fwrite(p, 1, retlen, stdout); - } - - free(in); - free(mapname); - UnmapViewOfFile(p); - CloseHandle(filemap); - - return r; -} diff --git a/reverse_engineering/node_modules/ssh2/util/pagent.exe b/reverse_engineering/node_modules/ssh2/util/pagent.exe deleted file mode 100644 index 6e8a71c..0000000 Binary files a/reverse_engineering/node_modules/ssh2/util/pagent.exe and /dev/null differ diff --git a/reverse_engineering/node_modules/string_decoder/LICENSE b/reverse_engineering/node_modules/string_decoder/LICENSE deleted file mode 100644 index 778edb2..0000000 --- a/reverse_engineering/node_modules/string_decoder/LICENSE +++ /dev/null @@ -1,48 +0,0 @@ -Node.js is licensed for use as follows: - -""" -Copyright Node.js contributors. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. -""" - -This license applies to parts of Node.js originating from the -https://github.com/joyent/node repository: - -""" -Copyright Joyent, Inc. and other Node contributors. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. -""" - diff --git a/reverse_engineering/node_modules/string_decoder/README.md b/reverse_engineering/node_modules/string_decoder/README.md deleted file mode 100644 index 5fd5831..0000000 --- a/reverse_engineering/node_modules/string_decoder/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# string_decoder - -***Node-core v8.9.4 string_decoder for userland*** - - -[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) -[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) - - -```bash -npm install --save string_decoder -``` - -***Node-core string_decoder for userland*** - -This package is a mirror of the string_decoder implementation in Node-core. - -Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). - -As of version 1.0.0 **string_decoder** uses semantic versioning. - -## Previous versions - -Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. - -## Update - -The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. - -## Streams Working Group - -`string_decoder` is maintained by the Streams Working Group, which -oversees the development and maintenance of the Streams API within -Node.js. The responsibilities of the Streams Working Group include: - -* Addressing stream issues on the Node.js issue tracker. -* Authoring and editing stream documentation within the Node.js project. -* Reviewing changes to stream subclasses within the Node.js project. -* Redirecting changes to streams from the Node.js project to this - project. -* Assisting in the implementation of stream providers within Node.js. -* Recommending versions of `readable-stream` to be included in Node.js. -* Messaging about the future of streams to give the community advance - notice of changes. - -See [readable-stream](https://github.com/nodejs/readable-stream) for -more details. diff --git a/reverse_engineering/node_modules/string_decoder/lib/string_decoder.js b/reverse_engineering/node_modules/string_decoder/lib/string_decoder.js deleted file mode 100644 index 2e89e63..0000000 --- a/reverse_engineering/node_modules/string_decoder/lib/string_decoder.js +++ /dev/null @@ -1,296 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} \ No newline at end of file diff --git a/reverse_engineering/node_modules/string_decoder/package.json b/reverse_engineering/node_modules/string_decoder/package.json deleted file mode 100644 index 2bdce38..0000000 --- a/reverse_engineering/node_modules/string_decoder/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "string_decoder@^1.1.1", - "_id": "string_decoder@1.3.0", - "_inBundle": false, - "_integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "_location": "/string_decoder", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "string_decoder@^1.1.1", - "name": "string_decoder", - "escapedName": "string_decoder", - "rawSpec": "^1.1.1", - "saveSpec": null, - "fetchSpec": "^1.1.1" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "_shasum": "42f114594a46cf1a8e30b0a84f56c78c3edac21e", - "_spec": "string_decoder@^1.1.1", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/readable-stream", - "bugs": { - "url": "https://github.com/nodejs/string_decoder/issues" - }, - "bundleDependencies": false, - "dependencies": { - "safe-buffer": "~5.2.0" - }, - "deprecated": false, - "description": "The string_decoder module from Node core", - "devDependencies": { - "babel-polyfill": "^6.23.0", - "core-util-is": "^1.0.2", - "inherits": "^2.0.3", - "tap": "~0.4.8" - }, - "files": [ - "lib" - ], - "homepage": "https://github.com/nodejs/string_decoder", - "keywords": [ - "string", - "decoder", - "browser", - "browserify" - ], - "license": "MIT", - "main": "lib/string_decoder.js", - "name": "string_decoder", - "repository": { - "type": "git", - "url": "git://github.com/nodejs/string_decoder.git" - }, - "scripts": { - "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js", - "test": "tap test/parallel/*.js && node test/verify-dependencies" - }, - "version": "1.3.0" -} diff --git a/reverse_engineering/node_modules/tunnel-ssh/.eslintignore b/reverse_engineering/node_modules/tunnel-ssh/.eslintignore deleted file mode 100644 index 1616ee7..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/.eslintignore +++ /dev/null @@ -1,4 +0,0 @@ -node_modules/** -.idea/** -build/** -examples diff --git a/reverse_engineering/node_modules/tunnel-ssh/.travis.yml b/reverse_engineering/node_modules/tunnel-ssh/.travis.yml deleted file mode 100644 index fbbe737..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js - -node_js: - - node diff --git a/reverse_engineering/node_modules/tunnel-ssh/LICENSE b/reverse_engineering/node_modules/tunnel-ssh/LICENSE deleted file mode 100644 index f731172..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Christoph Hagenbrock (agebrock.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/reverse_engineering/node_modules/tunnel-ssh/README.md b/reverse_engineering/node_modules/tunnel-ssh/README.md deleted file mode 100644 index 1ad850d..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/README.md +++ /dev/null @@ -1,139 +0,0 @@ -Tunnel-SSH -========== - -One to connect them all ! - -![Tunnel-SSH Logo](http://i.imgur.com/I5PRnDD.jpg) - -Tunnel-ssh is based on the fantastic [ssh2](https://github.com/mscdex/ssh2) library by Brian White. -Trouble ? Please study the ssh2 configuration. - -### Latest Relese 4.1.3 - -## Release notes -* Closing sshconnections correctly thx @actionshrimp -* Improved readme -* Updated modules - -Special thanks to -@vweevers and @dickeyxxx - - -### Related projects -* [If you don't want to wrap a tunnel around your code: inject-tunnel-ssh](https://github.com/agebrock/inject-tunnel-ssh) -* [If you need it the other way around: reverse-tunnel-ssh](https://github.com/agebrock/reverse-tunnel-ssh) - -### Integration -By default tunnel-ssh will close the tunnel after a client disconnects, so your cli tools should work in the same way, they do if you connect directly. -If you need the tunnel to stay open, use the "keepAlive:true" option within -the configuration. - - -```js - - var config = { - ... - keepAlive:true - }; - - var tnl = tunnel(config, function(error, tnl){ - yourClient.connect(); - yourClient.disconnect(); - setTimeout(function(){ - // you only need to close the tunnel by yourself if you set the - // keepAlive:true option in the configuration ! - tnl.close(); - },2000); - }); - - // you can also close the tunnel from here... - setTimeout(function(){ - tnl.close(); - },2000); - -``` - - -## Understanding the configuration - -1. A local server listening for connections to forward via ssh -Description: This is where you bind your interface. -Properties: -** localHost (default is '127.0.0.1') -** localPort (default is dstPort) - - -2. The ssh configuration -Description: The host you want to use as ssh-tunnel server. -Properties: -** host -** port (22) -** username -** ... - - -3. The destination host configuration (based on the ssh host) -Imagine you just connected to The host you want to connect to. (via host:port) -now that server connects requires a target to tunnel to. -Properties: -** dstHost (localhost) -** dstPort - - -### Config example - -```js - - var config = { - username:'root', - password:'secret', - host:sshServer, - port:22, - dstHost:destinationServer, - dstPort:27017, - localHost:'127.0.0.1', - localPort: 27000 - }; - - var tunnel = require('tunnel-ssh'); - tunnel(config, function (error, server) { - //.... - }); -``` -#### Sugar configuration - -tunnel-ssh assumes that you want to map the same port on a remote machine to your localhost using the ssh-server on the remote machine. - - -```js - - var config = { - username:'root', - dstHost:'remotehost.with.sshserver.com', - dstPort:27017, - privateKey:require(fs).readFileSync('/path/to/key'), - passphrase:'secret' - }; - -``` - -#### More configuration options -tunnel-ssh pipes the configuration direct into the ssh2 library so every config option provided by ssh2 still works. -[ssh2 configuration](https://github.com/mscdex/ssh2#client-methods) - - -#### catching errors: -```js - var tunnel = require('tunnel-ssh'); - //map port from remote 3306 to localhost 3306 - var server = tunnel({host: '172.16.0.8', dstPort: 3306}, function (error, server) { - if(error){ - //catch configuration and startup errors here. - } - }); - - // Use a listener to handle errors outside the callback - server.on('error', function(err){ - console.error('Something bad happened:', err); - }); -``` diff --git a/reverse_engineering/node_modules/tunnel-ssh/examples/default.js b/reverse_engineering/node_modules/tunnel-ssh/examples/default.js deleted file mode 100644 index c54e4e3..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/examples/default.js +++ /dev/null @@ -1,26 +0,0 @@ -var tunnel = require('../'); -var helper = require('./server'); - - -/** -make sure you can connect to your own machine with the current user without password. -Example: ssh $USER@127.0.0.1 - -Remember to add your privateKey to your ssh-agent (ssh-add) -**/ - -var config = { - host: '127.0.0.1', username: process.env.USER, dstPort: 8000, localPort: 7000 -}; - -var fakeServer = helper.createServer(config.dstPort, '127.0.0.1', function () { - tunnel(config, function () { - console.log('Tunnel open'); - helper.createClient(7000, '127.0.0.1', console.log); - helper.createClient(7000, '127.0.0.1', console.log); - }).on('error', function (e) { - console.log('error', e); - }); -}); - -fakeServer.unref(); diff --git a/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive.js b/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive.js deleted file mode 100644 index dbc4fe7..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive.js +++ /dev/null @@ -1,35 +0,0 @@ -var tunnel = require('../'); -var helper = require('./server'); - -// Keep alive example -// this example demonstrates the keepAlive option. -// keepAlive will reuse the connections -// note the "tunnelKeepAlive.close();" at the end. -// this step is required to finish execution nicely - -var configA = { - host: '127.0.0.1', username: process.env.USER, dstPort: 8000, localPort: 7000, // Use keepAlive:true to keep the tunnel open. - keepAlive: true -}; - -var fakeServer = helper.createServer(configA.dstPort, '127.0.0.1', function () { - var tunnelKeepAlive = tunnel(configA, function () { - console.log('Tunnel open'); - helper.createClient(7000, '127.0.0.1', console.log); - helper.createClient(7000, '127.0.0.1', console.log); - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - setTimeout(function () { - // Call tunnel.close() to shutdown the server. - console.log('TRYING TO CLOSE'); - tunnelKeepAlive.close(); - }, 2000); - }); - }); - }); - }).on('error', function (e) { - console.log('error', e); - }); -}); -fakeServer.unref(); diff --git a/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive_error.js b/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive_error.js deleted file mode 100644 index 329551e..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/examples/keepAlive_error.js +++ /dev/null @@ -1,35 +0,0 @@ -var tunnel = require('../'); -var helper = require('./server'); - -// Keep alive example -// this example demonstrates the keepAlive option. -// keepAlive will reuse the connections -// note the "tunnelKeepAlive.close();" at the end. -// this step is required to finish execution nicely - -var configA = { - host: '127.0.0.1', - username: process.env.USER, - dstPort: 8000, - localPort: 7000, // Use keepAlive:true to keep the tunnel open. - keepAlive: true -}; -var tunnelKeepAlive = tunnel(configA, function () { - console.log('Tunnel open'); - helper.createClient(7000, '127.0.0.1', console.log); - helper.createClient(7000, '127.0.0.1', console.log); - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function () { - setTimeout(function () { - // Call tunnel.close() to shutdown the server. - console.log('TRYING TO CLOSE'); - tunnelKeepAlive.close(); - }, 2000); - }); - }); - }); -}).on('error', function (e) { - console.log('error', e); -}); - diff --git a/reverse_engineering/node_modules/tunnel-ssh/examples/server/index.js b/reverse_engineering/node_modules/tunnel-ssh/examples/server/index.js deleted file mode 100644 index 6b44457..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/examples/server/index.js +++ /dev/null @@ -1,36 +0,0 @@ -var net = require('net'); -var debug = require('debug')('tunnel-ssh:test-server-client'); - -function createServer(port, addr, callback) { - var handleConnection = function (socket) { - socket.on('data', function (data) { - debug('server::data', data); - }); - debug('server::write'); - socket.write('Echo server\r\n'); - }; - - return net.createServer(handleConnection).listen(port, addr, callback); -} - -function createClient(port, addr, callback) { - var client = new net.Socket(); - - client.on('error', function (e) { - console.log('errortest', e); - }); - - client.connect(port, addr, function () { - debug('client::write'); - client.write('alive !'); - setTimeout(function () { - client.end(); - debug('client::end'); - callback(null, true); - }, 300); - }); - return client; -} - -exports.createServer = createServer; -exports.createClient = createClient; diff --git a/reverse_engineering/node_modules/tunnel-ssh/index.js b/reverse_engineering/node_modules/tunnel-ssh/index.js deleted file mode 100644 index 5f26080..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/index.js +++ /dev/null @@ -1,112 +0,0 @@ -var net = require('net'); -var debug = require('debug')('tunnel-ssh'); -var Connection = require('ssh2').Client; -var createConfig = require('./lib/config'); -var events = require('events'); -var noop = function () { -}; - -function bindSSHConnection(config, netConnection) { - var sshConnection = new Connection(); - netConnection.on('close', sshConnection.end.bind(sshConnection)); - - sshConnection.on('ready', function () { - debug('sshConnection:ready'); - netConnection.emit('sshConnection', sshConnection, netConnection); - sshConnection.forwardOut(config.srcHost, config.srcPort, config.dstHost, config.dstPort, function (err, sshStream) { - if (err) { - // Bubble up the error => netConnection => server - netConnection.emit('error', err); - debug('Destination port:', err); - return; - } - - debug('sshStream:create'); - netConnection.emit('sshStream', sshStream); - netConnection.pipe(sshStream).pipe(netConnection); - }); - }); - return sshConnection; -} - -function omit(obj, keys) { - return keys.reduce(function (copyObj, key) { - delete copyObj[key]; - return copyObj; - }, Object.assign({}, obj)); -} - -function createServer(config) { - var server; - var connections = []; - var connectionCount = 0; - - server = net.createServer(function (netConnection) { - var sshConnection; - connectionCount++; - netConnection.on('error', server.emit.bind(server, 'error')); - netConnection.on('close', function () { - connectionCount--; - if (connectionCount === 0) { - if (!config.keepAlive) { - setTimeout(function () { - if (connectionCount === 0) { - server.close(); - } - }, 2); - } - } - }); - - server.emit('netConnection', netConnection, server); - sshConnection = bindSSHConnection(config, netConnection); - sshConnection.on('error', server.emit.bind(server, 'error')); - - netConnection.on('sshStream', function (sshStream) { - sshStream.on('error', function () { - server.close(); - }); - }); - - connections.push(sshConnection, netConnection); - try { - sshConnection.connect(omit(config, ['localPort', 'localHost'])); - } catch (error) { - server.emit('error', error); - } - }); - - server.on('close', function () { - connections.forEach(function (connection) { - connection.end(); - }); - }); - - return server; -} - -function tunnel(configArgs, callback) { - var server; - var config; - - if (!callback) { - callback = noop; - } - try { - config = createConfig(configArgs); - server = createServer(config); - - server.listen(config.localPort, config.localHost, function (error) { - callback(error, server); - }); - } catch (e) { - server = new events.EventEmitter(); - setImmediate(function () { - callback(e); - server.emit('error', e); - }); - } - return server; -} - -module.exports = tunnel; diff --git a/reverse_engineering/node_modules/tunnel-ssh/lib/config.js b/reverse_engineering/node_modules/tunnel-ssh/lib/config.js deleted file mode 100644 index 99b1996..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/lib/config.js +++ /dev/null @@ -1,53 +0,0 @@ -var util = require('util'); -var defaults = require('lodash.defaults'); -var debug = require('debug')('tunnel-ssh-config'); - -var ConfigError = function (message, extra) { - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - this.message = message; - this.extra = extra; -}; - -util.inherits(ConfigError, Error); - -function createConfig(config) { - var env = process.env; - - defaults(config || {}, { - username: env.TUNNELSSH_USER || env.USER || env.USERNAME || 'root', - port: 22, - host: null, - srcPort: 0, - srcHost: '127.0.0.1', - dstPort: null, - dstHost: '127.0.0.1', - localHost: '127.0.0.1', - localPort: config.dstPort, - agent: process.env.SSH_AUTH_SOCK - }); - - if (!config.host) { - throw new ConfigError('host not set'); - } - - if (!config.dstPort) { - throw new ConfigError('dstPort not set'); - } - debug('ssh-config', (function () { - var hiddenValues = ['password', 'privateKey']; - - return Object.keys(config).reduce(function (obj, key) { - if (hiddenValues.indexOf(key) === -1) { - obj[key] = config[key]; - } else { - obj[key] = '***HIDDEN***'; - } - return obj; - }, {}); - })()); - - return config; -} - -module.exports = createConfig; diff --git a/reverse_engineering/node_modules/tunnel-ssh/package.json b/reverse_engineering/node_modules/tunnel-ssh/package.json deleted file mode 100644 index 9841fd9..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/package.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "_from": "tunnel-ssh@^4.1.6", - "_id": "tunnel-ssh@4.1.6", - "_inBundle": false, - "_integrity": "sha512-y7+x+T3F3rkx2Zov5Tk9DGfeEBVAdWU3A/91E0Dk5rrZ/VFIlpV2uhhRuaISJUdyG0N+Lcp1fXZMXz+ovPt5vA==", - "_location": "/tunnel-ssh", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "tunnel-ssh@^4.1.6", - "name": "tunnel-ssh", - "escapedName": "tunnel-ssh", - "rawSpec": "^4.1.6", - "saveSpec": null, - "fetchSpec": "^4.1.6" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmjs.org/tunnel-ssh/-/tunnel-ssh-4.1.6.tgz", - "_shasum": "9409e8e98d019ab6207d65807ad3851144dbc1d9", - "_spec": "tunnel-ssh@^4.1.6", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering", - "author": { - "name": "Christoph Hagenbrock", - "email": "christoph.hagenbrock@googlemail.com" - }, - "bugs": { - "url": "https://github.com/agebrock/tunnel-ssh/issues" - }, - "bundleDependencies": false, - "dependencies": { - "debug": "2.6.9", - "lodash.defaults": "^4.1.0", - "ssh2": "1.4.0" - }, - "deprecated": false, - "description": "Easy extendable SSH tunnel", - "devDependencies": { - "chai": "3.5.0", - "eslint": "^3.2.2", - "eslint-config-xo": "^0.17.0", - "mocha": "^3.5.3" - }, - "eslintConfig": { - "extends": "xo", - "env": { - "mocha": true - }, - "rules": { - "indent": [ - "error", - 4 - ] - } - }, - "homepage": "https://github.com/agebrock/tunnel-ssh#readme", - "keywords": [ - "tunnel", - "ssh", - "mysql", - "develop", - "net" - ], - "license": "MIT", - "main": "index.js", - "name": "tunnel-ssh", - "repository": { - "type": "git", - "url": "git+https://github.com/agebrock/tunnel-ssh.git" - }, - "scripts": { - "test": "mocha && eslint ." - }, - "version": "4.1.6" -} diff --git a/reverse_engineering/node_modules/tunnel-ssh/test/config-spec.js b/reverse_engineering/node_modules/tunnel-ssh/test/config-spec.js deleted file mode 100644 index 24229da..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/test/config-spec.js +++ /dev/null @@ -1,56 +0,0 @@ -var chai = require('chai'); -var expect = chai.expect; -var createConfig = require('../lib/config'); - -describe('config', function () { - it('use dstPort as localPort', function () { - var config = { - host: 'test.host', dstPort: 8000 - }; - expect(createConfig(config).localPort).to.be.equal(8000); - }); - - it('should emit an error', function () { - var config = { - host: 'remoteHost' - }; - expect(createConfig.bind(null, config)).to.throw('dstPort not set'); - }); - - it('throws an error if host is missing', function () { - var config = { - dstPort: 8000 - }; - expect(createConfig.bind(null, config)).to.throw('host not set'); - }); -}); - -/* - // Keep alive - var configA = { - host: '127.0.0.1', - username: process.env.USER, - dstPort: 8000, - localPort: 7000, - // Use keepAlive:true to keep the tunnel open. - keepAlive: true - }; - var tunnelKeepAlive = tunnel(configA, function() { - console.log('Tunnel open'); - helper.createClient(7000, '127.0.0.1', console.log).on('close', function() { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function() { - helper.createClient(7000, '127.0.0.1', console.log).on('close', function() { - setTimeout(function() { - // Call tunnel.close() to shutdown the server. - console.log('TRYING TO CLOSE'); - tunnelKeepAlive.close(); - }, 2000); - }); - }); - }); - }).on('error', function(e) { - console.log('error', e); - }); - }); - - */ diff --git a/reverse_engineering/node_modules/tunnel-ssh/test/main-spec.js b/reverse_engineering/node_modules/tunnel-ssh/test/main-spec.js deleted file mode 100644 index c95d2fa..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/test/main-spec.js +++ /dev/null @@ -1,37 +0,0 @@ -var tunnel = require('../'); -var helper = require('./server'); -var chai = require('chai'); -var expect = chai.expect; - -describe('tunnel-ssh', function () { - it('should emit an error', function (done) { - var config = { - host: '127.0.0.1', username: process.env.USER, dstPort: 8000, localPort: 7000 - }; - - tunnel(config, function () { - helper.createClient(7000, '127.0.0.1', done); - }).on('error', function (e) { - expect(e).to.be.instanceOf(Error); - done(null); - }); - }); - - it('brokenConfig, should callback an error', function (done) { - var brokenConfig = {}; - - tunnel(brokenConfig, function (e) { - expect(e).to.be.instanceOf(Error); - done(); - }); - }); - - it('brokenConfig, should emit an error', function (done) { - var brokenConfig = {}; - - tunnel(brokenConfig).on('error', function (e) { - expect(e).to.be.instanceOf(Error); - done(null); - }); - }); -}); diff --git a/reverse_engineering/node_modules/tunnel-ssh/test/server/index.js b/reverse_engineering/node_modules/tunnel-ssh/test/server/index.js deleted file mode 100644 index 2988288..0000000 --- a/reverse_engineering/node_modules/tunnel-ssh/test/server/index.js +++ /dev/null @@ -1,36 +0,0 @@ -var net = require('net'); -var debug = require('debug')('tunnel-ssh:test-server-client'); - -function createServer(port, addr, callback) { - var handleConnection = function (socket) { - socket.on('data', function (data) { - debug('server::data', data); - }); - debug('server::write'); - socket.write('Echo server\r\n'); - }; - - return net.createServer(handleConnection).listen(port, addr, callback); -} - -function createClient(port, addr, callback) { - var client = new net.Socket(); - - client.on('error', function (e) { - debug('clientError', e); - }); - - client.connect(port, addr, function () { - debug('client::write'); - client.write('alive !'); - setTimeout(function () { - client.end(); - debug('client::end'); - callback(null, true); - }, 300); - }); - return client; -} - -exports.createServer = createServer; -exports.createClient = createClient; diff --git a/reverse_engineering/node_modules/tweetnacl/.npmignore b/reverse_engineering/node_modules/tweetnacl/.npmignore deleted file mode 100644 index 7d98dcb..0000000 --- a/reverse_engineering/node_modules/tweetnacl/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -.eslintrc -.travis.yml -bower.json -test diff --git a/reverse_engineering/node_modules/tweetnacl/AUTHORS.md b/reverse_engineering/node_modules/tweetnacl/AUTHORS.md deleted file mode 100644 index 6d74d40..0000000 --- a/reverse_engineering/node_modules/tweetnacl/AUTHORS.md +++ /dev/null @@ -1,28 +0,0 @@ -List of TweetNaCl.js authors -============================ - - Alphabetical order by first name. - Format: Name (GitHub username or URL) - -* AndSDev (@AndSDev) -* Devi Mandiri (@devi) -* Dmitry Chestnykh (@dchest) - -List of authors of third-party public domain code from which TweetNaCl.js code was derived -========================================================================================== - -[TweetNaCl](http://tweetnacl.cr.yp.to/) --------------------------------------- - -* Bernard van Gastel -* Daniel J. Bernstein -* Peter Schwabe -* Sjaak Smetsers -* Tanja Lange -* Wesley Janssen - - -[Poly1305-donna](https://github.com/floodyberry/poly1305-donna) --------------------------------------------------------------- - -* Andrew Moon (@floodyberry) diff --git a/reverse_engineering/node_modules/tweetnacl/CHANGELOG.md b/reverse_engineering/node_modules/tweetnacl/CHANGELOG.md deleted file mode 100644 index 92a4fdc..0000000 --- a/reverse_engineering/node_modules/tweetnacl/CHANGELOG.md +++ /dev/null @@ -1,221 +0,0 @@ -TweetNaCl.js Changelog -====================== - - -v0.14.5 -------- - -* Fixed incomplete return types in TypeScript typings. -* Replaced COPYING.txt with LICENSE file, which now has public domain dedication - text from The Unlicense. License fields in package.json and bower.json have - been set to "Unlicense". The project was and will be in the public domain -- - this change just makes it easier for automated tools to know about this fact by - using the widely recognized and SPDX-compatible template for public domain - dedication. - - -v0.14.4 -------- - -* Added TypeScript type definitions (contributed by @AndSDev). -* Improved benchmarking code. - - -v0.14.3 -------- - -Fixed a bug in the fast version of Poly1305 and brought it back. - -Thanks to @floodyberry for promptly responding and fixing the original C code: - -> "The issue was not properly detecting if st->h was >= 2^130 - 5, coupled with -> [testing mistake] not catching the failure. The chance of the bug affecting -> anything in the real world is essentially zero luckily, but it's good to have -> it fixed." - -https://github.com/floodyberry/poly1305-donna/issues/2#issuecomment-202698577 - - -v0.14.2 -------- - -Switched Poly1305 fast version back to original (slow) version due to a bug. - - -v0.14.1 -------- - -No code changes, just tweaked packaging and added COPYING.txt. - - -v0.14.0 -------- - -* **Breaking change!** All functions from `nacl.util` have been removed. These - functions are no longer available: - - nacl.util.decodeUTF8 - nacl.util.encodeUTF8 - nacl.util.decodeBase64 - nacl.util.encodeBase64 - - If want to continue using them, you can include - package: - - - - - or - - var nacl = require('tweetnacl'); - nacl.util = require('tweetnacl-util'); - - However it is recommended to use better packages that have wider - compatibility and better performance. Functions from `nacl.util` were never - intended to be robust solution for string conversion and were included for - convenience: cryptography library is not the right place for them. - - Currently calling these functions will throw error pointing to - `tweetnacl-util-js` (in the next version this error message will be removed). - -* Improved detection of available random number generators, making it possible - to use `nacl.randomBytes` and related functions in Web Workers without - changes. - -* Changes to testing (see README). - - -v0.13.3 -------- - -No code changes. - -* Reverted license field in package.json to "Public domain". - -* Fixed typo in README. - - -v0.13.2 -------- - -* Fixed undefined variable bug in fast version of Poly1305. No worries, this - bug was *never* triggered. - -* Specified CC0 public domain dedication. - -* Updated development dependencies. - - -v0.13.1 -------- - -* Exclude `crypto` and `buffer` modules from browserify builds. - - -v0.13.0 -------- - -* Made `nacl-fast` the default version in NPM package. Now - `require("tweetnacl")` will use fast version; to get the original version, - use `require("tweetnacl/nacl.js")`. - -* Cleanup temporary array after generating random bytes. - - -v0.12.2 -------- - -* Improved performance of curve operations, making `nacl.scalarMult`, `nacl.box`, - `nacl.sign` and related functions up to 3x faster in `nacl-fast` version. - - -v0.12.1 -------- - -* Significantly improved performance of Salsa20 (~1.5x faster) and - Poly1305 (~3.5x faster) in `nacl-fast` version. - - -v0.12.0 -------- - -* Instead of using the given secret key directly, TweetNaCl.js now copies it to - a new array in `nacl.box.keyPair.fromSecretKey` and - `nacl.sign.keyPair.fromSecretKey`. - - -v0.11.2 -------- - -* Added new constant: `nacl.sign.seedLength`. - - -v0.11.1 -------- - -* Even faster hash for both short and long inputs (in `nacl-fast`). - - -v0.11.0 -------- - -* Implement `nacl.sign.keyPair.fromSeed` to enable creation of sign key pairs - deterministically from a 32-byte seed. (It behaves like - [libsodium's](http://doc.libsodium.org/public-key_cryptography/public-key_signatures.html) - `crypto_sign_seed_keypair`: the seed becomes a secret part of the secret key.) - -* Fast version now has an improved hash implementation that is 2x-5x faster. - -* Fixed benchmarks, which may have produced incorrect measurements. - - -v0.10.1 -------- - -* Exported undocumented `nacl.lowlevel.crypto_core_hsalsa20`. - - -v0.10.0 -------- - -* **Signature API breaking change!** `nacl.sign` and `nacl.sign.open` now deal - with signed messages, and new `nacl.sign.detached` and - `nacl.sign.detached.verify` are available. - - Previously, `nacl.sign` returned a signature, and `nacl.sign.open` accepted a - message and "detached" signature. This was unlike NaCl's API, which dealt with - signed messages (concatenation of signature and message). - - The new API is: - - nacl.sign(message, secretKey) -> signedMessage - nacl.sign.open(signedMessage, publicKey) -> message | null - - Since detached signatures are common, two new API functions were introduced: - - nacl.sign.detached(message, secretKey) -> signature - nacl.sign.detached.verify(message, signature, publicKey) -> true | false - - (Note that it's `verify`, not `open`, and it returns a boolean value, unlike - `open`, which returns an "unsigned" message.) - -* NPM package now comes without `test` directory to keep it small. - - -v0.9.2 ------- - -* Improved documentation. -* Fast version: increased theoretical message size limit from 2^32-1 to 2^52 - bytes in Poly1305 (and thus, secretbox and box). However this has no impact - in practice since JavaScript arrays or ArrayBuffers are limited to 32-bit - indexes, and most implementations won't allocate more than a gigabyte or so. - (Obviously, there are no tests for the correctness of implementation.) Also, - it's not recommended to use messages that large without splitting them into - smaller packets anyway. - - -v0.9.1 ------- - -* Initial release diff --git a/reverse_engineering/node_modules/tweetnacl/LICENSE b/reverse_engineering/node_modules/tweetnacl/LICENSE deleted file mode 100644 index cf1ab25..0000000 --- a/reverse_engineering/node_modules/tweetnacl/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - -For more information, please refer to diff --git a/reverse_engineering/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md b/reverse_engineering/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index a8eb4a9..0000000 --- a/reverse_engineering/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,20 +0,0 @@ -# Important! - -If your contribution is not trivial (not a typo fix, etc.), we can only accept -it if you dedicate your copyright for the contribution to the public domain. -Make sure you understand what it means (see http://unlicense.org/)! If you -agree, please add yourself to AUTHORS.md file, and include the following text -to your pull request description or a comment in it: - ------------------------------------------------------------------------------- - - I dedicate any and all copyright interest in this software to the - public domain. I make this dedication for the benefit of the public at - large and to the detriment of my heirs and successors. I intend this - dedication to be an overt act of relinquishment in perpetuity of all - present and future rights to this software under copyright law. - - Anyone is free to copy, modify, publish, use, compile, sell, or - distribute this software, either in source code form or as a compiled - binary, for any purpose, commercial or non-commercial, and by any - means. diff --git a/reverse_engineering/node_modules/tweetnacl/README.md b/reverse_engineering/node_modules/tweetnacl/README.md deleted file mode 100644 index ffb6871..0000000 --- a/reverse_engineering/node_modules/tweetnacl/README.md +++ /dev/null @@ -1,459 +0,0 @@ -TweetNaCl.js -============ - -Port of [TweetNaCl](http://tweetnacl.cr.yp.to) / [NaCl](http://nacl.cr.yp.to/) -to JavaScript for modern browsers and Node.js. Public domain. - -[![Build Status](https://travis-ci.org/dchest/tweetnacl-js.svg?branch=master) -](https://travis-ci.org/dchest/tweetnacl-js) - -Demo: - -**:warning: The library is stable and API is frozen, however it has not been -independently reviewed. If you can help reviewing it, please [contact -me](mailto:dmitry@codingrobots.com).** - -Documentation -============= - -* [Overview](#overview) -* [Installation](#installation) -* [Usage](#usage) - * [Public-key authenticated encryption (box)](#public-key-authenticated-encryption-box) - * [Secret-key authenticated encryption (secretbox)](#secret-key-authenticated-encryption-secretbox) - * [Scalar multiplication](#scalar-multiplication) - * [Signatures](#signatures) - * [Hashing](#hashing) - * [Random bytes generation](#random-bytes-generation) - * [Constant-time comparison](#constant-time-comparison) -* [System requirements](#system-requirements) -* [Development and testing](#development-and-testing) -* [Benchmarks](#benchmarks) -* [Contributors](#contributors) -* [Who uses it](#who-uses-it) - - -Overview --------- - -The primary goal of this project is to produce a translation of TweetNaCl to -JavaScript which is as close as possible to the original C implementation, plus -a thin layer of idiomatic high-level API on top of it. - -There are two versions, you can use either of them: - -* `nacl.js` is the port of TweetNaCl with minimum differences from the - original + high-level API. - -* `nacl-fast.js` is like `nacl.js`, but with some functions replaced with - faster versions. - - -Installation ------------- - -You can install TweetNaCl.js via a package manager: - -[Bower](http://bower.io): - - $ bower install tweetnacl - -[NPM](https://www.npmjs.org/): - - $ npm install tweetnacl - -or [download source code](https://github.com/dchest/tweetnacl-js/releases). - - -Usage ------ - -All API functions accept and return bytes as `Uint8Array`s. If you need to -encode or decode strings, use functions from - or one of the more robust codec -packages. - -In Node.js v4 and later `Buffer` objects are backed by `Uint8Array`s, so you -can freely pass them to TweetNaCl.js functions as arguments. The returned -objects are still `Uint8Array`s, so if you need `Buffer`s, you'll have to -convert them manually; make sure to convert using copying: `new Buffer(array)`, -instead of sharing: `new Buffer(array.buffer)`, because some functions return -subarrays of their buffers. - - -### Public-key authenticated encryption (box) - -Implements *curve25519-xsalsa20-poly1305*. - -#### nacl.box.keyPair() - -Generates a new random key pair for box and returns it as an object with -`publicKey` and `secretKey` members: - - { - publicKey: ..., // Uint8Array with 32-byte public key - secretKey: ... // Uint8Array with 32-byte secret key - } - - -#### nacl.box.keyPair.fromSecretKey(secretKey) - -Returns a key pair for box with public key corresponding to the given secret -key. - -#### nacl.box(message, nonce, theirPublicKey, mySecretKey) - -Encrypt and authenticates message using peer's public key, our secret key, and -the given nonce, which must be unique for each distinct message for a key pair. - -Returns an encrypted and authenticated message, which is -`nacl.box.overheadLength` longer than the original message. - -#### nacl.box.open(box, nonce, theirPublicKey, mySecretKey) - -Authenticates and decrypts the given box with peer's public key, our secret -key, and the given nonce. - -Returns the original message, or `false` if authentication fails. - -#### nacl.box.before(theirPublicKey, mySecretKey) - -Returns a precomputed shared key which can be used in `nacl.box.after` and -`nacl.box.open.after`. - -#### nacl.box.after(message, nonce, sharedKey) - -Same as `nacl.box`, but uses a shared key precomputed with `nacl.box.before`. - -#### nacl.box.open.after(box, nonce, sharedKey) - -Same as `nacl.box.open`, but uses a shared key precomputed with `nacl.box.before`. - -#### nacl.box.publicKeyLength = 32 - -Length of public key in bytes. - -#### nacl.box.secretKeyLength = 32 - -Length of secret key in bytes. - -#### nacl.box.sharedKeyLength = 32 - -Length of precomputed shared key in bytes. - -#### nacl.box.nonceLength = 24 - -Length of nonce in bytes. - -#### nacl.box.overheadLength = 16 - -Length of overhead added to box compared to original message. - - -### Secret-key authenticated encryption (secretbox) - -Implements *xsalsa20-poly1305*. - -#### nacl.secretbox(message, nonce, key) - -Encrypt and authenticates message using the key and the nonce. The nonce must -be unique for each distinct message for this key. - -Returns an encrypted and authenticated message, which is -`nacl.secretbox.overheadLength` longer than the original message. - -#### nacl.secretbox.open(box, nonce, key) - -Authenticates and decrypts the given secret box using the key and the nonce. - -Returns the original message, or `false` if authentication fails. - -#### nacl.secretbox.keyLength = 32 - -Length of key in bytes. - -#### nacl.secretbox.nonceLength = 24 - -Length of nonce in bytes. - -#### nacl.secretbox.overheadLength = 16 - -Length of overhead added to secret box compared to original message. - - -### Scalar multiplication - -Implements *curve25519*. - -#### nacl.scalarMult(n, p) - -Multiplies an integer `n` by a group element `p` and returns the resulting -group element. - -#### nacl.scalarMult.base(n) - -Multiplies an integer `n` by a standard group element and returns the resulting -group element. - -#### nacl.scalarMult.scalarLength = 32 - -Length of scalar in bytes. - -#### nacl.scalarMult.groupElementLength = 32 - -Length of group element in bytes. - - -### Signatures - -Implements [ed25519](http://ed25519.cr.yp.to). - -#### nacl.sign.keyPair() - -Generates new random key pair for signing and returns it as an object with -`publicKey` and `secretKey` members: - - { - publicKey: ..., // Uint8Array with 32-byte public key - secretKey: ... // Uint8Array with 64-byte secret key - } - -#### nacl.sign.keyPair.fromSecretKey(secretKey) - -Returns a signing key pair with public key corresponding to the given -64-byte secret key. The secret key must have been generated by -`nacl.sign.keyPair` or `nacl.sign.keyPair.fromSeed`. - -#### nacl.sign.keyPair.fromSeed(seed) - -Returns a new signing key pair generated deterministically from a 32-byte seed. -The seed must contain enough entropy to be secure. This method is not -recommended for general use: instead, use `nacl.sign.keyPair` to generate a new -key pair from a random seed. - -#### nacl.sign(message, secretKey) - -Signs the message using the secret key and returns a signed message. - -#### nacl.sign.open(signedMessage, publicKey) - -Verifies the signed message and returns the message without signature. - -Returns `null` if verification failed. - -#### nacl.sign.detached(message, secretKey) - -Signs the message using the secret key and returns a signature. - -#### nacl.sign.detached.verify(message, signature, publicKey) - -Verifies the signature for the message and returns `true` if verification -succeeded or `false` if it failed. - -#### nacl.sign.publicKeyLength = 32 - -Length of signing public key in bytes. - -#### nacl.sign.secretKeyLength = 64 - -Length of signing secret key in bytes. - -#### nacl.sign.seedLength = 32 - -Length of seed for `nacl.sign.keyPair.fromSeed` in bytes. - -#### nacl.sign.signatureLength = 64 - -Length of signature in bytes. - - -### Hashing - -Implements *SHA-512*. - -#### nacl.hash(message) - -Returns SHA-512 hash of the message. - -#### nacl.hash.hashLength = 64 - -Length of hash in bytes. - - -### Random bytes generation - -#### nacl.randomBytes(length) - -Returns a `Uint8Array` of the given length containing random bytes of -cryptographic quality. - -**Implementation note** - -TweetNaCl.js uses the following methods to generate random bytes, -depending on the platform it runs on: - -* `window.crypto.getRandomValues` (WebCrypto standard) -* `window.msCrypto.getRandomValues` (Internet Explorer 11) -* `crypto.randomBytes` (Node.js) - -If the platform doesn't provide a suitable PRNG, the following functions, -which require random numbers, will throw exception: - -* `nacl.randomBytes` -* `nacl.box.keyPair` -* `nacl.sign.keyPair` - -Other functions are deterministic and will continue working. - -If a platform you are targeting doesn't implement secure random number -generator, but you somehow have a cryptographically-strong source of entropy -(not `Math.random`!), and you know what you are doing, you can plug it into -TweetNaCl.js like this: - - nacl.setPRNG(function(x, n) { - // ... copy n random bytes into x ... - }); - -Note that `nacl.setPRNG` *completely replaces* internal random byte generator -with the one provided. - - -### Constant-time comparison - -#### nacl.verify(x, y) - -Compares `x` and `y` in constant time and returns `true` if their lengths are -non-zero and equal, and their contents are equal. - -Returns `false` if either of the arguments has zero length, or arguments have -different lengths, or their contents differ. - - -System requirements -------------------- - -TweetNaCl.js supports modern browsers that have a cryptographically secure -pseudorandom number generator and typed arrays, including the latest versions -of: - -* Chrome -* Firefox -* Safari (Mac, iOS) -* Internet Explorer 11 - -Other systems: - -* Node.js - - -Development and testing ------------------------- - -Install NPM modules needed for development: - - $ npm install - -To build minified versions: - - $ npm run build - -Tests use minified version, so make sure to rebuild it every time you change -`nacl.js` or `nacl-fast.js`. - -### Testing - -To run tests in Node.js: - - $ npm run test-node - -By default all tests described here work on `nacl.min.js`. To test other -versions, set environment variable `NACL_SRC` to the file name you want to test. -For example, the following command will test fast minified version: - - $ NACL_SRC=nacl-fast.min.js npm run test-node - -To run full suite of tests in Node.js, including comparing outputs of -JavaScript port to outputs of the original C version: - - $ npm run test-node-all - -To prepare tests for browsers: - - $ npm run build-test-browser - -and then open `test/browser/test.html` (or `test/browser/test-fast.html`) to -run them. - -To run headless browser tests with `tape-run` (powered by Electron): - - $ npm run test-browser - -(If you get `Error: spawn ENOENT`, install *xvfb*: `sudo apt-get install xvfb`.) - -To run tests in both Node and Electron: - - $ npm test - -### Benchmarking - -To run benchmarks in Node.js: - - $ npm run bench - $ NACL_SRC=nacl-fast.min.js npm run bench - -To run benchmarks in a browser, open `test/benchmark/bench.html` (or -`test/benchmark/bench-fast.html`). - - -Benchmarks ----------- - -For reference, here are benchmarks from MacBook Pro (Retina, 13-inch, Mid 2014) -laptop with 2.6 GHz Intel Core i5 CPU (Intel) in Chrome 53/OS X and Xiaomi Redmi -Note 3 smartphone with 1.8 GHz Qualcomm Snapdragon 650 64-bit CPU (ARM) in -Chrome 52/Android: - -| | nacl.js Intel | nacl-fast.js Intel | nacl.js ARM | nacl-fast.js ARM | -| ------------- |:-------------:|:-------------------:|:-------------:|:-----------------:| -| salsa20 | 1.3 MB/s | 128 MB/s | 0.4 MB/s | 43 MB/s | -| poly1305 | 13 MB/s | 171 MB/s | 4 MB/s | 52 MB/s | -| hash | 4 MB/s | 34 MB/s | 0.9 MB/s | 12 MB/s | -| secretbox 1K | 1113 op/s | 57583 op/s | 334 op/s | 14227 op/s | -| box 1K | 145 op/s | 718 op/s | 37 op/s | 368 op/s | -| scalarMult | 171 op/s | 733 op/s | 56 op/s | 380 op/s | -| sign | 77 op/s | 200 op/s | 20 op/s | 61 op/s | -| sign.open | 39 op/s | 102 op/s | 11 op/s | 31 op/s | - -(You can run benchmarks on your devices by clicking on the links at the bottom -of the [home page](https://tweetnacl.js.org)). - -In short, with *nacl-fast.js* and 1024-byte messages you can expect to encrypt and -authenticate more than 57000 messages per second on a typical laptop or more than -14000 messages per second on a $170 smartphone, sign about 200 and verify 100 -messages per second on a laptop or 60 and 30 messages per second on a smartphone, -per CPU core (with Web Workers you can do these operations in parallel), -which is good enough for most applications. - - -Contributors ------------- - -See AUTHORS.md file. - - -Third-party libraries based on TweetNaCl.js -------------------------------------------- - -* [forward-secrecy](https://github.com/alax/forward-secrecy) — Axolotl ratchet implementation -* [nacl-stream](https://github.com/dchest/nacl-stream-js) - streaming encryption -* [tweetnacl-auth-js](https://github.com/dchest/tweetnacl-auth-js) — implementation of [`crypto_auth`](http://nacl.cr.yp.to/auth.html) -* [chloride](https://github.com/dominictarr/chloride) - unified API for various NaCl modules - - -Who uses it ------------ - -Some notable users of TweetNaCl.js: - -* [miniLock](http://minilock.io/) -* [Stellar](https://www.stellar.org/) diff --git a/reverse_engineering/node_modules/tweetnacl/nacl-fast.js b/reverse_engineering/node_modules/tweetnacl/nacl-fast.js deleted file mode 100644 index 5e4562f..0000000 --- a/reverse_engineering/node_modules/tweetnacl/nacl-fast.js +++ /dev/null @@ -1,2388 +0,0 @@ -(function(nacl) { -'use strict'; - -// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -// -// Implementation derived from TweetNaCl version 20140427. -// See for details: http://tweetnacl.cr.yp.to/ - -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; -}; - -// Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - -var _0 = new Uint8Array(16); -var _9 = new Uint8Array(32); _9[0] = 9; - -var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - -function ts64(x, i, h, l) { - x[i] = (h >> 24) & 0xff; - x[i+1] = (h >> 16) & 0xff; - x[i+2] = (h >> 8) & 0xff; - x[i+3] = h & 0xff; - x[i+4] = (l >> 24) & 0xff; - x[i+5] = (l >> 16) & 0xff; - x[i+6] = (l >> 8) & 0xff; - x[i+7] = l & 0xff; -} - -function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; -} - -function crypto_verify_16(x, xi, y, yi) { - return vn(x,xi,y,yi,16); -} - -function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); -} - -function core_salsa20(o, p, k, c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; - - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; - - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); - - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); - - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); - - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); - - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); - - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); - - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); - - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); - } - x0 = x0 + j0 | 0; - x1 = x1 + j1 | 0; - x2 = x2 + j2 | 0; - x3 = x3 + j3 | 0; - x4 = x4 + j4 | 0; - x5 = x5 + j5 | 0; - x6 = x6 + j6 | 0; - x7 = x7 + j7 | 0; - x8 = x8 + j8 | 0; - x9 = x9 + j9 | 0; - x10 = x10 + j10 | 0; - x11 = x11 + j11 | 0; - x12 = x12 + j12 | 0; - x13 = x13 + j13 | 0; - x14 = x14 + j14 | 0; - x15 = x15 + j15 | 0; - - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; - - o[ 4] = x1 >>> 0 & 0xff; - o[ 5] = x1 >>> 8 & 0xff; - o[ 6] = x1 >>> 16 & 0xff; - o[ 7] = x1 >>> 24 & 0xff; - - o[ 8] = x2 >>> 0 & 0xff; - o[ 9] = x2 >>> 8 & 0xff; - o[10] = x2 >>> 16 & 0xff; - o[11] = x2 >>> 24 & 0xff; - - o[12] = x3 >>> 0 & 0xff; - o[13] = x3 >>> 8 & 0xff; - o[14] = x3 >>> 16 & 0xff; - o[15] = x3 >>> 24 & 0xff; - - o[16] = x4 >>> 0 & 0xff; - o[17] = x4 >>> 8 & 0xff; - o[18] = x4 >>> 16 & 0xff; - o[19] = x4 >>> 24 & 0xff; - - o[20] = x5 >>> 0 & 0xff; - o[21] = x5 >>> 8 & 0xff; - o[22] = x5 >>> 16 & 0xff; - o[23] = x5 >>> 24 & 0xff; - - o[24] = x6 >>> 0 & 0xff; - o[25] = x6 >>> 8 & 0xff; - o[26] = x6 >>> 16 & 0xff; - o[27] = x6 >>> 24 & 0xff; - - o[28] = x7 >>> 0 & 0xff; - o[29] = x7 >>> 8 & 0xff; - o[30] = x7 >>> 16 & 0xff; - o[31] = x7 >>> 24 & 0xff; - - o[32] = x8 >>> 0 & 0xff; - o[33] = x8 >>> 8 & 0xff; - o[34] = x8 >>> 16 & 0xff; - o[35] = x8 >>> 24 & 0xff; - - o[36] = x9 >>> 0 & 0xff; - o[37] = x9 >>> 8 & 0xff; - o[38] = x9 >>> 16 & 0xff; - o[39] = x9 >>> 24 & 0xff; - - o[40] = x10 >>> 0 & 0xff; - o[41] = x10 >>> 8 & 0xff; - o[42] = x10 >>> 16 & 0xff; - o[43] = x10 >>> 24 & 0xff; - - o[44] = x11 >>> 0 & 0xff; - o[45] = x11 >>> 8 & 0xff; - o[46] = x11 >>> 16 & 0xff; - o[47] = x11 >>> 24 & 0xff; - - o[48] = x12 >>> 0 & 0xff; - o[49] = x12 >>> 8 & 0xff; - o[50] = x12 >>> 16 & 0xff; - o[51] = x12 >>> 24 & 0xff; - - o[52] = x13 >>> 0 & 0xff; - o[53] = x13 >>> 8 & 0xff; - o[54] = x13 >>> 16 & 0xff; - o[55] = x13 >>> 24 & 0xff; - - o[56] = x14 >>> 0 & 0xff; - o[57] = x14 >>> 8 & 0xff; - o[58] = x14 >>> 16 & 0xff; - o[59] = x14 >>> 24 & 0xff; - - o[60] = x15 >>> 0 & 0xff; - o[61] = x15 >>> 8 & 0xff; - o[62] = x15 >>> 16 & 0xff; - o[63] = x15 >>> 24 & 0xff; -} - -function core_hsalsa20(o,p,k,c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; - - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; - - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); - - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); - - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); - - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); - - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); - - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); - - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); - - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); - } - - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; - - o[ 4] = x5 >>> 0 & 0xff; - o[ 5] = x5 >>> 8 & 0xff; - o[ 6] = x5 >>> 16 & 0xff; - o[ 7] = x5 >>> 24 & 0xff; - - o[ 8] = x10 >>> 0 & 0xff; - o[ 9] = x10 >>> 8 & 0xff; - o[10] = x10 >>> 16 & 0xff; - o[11] = x10 >>> 24 & 0xff; - - o[12] = x15 >>> 0 & 0xff; - o[13] = x15 >>> 8 & 0xff; - o[14] = x15 >>> 16 & 0xff; - o[15] = x15 >>> 24 & 0xff; - - o[16] = x6 >>> 0 & 0xff; - o[17] = x6 >>> 8 & 0xff; - o[18] = x6 >>> 16 & 0xff; - o[19] = x6 >>> 24 & 0xff; - - o[20] = x7 >>> 0 & 0xff; - o[21] = x7 >>> 8 & 0xff; - o[22] = x7 >>> 16 & 0xff; - o[23] = x7 >>> 24 & 0xff; - - o[24] = x8 >>> 0 & 0xff; - o[25] = x8 >>> 8 & 0xff; - o[26] = x8 >>> 16 & 0xff; - o[27] = x8 >>> 24 & 0xff; - - o[28] = x9 >>> 0 & 0xff; - o[29] = x9 >>> 8 & 0xff; - o[30] = x9 >>> 16 & 0xff; - o[31] = x9 >>> 24 & 0xff; -} - -function crypto_core_salsa20(out,inp,k,c) { - core_salsa20(out,inp,k,c); -} - -function crypto_core_hsalsa20(out,inp,k,c) { - core_hsalsa20(out,inp,k,c); -} - -var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); - // "expand 32-byte k" - -function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - mpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - } - return 0; -} - -function crypto_stream_salsa20(c,cpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = x[i]; - } - return 0; -} - -function crypto_stream(c,cpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20(c,cpos,d,sn,s); -} - -function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); -} - -/* -* Port of Andrew Moon's Poly1305-donna-16. Public domain. -* https://github.com/floodyberry/poly1305-donna -*/ - -var poly1305 = function(key) { - this.buffer = new Uint8Array(16); - this.r = new Uint16Array(10); - this.h = new Uint16Array(10); - this.pad = new Uint16Array(8); - this.leftover = 0; - this.fin = 0; - - var t0, t1, t2, t3, t4, t5, t6, t7; - - t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; - t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; - t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; - this.r[5] = ((t4 >>> 1)) & 0x1ffe; - t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; - t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - this.r[9] = ((t7 >>> 5)) & 0x007f; - - this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; - this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; - this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; - this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; - this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; - this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; - this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; - this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; -}; - -poly1305.prototype.blocks = function(m, mpos, bytes) { - var hibit = this.fin ? 0 : (1 << 11); - var t0, t1, t2, t3, t4, t5, t6, t7, c; - var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; - - var h0 = this.h[0], - h1 = this.h[1], - h2 = this.h[2], - h3 = this.h[3], - h4 = this.h[4], - h5 = this.h[5], - h6 = this.h[6], - h7 = this.h[7], - h8 = this.h[8], - h9 = this.h[9]; - - var r0 = this.r[0], - r1 = this.r[1], - r2 = this.r[2], - r3 = this.r[3], - r4 = this.r[4], - r5 = this.r[5], - r6 = this.r[6], - r7 = this.r[7], - r8 = this.r[8], - r9 = this.r[9]; - - while (bytes >= 16) { - t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; - t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; - t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; - h5 += ((t4 >>> 1)) & 0x1fff; - t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; - t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - h9 += ((t7 >>> 5)) | hibit; - - c = 0; - - d0 = c; - d0 += h0 * r0; - d0 += h1 * (5 * r9); - d0 += h2 * (5 * r8); - d0 += h3 * (5 * r7); - d0 += h4 * (5 * r6); - c = (d0 >>> 13); d0 &= 0x1fff; - d0 += h5 * (5 * r5); - d0 += h6 * (5 * r4); - d0 += h7 * (5 * r3); - d0 += h8 * (5 * r2); - d0 += h9 * (5 * r1); - c += (d0 >>> 13); d0 &= 0x1fff; - - d1 = c; - d1 += h0 * r1; - d1 += h1 * r0; - d1 += h2 * (5 * r9); - d1 += h3 * (5 * r8); - d1 += h4 * (5 * r7); - c = (d1 >>> 13); d1 &= 0x1fff; - d1 += h5 * (5 * r6); - d1 += h6 * (5 * r5); - d1 += h7 * (5 * r4); - d1 += h8 * (5 * r3); - d1 += h9 * (5 * r2); - c += (d1 >>> 13); d1 &= 0x1fff; - - d2 = c; - d2 += h0 * r2; - d2 += h1 * r1; - d2 += h2 * r0; - d2 += h3 * (5 * r9); - d2 += h4 * (5 * r8); - c = (d2 >>> 13); d2 &= 0x1fff; - d2 += h5 * (5 * r7); - d2 += h6 * (5 * r6); - d2 += h7 * (5 * r5); - d2 += h8 * (5 * r4); - d2 += h9 * (5 * r3); - c += (d2 >>> 13); d2 &= 0x1fff; - - d3 = c; - d3 += h0 * r3; - d3 += h1 * r2; - d3 += h2 * r1; - d3 += h3 * r0; - d3 += h4 * (5 * r9); - c = (d3 >>> 13); d3 &= 0x1fff; - d3 += h5 * (5 * r8); - d3 += h6 * (5 * r7); - d3 += h7 * (5 * r6); - d3 += h8 * (5 * r5); - d3 += h9 * (5 * r4); - c += (d3 >>> 13); d3 &= 0x1fff; - - d4 = c; - d4 += h0 * r4; - d4 += h1 * r3; - d4 += h2 * r2; - d4 += h3 * r1; - d4 += h4 * r0; - c = (d4 >>> 13); d4 &= 0x1fff; - d4 += h5 * (5 * r9); - d4 += h6 * (5 * r8); - d4 += h7 * (5 * r7); - d4 += h8 * (5 * r6); - d4 += h9 * (5 * r5); - c += (d4 >>> 13); d4 &= 0x1fff; - - d5 = c; - d5 += h0 * r5; - d5 += h1 * r4; - d5 += h2 * r3; - d5 += h3 * r2; - d5 += h4 * r1; - c = (d5 >>> 13); d5 &= 0x1fff; - d5 += h5 * r0; - d5 += h6 * (5 * r9); - d5 += h7 * (5 * r8); - d5 += h8 * (5 * r7); - d5 += h9 * (5 * r6); - c += (d5 >>> 13); d5 &= 0x1fff; - - d6 = c; - d6 += h0 * r6; - d6 += h1 * r5; - d6 += h2 * r4; - d6 += h3 * r3; - d6 += h4 * r2; - c = (d6 >>> 13); d6 &= 0x1fff; - d6 += h5 * r1; - d6 += h6 * r0; - d6 += h7 * (5 * r9); - d6 += h8 * (5 * r8); - d6 += h9 * (5 * r7); - c += (d6 >>> 13); d6 &= 0x1fff; - - d7 = c; - d7 += h0 * r7; - d7 += h1 * r6; - d7 += h2 * r5; - d7 += h3 * r4; - d7 += h4 * r3; - c = (d7 >>> 13); d7 &= 0x1fff; - d7 += h5 * r2; - d7 += h6 * r1; - d7 += h7 * r0; - d7 += h8 * (5 * r9); - d7 += h9 * (5 * r8); - c += (d7 >>> 13); d7 &= 0x1fff; - - d8 = c; - d8 += h0 * r8; - d8 += h1 * r7; - d8 += h2 * r6; - d8 += h3 * r5; - d8 += h4 * r4; - c = (d8 >>> 13); d8 &= 0x1fff; - d8 += h5 * r3; - d8 += h6 * r2; - d8 += h7 * r1; - d8 += h8 * r0; - d8 += h9 * (5 * r9); - c += (d8 >>> 13); d8 &= 0x1fff; - - d9 = c; - d9 += h0 * r9; - d9 += h1 * r8; - d9 += h2 * r7; - d9 += h3 * r6; - d9 += h4 * r5; - c = (d9 >>> 13); d9 &= 0x1fff; - d9 += h5 * r4; - d9 += h6 * r3; - d9 += h7 * r2; - d9 += h8 * r1; - d9 += h9 * r0; - c += (d9 >>> 13); d9 &= 0x1fff; - - c = (((c << 2) + c)) | 0; - c = (c + d0) | 0; - d0 = c & 0x1fff; - c = (c >>> 13); - d1 += c; - - h0 = d0; - h1 = d1; - h2 = d2; - h3 = d3; - h4 = d4; - h5 = d5; - h6 = d6; - h7 = d7; - h8 = d8; - h9 = d9; - - mpos += 16; - bytes -= 16; - } - this.h[0] = h0; - this.h[1] = h1; - this.h[2] = h2; - this.h[3] = h3; - this.h[4] = h4; - this.h[5] = h5; - this.h[6] = h6; - this.h[7] = h7; - this.h[8] = h8; - this.h[9] = h9; -}; - -poly1305.prototype.finish = function(mac, macpos) { - var g = new Uint16Array(10); - var c, mask, f, i; - - if (this.leftover) { - i = this.leftover; - this.buffer[i++] = 1; - for (; i < 16; i++) this.buffer[i] = 0; - this.fin = 1; - this.blocks(this.buffer, 0, 16); - } - - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - for (i = 2; i < 10; i++) { - this.h[i] += c; - c = this.h[i] >>> 13; - this.h[i] &= 0x1fff; - } - this.h[0] += (c * 5); - c = this.h[0] >>> 13; - this.h[0] &= 0x1fff; - this.h[1] += c; - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - this.h[2] += c; - - g[0] = this.h[0] + 5; - c = g[0] >>> 13; - g[0] &= 0x1fff; - for (i = 1; i < 10; i++) { - g[i] = this.h[i] + c; - c = g[i] >>> 13; - g[i] &= 0x1fff; - } - g[9] -= (1 << 13); - - mask = (c ^ 1) - 1; - for (i = 0; i < 10; i++) g[i] &= mask; - mask = ~mask; - for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; - - this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; - this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; - this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; - this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; - this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; - this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; - this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; - this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; - - f = this.h[0] + this.pad[0]; - this.h[0] = f & 0xffff; - for (i = 1; i < 8; i++) { - f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; - this.h[i] = f & 0xffff; - } - - mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; - mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; - mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; - mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; - mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; - mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; - mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; - mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; - mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; - mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; - mac[macpos+10] = (this.h[5] >>> 0) & 0xff; - mac[macpos+11] = (this.h[5] >>> 8) & 0xff; - mac[macpos+12] = (this.h[6] >>> 0) & 0xff; - mac[macpos+13] = (this.h[6] >>> 8) & 0xff; - mac[macpos+14] = (this.h[7] >>> 0) & 0xff; - mac[macpos+15] = (this.h[7] >>> 8) & 0xff; -}; - -poly1305.prototype.update = function(m, mpos, bytes) { - var i, want; - - if (this.leftover) { - want = (16 - this.leftover); - if (want > bytes) - want = bytes; - for (i = 0; i < want; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - bytes -= want; - mpos += want; - this.leftover += want; - if (this.leftover < 16) - return; - this.blocks(this.buffer, 0, 16); - this.leftover = 0; - } - - if (bytes >= 16) { - want = bytes - (bytes % 16); - this.blocks(m, mpos, want); - mpos += want; - bytes -= want; - } - - if (bytes) { - for (i = 0; i < bytes; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - this.leftover += bytes; - } -}; - -function crypto_onetimeauth(out, outpos, m, mpos, n, k) { - var s = new poly1305(k); - s.update(m, mpos, n); - s.finish(out, outpos); - return 0; -} - -function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { - var x = new Uint8Array(16); - crypto_onetimeauth(x,0,m,mpos,n,k); - return crypto_verify_16(h,hpos,x,0); -} - -function crypto_secretbox(c,m,d,n,k) { - var i; - if (d < 32) return -1; - crypto_stream_xor(c,0,m,0,d,n,k); - crypto_onetimeauth(c, 16, c, 32, d - 32, c); - for (i = 0; i < 16; i++) c[i] = 0; - return 0; -} - -function crypto_secretbox_open(m,c,d,n,k) { - var i; - var x = new Uint8Array(32); - if (d < 32) return -1; - crypto_stream(x,0,32,n,k); - if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; - crypto_stream_xor(m,0,c,0,d,n,k); - for (i = 0; i < 32; i++) m[i] = 0; - return 0; -} - -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} - -function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c-1 + 37 * (c-1); -} - -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} - -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; - } -} - -function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); -} - -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; -} - -function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; -} - -function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; -} - -function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; -} - -function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; - - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is - - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); - - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; -} - -function S(o, a) { - M(o, a, a); -} - -function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; -} - -function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); -} - -function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); -} - -function crypto_box_beforenm(k, y, x) { - var s = new Uint8Array(32); - crypto_scalarmult(s, x, y); - return crypto_core_hsalsa20(k, _0, s, sigma); -} - -var crypto_box_afternm = crypto_secretbox; -var crypto_box_open_afternm = crypto_secretbox_open; - -function crypto_box(c, m, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_afternm(c, m, d, n, k); -} - -function crypto_box_open(m, c, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_open_afternm(m, c, d, n, k); -} - -var K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; - -function crypto_hashblocks_hl(hh, hl, m, n) { - var wh = new Int32Array(16), wl = new Int32Array(16), - bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, - bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, - th, tl, i, j, h, l, a, b, c, d; - - var ah0 = hh[0], - ah1 = hh[1], - ah2 = hh[2], - ah3 = hh[3], - ah4 = hh[4], - ah5 = hh[5], - ah6 = hh[6], - ah7 = hh[7], - - al0 = hl[0], - al1 = hl[1], - al2 = hl[2], - al3 = hl[3], - al4 = hl[4], - al5 = hl[5], - al6 = hl[6], - al7 = hl[7]; - - var pos = 0; - while (n >= 128) { - for (i = 0; i < 16; i++) { - j = 8 * i + pos; - wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; - wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; - } - for (i = 0; i < 80; i++) { - bh0 = ah0; - bh1 = ah1; - bh2 = ah2; - bh3 = ah3; - bh4 = ah4; - bh5 = ah5; - bh6 = ah6; - bh7 = ah7; - - bl0 = al0; - bl1 = al1; - bl2 = al2; - bl3 = al3; - bl4 = al4; - bl5 = al5; - bl6 = al6; - bl7 = al7; - - // add - h = ah7; - l = al7; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - // Sigma1 - h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); - l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // Ch - h = (ah4 & ah5) ^ (~ah4 & ah6); - l = (al4 & al5) ^ (~al4 & al6); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // K - h = K[i*2]; - l = K[i*2+1]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // w - h = wh[i%16]; - l = wl[i%16]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - th = c & 0xffff | d << 16; - tl = a & 0xffff | b << 16; - - // add - h = th; - l = tl; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - // Sigma0 - h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); - l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // Maj - h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); - l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - bh7 = (c & 0xffff) | (d << 16); - bl7 = (a & 0xffff) | (b << 16); - - // add - h = bh3; - l = bl3; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = th; - l = tl; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - bh3 = (c & 0xffff) | (d << 16); - bl3 = (a & 0xffff) | (b << 16); - - ah1 = bh0; - ah2 = bh1; - ah3 = bh2; - ah4 = bh3; - ah5 = bh4; - ah6 = bh5; - ah7 = bh6; - ah0 = bh7; - - al1 = bl0; - al2 = bl1; - al3 = bl2; - al4 = bl3; - al5 = bl4; - al6 = bl5; - al7 = bl6; - al0 = bl7; - - if (i%16 === 15) { - for (j = 0; j < 16; j++) { - // add - h = wh[j]; - l = wl[j]; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = wh[(j+9)%16]; - l = wl[(j+9)%16]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // sigma0 - th = wh[(j+1)%16]; - tl = wl[(j+1)%16]; - h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); - l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - // sigma1 - th = wh[(j+14)%16]; - tl = wl[(j+14)%16]; - h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); - l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - wh[j] = (c & 0xffff) | (d << 16); - wl[j] = (a & 0xffff) | (b << 16); - } - } - } - - // add - h = ah0; - l = al0; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[0]; - l = hl[0]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[0] = ah0 = (c & 0xffff) | (d << 16); - hl[0] = al0 = (a & 0xffff) | (b << 16); - - h = ah1; - l = al1; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[1]; - l = hl[1]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[1] = ah1 = (c & 0xffff) | (d << 16); - hl[1] = al1 = (a & 0xffff) | (b << 16); - - h = ah2; - l = al2; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[2]; - l = hl[2]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[2] = ah2 = (c & 0xffff) | (d << 16); - hl[2] = al2 = (a & 0xffff) | (b << 16); - - h = ah3; - l = al3; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[3]; - l = hl[3]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[3] = ah3 = (c & 0xffff) | (d << 16); - hl[3] = al3 = (a & 0xffff) | (b << 16); - - h = ah4; - l = al4; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[4]; - l = hl[4]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[4] = ah4 = (c & 0xffff) | (d << 16); - hl[4] = al4 = (a & 0xffff) | (b << 16); - - h = ah5; - l = al5; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[5]; - l = hl[5]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[5] = ah5 = (c & 0xffff) | (d << 16); - hl[5] = al5 = (a & 0xffff) | (b << 16); - - h = ah6; - l = al6; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[6]; - l = hl[6]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[6] = ah6 = (c & 0xffff) | (d << 16); - hl[6] = al6 = (a & 0xffff) | (b << 16); - - h = ah7; - l = al7; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[7]; - l = hl[7]; - - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - - hh[7] = ah7 = (c & 0xffff) | (d << 16); - hl[7] = al7 = (a & 0xffff) | (b << 16); - - pos += 128; - n -= 128; - } - - return n; -} - -function crypto_hash(out, m, n) { - var hh = new Int32Array(8), - hl = new Int32Array(8), - x = new Uint8Array(256), - i, b = n; - - hh[0] = 0x6a09e667; - hh[1] = 0xbb67ae85; - hh[2] = 0x3c6ef372; - hh[3] = 0xa54ff53a; - hh[4] = 0x510e527f; - hh[5] = 0x9b05688c; - hh[6] = 0x1f83d9ab; - hh[7] = 0x5be0cd19; - - hl[0] = 0xf3bcc908; - hl[1] = 0x84caa73b; - hl[2] = 0xfe94f82b; - hl[3] = 0x5f1d36f1; - hl[4] = 0xade682d1; - hl[5] = 0x2b3e6c1f; - hl[6] = 0xfb41bd6b; - hl[7] = 0x137e2179; - - crypto_hashblocks_hl(hh, hl, m, n); - n %= 128; - - for (i = 0; i < n; i++) x[i] = m[b-n+i]; - x[n] = 128; - - n = 256-128*(n<112?1:0); - x[n-9] = 0; - ts64(x, n-8, (b / 0x20000000) | 0, b << 3); - crypto_hashblocks_hl(hh, hl, x, n); - - for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); - - return 0; -} - -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); - - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} - -function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } -} - -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} - -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } -} - -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); -} - -function crypto_sign_keypair(pk, sk, seeded) { - var d = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()]; - var i; - - if (!seeded) randombytes(sk, 32); - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - scalarbase(p, d); - pack(pk, p); - - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} - -var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = (x[j] + 128) >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} - -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); -} - -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - - crypto_hash(r, sm.subarray(32), n+32); - reduce(r); - scalarbase(p, r); - pack(sm, p); - - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h, sm, n + 64); - reduce(h); - - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } - - modL(sm.subarray(32), x); - return smlen; -} - -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); - - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - - M(r[3], r[0], r[1]); - return 0; -} - -function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new Uint8Array(32), h = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; - - mlen = -1; - if (n < 64) return -1; - - if (unpackneg(q, pk)) return -1; - - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - crypto_hash(h, m, n); - reduce(h); - scalarmult(p, q, h); - - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } - - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - mlen = n; - return mlen; -} - -var crypto_secretbox_KEYBYTES = 32, - crypto_secretbox_NONCEBYTES = 24, - crypto_secretbox_ZEROBYTES = 32, - crypto_secretbox_BOXZEROBYTES = 16, - crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_box_BEFORENMBYTES = 32, - crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, - crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, - crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32, - crypto_hash_BYTES = 64; - -nacl.lowlevel = { - crypto_core_hsalsa20: crypto_core_hsalsa20, - crypto_stream_xor: crypto_stream_xor, - crypto_stream: crypto_stream, - crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, - crypto_stream_salsa20: crypto_stream_salsa20, - crypto_onetimeauth: crypto_onetimeauth, - crypto_onetimeauth_verify: crypto_onetimeauth_verify, - crypto_verify_16: crypto_verify_16, - crypto_verify_32: crypto_verify_32, - crypto_secretbox: crypto_secretbox, - crypto_secretbox_open: crypto_secretbox_open, - crypto_scalarmult: crypto_scalarmult, - crypto_scalarmult_base: crypto_scalarmult_base, - crypto_box_beforenm: crypto_box_beforenm, - crypto_box_afternm: crypto_box_afternm, - crypto_box: crypto_box, - crypto_box_open: crypto_box_open, - crypto_box_keypair: crypto_box_keypair, - crypto_hash: crypto_hash, - crypto_sign: crypto_sign, - crypto_sign_keypair: crypto_sign_keypair, - crypto_sign_open: crypto_sign_open, - - crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, - crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, - crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, - crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, - crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, - crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, - crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, - crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, - crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, - crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, - crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, - crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, - crypto_sign_BYTES: crypto_sign_BYTES, - crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, - crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, - crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, - crypto_hash_BYTES: crypto_hash_BYTES -}; - -/* High-level API */ - -function checkLengths(k, n) { - if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); - if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); -} - -function checkBoxLengths(pk, sk) { - if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); - if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); -} - -function checkArrayTypes() { - var t, i; - for (i = 0; i < arguments.length; i++) { - if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') - throw new TypeError('unexpected type ' + t + ', use Uint8Array'); - } -} - -function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; -} - -// TODO: Completely remove this in v0.15. -if (!nacl.util) { - nacl.util = {}; - nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { - throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); - }; -} - -nacl.randomBytes = function(n) { - var b = new Uint8Array(n); - randombytes(b, n); - return b; -}; - -nacl.secretbox = function(msg, nonce, key) { - checkArrayTypes(msg, nonce, key); - checkLengths(key, nonce); - var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); - var c = new Uint8Array(m.length); - for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; - crypto_secretbox(c, m, m.length, nonce, key); - return c.subarray(crypto_secretbox_BOXZEROBYTES); -}; - -nacl.secretbox.open = function(box, nonce, key) { - checkArrayTypes(box, nonce, key); - checkLengths(key, nonce); - var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); - var m = new Uint8Array(c.length); - for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; - if (c.length < 32) return false; - if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; - return m.subarray(crypto_secretbox_ZEROBYTES); -}; - -nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; -nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; -nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; - -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; -}; - -nacl.scalarMult.base = function(n) { - checkArrayTypes(n); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult_base(q, n); - return q; -}; - -nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; -nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; - -nacl.box = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox(msg, nonce, k); -}; - -nacl.box.before = function(publicKey, secretKey) { - checkArrayTypes(publicKey, secretKey); - checkBoxLengths(publicKey, secretKey); - var k = new Uint8Array(crypto_box_BEFORENMBYTES); - crypto_box_beforenm(k, publicKey, secretKey); - return k; -}; - -nacl.box.after = nacl.secretbox; - -nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k); -}; - -nacl.box.open.after = nacl.secretbox.open; - -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; -nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; -nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; -nacl.box.nonceLength = crypto_box_NONCEBYTES; -nacl.box.overheadLength = nacl.secretbox.overheadLength; - -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; -}; - -nacl.sign.open = function(signedMsg, publicKey) { - if (arguments.length !== 2) - throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); - checkArrayTypes(signedMsg, publicKey); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var tmp = new Uint8Array(signedMsg.length); - var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); - if (mlen < 0) return null; - var m = new Uint8Array(mlen); - for (var i = 0; i < m.length; i++) m[i] = tmp[i]; - return m; -}; - -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; -}; - -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); -}; - -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; -nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; -nacl.sign.seedLength = crypto_sign_SEEDBYTES; -nacl.sign.signatureLength = crypto_sign_BYTES; - -nacl.hash = function(msg) { - checkArrayTypes(msg); - var h = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h, msg, msg.length); - return h; -}; - -nacl.hash.hashLength = crypto_hash_BYTES; - -nacl.verify = function(x, y) { - checkArrayTypes(x, y); - // Zero length arguments are considered not equal. - if (x.length === 0 || y.length === 0) return false; - if (x.length !== y.length) return false; - return (vn(x, 0, y, 0, x.length) === 0) ? true : false; -}; - -nacl.setPRNG = function(fn) { - randombytes = fn; -}; - -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (typeof require !== 'undefined') { - // Node.js. - crypto = require('crypto'); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } -})(); - -})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {})); diff --git a/reverse_engineering/node_modules/tweetnacl/nacl-fast.min.js b/reverse_engineering/node_modules/tweetnacl/nacl-fast.min.js deleted file mode 100644 index 8bc47da..0000000 --- a/reverse_engineering/node_modules/tweetnacl/nacl-fast.min.js +++ /dev/null @@ -1,2 +0,0 @@ -!function(r){"use strict";function t(r,t,n,e){r[t]=n>>24&255,r[t+1]=n>>16&255,r[t+2]=n>>8&255,r[t+3]=255&n,r[t+4]=e>>24&255,r[t+5]=e>>16&255,r[t+6]=e>>8&255,r[t+7]=255&e}function n(r,t,n,e,o){var i,h=0;for(i=0;i>>8)-1}function e(r,t,e,o){return n(r,t,e,o,16)}function o(r,t,e,o){return n(r,t,e,o,32)}function i(r,t,n,e){for(var o,i=255&e[0]|(255&e[1])<<8|(255&e[2])<<16|(255&e[3])<<24,h=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,s=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,c=255&e[4]|(255&e[5])<<8|(255&e[6])<<16|(255&e[7])<<24,u=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,y=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,l=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,w=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,p=255&e[8]|(255&e[9])<<8|(255&e[10])<<16|(255&e[11])<<24,v=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,b=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,g=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,_=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,A=255&e[12]|(255&e[13])<<8|(255&e[14])<<16|(255&e[15])<<24,d=i,U=h,E=a,x=f,M=s,m=c,B=u,S=y,K=l,T=w,Y=p,k=v,L=b,z=g,R=_,P=A,O=0;O<20;O+=2)o=d+L|0,M^=o<<7|o>>>25,o=M+d|0,K^=o<<9|o>>>23,o=K+M|0,L^=o<<13|o>>>19,o=L+K|0,d^=o<<18|o>>>14,o=m+U|0,T^=o<<7|o>>>25,o=T+m|0,z^=o<<9|o>>>23,o=z+T|0,U^=o<<13|o>>>19,o=U+z|0,m^=o<<18|o>>>14,o=Y+B|0,R^=o<<7|o>>>25,o=R+Y|0,E^=o<<9|o>>>23,o=E+R|0,B^=o<<13|o>>>19,o=B+E|0,Y^=o<<18|o>>>14,o=P+k|0,x^=o<<7|o>>>25,o=x+P|0,S^=o<<9|o>>>23,o=S+x|0,k^=o<<13|o>>>19,o=k+S|0,P^=o<<18|o>>>14,o=d+x|0,U^=o<<7|o>>>25,o=U+d|0,E^=o<<9|o>>>23,o=E+U|0,x^=o<<13|o>>>19,o=x+E|0,d^=o<<18|o>>>14,o=m+M|0,B^=o<<7|o>>>25,o=B+m|0,S^=o<<9|o>>>23,o=S+B|0,M^=o<<13|o>>>19,o=M+S|0,m^=o<<18|o>>>14,o=Y+T|0,k^=o<<7|o>>>25,o=k+Y|0,K^=o<<9|o>>>23,o=K+k|0,T^=o<<13|o>>>19,o=T+K|0,Y^=o<<18|o>>>14,o=P+R|0,L^=o<<7|o>>>25,o=L+P|0,z^=o<<9|o>>>23,o=z+L|0,R^=o<<13|o>>>19,o=R+z|0,P^=o<<18|o>>>14;d=d+i|0,U=U+h|0,E=E+a|0,x=x+f|0,M=M+s|0,m=m+c|0,B=B+u|0,S=S+y|0,K=K+l|0,T=T+w|0,Y=Y+p|0,k=k+v|0,L=L+b|0,z=z+g|0,R=R+_|0,P=P+A|0,r[0]=d>>>0&255,r[1]=d>>>8&255,r[2]=d>>>16&255,r[3]=d>>>24&255,r[4]=U>>>0&255,r[5]=U>>>8&255,r[6]=U>>>16&255,r[7]=U>>>24&255,r[8]=E>>>0&255,r[9]=E>>>8&255,r[10]=E>>>16&255,r[11]=E>>>24&255,r[12]=x>>>0&255,r[13]=x>>>8&255,r[14]=x>>>16&255,r[15]=x>>>24&255,r[16]=M>>>0&255,r[17]=M>>>8&255,r[18]=M>>>16&255,r[19]=M>>>24&255,r[20]=m>>>0&255,r[21]=m>>>8&255,r[22]=m>>>16&255,r[23]=m>>>24&255,r[24]=B>>>0&255,r[25]=B>>>8&255,r[26]=B>>>16&255,r[27]=B>>>24&255,r[28]=S>>>0&255,r[29]=S>>>8&255,r[30]=S>>>16&255,r[31]=S>>>24&255,r[32]=K>>>0&255,r[33]=K>>>8&255,r[34]=K>>>16&255,r[35]=K>>>24&255,r[36]=T>>>0&255,r[37]=T>>>8&255,r[38]=T>>>16&255,r[39]=T>>>24&255,r[40]=Y>>>0&255,r[41]=Y>>>8&255,r[42]=Y>>>16&255,r[43]=Y>>>24&255,r[44]=k>>>0&255,r[45]=k>>>8&255,r[46]=k>>>16&255,r[47]=k>>>24&255,r[48]=L>>>0&255,r[49]=L>>>8&255,r[50]=L>>>16&255,r[51]=L>>>24&255,r[52]=z>>>0&255,r[53]=z>>>8&255,r[54]=z>>>16&255,r[55]=z>>>24&255,r[56]=R>>>0&255,r[57]=R>>>8&255,r[58]=R>>>16&255,r[59]=R>>>24&255,r[60]=P>>>0&255,r[61]=P>>>8&255,r[62]=P>>>16&255,r[63]=P>>>24&255}function h(r,t,n,e){for(var o,i=255&e[0]|(255&e[1])<<8|(255&e[2])<<16|(255&e[3])<<24,h=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,s=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,c=255&e[4]|(255&e[5])<<8|(255&e[6])<<16|(255&e[7])<<24,u=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,y=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,l=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,w=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,p=255&e[8]|(255&e[9])<<8|(255&e[10])<<16|(255&e[11])<<24,v=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,b=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,g=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,_=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,A=255&e[12]|(255&e[13])<<8|(255&e[14])<<16|(255&e[15])<<24,d=i,U=h,E=a,x=f,M=s,m=c,B=u,S=y,K=l,T=w,Y=p,k=v,L=b,z=g,R=_,P=A,O=0;O<20;O+=2)o=d+L|0,M^=o<<7|o>>>25,o=M+d|0,K^=o<<9|o>>>23,o=K+M|0,L^=o<<13|o>>>19,o=L+K|0,d^=o<<18|o>>>14,o=m+U|0,T^=o<<7|o>>>25,o=T+m|0,z^=o<<9|o>>>23,o=z+T|0,U^=o<<13|o>>>19,o=U+z|0,m^=o<<18|o>>>14,o=Y+B|0,R^=o<<7|o>>>25,o=R+Y|0,E^=o<<9|o>>>23,o=E+R|0,B^=o<<13|o>>>19,o=B+E|0,Y^=o<<18|o>>>14,o=P+k|0,x^=o<<7|o>>>25,o=x+P|0,S^=o<<9|o>>>23,o=S+x|0,k^=o<<13|o>>>19,o=k+S|0,P^=o<<18|o>>>14,o=d+x|0,U^=o<<7|o>>>25,o=U+d|0,E^=o<<9|o>>>23,o=E+U|0,x^=o<<13|o>>>19,o=x+E|0,d^=o<<18|o>>>14,o=m+M|0,B^=o<<7|o>>>25,o=B+m|0,S^=o<<9|o>>>23,o=S+B|0,M^=o<<13|o>>>19,o=M+S|0,m^=o<<18|o>>>14,o=Y+T|0,k^=o<<7|o>>>25,o=k+Y|0,K^=o<<9|o>>>23,o=K+k|0,T^=o<<13|o>>>19,o=T+K|0,Y^=o<<18|o>>>14,o=P+R|0,L^=o<<7|o>>>25,o=L+P|0,z^=o<<9|o>>>23,o=z+L|0,R^=o<<13|o>>>19,o=R+z|0,P^=o<<18|o>>>14;r[0]=d>>>0&255,r[1]=d>>>8&255,r[2]=d>>>16&255,r[3]=d>>>24&255,r[4]=m>>>0&255,r[5]=m>>>8&255,r[6]=m>>>16&255,r[7]=m>>>24&255,r[8]=Y>>>0&255,r[9]=Y>>>8&255,r[10]=Y>>>16&255,r[11]=Y>>>24&255,r[12]=P>>>0&255,r[13]=P>>>8&255,r[14]=P>>>16&255,r[15]=P>>>24&255,r[16]=B>>>0&255,r[17]=B>>>8&255,r[18]=B>>>16&255,r[19]=B>>>24&255,r[20]=S>>>0&255,r[21]=S>>>8&255,r[22]=S>>>16&255,r[23]=S>>>24&255,r[24]=K>>>0&255,r[25]=K>>>8&255,r[26]=K>>>16&255,r[27]=K>>>24&255,r[28]=T>>>0&255,r[29]=T>>>8&255,r[30]=T>>>16&255,r[31]=T>>>24&255}function a(r,t,n,e){i(r,t,n,e)}function f(r,t,n,e){h(r,t,n,e)}function s(r,t,n,e,o,i,h){var f,s,c=new Uint8Array(16),u=new Uint8Array(64);for(s=0;s<16;s++)c[s]=0;for(s=0;s<8;s++)c[s]=i[s];for(;o>=64;){for(a(u,c,h,ur),s=0;s<64;s++)r[t+s]=n[e+s]^u[s];for(f=1,s=8;s<16;s++)f=f+(255&c[s])|0,c[s]=255&f,f>>>=8;o-=64,t+=64,e+=64}if(o>0)for(a(u,c,h,ur),s=0;s=64;){for(a(s,f,o,ur),h=0;h<64;h++)r[t+h]=s[h];for(i=1,h=8;h<16;h++)i=i+(255&f[h])|0,f[h]=255&i,i>>>=8;n-=64,t+=64}if(n>0)for(a(s,f,o,ur),h=0;h>16&1),i[n-1]&=65535;i[15]=h[15]-32767-(i[14]>>16&1),o=i[15]>>16&1,i[14]&=65535,_(h,i,1-o)}for(n=0;n<16;n++)r[2*n]=255&h[n],r[2*n+1]=h[n]>>8}function d(r,t){var n=new Uint8Array(32),e=new Uint8Array(32);return A(n,r),A(e,t),o(n,0,e,0)}function U(r){var t=new Uint8Array(32);return A(t,r),1&t[0]}function E(r,t){var n;for(n=0;n<16;n++)r[n]=t[2*n]+(t[2*n+1]<<8);r[15]&=32767}function x(r,t,n){for(var e=0;e<16;e++)r[e]=t[e]+n[e]}function M(r,t,n){for(var e=0;e<16;e++)r[e]=t[e]-n[e]}function m(r,t,n){var e,o,i=0,h=0,a=0,f=0,s=0,c=0,u=0,y=0,l=0,w=0,p=0,v=0,b=0,g=0,_=0,A=0,d=0,U=0,E=0,x=0,M=0,m=0,B=0,S=0,K=0,T=0,Y=0,k=0,L=0,z=0,R=0,P=n[0],O=n[1],N=n[2],C=n[3],F=n[4],I=n[5],G=n[6],Z=n[7],j=n[8],q=n[9],V=n[10],X=n[11],D=n[12],H=n[13],J=n[14],Q=n[15];e=t[0],i+=e*P,h+=e*O,a+=e*N,f+=e*C,s+=e*F,c+=e*I,u+=e*G,y+=e*Z,l+=e*j,w+=e*q,p+=e*V,v+=e*X,b+=e*D,g+=e*H,_+=e*J,A+=e*Q,e=t[1],h+=e*P,a+=e*O,f+=e*N,s+=e*C,c+=e*F,u+=e*I,y+=e*G,l+=e*Z,w+=e*j,p+=e*q,v+=e*V,b+=e*X,g+=e*D,_+=e*H,A+=e*J,d+=e*Q,e=t[2],a+=e*P,f+=e*O,s+=e*N,c+=e*C,u+=e*F,y+=e*I,l+=e*G,w+=e*Z,p+=e*j,v+=e*q,b+=e*V,g+=e*X,_+=e*D,A+=e*H,d+=e*J,U+=e*Q,e=t[3],f+=e*P,s+=e*O,c+=e*N,u+=e*C,y+=e*F,l+=e*I,w+=e*G,p+=e*Z,v+=e*j,b+=e*q,g+=e*V,_+=e*X,A+=e*D,d+=e*H,U+=e*J,E+=e*Q,e=t[4],s+=e*P,c+=e*O,u+=e*N,y+=e*C,l+=e*F,w+=e*I,p+=e*G,v+=e*Z,b+=e*j,g+=e*q,_+=e*V,A+=e*X,d+=e*D,U+=e*H,E+=e*J,x+=e*Q,e=t[5],c+=e*P,u+=e*O,y+=e*N,l+=e*C,w+=e*F,p+=e*I,v+=e*G,b+=e*Z,g+=e*j,_+=e*q,A+=e*V,d+=e*X,U+=e*D,E+=e*H,x+=e*J,M+=e*Q,e=t[6],u+=e*P,y+=e*O,l+=e*N,w+=e*C,p+=e*F,v+=e*I,b+=e*G,g+=e*Z,_+=e*j,A+=e*q,d+=e*V,U+=e*X,E+=e*D,x+=e*H,M+=e*J,m+=e*Q,e=t[7],y+=e*P,l+=e*O,w+=e*N,p+=e*C,v+=e*F,b+=e*I,g+=e*G,_+=e*Z,A+=e*j,d+=e*q,U+=e*V,E+=e*X,x+=e*D,M+=e*H,m+=e*J,B+=e*Q,e=t[8],l+=e*P,w+=e*O,p+=e*N,v+=e*C,b+=e*F,g+=e*I,_+=e*G,A+=e*Z,d+=e*j,U+=e*q,E+=e*V,x+=e*X,M+=e*D,m+=e*H,B+=e*J,S+=e*Q,e=t[9],w+=e*P,p+=e*O,v+=e*N,b+=e*C,g+=e*F,_+=e*I,A+=e*G,d+=e*Z,U+=e*j,E+=e*q,x+=e*V,M+=e*X,m+=e*D,B+=e*H,S+=e*J,K+=e*Q,e=t[10],p+=e*P,v+=e*O,b+=e*N,g+=e*C,_+=e*F,A+=e*I,d+=e*G,U+=e*Z,E+=e*j,x+=e*q,M+=e*V,m+=e*X,B+=e*D,S+=e*H,K+=e*J,T+=e*Q,e=t[11],v+=e*P,b+=e*O,g+=e*N,_+=e*C,A+=e*F,d+=e*I,U+=e*G,E+=e*Z,x+=e*j,M+=e*q,m+=e*V,B+=e*X;S+=e*D;K+=e*H,T+=e*J,Y+=e*Q,e=t[12],b+=e*P,g+=e*O,_+=e*N,A+=e*C,d+=e*F,U+=e*I,E+=e*G,x+=e*Z,M+=e*j,m+=e*q,B+=e*V,S+=e*X,K+=e*D,T+=e*H,Y+=e*J,k+=e*Q,e=t[13],g+=e*P,_+=e*O,A+=e*N,d+=e*C,U+=e*F,E+=e*I,x+=e*G,M+=e*Z,m+=e*j,B+=e*q,S+=e*V,K+=e*X,T+=e*D,Y+=e*H,k+=e*J,L+=e*Q,e=t[14],_+=e*P,A+=e*O,d+=e*N,U+=e*C,E+=e*F,x+=e*I,M+=e*G,m+=e*Z,B+=e*j,S+=e*q,K+=e*V,T+=e*X,Y+=e*D,k+=e*H,L+=e*J,z+=e*Q,e=t[15],A+=e*P,d+=e*O,U+=e*N,E+=e*C,x+=e*F,M+=e*I,m+=e*G,B+=e*Z,S+=e*j,K+=e*q,T+=e*V,Y+=e*X,k+=e*D,L+=e*H,z+=e*J,R+=e*Q,i+=38*d,h+=38*U,a+=38*E,f+=38*x,s+=38*M,c+=38*m,u+=38*B,y+=38*S,l+=38*K,w+=38*T,p+=38*Y,v+=38*k,b+=38*L,g+=38*z,_+=38*R,o=1,e=i+o+65535,o=Math.floor(e/65536),i=e-65536*o,e=h+o+65535,o=Math.floor(e/65536),h=e-65536*o,e=a+o+65535,o=Math.floor(e/65536),a=e-65536*o,e=f+o+65535,o=Math.floor(e/65536),f=e-65536*o,e=s+o+65535,o=Math.floor(e/65536),s=e-65536*o,e=c+o+65535,o=Math.floor(e/65536),c=e-65536*o,e=u+o+65535,o=Math.floor(e/65536),u=e-65536*o,e=y+o+65535,o=Math.floor(e/65536),y=e-65536*o,e=l+o+65535,o=Math.floor(e/65536),l=e-65536*o,e=w+o+65535,o=Math.floor(e/65536),w=e-65536*o,e=p+o+65535,o=Math.floor(e/65536),p=e-65536*o,e=v+o+65535,o=Math.floor(e/65536),v=e-65536*o,e=b+o+65535,o=Math.floor(e/65536),b=e-65536*o,e=g+o+65535,o=Math.floor(e/65536),g=e-65536*o,e=_+o+65535,o=Math.floor(e/65536),_=e-65536*o,e=A+o+65535,o=Math.floor(e/65536),A=e-65536*o,i+=o-1+37*(o-1),o=1,e=i+o+65535,o=Math.floor(e/65536),i=e-65536*o,e=h+o+65535,o=Math.floor(e/65536),h=e-65536*o,e=a+o+65535,o=Math.floor(e/65536),a=e-65536*o,e=f+o+65535,o=Math.floor(e/65536),f=e-65536*o,e=s+o+65535,o=Math.floor(e/65536),s=e-65536*o,e=c+o+65535,o=Math.floor(e/65536),c=e-65536*o,e=u+o+65535,o=Math.floor(e/65536),u=e-65536*o,e=y+o+65535,o=Math.floor(e/65536),y=e-65536*o,e=l+o+65535,o=Math.floor(e/65536),l=e-65536*o,e=w+o+65535,o=Math.floor(e/65536),w=e-65536*o,e=p+o+65535,o=Math.floor(e/65536),p=e-65536*o,e=v+o+65535,o=Math.floor(e/65536),v=e-65536*o,e=b+o+65535,o=Math.floor(e/65536),b=e-65536*o,e=g+o+65535,o=Math.floor(e/65536),g=e-65536*o,e=_+o+65535,o=Math.floor(e/65536),_=e-65536*o,e=A+o+65535,o=Math.floor(e/65536),A=e-65536*o,i+=o-1+37*(o-1),r[0]=i,r[1]=h,r[2]=a,r[3]=f,r[4]=s,r[5]=c,r[6]=u,r[7]=y,r[8]=l,r[9]=w,r[10]=p,r[11]=v,r[12]=b,r[13]=g;r[14]=_;r[15]=A}function B(r,t){m(r,t,t)}function S(r,t){var n,e=$();for(n=0;n<16;n++)e[n]=t[n];for(n=253;n>=0;n--)B(e,e),2!==n&&4!==n&&m(e,e,t);for(n=0;n<16;n++)r[n]=e[n]}function K(r,t){var n,e=$();for(n=0;n<16;n++)e[n]=t[n];for(n=250;n>=0;n--)B(e,e),1!==n&&m(e,e,t);for(n=0;n<16;n++)r[n]=e[n]}function T(r,t,n){var e,o,i=new Uint8Array(32),h=new Float64Array(80),a=$(),f=$(),s=$(),c=$(),u=$(),y=$();for(o=0;o<31;o++)i[o]=t[o];for(i[31]=127&t[31]|64,i[0]&=248,E(h,n),o=0;o<16;o++)f[o]=h[o],c[o]=a[o]=s[o]=0;for(a[0]=c[0]=1,o=254;o>=0;--o)e=i[o>>>3]>>>(7&o)&1,_(a,f,e),_(s,c,e),x(u,a,s),M(a,a,s),x(s,f,c),M(f,f,c),B(c,u),B(y,a),m(a,s,a),m(s,f,u),x(u,a,s),M(a,a,s),B(f,a),M(s,c,y),m(a,s,ir),x(a,a,c),m(s,s,a),m(a,c,y),m(c,f,h),B(f,u),_(a,f,e),_(s,c,e);for(o=0;o<16;o++)h[o+16]=a[o],h[o+32]=s[o],h[o+48]=f[o],h[o+64]=c[o];var l=h.subarray(32),w=h.subarray(16);return S(l,l),m(w,w,l),A(r,w),0}function Y(r,t){return T(r,t,nr)}function k(r,t){return rr(t,32),Y(r,t)}function L(r,t,n){var e=new Uint8Array(32);return T(e,n,t),f(r,tr,e,ur)}function z(r,t,n,e,o,i){var h=new Uint8Array(32);return L(h,o,i),lr(r,t,n,e,h)}function R(r,t,n,e,o,i){var h=new Uint8Array(32);return L(h,o,i),wr(r,t,n,e,h)}function P(r,t,n,e){for(var o,i,h,a,f,s,c,u,y,l,w,p,v,b,g,_,A,d,U,E,x,M,m,B,S,K,T=new Int32Array(16),Y=new Int32Array(16),k=r[0],L=r[1],z=r[2],R=r[3],P=r[4],O=r[5],N=r[6],C=r[7],F=t[0],I=t[1],G=t[2],Z=t[3],j=t[4],q=t[5],V=t[6],X=t[7],D=0;e>=128;){for(U=0;U<16;U++)E=8*U+D,T[U]=n[E+0]<<24|n[E+1]<<16|n[E+2]<<8|n[E+3],Y[U]=n[E+4]<<24|n[E+5]<<16|n[E+6]<<8|n[E+7];for(U=0;U<80;U++)if(o=k,i=L,h=z,a=R,f=P,s=O,c=N,u=C,y=F,l=I,w=G,p=Z,v=j,b=q,g=V,_=X,x=C,M=X,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=(P>>>14|j<<18)^(P>>>18|j<<14)^(j>>>9|P<<23),M=(j>>>14|P<<18)^(j>>>18|P<<14)^(P>>>9|j<<23),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=P&O^~P&N,M=j&q^~j&V,m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=pr[2*U],M=pr[2*U+1],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=T[U%16],M=Y[U%16],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,A=65535&S|K<<16,d=65535&m|B<<16,x=A,M=d,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=(k>>>28|F<<4)^(F>>>2|k<<30)^(F>>>7|k<<25),M=(F>>>28|k<<4)^(k>>>2|F<<30)^(k>>>7|F<<25),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,x=k&L^k&z^L&z,M=F&I^F&G^I&G,m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,u=65535&S|K<<16,_=65535&m|B<<16,x=a,M=p,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=A,M=d,m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,a=65535&S|K<<16,p=65535&m|B<<16,L=o,z=i,R=h,P=a,O=f,N=s,C=c,k=u,I=y,G=l,Z=w,j=p,q=v,V=b,X=g,F=_,U%16===15)for(E=0;E<16;E++)x=T[E],M=Y[E],m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=T[(E+9)%16],M=Y[(E+9)%16],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,A=T[(E+1)%16],d=Y[(E+1)%16],x=(A>>>1|d<<31)^(A>>>8|d<<24)^A>>>7,M=(d>>>1|A<<31)^(d>>>8|A<<24)^(d>>>7|A<<25),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,A=T[(E+14)%16],d=Y[(E+14)%16],x=(A>>>19|d<<13)^(d>>>29|A<<3)^A>>>6,M=(d>>>19|A<<13)^(A>>>29|d<<3)^(d>>>6|A<<26),m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,T[E]=65535&S|K<<16,Y[E]=65535&m|B<<16;x=k,M=F,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[0],M=t[0],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[0]=k=65535&S|K<<16,t[0]=F=65535&m|B<<16,x=L,M=I,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[1],M=t[1],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[1]=L=65535&S|K<<16,t[1]=I=65535&m|B<<16,x=z,M=G,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[2],M=t[2],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[2]=z=65535&S|K<<16,t[2]=G=65535&m|B<<16,x=R,M=Z,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[3],M=t[3],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[3]=R=65535&S|K<<16,t[3]=Z=65535&m|B<<16,x=P,M=j,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[4],M=t[4],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[4]=P=65535&S|K<<16,t[4]=j=65535&m|B<<16,x=O,M=q,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[5],M=t[5],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[5]=O=65535&S|K<<16,t[5]=q=65535&m|B<<16,x=N,M=V,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[6],M=t[6],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[6]=N=65535&S|K<<16,t[6]=V=65535&m|B<<16,x=C,M=X,m=65535&M,B=M>>>16,S=65535&x,K=x>>>16,x=r[7],M=t[7],m+=65535&M,B+=M>>>16,S+=65535&x,K+=x>>>16,B+=m>>>16,S+=B>>>16,K+=S>>>16,r[7]=C=65535&S|K<<16,t[7]=X=65535&m|B<<16,D+=128,e-=128}return e}function O(r,n,e){var o,i=new Int32Array(8),h=new Int32Array(8),a=new Uint8Array(256),f=e;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,h[0]=4089235720,h[1]=2227873595,h[2]=4271175723,h[3]=1595750129,h[4]=2917565137,h[5]=725511199,h[6]=4215389547,h[7]=327033209,P(i,h,n,e),e%=128,o=0;o=0;--o)e=n[o/8|0]>>(7&o)&1,C(r,t,e),N(t,r),N(r,r),C(r,t,e)}function G(r,t){var n=[$(),$(),$(),$()];b(n[0],fr),b(n[1],sr),b(n[2],or),m(n[3],fr,sr),I(r,n,t)}function Z(r,t,n){var e,o=new Uint8Array(64),i=[$(),$(),$(),$()];for(n||rr(t,32),O(o,t,32),o[0]&=248,o[31]&=127,o[31]|=64,G(i,o),F(r,i),e=0;e<32;e++)t[e+32]=r[e];return 0}function j(r,t){var n,e,o,i;for(e=63;e>=32;--e){for(n=0,o=e-32,i=e-12;o>8,t[o]-=256*n;t[o]+=n,t[e]=0}for(n=0,o=0;o<32;o++)t[o]+=n-(t[31]>>4)*vr[o],n=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=n*vr[o];for(e=0;e<32;e++)t[e+1]+=t[e]>>8,r[e]=255&t[e]}function q(r){var t,n=new Float64Array(64);for(t=0;t<64;t++)n[t]=r[t];for(t=0;t<64;t++)r[t]=0;j(r,n)}function V(r,t,n,e){var o,i,h=new Uint8Array(64),a=new Uint8Array(64),f=new Uint8Array(64),s=new Float64Array(64),c=[$(),$(),$(),$()];O(h,e,32),h[0]&=248,h[31]&=127,h[31]|=64;var u=n+64;for(o=0;o>7&&M(r[0],er,r[0]),m(r[3],r[0],r[1]),0)}function D(r,t,n,e){var i,h,a=new Uint8Array(32),f=new Uint8Array(64),s=[$(),$(),$(),$()],c=[$(),$(),$(),$()];if(h=-1,n<64)return-1;if(X(c,e))return-1;for(i=0;i>>13|n<<3),e=255&r[4]|(255&r[5])<<8,this.r[2]=7939&(n>>>10|e<<6),o=255&r[6]|(255&r[7])<<8,this.r[3]=8191&(e>>>7|o<<9),i=255&r[8]|(255&r[9])<<8,this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,h=255&r[10]|(255&r[11])<<8,this.r[6]=8191&(i>>>14|h<<2),a=255&r[12]|(255&r[13])<<8,this.r[7]=8065&(h>>>11|a<<5),f=255&r[14]|(255&r[15])<<8,this.r[8]=8191&(a>>>8|f<<8),this.r[9]=f>>>5&127,this.pad[0]=255&r[16]|(255&r[17])<<8,this.pad[1]=255&r[18]|(255&r[19])<<8,this.pad[2]=255&r[20]|(255&r[21])<<8,this.pad[3]=255&r[22]|(255&r[23])<<8,this.pad[4]=255&r[24]|(255&r[25])<<8,this.pad[5]=255&r[26]|(255&r[27])<<8,this.pad[6]=255&r[28]|(255&r[29])<<8,this.pad[7]=255&r[30]|(255&r[31])<<8};yr.prototype.blocks=function(r,t,n){for(var e,o,i,h,a,f,s,c,u,y,l,w,p,v,b,g,_,A,d,U=this.fin?0:2048,E=this.h[0],x=this.h[1],M=this.h[2],m=this.h[3],B=this.h[4],S=this.h[5],K=this.h[6],T=this.h[7],Y=this.h[8],k=this.h[9],L=this.r[0],z=this.r[1],R=this.r[2],P=this.r[3],O=this.r[4],N=this.r[5],C=this.r[6],F=this.r[7],I=this.r[8],G=this.r[9];n>=16;)e=255&r[t+0]|(255&r[t+1])<<8,E+=8191&e,o=255&r[t+2]|(255&r[t+3])<<8,x+=8191&(e>>>13|o<<3),i=255&r[t+4]|(255&r[t+5])<<8,M+=8191&(o>>>10|i<<6),h=255&r[t+6]|(255&r[t+7])<<8,m+=8191&(i>>>7|h<<9),a=255&r[t+8]|(255&r[t+9])<<8,B+=8191&(h>>>4|a<<12),S+=a>>>1&8191,f=255&r[t+10]|(255&r[t+11])<<8,K+=8191&(a>>>14|f<<2),s=255&r[t+12]|(255&r[t+13])<<8,T+=8191&(f>>>11|s<<5),c=255&r[t+14]|(255&r[t+15])<<8,Y+=8191&(s>>>8|c<<8),k+=c>>>5|U,u=0,y=u,y+=E*L,y+=x*(5*G),y+=M*(5*I),y+=m*(5*F),y+=B*(5*C),u=y>>>13,y&=8191,y+=S*(5*N),y+=K*(5*O),y+=T*(5*P),y+=Y*(5*R),y+=k*(5*z),u+=y>>>13,y&=8191,l=u,l+=E*z,l+=x*L,l+=M*(5*G),l+=m*(5*I),l+=B*(5*F),u=l>>>13,l&=8191,l+=S*(5*C),l+=K*(5*N),l+=T*(5*O),l+=Y*(5*P),l+=k*(5*R),u+=l>>>13,l&=8191,w=u,w+=E*R,w+=x*z,w+=M*L,w+=m*(5*G),w+=B*(5*I),u=w>>>13,w&=8191,w+=S*(5*F),w+=K*(5*C),w+=T*(5*N),w+=Y*(5*O),w+=k*(5*P),u+=w>>>13,w&=8191,p=u,p+=E*P,p+=x*R,p+=M*z,p+=m*L,p+=B*(5*G),u=p>>>13,p&=8191,p+=S*(5*I),p+=K*(5*F),p+=T*(5*C),p+=Y*(5*N),p+=k*(5*O),u+=p>>>13,p&=8191,v=u,v+=E*O,v+=x*P,v+=M*R,v+=m*z,v+=B*L,u=v>>>13,v&=8191,v+=S*(5*G),v+=K*(5*I),v+=T*(5*F),v+=Y*(5*C),v+=k*(5*N),u+=v>>>13,v&=8191,b=u,b+=E*N,b+=x*O,b+=M*P,b+=m*R,b+=B*z,u=b>>>13,b&=8191,b+=S*L,b+=K*(5*G),b+=T*(5*I),b+=Y*(5*F),b+=k*(5*C),u+=b>>>13,b&=8191,g=u,g+=E*C,g+=x*N,g+=M*O,g+=m*P,g+=B*R,u=g>>>13,g&=8191,g+=S*z,g+=K*L,g+=T*(5*G),g+=Y*(5*I),g+=k*(5*F),u+=g>>>13,g&=8191,_=u,_+=E*F,_+=x*C,_+=M*N,_+=m*O,_+=B*P,u=_>>>13,_&=8191,_+=S*R,_+=K*z,_+=T*L,_+=Y*(5*G),_+=k*(5*I),u+=_>>>13,_&=8191,A=u,A+=E*I,A+=x*F,A+=M*C,A+=m*N,A+=B*O,u=A>>>13,A&=8191,A+=S*P,A+=K*R,A+=T*z,A+=Y*L,A+=k*(5*G),u+=A>>>13,A&=8191,d=u,d+=E*G,d+=x*I,d+=M*F,d+=m*C,d+=B*N,u=d>>>13,d&=8191,d+=S*O,d+=K*P,d+=T*R,d+=Y*z,d+=k*L,u+=d>>>13,d&=8191,u=(u<<2)+u|0,u=u+y|0,y=8191&u,u>>>=13,l+=u,E=y,x=l,M=w,m=p,B=v,S=b,K=g,T=_,Y=A,k=d,t+=16,n-=16;this.h[0]=E,this.h[1]=x,this.h[2]=M,this.h[3]=m,this.h[4]=B,this.h[5]=S,this.h[6]=K,this.h[7]=T,this.h[8]=Y,this.h[9]=k},yr.prototype.finish=function(r,t){var n,e,o,i,h=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(n=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=n,n=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*n,n=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=n,n=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=n,h[0]=this.h[0]+5,n=h[0]>>>13,h[0]&=8191,i=1;i<10;i++)h[i]=this.h[i]+n,n=h[i]>>>13,h[i]&=8191;for(h[9]-=8192,e=(1^n)-1,i=0;i<10;i++)h[i]&=e;for(e=~e,i=0;i<10;i++)this.h[i]=this.h[i]&e|h[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,i=1;i<8;i++)o=(this.h[i]+this.pad[i]|0)+(o>>>16)|0,this.h[i]=65535&o;r[t+0]=this.h[0]>>>0&255,r[t+1]=this.h[0]>>>8&255,r[t+2]=this.h[1]>>>0&255,r[t+3]=this.h[1]>>>8&255,r[t+4]=this.h[2]>>>0&255,r[t+5]=this.h[2]>>>8&255,r[t+6]=this.h[3]>>>0&255,r[t+7]=this.h[3]>>>8&255,r[t+8]=this.h[4]>>>0&255,r[t+9]=this.h[4]>>>8&255,r[t+10]=this.h[5]>>>0&255,r[t+11]=this.h[5]>>>8&255,r[t+12]=this.h[6]>>>0&255,r[t+13]=this.h[6]>>>8&255,r[t+14]=this.h[7]>>>0&255,r[t+15]=this.h[7]>>>8&255},yr.prototype.update=function(r,t,n){var e,o;if(this.leftover){for(o=16-this.leftover,o>n&&(o=n),e=0;e=16&&(o=n-n%16,this.blocks(r,t,o),t+=o,n-=o),n){for(e=0;e=0},r.sign.keyPair=function(){var r=new Uint8Array(Tr),t=new Uint8Array(Yr);return Z(r,t),{publicKey:r,secretKey:t}},r.sign.keyPair.fromSecretKey=function(r){if(Q(r),r.length!==Yr)throw new Error("bad secret key size");for(var t=new Uint8Array(Tr),n=0;n void): void; -} diff --git a/reverse_engineering/node_modules/tweetnacl/nacl.js b/reverse_engineering/node_modules/tweetnacl/nacl.js deleted file mode 100644 index f72dd78..0000000 --- a/reverse_engineering/node_modules/tweetnacl/nacl.js +++ /dev/null @@ -1,1175 +0,0 @@ -(function(nacl) { -'use strict'; - -// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -// -// Implementation derived from TweetNaCl version 20140427. -// See for details: http://tweetnacl.cr.yp.to/ - -var u64 = function(h, l) { this.hi = h|0 >>> 0; this.lo = l|0 >>> 0; }; -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; -}; - -// Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - -var _0 = new Uint8Array(16); -var _9 = new Uint8Array(32); _9[0] = 9; - -var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); - -function L32(x, c) { return (x << c) | (x >>> (32 - c)); } - -function ld32(x, i) { - var u = x[i+3] & 0xff; - u = (u<<8)|(x[i+2] & 0xff); - u = (u<<8)|(x[i+1] & 0xff); - return (u<<8)|(x[i+0] & 0xff); -} - -function dl64(x, i) { - var h = (x[i] << 24) | (x[i+1] << 16) | (x[i+2] << 8) | x[i+3]; - var l = (x[i+4] << 24) | (x[i+5] << 16) | (x[i+6] << 8) | x[i+7]; - return new u64(h, l); -} - -function st32(x, j, u) { - var i; - for (i = 0; i < 4; i++) { x[j+i] = u & 255; u >>>= 8; } -} - -function ts64(x, i, u) { - x[i] = (u.hi >> 24) & 0xff; - x[i+1] = (u.hi >> 16) & 0xff; - x[i+2] = (u.hi >> 8) & 0xff; - x[i+3] = u.hi & 0xff; - x[i+4] = (u.lo >> 24) & 0xff; - x[i+5] = (u.lo >> 16) & 0xff; - x[i+6] = (u.lo >> 8) & 0xff; - x[i+7] = u.lo & 0xff; -} - -function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; -} - -function crypto_verify_16(x, xi, y, yi) { - return vn(x,xi,y,yi,16); -} - -function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); -} - -function core(out,inp,k,c,h) { - var w = new Uint32Array(16), x = new Uint32Array(16), - y = new Uint32Array(16), t = new Uint32Array(4); - var i, j, m; - - for (i = 0; i < 4; i++) { - x[5*i] = ld32(c, 4*i); - x[1+i] = ld32(k, 4*i); - x[6+i] = ld32(inp, 4*i); - x[11+i] = ld32(k, 16+4*i); - } - - for (i = 0; i < 16; i++) y[i] = x[i]; - - for (i = 0; i < 20; i++) { - for (j = 0; j < 4; j++) { - for (m = 0; m < 4; m++) t[m] = x[(5*j+4*m)%16]; - t[1] ^= L32((t[0]+t[3])|0, 7); - t[2] ^= L32((t[1]+t[0])|0, 9); - t[3] ^= L32((t[2]+t[1])|0,13); - t[0] ^= L32((t[3]+t[2])|0,18); - for (m = 0; m < 4; m++) w[4*j+(j+m)%4] = t[m]; - } - for (m = 0; m < 16; m++) x[m] = w[m]; - } - - if (h) { - for (i = 0; i < 16; i++) x[i] = (x[i] + y[i]) | 0; - for (i = 0; i < 4; i++) { - x[5*i] = (x[5*i] - ld32(c, 4*i)) | 0; - x[6+i] = (x[6+i] - ld32(inp, 4*i)) | 0; - } - for (i = 0; i < 4; i++) { - st32(out,4*i,x[5*i]); - st32(out,16+4*i,x[6+i]); - } - } else { - for (i = 0; i < 16; i++) st32(out, 4 * i, (x[i] + y[i]) | 0); - } -} - -function crypto_core_salsa20(out,inp,k,c) { - core(out,inp,k,c,false); - return 0; -} - -function crypto_core_hsalsa20(out,inp,k,c) { - core(out,inp,k,c,true); - return 0; -} - -var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); - // "expand 32-byte k" - -function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - if (!b) return 0; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = (m?m[mpos+i]:0) ^ x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - if (m) mpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = (m?m[mpos+i]:0) ^ x[i]; - } - return 0; -} - -function crypto_stream_salsa20(c,cpos,d,n,k) { - return crypto_stream_salsa20_xor(c,cpos,null,0,d,n,k); -} - -function crypto_stream(c,cpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - return crypto_stream_salsa20(c,cpos,d,n.subarray(16),s); -} - -function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,n.subarray(16),s); -} - -function add1305(h, c) { - var j, u = 0; - for (j = 0; j < 17; j++) { - u = (u + ((h[j] + c[j]) | 0)) | 0; - h[j] = u & 255; - u >>>= 8; - } -} - -var minusp = new Uint32Array([ - 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252 -]); - -function crypto_onetimeauth(out, outpos, m, mpos, n, k) { - var s, i, j, u; - var x = new Uint32Array(17), r = new Uint32Array(17), - h = new Uint32Array(17), c = new Uint32Array(17), - g = new Uint32Array(17); - for (j = 0; j < 17; j++) r[j]=h[j]=0; - for (j = 0; j < 16; j++) r[j]=k[j]; - r[3]&=15; - r[4]&=252; - r[7]&=15; - r[8]&=252; - r[11]&=15; - r[12]&=252; - r[15]&=15; - - while (n > 0) { - for (j = 0; j < 17; j++) c[j] = 0; - for (j = 0; (j < 16) && (j < n); ++j) c[j] = m[mpos+j]; - c[j] = 1; - mpos += j; n -= j; - add1305(h,c); - for (i = 0; i < 17; i++) { - x[i] = 0; - for (j = 0; j < 17; j++) x[i] = (x[i] + (h[j] * ((j <= i) ? r[i - j] : ((320 * r[i + 17 - j])|0))) | 0) | 0; - } - for (i = 0; i < 17; i++) h[i] = x[i]; - u = 0; - for (j = 0; j < 16; j++) { - u = (u + h[j]) | 0; - h[j] = u & 255; - u >>>= 8; - } - u = (u + h[16]) | 0; h[16] = u & 3; - u = (5 * (u >>> 2)) | 0; - for (j = 0; j < 16; j++) { - u = (u + h[j]) | 0; - h[j] = u & 255; - u >>>= 8; - } - u = (u + h[16]) | 0; h[16] = u; - } - - for (j = 0; j < 17; j++) g[j] = h[j]; - add1305(h,minusp); - s = (-(h[16] >>> 7) | 0); - for (j = 0; j < 17; j++) h[j] ^= s & (g[j] ^ h[j]); - - for (j = 0; j < 16; j++) c[j] = k[j + 16]; - c[16] = 0; - add1305(h,c); - for (j = 0; j < 16; j++) out[outpos+j] = h[j]; - return 0; -} - -function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { - var x = new Uint8Array(16); - crypto_onetimeauth(x,0,m,mpos,n,k); - return crypto_verify_16(h,hpos,x,0); -} - -function crypto_secretbox(c,m,d,n,k) { - var i; - if (d < 32) return -1; - crypto_stream_xor(c,0,m,0,d,n,k); - crypto_onetimeauth(c, 16, c, 32, d - 32, c); - for (i = 0; i < 16; i++) c[i] = 0; - return 0; -} - -function crypto_secretbox_open(m,c,d,n,k) { - var i; - var x = new Uint8Array(32); - if (d < 32) return -1; - crypto_stream(x,0,32,n,k); - if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; - crypto_stream_xor(m,0,c,0,d,n,k); - for (i = 0; i < 32; i++) m[i] = 0; - return 0; -} - -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} - -function car25519(o) { - var c; - var i; - for (i = 0; i < 16; i++) { - o[i] += 65536; - c = Math.floor(o[i] / 65536); - o[(i+1)*(i<15?1:0)] += c - 1 + 37 * (c-1) * (i===15?1:0); - o[i] -= (c * 65536); - } -} - -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} - -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; - } -} - -function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); -} - -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; -} - -function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; -} - -function A(o, a, b) { - var i; - for (i = 0; i < 16; i++) o[i] = (a[i] + b[i])|0; -} - -function Z(o, a, b) { - var i; - for (i = 0; i < 16; i++) o[i] = (a[i] - b[i])|0; -} - -function M(o, a, b) { - var i, j, t = new Float64Array(31); - for (i = 0; i < 31; i++) t[i] = 0; - for (i = 0; i < 16; i++) { - for (j = 0; j < 16; j++) { - t[i+j] += a[i] * b[j]; - } - } - for (i = 0; i < 15; i++) { - t[i] += 38 * t[i+16]; - } - for (i = 0; i < 16; i++) o[i] = t[i]; - car25519(o); - car25519(o); -} - -function S(o, a) { - M(o, a, a); -} - -function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; -} - -function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); -} - -function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); -} - -function crypto_box_beforenm(k, y, x) { - var s = new Uint8Array(32); - crypto_scalarmult(s, x, y); - return crypto_core_hsalsa20(k, _0, s, sigma); -} - -var crypto_box_afternm = crypto_secretbox; -var crypto_box_open_afternm = crypto_secretbox_open; - -function crypto_box(c, m, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_afternm(c, m, d, n, k); -} - -function crypto_box_open(m, c, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_open_afternm(m, c, d, n, k); -} - -function add64() { - var a = 0, b = 0, c = 0, d = 0, m16 = 65535, l, h, i; - for (i = 0; i < arguments.length; i++) { - l = arguments[i].lo; - h = arguments[i].hi; - a += (l & m16); b += (l >>> 16); - c += (h & m16); d += (h >>> 16); - } - - b += (a >>> 16); - c += (b >>> 16); - d += (c >>> 16); - - return new u64((c & m16) | (d << 16), (a & m16) | (b << 16)); -} - -function shr64(x, c) { - return new u64((x.hi >>> c), (x.lo >>> c) | (x.hi << (32 - c))); -} - -function xor64() { - var l = 0, h = 0, i; - for (i = 0; i < arguments.length; i++) { - l ^= arguments[i].lo; - h ^= arguments[i].hi; - } - return new u64(h, l); -} - -function R(x, c) { - var h, l, c1 = 32 - c; - if (c < 32) { - h = (x.hi >>> c) | (x.lo << c1); - l = (x.lo >>> c) | (x.hi << c1); - } else if (c < 64) { - h = (x.lo >>> c) | (x.hi << c1); - l = (x.hi >>> c) | (x.lo << c1); - } - return new u64(h, l); -} - -function Ch(x, y, z) { - var h = (x.hi & y.hi) ^ (~x.hi & z.hi), - l = (x.lo & y.lo) ^ (~x.lo & z.lo); - return new u64(h, l); -} - -function Maj(x, y, z) { - var h = (x.hi & y.hi) ^ (x.hi & z.hi) ^ (y.hi & z.hi), - l = (x.lo & y.lo) ^ (x.lo & z.lo) ^ (y.lo & z.lo); - return new u64(h, l); -} - -function Sigma0(x) { return xor64(R(x,28), R(x,34), R(x,39)); } -function Sigma1(x) { return xor64(R(x,14), R(x,18), R(x,41)); } -function sigma0(x) { return xor64(R(x, 1), R(x, 8), shr64(x,7)); } -function sigma1(x) { return xor64(R(x,19), R(x,61), shr64(x,6)); } - -var K = [ - new u64(0x428a2f98, 0xd728ae22), new u64(0x71374491, 0x23ef65cd), - new u64(0xb5c0fbcf, 0xec4d3b2f), new u64(0xe9b5dba5, 0x8189dbbc), - new u64(0x3956c25b, 0xf348b538), new u64(0x59f111f1, 0xb605d019), - new u64(0x923f82a4, 0xaf194f9b), new u64(0xab1c5ed5, 0xda6d8118), - new u64(0xd807aa98, 0xa3030242), new u64(0x12835b01, 0x45706fbe), - new u64(0x243185be, 0x4ee4b28c), new u64(0x550c7dc3, 0xd5ffb4e2), - new u64(0x72be5d74, 0xf27b896f), new u64(0x80deb1fe, 0x3b1696b1), - new u64(0x9bdc06a7, 0x25c71235), new u64(0xc19bf174, 0xcf692694), - new u64(0xe49b69c1, 0x9ef14ad2), new u64(0xefbe4786, 0x384f25e3), - new u64(0x0fc19dc6, 0x8b8cd5b5), new u64(0x240ca1cc, 0x77ac9c65), - new u64(0x2de92c6f, 0x592b0275), new u64(0x4a7484aa, 0x6ea6e483), - new u64(0x5cb0a9dc, 0xbd41fbd4), new u64(0x76f988da, 0x831153b5), - new u64(0x983e5152, 0xee66dfab), new u64(0xa831c66d, 0x2db43210), - new u64(0xb00327c8, 0x98fb213f), new u64(0xbf597fc7, 0xbeef0ee4), - new u64(0xc6e00bf3, 0x3da88fc2), new u64(0xd5a79147, 0x930aa725), - new u64(0x06ca6351, 0xe003826f), new u64(0x14292967, 0x0a0e6e70), - new u64(0x27b70a85, 0x46d22ffc), new u64(0x2e1b2138, 0x5c26c926), - new u64(0x4d2c6dfc, 0x5ac42aed), new u64(0x53380d13, 0x9d95b3df), - new u64(0x650a7354, 0x8baf63de), new u64(0x766a0abb, 0x3c77b2a8), - new u64(0x81c2c92e, 0x47edaee6), new u64(0x92722c85, 0x1482353b), - new u64(0xa2bfe8a1, 0x4cf10364), new u64(0xa81a664b, 0xbc423001), - new u64(0xc24b8b70, 0xd0f89791), new u64(0xc76c51a3, 0x0654be30), - new u64(0xd192e819, 0xd6ef5218), new u64(0xd6990624, 0x5565a910), - new u64(0xf40e3585, 0x5771202a), new u64(0x106aa070, 0x32bbd1b8), - new u64(0x19a4c116, 0xb8d2d0c8), new u64(0x1e376c08, 0x5141ab53), - new u64(0x2748774c, 0xdf8eeb99), new u64(0x34b0bcb5, 0xe19b48a8), - new u64(0x391c0cb3, 0xc5c95a63), new u64(0x4ed8aa4a, 0xe3418acb), - new u64(0x5b9cca4f, 0x7763e373), new u64(0x682e6ff3, 0xd6b2b8a3), - new u64(0x748f82ee, 0x5defb2fc), new u64(0x78a5636f, 0x43172f60), - new u64(0x84c87814, 0xa1f0ab72), new u64(0x8cc70208, 0x1a6439ec), - new u64(0x90befffa, 0x23631e28), new u64(0xa4506ceb, 0xde82bde9), - new u64(0xbef9a3f7, 0xb2c67915), new u64(0xc67178f2, 0xe372532b), - new u64(0xca273ece, 0xea26619c), new u64(0xd186b8c7, 0x21c0c207), - new u64(0xeada7dd6, 0xcde0eb1e), new u64(0xf57d4f7f, 0xee6ed178), - new u64(0x06f067aa, 0x72176fba), new u64(0x0a637dc5, 0xa2c898a6), - new u64(0x113f9804, 0xbef90dae), new u64(0x1b710b35, 0x131c471b), - new u64(0x28db77f5, 0x23047d84), new u64(0x32caab7b, 0x40c72493), - new u64(0x3c9ebe0a, 0x15c9bebc), new u64(0x431d67c4, 0x9c100d4c), - new u64(0x4cc5d4be, 0xcb3e42b6), new u64(0x597f299c, 0xfc657e2a), - new u64(0x5fcb6fab, 0x3ad6faec), new u64(0x6c44198c, 0x4a475817) -]; - -function crypto_hashblocks(x, m, n) { - var z = [], b = [], a = [], w = [], t, i, j; - - for (i = 0; i < 8; i++) z[i] = a[i] = dl64(x, 8*i); - - var pos = 0; - while (n >= 128) { - for (i = 0; i < 16; i++) w[i] = dl64(m, 8*i+pos); - for (i = 0; i < 80; i++) { - for (j = 0; j < 8; j++) b[j] = a[j]; - t = add64(a[7], Sigma1(a[4]), Ch(a[4], a[5], a[6]), K[i], w[i%16]); - b[7] = add64(t, Sigma0(a[0]), Maj(a[0], a[1], a[2])); - b[3] = add64(b[3], t); - for (j = 0; j < 8; j++) a[(j+1)%8] = b[j]; - if (i%16 === 15) { - for (j = 0; j < 16; j++) { - w[j] = add64(w[j], w[(j+9)%16], sigma0(w[(j+1)%16]), sigma1(w[(j+14)%16])); - } - } - } - - for (i = 0; i < 8; i++) { - a[i] = add64(a[i], z[i]); - z[i] = a[i]; - } - - pos += 128; - n -= 128; - } - - for (i = 0; i < 8; i++) ts64(x, 8*i, z[i]); - return n; -} - -var iv = new Uint8Array([ - 0x6a,0x09,0xe6,0x67,0xf3,0xbc,0xc9,0x08, - 0xbb,0x67,0xae,0x85,0x84,0xca,0xa7,0x3b, - 0x3c,0x6e,0xf3,0x72,0xfe,0x94,0xf8,0x2b, - 0xa5,0x4f,0xf5,0x3a,0x5f,0x1d,0x36,0xf1, - 0x51,0x0e,0x52,0x7f,0xad,0xe6,0x82,0xd1, - 0x9b,0x05,0x68,0x8c,0x2b,0x3e,0x6c,0x1f, - 0x1f,0x83,0xd9,0xab,0xfb,0x41,0xbd,0x6b, - 0x5b,0xe0,0xcd,0x19,0x13,0x7e,0x21,0x79 -]); - -function crypto_hash(out, m, n) { - var h = new Uint8Array(64), x = new Uint8Array(256); - var i, b = n; - - for (i = 0; i < 64; i++) h[i] = iv[i]; - - crypto_hashblocks(h, m, n); - n %= 128; - - for (i = 0; i < 256; i++) x[i] = 0; - for (i = 0; i < n; i++) x[i] = m[b-n+i]; - x[n] = 128; - - n = 256-128*(n<112?1:0); - x[n-9] = 0; - ts64(x, n-8, new u64((b / 0x20000000) | 0, b << 3)); - crypto_hashblocks(h, x, n); - - for (i = 0; i < 64; i++) out[i] = h[i]; - - return 0; -} - -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); - - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} - -function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } -} - -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} - -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } -} - -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); -} - -function crypto_sign_keypair(pk, sk, seeded) { - var d = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()]; - var i; - - if (!seeded) randombytes(sk, 32); - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - scalarbase(p, d); - pack(pk, p); - - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} - -var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = (x[j] + 128) >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} - -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); -} - -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - - crypto_hash(r, sm.subarray(32), n+32); - reduce(r); - scalarbase(p, r); - pack(sm, p); - - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h, sm, n + 64); - reduce(h); - - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } - - modL(sm.subarray(32), x); - return smlen; -} - -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); - - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); - - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - - M(r[3], r[0], r[1]); - return 0; -} - -function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new Uint8Array(32), h = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; - - mlen = -1; - if (n < 64) return -1; - - if (unpackneg(q, pk)) return -1; - - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - crypto_hash(h, m, n); - reduce(h); - scalarmult(p, q, h); - - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } - - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - mlen = n; - return mlen; -} - -var crypto_secretbox_KEYBYTES = 32, - crypto_secretbox_NONCEBYTES = 24, - crypto_secretbox_ZEROBYTES = 32, - crypto_secretbox_BOXZEROBYTES = 16, - crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_box_BEFORENMBYTES = 32, - crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, - crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, - crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32, - crypto_hash_BYTES = 64; - -nacl.lowlevel = { - crypto_core_hsalsa20: crypto_core_hsalsa20, - crypto_stream_xor: crypto_stream_xor, - crypto_stream: crypto_stream, - crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, - crypto_stream_salsa20: crypto_stream_salsa20, - crypto_onetimeauth: crypto_onetimeauth, - crypto_onetimeauth_verify: crypto_onetimeauth_verify, - crypto_verify_16: crypto_verify_16, - crypto_verify_32: crypto_verify_32, - crypto_secretbox: crypto_secretbox, - crypto_secretbox_open: crypto_secretbox_open, - crypto_scalarmult: crypto_scalarmult, - crypto_scalarmult_base: crypto_scalarmult_base, - crypto_box_beforenm: crypto_box_beforenm, - crypto_box_afternm: crypto_box_afternm, - crypto_box: crypto_box, - crypto_box_open: crypto_box_open, - crypto_box_keypair: crypto_box_keypair, - crypto_hash: crypto_hash, - crypto_sign: crypto_sign, - crypto_sign_keypair: crypto_sign_keypair, - crypto_sign_open: crypto_sign_open, - - crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, - crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, - crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, - crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, - crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, - crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, - crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, - crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, - crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, - crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, - crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, - crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, - crypto_sign_BYTES: crypto_sign_BYTES, - crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, - crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, - crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, - crypto_hash_BYTES: crypto_hash_BYTES -}; - -/* High-level API */ - -function checkLengths(k, n) { - if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); - if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); -} - -function checkBoxLengths(pk, sk) { - if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); - if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); -} - -function checkArrayTypes() { - var t, i; - for (i = 0; i < arguments.length; i++) { - if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') - throw new TypeError('unexpected type ' + t + ', use Uint8Array'); - } -} - -function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; -} - -// TODO: Completely remove this in v0.15. -if (!nacl.util) { - nacl.util = {}; - nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { - throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); - }; -} - -nacl.randomBytes = function(n) { - var b = new Uint8Array(n); - randombytes(b, n); - return b; -}; - -nacl.secretbox = function(msg, nonce, key) { - checkArrayTypes(msg, nonce, key); - checkLengths(key, nonce); - var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); - var c = new Uint8Array(m.length); - for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; - crypto_secretbox(c, m, m.length, nonce, key); - return c.subarray(crypto_secretbox_BOXZEROBYTES); -}; - -nacl.secretbox.open = function(box, nonce, key) { - checkArrayTypes(box, nonce, key); - checkLengths(key, nonce); - var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); - var m = new Uint8Array(c.length); - for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; - if (c.length < 32) return false; - if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; - return m.subarray(crypto_secretbox_ZEROBYTES); -}; - -nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; -nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; -nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; - -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; -}; - -nacl.scalarMult.base = function(n) { - checkArrayTypes(n); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult_base(q, n); - return q; -}; - -nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; -nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; - -nacl.box = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox(msg, nonce, k); -}; - -nacl.box.before = function(publicKey, secretKey) { - checkArrayTypes(publicKey, secretKey); - checkBoxLengths(publicKey, secretKey); - var k = new Uint8Array(crypto_box_BEFORENMBYTES); - crypto_box_beforenm(k, publicKey, secretKey); - return k; -}; - -nacl.box.after = nacl.secretbox; - -nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k); -}; - -nacl.box.open.after = nacl.secretbox.open; - -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; -nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; -nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; -nacl.box.nonceLength = crypto_box_NONCEBYTES; -nacl.box.overheadLength = nacl.secretbox.overheadLength; - -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; -}; - -nacl.sign.open = function(signedMsg, publicKey) { - if (arguments.length !== 2) - throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); - checkArrayTypes(signedMsg, publicKey); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var tmp = new Uint8Array(signedMsg.length); - var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); - if (mlen < 0) return null; - var m = new Uint8Array(mlen); - for (var i = 0; i < m.length; i++) m[i] = tmp[i]; - return m; -}; - -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; -}; - -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); -}; - -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; -nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; -nacl.sign.seedLength = crypto_sign_SEEDBYTES; -nacl.sign.signatureLength = crypto_sign_BYTES; - -nacl.hash = function(msg) { - checkArrayTypes(msg); - var h = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h, msg, msg.length); - return h; -}; - -nacl.hash.hashLength = crypto_hash_BYTES; - -nacl.verify = function(x, y) { - checkArrayTypes(x, y); - // Zero length arguments are considered not equal. - if (x.length === 0 || y.length === 0) return false; - if (x.length !== y.length) return false; - return (vn(x, 0, y, 0, x.length) === 0) ? true : false; -}; - -nacl.setPRNG = function(fn) { - randombytes = fn; -}; - -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (typeof require !== 'undefined') { - // Node.js. - crypto = require('crypto'); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } -})(); - -})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {})); diff --git a/reverse_engineering/node_modules/tweetnacl/nacl.min.js b/reverse_engineering/node_modules/tweetnacl/nacl.min.js deleted file mode 100644 index 4484974..0000000 --- a/reverse_engineering/node_modules/tweetnacl/nacl.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(r){"use strict";function n(r,n){return r<>>32-n}function e(r,n){var e=255&r[n+3];return e=e<<8|255&r[n+2],e=e<<8|255&r[n+1],e<<8|255&r[n+0]}function t(r,n){var e=r[n]<<24|r[n+1]<<16|r[n+2]<<8|r[n+3],t=r[n+4]<<24|r[n+5]<<16|r[n+6]<<8|r[n+7];return new sr(e,t)}function o(r,n,e){var t;for(t=0;t<4;t++)r[n+t]=255&e,e>>>=8}function i(r,n,e){r[n]=e.hi>>24&255,r[n+1]=e.hi>>16&255,r[n+2]=e.hi>>8&255,r[n+3]=255&e.hi,r[n+4]=e.lo>>24&255,r[n+5]=e.lo>>16&255,r[n+6]=e.lo>>8&255,r[n+7]=255&e.lo}function a(r,n,e,t,o){var i,a=0;for(i=0;i>>8)-1}function f(r,n,e,t){return a(r,n,e,t,16)}function u(r,n,e,t){return a(r,n,e,t,32)}function c(r,t,i,a,f){var u,c,w,y=new Uint32Array(16),l=new Uint32Array(16),s=new Uint32Array(16),h=new Uint32Array(4);for(u=0;u<4;u++)l[5*u]=e(a,4*u),l[1+u]=e(i,4*u),l[6+u]=e(t,4*u),l[11+u]=e(i,16+4*u);for(u=0;u<16;u++)s[u]=l[u];for(u=0;u<20;u++){for(c=0;c<4;c++){for(w=0;w<4;w++)h[w]=l[(5*c+4*w)%16];for(h[1]^=n(h[0]+h[3]|0,7),h[2]^=n(h[1]+h[0]|0,9),h[3]^=n(h[2]+h[1]|0,13),h[0]^=n(h[3]+h[2]|0,18),w=0;w<4;w++)y[4*c+(c+w)%4]=h[w]}for(w=0;w<16;w++)l[w]=y[w]}if(f){for(u=0;u<16;u++)l[u]=l[u]+s[u]|0;for(u=0;u<4;u++)l[5*u]=l[5*u]-e(a,4*u)|0,l[6+u]=l[6+u]-e(t,4*u)|0;for(u=0;u<4;u++)o(r,4*u,l[5*u]),o(r,16+4*u,l[6+u])}else for(u=0;u<16;u++)o(r,4*u,l[u]+s[u]|0)}function w(r,n,e,t){return c(r,n,e,t,!1),0}function y(r,n,e,t){return c(r,n,e,t,!0),0}function l(r,n,e,t,o,i,a){var f,u,c=new Uint8Array(16),y=new Uint8Array(64);if(!o)return 0;for(u=0;u<16;u++)c[u]=0;for(u=0;u<8;u++)c[u]=i[u];for(;o>=64;){for(w(y,c,a,Br),u=0;u<64;u++)r[n+u]=(e?e[t+u]:0)^y[u];for(f=1,u=8;u<16;u++)f=f+(255&c[u])|0,c[u]=255&f,f>>>=8;o-=64,n+=64,e&&(t+=64)}if(o>0)for(w(y,c,a,Br),u=0;u>>=8}function b(r,n,e,t,o,i){var a,f,u,c,w=new Uint32Array(17),y=new Uint32Array(17),l=new Uint32Array(17),s=new Uint32Array(17),h=new Uint32Array(17);for(u=0;u<17;u++)y[u]=l[u]=0;for(u=0;u<16;u++)y[u]=i[u];for(y[3]&=15,y[4]&=252,y[7]&=15,y[8]&=252,y[11]&=15,y[12]&=252,y[15]&=15;o>0;){for(u=0;u<17;u++)s[u]=0;for(u=0;u<16&&u>>=8;for(c=c+l[16]|0,l[16]=3&c,c=5*(c>>>2)|0,u=0;u<16;u++)c=c+l[u]|0,l[u]=255&c,c>>>=8;c=c+l[16]|0,l[16]=c}for(u=0;u<17;u++)h[u]=l[u];for(v(l,Sr),a=0|-(l[16]>>>7),u=0;u<17;u++)l[u]^=a&(h[u]^l[u]);for(u=0;u<16;u++)s[u]=i[u+16];for(s[16]=0,v(l,s),u=0;u<16;u++)r[n+u]=l[u];return 0}function p(r,n,e,t,o,i){var a=new Uint8Array(16);return b(a,0,e,t,o,i),f(r,n,a,0)}function _(r,n,e,t,o){var i;if(e<32)return-1;for(g(r,0,n,0,e,t,o),b(r,16,r,32,e-32,r),i=0;i<16;i++)r[i]=0;return 0}function A(r,n,e,t,o){var i,a=new Uint8Array(32);if(e<32)return-1;if(h(a,0,32,t,o),0!==p(n,16,n,32,e-32,a))return-1;for(g(r,0,n,0,e,t,o),i=0;i<32;i++)r[i]=0;return 0}function U(r,n){var e;for(e=0;e<16;e++)r[e]=0|n[e]}function E(r){var n,e;for(e=0;e<16;e++)r[e]+=65536,n=Math.floor(r[e]/65536),r[(e+1)*(e<15?1:0)]+=n-1+37*(n-1)*(15===e?1:0),r[e]-=65536*n}function d(r,n,e){for(var t,o=~(e-1),i=0;i<16;i++)t=o&(r[i]^n[i]),r[i]^=t,n[i]^=t}function x(r,n){var e,t,o,i=hr(),a=hr();for(e=0;e<16;e++)a[e]=n[e];for(E(a),E(a),E(a),t=0;t<2;t++){for(i[0]=a[0]-65517,e=1;e<15;e++)i[e]=a[e]-65535-(i[e-1]>>16&1),i[e-1]&=65535;i[15]=a[15]-32767-(i[14]>>16&1),o=i[15]>>16&1,i[14]&=65535,d(a,i,1-o)}for(e=0;e<16;e++)r[2*e]=255&a[e],r[2*e+1]=a[e]>>8}function m(r,n){var e=new Uint8Array(32),t=new Uint8Array(32);return x(e,r),x(t,n),u(e,0,t,0)}function B(r){var n=new Uint8Array(32);return x(n,r),1&n[0]}function S(r,n){var e;for(e=0;e<16;e++)r[e]=n[2*e]+(n[2*e+1]<<8);r[15]&=32767}function K(r,n,e){var t;for(t=0;t<16;t++)r[t]=n[t]+e[t]|0}function T(r,n,e){var t;for(t=0;t<16;t++)r[t]=n[t]-e[t]|0}function Y(r,n,e){var t,o,i=new Float64Array(31);for(t=0;t<31;t++)i[t]=0;for(t=0;t<16;t++)for(o=0;o<16;o++)i[t+o]+=n[t]*e[o];for(t=0;t<15;t++)i[t]+=38*i[t+16];for(t=0;t<16;t++)r[t]=i[t];E(r),E(r)}function L(r,n){Y(r,n,n)}function k(r,n){var e,t=hr();for(e=0;e<16;e++)t[e]=n[e];for(e=253;e>=0;e--)L(t,t),2!==e&&4!==e&&Y(t,t,n);for(e=0;e<16;e++)r[e]=t[e]}function z(r,n){var e,t=hr();for(e=0;e<16;e++)t[e]=n[e];for(e=250;e>=0;e--)L(t,t),1!==e&&Y(t,t,n);for(e=0;e<16;e++)r[e]=t[e]}function R(r,n,e){var t,o,i=new Uint8Array(32),a=new Float64Array(80),f=hr(),u=hr(),c=hr(),w=hr(),y=hr(),l=hr();for(o=0;o<31;o++)i[o]=n[o];for(i[31]=127&n[31]|64,i[0]&=248,S(a,e),o=0;o<16;o++)u[o]=a[o],w[o]=f[o]=c[o]=0;for(f[0]=w[0]=1,o=254;o>=0;--o)t=i[o>>>3]>>>(7&o)&1,d(f,u,t),d(c,w,t),K(y,f,c),T(f,f,c),K(c,u,w),T(u,u,w),L(w,y),L(l,f),Y(f,c,f),Y(c,u,y),K(y,f,c),T(f,f,c),L(u,f),T(c,w,l),Y(f,c,Ar),K(f,f,w),Y(c,c,f),Y(f,w,l),Y(w,u,a),L(u,y),d(f,u,t),d(c,w,t);for(o=0;o<16;o++)a[o+16]=f[o],a[o+32]=c[o],a[o+48]=u[o],a[o+64]=w[o];var s=a.subarray(32),h=a.subarray(16);return k(s,s),Y(h,h,s),x(r,h),0}function P(r,n){return R(r,n,br)}function O(r,n){return gr(n,32),P(r,n)}function F(r,n,e){var t=new Uint8Array(32);return R(t,e,n),y(r,vr,t,Br)}function N(r,n,e,t,o,i){var a=new Uint8Array(32);return F(a,o,i),Kr(r,n,e,t,a)}function C(r,n,e,t,o,i){var a=new Uint8Array(32);return F(a,o,i),Tr(r,n,e,t,a)}function M(){var r,n,e,t=0,o=0,i=0,a=0,f=65535;for(e=0;e>>16,i+=n&f,a+=n>>>16;return o+=t>>>16,i+=o>>>16,a+=i>>>16,new sr(i&f|a<<16,t&f|o<<16)}function G(r,n){return new sr(r.hi>>>n,r.lo>>>n|r.hi<<32-n)}function Z(){var r,n=0,e=0;for(r=0;r>>n|r.lo<>>n|r.hi<>>n|r.hi<>>n|r.lo<=128;){for(a=0;a<16;a++)y[a]=t(n,8*a+l);for(a=0;a<80;a++){for(f=0;f<8;f++)c[f]=w[f];for(o=M(w[7],X(w[4]),q(w[4],w[5],w[6]),Yr[a],y[a%16]),c[7]=M(o,V(w[0]),I(w[0],w[1],w[2])),c[3]=M(c[3],o),f=0;f<8;f++)w[(f+1)%8]=c[f];if(a%16===15)for(f=0;f<16;f++)y[f]=M(y[f],y[(f+9)%16],D(y[(f+1)%16]),H(y[(f+14)%16]))}for(a=0;a<8;a++)w[a]=M(w[a],u[a]),u[a]=w[a];l+=128,e-=128}for(a=0;a<8;a++)i(r,8*a,u[a]);return e}function Q(r,n,e){var t,o=new Uint8Array(64),a=new Uint8Array(256),f=e;for(t=0;t<64;t++)o[t]=Lr[t];for(J(o,n,e),e%=128,t=0;t<256;t++)a[t]=0;for(t=0;t=0;--o)t=e[o/8|0]>>(7&o)&1,$(r,n,t),W(n,r),W(r,r),$(r,n,t)}function er(r,n){var e=[hr(),hr(),hr(),hr()];U(e[0],dr),U(e[1],xr),U(e[2],_r),Y(e[3],dr,xr),nr(r,e,n)}function tr(r,n,e){var t,o=new Uint8Array(64),i=[hr(),hr(),hr(),hr()];for(e||gr(n,32),Q(o,n,32),o[0]&=248,o[31]&=127,o[31]|=64,er(i,o),rr(r,i),t=0;t<32;t++)n[t+32]=r[t];return 0}function or(r,n){var e,t,o,i;for(t=63;t>=32;--t){for(e=0,o=t-32,i=t-12;o>8,n[o]-=256*e;n[o]+=e,n[t]=0}for(e=0,o=0;o<32;o++)n[o]+=e-(n[31]>>4)*kr[o],e=n[o]>>8,n[o]&=255;for(o=0;o<32;o++)n[o]-=e*kr[o];for(t=0;t<32;t++)n[t+1]+=n[t]>>8,r[t]=255&n[t]}function ir(r){var n,e=new Float64Array(64);for(n=0;n<64;n++)e[n]=r[n];for(n=0;n<64;n++)r[n]=0;or(r,e)}function ar(r,n,e,t){var o,i,a=new Uint8Array(64),f=new Uint8Array(64),u=new Uint8Array(64),c=new Float64Array(64),w=[hr(),hr(),hr(),hr()];Q(a,t,32),a[0]&=248,a[31]&=127,a[31]|=64;var y=e+64;for(o=0;o>7&&T(r[0],pr,r[0]),Y(r[3],r[0],r[1]),0)}function ur(r,n,e,t){var o,i,a=new Uint8Array(32),f=new Uint8Array(64),c=[hr(),hr(),hr(),hr()],w=[hr(),hr(),hr(),hr()];if(i=-1,e<64)return-1;if(fr(w,t))return-1;for(o=0;o=0},r.sign.keyPair=function(){var r=new Uint8Array(Vr),n=new Uint8Array(Xr);return tr(r,n),{publicKey:r,secretKey:n}},r.sign.keyPair.fromSecretKey=function(r){if(yr(r),r.length!==Xr)throw new Error("bad secret key size");for(var n=new Uint8Array(Vr),e=0;e/dev/null && browserify test/browser/init.js test/*.quick.js | uglifyjs -c -m -o test/browser/_bundle-quick.js 2>/dev/null", - "lint": "eslint nacl.js nacl-fast.js test/*.js test/benchmark/*.js", - "test": "npm run test-node-all && npm run test-browser", - "test-browser": "NACL_SRC=${NACL_SRC:='nacl.min.js'} && npm run build-test-browser && cat $NACL_SRC test/browser/_bundle.js | tape-run | faucet", - "test-node": "tape test/*.js | faucet", - "test-node-all": "make -C test/c && tape test/*.js test/c/*.js | faucet" - }, - "types": "nacl.d.ts", - "version": "0.14.5" -} diff --git a/reverse_engineering/node_modules/util-deprecate/History.md b/reverse_engineering/node_modules/util-deprecate/History.md deleted file mode 100644 index acc8675..0000000 --- a/reverse_engineering/node_modules/util-deprecate/History.md +++ /dev/null @@ -1,16 +0,0 @@ - -1.0.2 / 2015-10-07 -================== - - * use try/catch when checking `localStorage` (#3, @kumavis) - -1.0.1 / 2014-11-25 -================== - - * browser: use `console.warn()` for deprecation calls - * browser: more jsdocs - -1.0.0 / 2014-04-30 -================== - - * initial commit diff --git a/reverse_engineering/node_modules/util-deprecate/LICENSE b/reverse_engineering/node_modules/util-deprecate/LICENSE deleted file mode 100644 index 6a60e8c..0000000 --- a/reverse_engineering/node_modules/util-deprecate/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 Nathan Rajlich - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/util-deprecate/README.md b/reverse_engineering/node_modules/util-deprecate/README.md deleted file mode 100644 index 75622fa..0000000 --- a/reverse_engineering/node_modules/util-deprecate/README.md +++ /dev/null @@ -1,53 +0,0 @@ -util-deprecate -============== -### The Node.js `util.deprecate()` function with browser support - -In Node.js, this module simply re-exports the `util.deprecate()` function. - -In the web browser (i.e. via browserify), a browser-specific implementation -of the `util.deprecate()` function is used. - - -## API - -A `deprecate()` function is the only thing exposed by this module. - -``` javascript -// setup: -exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); - - -// users see: -foo(); -// foo() is deprecated, use bar() instead -foo(); -foo(); -``` - - -## License - -(The MIT License) - -Copyright (c) 2014 Nathan Rajlich - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/reverse_engineering/node_modules/util-deprecate/browser.js b/reverse_engineering/node_modules/util-deprecate/browser.js deleted file mode 100644 index 549ae2f..0000000 --- a/reverse_engineering/node_modules/util-deprecate/browser.js +++ /dev/null @@ -1,67 +0,0 @@ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} diff --git a/reverse_engineering/node_modules/util-deprecate/node.js b/reverse_engineering/node_modules/util-deprecate/node.js deleted file mode 100644 index 5e6fcff..0000000 --- a/reverse_engineering/node_modules/util-deprecate/node.js +++ /dev/null @@ -1,6 +0,0 @@ - -/** - * For Node.js, simply re-export the core `util.deprecate` function. - */ - -module.exports = require('util').deprecate; diff --git a/reverse_engineering/node_modules/util-deprecate/package.json b/reverse_engineering/node_modules/util-deprecate/package.json deleted file mode 100644 index 2e854d8..0000000 --- a/reverse_engineering/node_modules/util-deprecate/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "_from": "util-deprecate@^1.0.1", - "_id": "util-deprecate@1.0.2", - "_inBundle": false, - "_integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", - "_location": "/util-deprecate", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "util-deprecate@^1.0.1", - "name": "util-deprecate", - "escapedName": "util-deprecate", - "rawSpec": "^1.0.1", - "saveSpec": null, - "fetchSpec": "^1.0.1" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "_shasum": "450d4dc9fa70de732762fbd2d4a28981419a0ccf", - "_spec": "util-deprecate@^1.0.1", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/readable-stream", - "author": { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "http://n8.io/" - }, - "browser": "browser.js", - "bugs": { - "url": "https://github.com/TooTallNate/util-deprecate/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "The Node.js `util.deprecate()` function with browser support", - "homepage": "https://github.com/TooTallNate/util-deprecate", - "keywords": [ - "util", - "deprecate", - "browserify", - "browser", - "node" - ], - "license": "MIT", - "main": "node.js", - "name": "util-deprecate", - "repository": { - "type": "git", - "url": "git://github.com/TooTallNate/util-deprecate.git" - }, - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "version": "1.0.2" -} diff --git a/reverse_engineering/node_modules/xtend/.jshintrc b/reverse_engineering/node_modules/xtend/.jshintrc deleted file mode 100644 index 77887b5..0000000 --- a/reverse_engineering/node_modules/xtend/.jshintrc +++ /dev/null @@ -1,30 +0,0 @@ -{ - "maxdepth": 4, - "maxstatements": 200, - "maxcomplexity": 12, - "maxlen": 80, - "maxparams": 5, - - "curly": true, - "eqeqeq": true, - "immed": true, - "latedef": false, - "noarg": true, - "noempty": true, - "nonew": true, - "undef": true, - "unused": "vars", - "trailing": true, - - "quotmark": true, - "expr": true, - "asi": true, - - "browser": false, - "esnext": true, - "devel": false, - "node": false, - "nonstandard": false, - - "predef": ["require", "module", "__dirname", "__filename"] -} diff --git a/reverse_engineering/node_modules/xtend/LICENSE b/reverse_engineering/node_modules/xtend/LICENSE deleted file mode 100644 index 0099f4f..0000000 --- a/reverse_engineering/node_modules/xtend/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) -Copyright (c) 2012-2014 Raynos. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/reverse_engineering/node_modules/xtend/README.md b/reverse_engineering/node_modules/xtend/README.md deleted file mode 100644 index 4a2703c..0000000 --- a/reverse_engineering/node_modules/xtend/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# xtend - -[![browser support][3]][4] - -[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) - -Extend like a boss - -xtend is a basic utility library which allows you to extend an object by appending all of the properties from each object in a list. When there are identical properties, the right-most property takes precedence. - -## Examples - -```js -var extend = require("xtend") - -// extend returns a new object. Does not mutate arguments -var combination = extend({ - a: "a", - b: "c" -}, { - b: "b" -}) -// { a: "a", b: "b" } -``` - -## Stability status: Locked - -## MIT Licensed - - - [3]: http://ci.testling.com/Raynos/xtend.png - [4]: http://ci.testling.com/Raynos/xtend diff --git a/reverse_engineering/node_modules/xtend/immutable.js b/reverse_engineering/node_modules/xtend/immutable.js deleted file mode 100644 index 94889c9..0000000 --- a/reverse_engineering/node_modules/xtend/immutable.js +++ /dev/null @@ -1,19 +0,0 @@ -module.exports = extend - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -function extend() { - var target = {} - - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i] - - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } - - return target -} diff --git a/reverse_engineering/node_modules/xtend/mutable.js b/reverse_engineering/node_modules/xtend/mutable.js deleted file mode 100644 index 72debed..0000000 --- a/reverse_engineering/node_modules/xtend/mutable.js +++ /dev/null @@ -1,17 +0,0 @@ -module.exports = extend - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -function extend(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] - - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } - - return target -} diff --git a/reverse_engineering/node_modules/xtend/package.json b/reverse_engineering/node_modules/xtend/package.json deleted file mode 100644 index e885066..0000000 --- a/reverse_engineering/node_modules/xtend/package.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "_from": "xtend@^4.0.0", - "_id": "xtend@4.0.2", - "_inBundle": false, - "_integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", - "_location": "/xtend", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "xtend@^4.0.0", - "name": "xtend", - "escapedName": "xtend", - "rawSpec": "^4.0.0", - "saveSpec": null, - "fetchSpec": "^4.0.0" - }, - "_requiredBy": [ - "/postgres-interval" - ], - "_resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", - "_shasum": "bb72779f5fa465186b1f438f674fa347fdb5db54", - "_spec": "xtend@^4.0.0", - "_where": "/home/vitalii/.hackolade/plugins/clones/PostgreSQL/reverse_engineering/node_modules/postgres-interval", - "author": { - "name": "Raynos", - "email": "raynos2@gmail.com" - }, - "bugs": { - "url": "https://github.com/Raynos/xtend/issues", - "email": "raynos2@gmail.com" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jake Verbaten" - }, - { - "name": "Matt Esch" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "extend like a boss", - "devDependencies": { - "tape": "~1.1.0" - }, - "engines": { - "node": ">=0.4" - }, - "homepage": "https://github.com/Raynos/xtend", - "keywords": [ - "extend", - "merge", - "options", - "opts", - "object", - "array" - ], - "license": "MIT", - "main": "immutable", - "name": "xtend", - "repository": { - "type": "git", - "url": "git://github.com/Raynos/xtend.git" - }, - "scripts": { - "test": "node test" - }, - "testling": { - "files": "test.js", - "browsers": [ - "ie/7..latest", - "firefox/16..latest", - "firefox/nightly", - "chrome/22..latest", - "chrome/canary", - "opera/12..latest", - "opera/next", - "safari/5.1..latest", - "ipad/6.0..latest", - "iphone/6.0..latest" - ] - }, - "version": "4.0.2" -} diff --git a/reverse_engineering/node_modules/xtend/test.js b/reverse_engineering/node_modules/xtend/test.js deleted file mode 100644 index b895b42..0000000 --- a/reverse_engineering/node_modules/xtend/test.js +++ /dev/null @@ -1,103 +0,0 @@ -var test = require("tape") -var extend = require("./") -var mutableExtend = require("./mutable") - -test("merge", function(assert) { - var a = { a: "foo" } - var b = { b: "bar" } - - assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) - assert.end() -}) - -test("replace", function(assert) { - var a = { a: "foo" } - var b = { a: "bar" } - - assert.deepEqual(extend(a, b), { a: "bar" }) - assert.end() -}) - -test("undefined", function(assert) { - var a = { a: undefined } - var b = { b: "foo" } - - assert.deepEqual(extend(a, b), { a: undefined, b: "foo" }) - assert.deepEqual(extend(b, a), { a: undefined, b: "foo" }) - assert.end() -}) - -test("handle 0", function(assert) { - var a = { a: "default" } - var b = { a: 0 } - - assert.deepEqual(extend(a, b), { a: 0 }) - assert.deepEqual(extend(b, a), { a: "default" }) - assert.end() -}) - -test("is immutable", function (assert) { - var record = {} - - extend(record, { foo: "bar" }) - assert.equal(record.foo, undefined) - assert.end() -}) - -test("null as argument", function (assert) { - var a = { foo: "bar" } - var b = null - var c = void 0 - - assert.deepEqual(extend(b, a, c), { foo: "bar" }) - assert.end() -}) - -test("mutable", function (assert) { - var a = { foo: "bar" } - - mutableExtend(a, { bar: "baz" }) - - assert.equal(a.bar, "baz") - assert.end() -}) - -test("null prototype", function(assert) { - var a = { a: "foo" } - var b = Object.create(null) - b.b = "bar"; - - assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) - assert.end() -}) - -test("null prototype mutable", function (assert) { - var a = { foo: "bar" } - var b = Object.create(null) - b.bar = "baz"; - - mutableExtend(a, b) - - assert.equal(a.bar, "baz") - assert.end() -}) - -test("prototype pollution", function (assert) { - var a = {} - var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' - - assert.strictEqual(a.oops, undefined) - extend({}, maliciousPayload) - assert.strictEqual(a.oops, undefined) - assert.end() -}) - -test("prototype pollution mutable", function (assert) { - var a = {} - var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' - - assert.strictEqual(a.oops, undefined) - mutableExtend({}, maliciousPayload) - assert.strictEqual(a.oops, undefined) - assert.end() -}) diff --git a/reverse_engineering/package.json b/reverse_engineering/package.json deleted file mode 100644 index c9ef1f2..0000000 --- a/reverse_engineering/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "CockroachDB", - "version": "1.0.0", - "description": "", - "author": "Hackolade", - "dependencies": { - "pg": "^8.7.1", - "tunnel-ssh": "^4.1.6" - }, - "installed": true -} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..c5275b0 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "baseUrl": ".", + "outDir": "./tscDist", + "allowJs": true, + "checkJs": false, + "target": "ES2016", + "lib": ["ESNext", "DOM"], + "sourceMap": true, + "jsx": "react-jsx", + "moduleResolution": "node", + "experimentalDecorators": true, + "noUnusedParameters": true, + "noUnusedLocals": true, + "noImplicitThis": true, + "noImplicitAny": false, + "alwaysStrict": true, + "skipLibCheck": true, + "module": "ESNext", + "strict": true, + "useUnknownInCatchVariables": true, + "allowSyntheticDefaultImports": true, + "isolatedModules": true, + "resolveJsonModule": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "typeRoots": ["./node_modules/@types", "./types"] + }, + "include": ["reverse_engineering", "forward_engineering"], + "exclude": ["**/node_modules/**", "release/**/*"] +} diff --git a/types/binary.json b/types/binary.json index a44488f..23fae0b 100644 --- a/types/binary.json +++ b/types/binary.json @@ -25,4 +25,4 @@ "mode": "binary" } ] -} \ No newline at end of file +} diff --git a/types/boolean.json b/types/boolean.json index 1846399..cc2998d 100644 --- a/types/boolean.json +++ b/types/boolean.json @@ -12,4 +12,4 @@ "enum": [], "sample": "" } -} \ No newline at end of file +} diff --git a/types/char.json b/types/char.json index f3ac3b4..14cce4b 100644 --- a/types/char.json +++ b/types/char.json @@ -16,4 +16,4 @@ "mode": "varchar", "length": 10 } -} \ No newline at end of file +} diff --git a/types/composite.json b/types/composite.json index c458057..d5b03f4 100644 --- a/types/composite.json +++ b/types/composite.json @@ -1,18 +1,16 @@ { - "name": "composite", - "erdAbbreviation": "", - "dtdAbbreviation": "{...}", - "parentType": "document", - "hiddenOnEntity": [ - "view" - ], - "dependency": { - "level": "parent", - "key": "type", - "value": "definitions" - }, - "disabledTooltip": "For these datatypes, the CockroachDB specification requires that you create first a UDT, then reference it in your model.", - "defaultValues": { - "properties": [] - } + "name": "composite", + "erdAbbreviation": "", + "dtdAbbreviation": "{...}", + "parentType": "document", + "hiddenOnEntity": ["view"], + "dependency": { + "level": "parent", + "key": "type", + "value": "definitions" + }, + "disabledTooltip": "For these datatypes, the CockroachDB specification requires that you create first a UDT, then reference it in your model.", + "defaultValues": { + "properties": [] + } } diff --git a/types/datetime.json b/types/datetime.json index 6b556d5..5926184 100644 --- a/types/datetime.json +++ b/types/datetime.json @@ -88,4 +88,4 @@ "format": "PnYnMnDTnHnMnS" } ] -} \ No newline at end of file +} diff --git a/types/enum.json b/types/enum.json index f50973f..91161a3 100644 --- a/types/enum.json +++ b/types/enum.json @@ -3,9 +3,7 @@ "erdAbbreviation": "", "dtdAbbreviation": "{enum}", "parentType": "string", - "hiddenOnEntity": [ - "view" - ], + "hiddenOnEntity": ["view"], "dependency": { "level": "parent", "key": "type", diff --git a/types/geometry.json b/types/geometry.json index 1006e40..016c04c 100644 --- a/types/geometry.json +++ b/types/geometry.json @@ -20,4 +20,4 @@ "mode": "geospatial" } ] -} \ No newline at end of file +} diff --git a/types/inet.json b/types/inet.json index 6da6995..b91d17f 100644 --- a/types/inet.json +++ b/types/inet.json @@ -17,8 +17,8 @@ "minLength": "", "maxLength": "", "enum": [], - "sample":"", + "sample": "", "pattern": "", - "comments":"" + "comments": "" } -} \ No newline at end of file +} diff --git a/types/json.json b/types/json.json index 66a0b5e..e604034 100644 --- a/types/json.json +++ b/types/json.json @@ -24,25 +24,11 @@ "subtypes": { "object": { "parentType": "jsonObject", - "childValueType": [ - "jsonString", - "jsonNumber", - "jsonObject", - "jsonArray", - "jsonBoolean", - "jsonNull" - ] + "childValueType": ["jsonString", "jsonNumber", "jsonObject", "jsonArray", "jsonBoolean", "jsonNull"] }, "array": { "parentType": "jsonArray", - "childValueType": [ - "jsonString", - "jsonNumber", - "jsonObject", - "jsonArray", - "jsonBoolean", - "jsonNull" - ] + "childValueType": ["jsonString", "jsonNumber", "jsonObject", "jsonArray", "jsonBoolean", "jsonNull"] }, "string": { "parentType": "jsonString" @@ -57,4 +43,4 @@ "parentType": "jsonNull" } } -} \ No newline at end of file +} diff --git a/types/oid.json b/types/oid.json index bfa6809..da54171 100644 --- a/types/oid.json +++ b/types/oid.json @@ -17,8 +17,8 @@ "minLength": "", "maxLength": "", "enum": [], - "sample":"", + "sample": "", "pattern": "", - "comments":"" + "comments": "" } -} \ No newline at end of file +} diff --git a/types/uuid.json b/types/uuid.json index bf541c7..926bdc7 100644 --- a/types/uuid.json +++ b/types/uuid.json @@ -17,8 +17,8 @@ "minLength": "", "maxLength": "", "enum": [], - "sample":"", + "sample": "", "pattern": "", - "comments":"" + "comments": "" } -} \ No newline at end of file +} diff --git a/validation/validationRegularExpressions.json b/validation/validationRegularExpressions.json index 3abb213..4d60931 100644 --- a/validation/validationRegularExpressions.json +++ b/validation/validationRegularExpressions.json @@ -1,3 +1,3 @@ { "code": "^[A-Za-z_0-9]{0,64}$" -} \ No newline at end of file +}