semver#satisfies TypeScript Examples

The following examples show how to use semver#satisfies. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From solc-typed-ast with Apache License 2.0 6 votes vote down vote up
export function getTypeForCompilerVersion(
    typing: VersionDependentType,
    compilerVersion: string
): TypeNode | undefined {
    const [type, version] = typing;

    return satisfies(compilerVersion, version) ? type : undefined;
}
Example #2
Source File: dbmss.local.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
upgrade(dbmsId: string, version: string, options: IDbmsUpgradeOptions = {migrate: true}): Promise<IDbmsInfo> {
        if (!semver.satisfies(version, NEO4J_SUPPORTED_VERSION_RANGE)) {
            throw new InvalidArgumentError(`Version not in range ${NEO4J_SUPPORTED_VERSION_RANGE}`, [
                'Use valid version',
            ]);
        }

        return upgradeNeo4j(this.environment, dbmsId, version, options);
    }
Example #3
Source File: pool.ts    From lightning-terminal with MIT License 6 votes vote down vote up
/**
   * Determines which order version to use based on the provided version string
   * @param version the version of pool
   *    (ex: 0.5.4-alpha commit=v0.5.4-alpha.0.20220114202858-525fe156d240)
   */
  getOrderVersion(version: string): number {
    // try to convert the pool version string to a SemVer object (ex: 0.5.4)
    const verNum = coerce(version);
    if (!verNum) return DEFAULT_ORDER_VERSION;

    // find the first key which the pool version satisfies
    const matchedKey = Object.keys(ORDER_VERSION_COMPAT).find(condition =>
      satisfies(verNum, condition),
    );
    if (!matchedKey) return DEFAULT_ORDER_VERSION;

    // return the order version that was matched
    return ORDER_VERSION_COMPAT[matchedKey];
  }
Example #4
Source File: dependency-version-compare.ts    From eslint-config-kit with MIT License 6 votes vote down vote up
function compare(
  versionOrRange: string,
  target: string,
  sign: '<' | '>'
): boolean {
  if (valid(versionOrRange)) {
    return satisfies(versionOrRange, sign + target)
  }

  if (validRange(versionOrRange)) {
    const matches = satisfies(target, versionOrRange)
    return subset(versionOrRange, sign + target) || (sign === '>' && matches)
  }

  throw new InvalidVersionError()
}
Example #5
Source File: patch.ts    From graphql-typed-document-node with MIT License 6 votes vote down vote up
export async function applyPatches(rootDirectory: string, reverse = false): Promise<void> {
  const { availablePatches, baseDir } = await getAvailablePatches();

  for (const patch of availablePatches) {
    if (patch.details) {
      const packageResolution = resolvePackage(rootDirectory, patch);

      if (packageResolution) {
        const isValidVersion = satisfies(packageResolution, patch.details.version);

        if (isValidVersion) {
          const result = applyPatchFile(baseDir, patch, reverse);

          if (result) {
            // eslint-disable-next-line
            console.info(`[TypedDocumentNode] Patch for ${patch.details.name}@${packageResolution} has been ${reverse ? 'reversed' : 'applied'}!`);
          } else {
            // eslint-disable-next-line
            console.warn(`[TypedDocumentNode] Something went wrong, unable to patch ${patch.details.name} (Patch: ${patch.details.version}, Installed: ${packageResolution})`);
          }
        } else {
          // eslint-disable-next-line
          verbose(`[TypedDocumentNode] Patch for ${patch.details.name} exists, but you have a version mismatch! (Supported: ${patch.details.version}, you have: ${packageResolution})`);
        }
      } else {
        verbose(`[TypedDocumentNode] Skipping ${patch.fileName} patch, didn't find any package resolution!`)
      }
    } else {
      verbose(`[TypedDocumentNode] Unable to extract package details for patch file ${patch.fileName}!`)
    }
  }
}
Example #6
Source File: setup.ts    From amplication with Apache License 2.0 6 votes vote down vote up
function preValidate() {
  const { engines } = require("../package.json");
  const { node: nodeRange, npm } = engines;
  const npm_config_user_agent = process.env.npm_config_user_agent;
  const currentNpmVersionArray = npm_config_user_agent?.match(
    /npm\/[\^*\~*]*[\d\.]+/
  );
  const currentNpmVersion = currentNpmVersionArray[0]?.slice(4);
  if (!currentNpmVersionArray || !currentNpmVersion) {
    logger.error(
      "Mmmmm... it seems like you don't have permission to run the script. Try to run it as an administrator."
    );
    process.exit(1);
  }
  const currentNode = process.versions.node;
  if (!satisfies(currentNode, nodeRange)) {
    logger.error(
      `This system seems to use an incompatible Node.js version, current version: ${currentNode} required version: ${nodeRange}`
    );
    process.exit(1);
  }
  if (!satisfies(currentNpmVersion, npm)) {
    logger.error(
      `This system seems to use an incompatible NPM version, current version: ${currentNpmVersion} required version: ${npm}`
    );
    process.exit(1);
  }
}
Example #7
Source File: ast_mapping.ts    From solc-typed-ast with Apache License 2.0 6 votes vote down vote up
writeInner(node: ElementaryTypeName, writer: ASTWriter): SrcDesc {
        if (satisfies(writer.targetCompilerVersion, "0.4")) {
            return [node.name];
        }

        if (
            gte(writer.targetCompilerVersion, "0.6.0") &&
            node.name === "address" &&
            node.parent instanceof ElementaryTypeNameExpression
        ) {
            return [node.stateMutability === "payable" ? "payable" : "address"];
        }

        return [node.stateMutability === "payable" ? node.name + " payable" : node.name];
    }
Example #8
Source File: config.spec.ts    From cli with Apache License 2.0 5 votes vote down vote up
mockedSemverSatisifies = jest.mocked(satisfies)
Example #9
Source File: config.ts    From cli with Apache License 2.0 5 votes vote down vote up
private isSettingVersionInRange(content: Configuration) {
    return satisfies(content.version, `^${CurrentSchemaVersion}`);
  }
Example #10
Source File: binPreconditionsFactory.ts    From cli with Apache License 2.0 5 votes vote down vote up
export function getBinVersionPrecondition(
  binaryName: string,
  options: BinPreconditionsOptions,
  versionExtractor: (stdout: string) => string = (stdout) => stdout
) {
  const appliedOptions: Required<BinPreconditionsOptions> = {
    ...defaultOptions,
    ...options,
    prettyName: options.prettyName,
  };
  return function (versionRange: string) {
    return async function (target: Command) {
      if (!validRange(versionRange)) {
        const message = dedent`
          Required version invalid: "${versionRange}".
          Please report this error to Coveo: https://github.com/coveo/cli/issues/new
        `;
        throw new PreconditionError(message, {
          category: PreconditionErrorCategory.InvalidBinVersionRange,
        });
      }

      const output = await spawnProcessOutput(
        binaryName,
        appliedOptions.params
      );

      await checkIfBinIsInstalled(target, binaryName, appliedOptions, output);
      const version = versionExtractor(output.stdout);

      if (!satisfies(version, versionRange)) {
        const message = dedent`
          ${target.id} needs a ${
          appliedOptions.prettyName
        } version in this range: "${versionRange}"
          Version detected: ${version}

          ${warnHowToInstallBin(appliedOptions)}
        `;
        throw new PreconditionError(message, {
          category: PreconditionErrorCategory.InvalidBinVersionRange,
        });
      }
    };
  };
}
Example #11
Source File: constants.spec.ts    From solc-typed-ast with Apache License 2.0 5 votes vote down vote up
describe("Compile version utils", () => {
    it("Compiler 0.4.* versions array is valid", () => {
        expect(CompilerVersions04.length).toBeGreaterThan(0);

        expect(CompilerVersions04.every((v) => satisfies(v, "0.4"))).toBeTruthy();
    });

    it("Compiler 0.5.* versions array is valid", () => {
        expect(CompilerVersions05.length).toBeGreaterThan(0);

        expect(CompilerVersions05.every((v) => satisfies(v, "0.5"))).toBeTruthy();
    });

    it("Compiler 0.6.* versions array is valid", () => {
        expect(CompilerVersions06.length).toBeGreaterThan(0);

        expect(CompilerVersions06.every((v) => satisfies(v, "0.6"))).toBeTruthy();
    });

    it("Compiler 0.7.* versions array is valid", () => {
        expect(CompilerVersions07.length).toBeGreaterThan(0);

        expect(CompilerVersions07.every((v) => satisfies(v, "0.7"))).toBeTruthy();
    });

    it("Compiler 0.8.* versions array is valid", () => {
        expect(CompilerVersions08.length).toBeGreaterThan(0);

        expect(CompilerVersions08.every((v) => satisfies(v, "0.8"))).toBeTruthy();
    });

    it("General supported compiler series array is valid", () => {
        expect(CompilerSeries).toHaveLength(5);

        expect(CompilerSeries).toContain(CompilerVersions04);
        expect(CompilerSeries).toContain(CompilerVersions05);
        expect(CompilerSeries).toContain(CompilerVersions06);
        expect(CompilerSeries).toContain(CompilerVersions07);
        expect(CompilerSeries).toContain(CompilerVersions08);
    });

    it("General supported compiler versions array is valid", () => {
        expect(CompilerVersions).toHaveLength(
            CompilerVersions04.length +
                CompilerVersions05.length +
                CompilerVersions06.length +
                CompilerVersions07.length +
                CompilerVersions08.length
        );

        expect(CompilerVersions).toEqual(expect.arrayContaining(CompilerVersions04));
        expect(CompilerVersions).toEqual(expect.arrayContaining(CompilerVersions05));
        expect(CompilerVersions).toEqual(expect.arrayContaining(CompilerVersions06));
        expect(CompilerVersions).toEqual(expect.arrayContaining(CompilerVersions07));
        expect(CompilerVersions).toEqual(expect.arrayContaining(CompilerVersions08));
    });

    it("Latest compiler version is equal to the last element of general supported compiler versions array", () => {
        expect(LatestCompilerVersion).toEqual(CompilerVersions[CompilerVersions.length - 1]);
    });
});
Example #12
Source File: unary_operation.spec.ts    From solc-typed-ast with Apache License 2.0 5 votes vote down vote up
describe("UnaryOperation", () => {
    const samples = new Map([
        ["0.4.13", "test/samples/solidity/expressions/unary_operation_0413.json"],
        ["0.5.0", "test/samples/solidity/expressions/unary_operation_050.json"]
    ]);

    for (const [version, sample] of samples.entries()) {
        describe(`Solc ${version}: ${sample}`, () => {
            let nodes: UnaryOperation[];

            const cases = [
                ["-", 13, 12],
                ["~", 18, 17],
                ["delete", 22, 21],
                ["!", 26, 25],
                ["+", 31, 30]
            ];

            if (!satisfies(version, "0.4")) {
                cases.pop();
            }

            before(async () => {
                const reader = new ASTReader();
                const { data } = await compileJson(sample, version);
                const [mainUnit] = reader.read(data);

                nodes = mainUnit.getChildrenByType(UnaryOperation);
            });

            it("Detect correct number of nodes", () => {
                expect(nodes.length).toEqual(cases.length);
            });

            cases.forEach(([operator, id, subId], index) => {
                it(`Operator ${operator}`, () => {
                    const operation = nodes[index];

                    expect(operation instanceof UnaryOperation).toEqual(true);
                    expect(operation.id).toEqual(id);

                    const sub = operation.vSubExpression as Identifier;

                    expect(sub instanceof Identifier).toEqual(true);
                    expect(sub.id).toEqual(subId);
                });
            });
        });
    }
});
Example #13
Source File: dependency-version-compare.ts    From eslint-config-kit with MIT License 5 votes vote down vote up
export function greater(versionOrRange: string, target: string): boolean {
  const version = toVersion(versionOrRange)
  return satisfies(version, '>' + target)
}
Example #14
Source File: dependency-version-compare.ts    From eslint-config-kit with MIT License 5 votes vote down vote up
export function greaterOrEquals(
  versionOrRange: string,
  target: string
): boolean {
  const version = toVersion(versionOrRange)
  return satisfies(version, '>=' + target)
}
Example #15
Source File: binary_operation.spec.ts    From solc-typed-ast with Apache License 2.0 5 votes vote down vote up
describe("BinaryOperation", () => {
    const samples = new Map([
        ["0.4.13", "test/samples/solidity/expressions/binary_operation_0413.json"],
        ["0.5.0", "test/samples/solidity/expressions/binary_operation_050.json"]
    ]);

    for (const [version, sample] of samples.entries()) {
        describe(`Solc ${version}: ${sample}`, () => {
            let nodes: BinaryOperation[];

            const cases = [
                ["+", 10, "1", 9],
                ["-", 16, "2", 15],
                ["*", 22, "20", 21],
                ["/", 28, "2", 27],
                ["%", 34, "5", 33],

                ["&", 40, "1", 39],
                ["|", 46, "1", 45],
                ["^", 52, "1", 51],
                ["**", 58, "2", 57]
            ];

            if (satisfies(version, "0.4")) {
                cases.pop();
            }

            before(async () => {
                const reader = new ASTReader();
                const { data } = await compileJson(sample, version);
                const [mainUnit] = reader.read(data);

                nodes = mainUnit.getChildrenByType(BinaryOperation);
            });

            it("Detect correct number of nodes", () => {
                expect(nodes.length).toEqual(cases.length);
            });

            cases.forEach(([operator, id, value, valueId], index) => {
                it(`Operator ${operator}`, () => {
                    const operation = nodes[index];

                    expect(operation instanceof BinaryOperation).toEqual(true);
                    expect(operation.id).toEqual(id);

                    const l = operation.vLeftExpression as Identifier;

                    expect(l instanceof Identifier).toEqual(true);
                    expect(l.name).toEqual("b");

                    const r = operation.vRightExpression as Literal;

                    expect(r instanceof Literal).toEqual(true);
                    expect(r.id).toEqual(valueId);
                    expect(r.value).toEqual(value);
                });
            });
        });
    }
});
Example #16
Source File: dbmss.local.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
async link(externalPath: string, name: string): Promise<IDbmsInfo> {
        // Make sure the path we're getting is an actual DBMS
        const info = await getDistributionInfo(externalPath);
        if (!info || !semver.satisfies(info.version, NEO4J_SUPPORTED_VERSION_RANGE)) {
            throw new InvalidArgumentError(`Path "${externalPath}" does not seem to be a valid neo4j DBMS`, [
                'Use a valid path',
            ]);
        }

        const manifestPath = path.join(externalPath, DBMS_MANIFEST_FILE);
        const manifestExists = await fse.pathExists(manifestPath);

        // If a manifest exists in the target, path use it
        /* eslint-disable indent */
        const rawManifest = manifestExists
            ? await fse.readJSON(manifestPath, {encoding: 'utf-8'})
            : {
                  name,
                  id: uuidv4(),
              };
        /* eslint-enable indent */
        const manifestModel = new DbmsManifestModel(rawManifest);

        // Don't override existing data
        const dbmsExists = await this.environment.entityExists(ENTITY_TYPES.DBMS, manifestModel.id);
        if (dbmsExists) {
            throw new InvalidArgumentError(`DBMS "${manifestModel.name}" already managed by relate`);
        }

        // Replace broken symlinks
        const dbmsPath = this.environment.getEntityRootPath(ENTITY_TYPES.DBMS, manifestModel.id);
        if (await isSymlink(dbmsPath)) {
            await fse.unlink(dbmsPath);
        }

        // Enforce unique names
        const dbmsNameExists = await this.getDbms(manifestModel.name).catch(() => null);
        if (dbmsNameExists) {
            throw new InvalidArgumentError(`DBMS "${manifestModel.name}" already exists`, ['Use a unique name']);
        }

        await fse.symlink(externalPath, dbmsPath, 'junction');
        await this.manifest.update(manifestModel.id, manifestModel);

        if (supportsAccessTokens(info)) {
            await this.installSecurityPlugin(manifestModel.id);
        }

        await this.discoverDbmss();
        return this.get(manifestModel.id);
    }
Example #17
Source File: nodeVersionChecker.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
nodeVersionCheckerRunner: TaskRunner<NodeVersionCheckerOptions> = async () => {
  // Read version from package json and treat that as the expected version in all other locations
  const packageJson = require(`${process.cwd()}/${packageJsonFile}`);
  const expectedVersion = packageJson.engines.node;

  console.log(chalk.yellow(`Specified node version in package.json is: ${expectedVersion}`));

  for (const file of nodeVersionFiles) {
    const fileContent = readFileSync(`${process.cwd()}/${file}`);
    const matches = fileContent.toString('utf8').match(pattern);

    if (!matches) {
      continue;
    }

    for (const match of matches) {
      const actualVersion = coerce(match);
      if (!actualVersion) {
        failures.push({
          file,
          line: match,
        });
        continue;
      }

      const satisfied = satisfies(actualVersion, expectedVersion);
      if (!satisfied) {
        failures.push({
          file,
          line: match,
        });
      }
    }
  }

  if (failures.length > 0) {
    console.log(chalk.red('--------------------------------------------------------------------'));
    console.log(chalk.red(`These entries don't satisfy the engine version in ${packageJsonFile}`));
    console.log(chalk.red('--------------------------------------------------------------------'));

    for (let index = 0; index < failures.length; index++) {
      const failure = failures[index];
      console.log(chalk.green(`\tIn ${failure.file} the line ${failure.line} does not satisfy ${expectedVersion}.`));
    }

    throw new Error('Node versions not in sync');
  }

  console.log(chalk.yellow('--------------------------------------------------------------------'));
  console.log(chalk.yellow('All node versions seem ok.'));
  console.log(chalk.yellow("Don't forget to sync https://github.com/grafana/grafana-build-container"));
  console.log(chalk.yellow(`also if you changed the engine version in ${packageJsonFile}`));
  console.log(chalk.yellow('--------------------------------------------------------------------'));
}
Example #18
Source File: dbmss.local.ts    From relate with GNU General Public License v3.0 4 votes vote down vote up
async install(
        name: string,
        version: string,
        edition: NEO4J_EDITION = NEO4J_EDITION.ENTERPRISE,
        credentials = '',
        overrideCache = false,
        limited = false,
        installPath?: string,
    ): Promise<IDbmsInfo> {
        if (!version) {
            throw new InvalidArgumentError('Version must be specified');
        }

        let dbmsExists;
        try {
            await this.get(name);
            dbmsExists = true;
        } catch {
            dbmsExists = false;
        }

        if (dbmsExists) {
            throw new DbmsExistsError(`DBMS with name "${name}" already exists`);
        }

        // version as a file path.
        if ((await fse.pathExists(version)) && (await fse.stat(version)).isFile()) {
            const tmpPath = path.join(this.environment.dirPaths.tmp, uuidv4());
            const {extractedDistPath} = await extractNeo4j(version, tmpPath);
            const dbms = await this.installNeo4j(
                name,
                this.getDbmsRootPath(),
                extractedDistPath,
                credentials,
                installPath,
            );

            await fse.remove(tmpPath);

            return dbms;
        }

        // @todo: version as a URL.
        if (isValidUrl(version)) {
            throw new NotSupportedError(`fetch and install ${version}`);
        }

        const coercedVersion = coerce(version)?.version;

        if (coercedVersion) {
            if (!satisfies(coercedVersion, NEO4J_SUPPORTED_VERSION_RANGE)) {
                throw new NotSupportedError(`version not in range ${NEO4J_SUPPORTED_VERSION_RANGE}`);
            }

            const beforeDownload = await discoverNeo4jDistributions(this.environment.dirPaths.dbmssCache);
            const requestedDistribution = beforeDownload.find(
                (dist) => dist.version === coercedVersion && dist.edition === edition,
            );
            const found = await requestedDistribution.flatMap(async (dist) => {
                const shouldDownload = overrideCache || None.isNone(dist);

                if (shouldDownload && !None.isNone(dist)) {
                    await fse.remove(dist.dist);
                }

                if (shouldDownload) {
                    await downloadNeo4j(coercedVersion, edition, this.environment.dirPaths.dbmssCache, limited);
                    const afterDownload = await discoverNeo4jDistributions(this.environment.dirPaths.dbmssCache);

                    return afterDownload.find((down) => down.version === coercedVersion && down.edition === edition);
                }

                return Maybe.of(dist);
            });

            return found.flatMap((dist) => {
                if (None.isNone(dist)) {
                    throw new NotFoundError(`Unable to find the requested version: ${version}-${edition} online`);
                }

                return this.installNeo4j(name, this.getDbmsRootPath(), dist.dist, credentials, installPath);
            });
        }

        throw new InvalidArgumentError('Provided version argument is not valid semver, url or path.');
    }