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A0C;YAC1C,MAAM,IAAA,oBAAQ,EAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import {\n copyFileSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { basename, dirname, join, relative } from 'node:path';\nimport { main as downlevel } from 'downlevel-dts';\nimport * as log4js from 'log4js';\nimport { SemVer } from 'semver';\nimport * as ts from 'typescript';\nimport type { PackageJson, ProjectInfo } from './project-info';\nimport type { Mutable } from './utils';\n\nexport const TYPES_COMPAT = '.types-compat';\n\nconst LOG = log4js.getLogger('jsii/compiler');\n\nconst TS_VERSION = new SemVer(`${ts.versionMajorMinor}.0`);\n\n/**\n * Declares what versions of the TypeScript language will be supported by the\n * declarations files (and `typesVersions` entries) produced by this compiler\n * release.\n *\n * This should contain only `major.minor` specifiers, similar to the value of\n * the `ts.versionMajorMinor` property, and must be sorted in ascending version\n * order, as this dictates the order of entries in the `typesVersions` redirects\n * which has a direct impact on resolution (first match wins), and we don't want\n * to have to perform a sort pass on this list.\n */\nconst DOWNLEVEL_BREAKPOINTS: readonly SemVer[] = ['3.9'].map((ver) => new SemVer(`${ver}.0`));\n\n/**\n * Produces down-leveled declaration files to ensure compatibility with previous\n * compiler releases (macthing TypeScript's `major.minor` versioning scheme).\n * This is necessary in order to ensure a package change compiler release lines\n * does not force all it's consumers to do the same (and vice-versa).\n *\n * @returns the `typesVersions` object that should be recorded in `package.json`\n */\nexport function emitDownleveledDeclarations({ packageJson, projectRoot, tsc }: ProjectInfo) {\n const compatRoot = join(projectRoot, ...(tsc?.outDir != null ? [tsc?.outDir] : []), TYPES_COMPAT);\n rmSync(compatRoot, { force: true, recursive: true });\n\n const rewrites = new Set<`${number}.${number}`>();\n\n for (const breakpoint of DOWNLEVEL_BREAKPOINTS) {\n if (TS_VERSION.compare(breakpoint) <= 0) {\n // This TypeScript release is older or same as the breakpoint, so no need\n // for down-leveling here.\n continue;\n }\n\n const rewriteSet = new Map<string, string>();\n let needed = false;\n\n // We'll emit down-leveled declarations in a temporary directory...\n const workdir = mkdtempSync(join(tmpdir(), `downlevel-dts-${breakpoint}-${basename(projectRoot)}-`));\n try {\n downlevel(projectRoot, workdir, breakpoint.version);\n const projectOutDir = tsc?.outDir != null ? join(projectRoot, tsc.outDir) : projectRoot;\n const workOutDir = tsc?.outDir != null ? join(workdir, tsc.outDir) : workdir;\n for (const dts of walkDirectory(workOutDir)) {\n const original = readFileSync(join(projectOutDir, dts), 'utf-8');\n const downleveledPath = join(workOutDir, dts);\n const downleveled = readFileSync(downleveledPath, 'utf-8');\n needed ||= !semanticallyEqualDeclarations(original, downleveled);\n rewriteSet.set(dts, downleveledPath);\n }\n\n // If none of the declarations files changed during the down-level, then\n // we don't need to actually write it out & cause a redirect. This would\n // be wasteful. Most codebases won't incur any rewrite at all, since the\n // declarations files only reference \"visible\" members, and `jsii`\n // actually does not allow most of the unsupported syntaxes to be used\n // anyway.\n if (needed) {\n rewrites.add(`${breakpoint.major}.${breakpoint.minor}`);\n\n const versionSuffix = `ts${breakpoint.major}.${breakpoint.minor}`;\n const compatDir = join(compatRoot, versionSuffix);\n if (!existsSync(compatDir)) {\n mkdirSync(compatDir, { recursive: true });\n try {\n // Write an empty .npmignore file so that npm pack doesn't use the .gitignore file...\n writeFileSync(join(compatRoot, '.npmignore'), '\\n', 'utf-8');\n // Make sure all of this is gitignored, out of courtesy...\n writeFileSync(join(compatRoot, '.gitignore'), '*\\n', 'utf-8');\n } catch {\n // Ignore any error here... This is inconsequential.\n }\n }\n\n for (const [dts, downleveledPath] of rewriteSet) {\n const rewritten = join(compatDir, dts);\n // Make sure the parent directory exists (dts might be nested)\n mkdirSync(dirname(rewritten), { recursive: true });\n // Write the re-written declarations file there...\n copyFileSync(downleveledPath, rewritten);\n }\n }\n } finally {\n // Clean up after outselves...\n rmSync(workdir, { force: true, recursive: true });\n }\n }\n\n let typesVersions: Mutable<PackageJson['typesVersions']>;\n\n for (const version of rewrites) {\n // Register the type redirect in the typesVersions configuration\n typesVersions ??= {};\n const from = [...(tsc?.outDir != null ? [tsc?.outDir] : []), '*'].join('/');\n const to = [...(tsc?.outDir != null ? [tsc?.outDir] : []), TYPES_COMPAT, `ts${version}`, '*'].join('/');\n // We put 2 candidate redirects (first match wins), so that it works for nested imports, too (see: https://github.com/microsoft/TypeScript/issues/43133)\n typesVersions[`<=${version}`] = { [from]: [to, `${to}/index.d.ts`] };\n }\n\n // Compare JSON stringifications, as the order of keys is important here...\n if (JSON.stringify(packageJson.typesVersions) === JSON.stringify(typesVersions)) {\n // The existing configuration matches the new one. We're done here.\n return;\n }\n\n LOG.info('The required `typesVersions` configuration has changed. Updating \"package.json\" accordingly...');\n\n // Prepare the new contents of `PackageJson`.\n const newPackageJson = Object.entries(packageJson).reduce((obj, [key, value]) => {\n // NB: \"as any\" below are required becuase we must ignore `readonly` attributes from the source.\n if (key === 'typesVersions') {\n if (typesVersions != null) {\n obj[key] = typesVersions as any;\n }\n } else {\n obj[key] = value as any;\n // If there isn't currently a `typesVersions` entry, but there is a `types` entry,\n // we'll insert `typesVersions` right after `types`.\n if (key === 'types' && typesVersions != null && !('typesVersions' in packageJson)) {\n obj.typesVersions = typesVersions as any;\n }\n }\n return obj;\n }, {} as Mutable<PackageJson>);\n // If there was neither `types` nor `typesVersions` in the original `package.json`, we'll\n // add `typesVersions` at the end of it.\n if (!('typesVersions' in newPackageJson)) {\n newPackageJson.typesVersions = typesVersions as any;\n }\n\n const packageJsonFile = join(projectRoot, 'package.json');\n\n // We try \"hard\" to preserve the existing indent in the `package.json` file when updating it.\n const [, indent] = readFileSync(packageJsonFile, 'utf-8').match(/^(\\s*)\"/m) ?? [null, 2];\n\n writeFileSync(packageJsonFile, `${JSON.stringify(newPackageJson, undefined, indent)}\\n`, 'utf-8');\n}\n\n/**\n * Compares the contents of two declaration files semantically.\n *\n * @param left the first string.\n * @param right the second string.\n *\n * @returns `true` if `left` and `right` contain the same declarations.\n */\nfunction semanticallyEqualDeclarations(left: string, right: string): boolean {\n // We normalize declarations largely by parsing & re-printing them.\n const normalizeDeclarations = (code: string): string => {\n const sourceFile = ts.createSourceFile('index.d.ts', code, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);\n const printer = ts.createPrinter({\n newLine: ts.NewLineKind.LineFeed,\n noEmitHelpers: true,\n omitTrailingSemicolon: false,\n removeComments: true,\n });\n let normalized = printer.printFile(sourceFile);\n\n // TypeScript may emit duplicated reference declarations... which are absent from Downlevel-DTS' output...\n // https://github.com/microsoft/TypeScript/issues/48143\n const REFERENCES_TYPES_NODE = '/// <reference types=\"node\" />';\n while (normalized.startsWith(`${REFERENCES_TYPES_NODE}\\n${REFERENCES_TYPES_NODE}`)) {\n normalized = normalized.slice(REFERENCES_TYPES_NODE.length + 1);\n }\n\n return normalized;\n };\n\n left = normalizeDeclarations(left);\n right = normalizeDeclarations(right);\n\n return left === right;\n}\n\n/**\n * Recursively traverse the provided directory and yield the relative (to the\n * specified `root`) paths of all the `.d.ts` files found there.\n *\n * @param dir the directory to be walked.\n * @param root the root to which paths should be relative.\n */\nfunction* walkDirectory(dir: string, root: string = dir): Generator<string, void, void> {\n for (const file of readdirSync(dir)) {\n const filePath = join(dir, file);\n if (statSync(filePath).isDirectory()) {\n // This is a directory, recurse down...\n yield* walkDirectory(filePath, root);\n } else if (file.toLowerCase().endsWith('.d.ts')) {\n // This is a declaration file, yield it...\n yield relative(root, filePath);\n }\n }\n}\n"]}
\No newline at end of file