import { prettify, readPackageJSON, writeGeneratedFile } from './utils.ts';

const { version } = readPackageJSON();
const versionMatch = /^(\d+)\.(\d+)\.(\d+)-?(.*)?$/.exec(version);
if (!versionMatch) {
  throw new Error('Version does not match semver spec: ' + version);
}

const [, major, minor, patch, preReleaseTag] = versionMatch;

const body = `
/** @category Version */

// Note: This file is autogenerated using "resources/gen-version.js" script and
// automatically updated by "npm version" command.

/** A string containing the version of the GraphQL.js library */
export const version = '${version}' as string;

/** An object containing the components of the GraphQL.js version string */
export const versionInfo: Readonly<{
  major: number;
  minor: number;
  patch: number;
  preReleaseTag: string | null;
}> = Object.freeze({
  major: ${major},
  minor: ${minor},
  patch: ${patch},
  preReleaseTag: ${preReleaseTag ? `'${preReleaseTag}'` : 'null'},
});
`;

const prettified = await prettify('./src/version.ts', body);
writeGeneratedFile('./src/version.ts', prettified);