jsii-rosetta 5.4.32-dev.4 → 5.5.1-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/commands/convert.js +1 -2
- package/lib/commands/convert.js.map +1 -1
- package/lib/commands/coverage.js +1 -2
- package/lib/commands/coverage.js.map +1 -1
- package/lib/commands/extract.js +2 -3
- package/lib/commands/extract.js.map +1 -1
- package/lib/commands/infuse.js +2 -2
- package/lib/commands/infuse.js.map +1 -1
- package/lib/commands/read.js +1 -2
- package/lib/commands/read.js.map +1 -1
- package/lib/commands/transliterate.js +1 -2
- package/lib/commands/transliterate.js.map +1 -1
- package/lib/commands/trim-cache.js +1 -2
- package/lib/commands/trim-cache.js.map +1 -1
- package/lib/find-utils.js +4 -5
- package/lib/find-utils.js.map +1 -1
- package/lib/fixtures.js +1 -2
- package/lib/fixtures.js.map +1 -1
- package/lib/jsii/assemblies.js +9 -9
- package/lib/jsii/assemblies.js.map +1 -1
- package/lib/jsii/jsii-types.js +2 -3
- package/lib/jsii/jsii-types.js.map +1 -1
- package/lib/jsii/jsii-utils.js +15 -16
- package/lib/jsii/jsii-utils.js.map +1 -1
- package/lib/jsii/packages.js +1 -2
- package/lib/jsii/packages.js.map +1 -1
- package/lib/json.d.ts +0 -2
- package/lib/json.js +2 -3
- package/lib/json.js.map +1 -1
- package/lib/languages/target-language.js +3 -3
- package/lib/languages/target-language.js.map +1 -1
- package/lib/logging.js +6 -6
- package/lib/logging.js.map +1 -1
- package/lib/markdown/escapes.js +2 -3
- package/lib/markdown/escapes.js.map +1 -1
- package/lib/markdown/extract-snippets.js +1 -2
- package/lib/markdown/extract-snippets.js.map +1 -1
- package/lib/markdown/index.js +3 -4
- package/lib/markdown/index.js.map +1 -1
- package/lib/markdown/markdown-renderer.js +5 -5
- package/lib/markdown/markdown-renderer.js.map +1 -1
- package/lib/markdown/markdown.js +5 -6
- package/lib/markdown/markdown.js.map +1 -1
- package/lib/o-tree.js +2 -2
- package/lib/o-tree.js.map +1 -1
- package/lib/renderer.js +2 -2
- package/lib/renderer.js.map +1 -1
- package/lib/rosetta-reader.d.ts +0 -1
- package/lib/snippet-dependencies.js +5 -6
- package/lib/snippet-dependencies.js.map +1 -1
- package/lib/snippet-selectors.js +4 -5
- package/lib/snippet-selectors.js.map +1 -1
- package/lib/snippet.js +11 -11
- package/lib/snippet.js.map +1 -1
- package/lib/strict.js +1 -2
- package/lib/strict.js.map +1 -1
- package/lib/support.js +1 -2
- package/lib/support.js.map +1 -1
- package/lib/tablets/key.js +1 -2
- package/lib/tablets/key.js.map +1 -1
- package/lib/translate.js +4 -4
- package/lib/translate.js.map +1 -1
- package/lib/translate_all.js +1 -2
- package/lib/translate_all.js.map +1 -1
- package/lib/translate_all_worker.js +1 -2
- package/lib/translate_all_worker.js.map +1 -1
- package/lib/typescript/ast-utils.d.ts +1 -1
- package/lib/typescript/ast-utils.js +23 -23
- package/lib/typescript/ast-utils.js.map +1 -1
- package/lib/typescript/imports.d.ts +2 -2
- package/lib/typescript/imports.js +2 -3
- package/lib/typescript/imports.js.map +1 -1
- package/lib/typescript/types.js +16 -17
- package/lib/typescript/types.js.map +1 -1
- package/lib/typescript/visible-spans.js +4 -4
- package/lib/typescript/visible-spans.js.map +1 -1
- package/lib/util.d.ts +0 -1
- package/lib/util.js +19 -19
- package/lib/util.js.map +1 -1
- package/package.json +3 -3
- package/releases.json +2 -2
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"snippet-dependencies.js","sourceRoot":"","sources":["../src/snippet-dependencies.ts"],"names":[],"mappings":";;;AAAA,yCAAyC;AACzC,qCAAiD;AACjD,8BAA8B;AAC9B,8BAA8B;AAC9B,kCAAkC;AAElC,sCAAsC;AACtC,iCAAiC;AAEjC,6CAAgF;AAChF,qCAAqC;AAErC,iCAAwD;AACxD,iEAAiE;AACjE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAElD;;;;GAI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AAC;AAED,SAAS,UAAU,CAAC,CAAwB;IAC1C,OAAO,CAAC,CAAC,IAAI,KAAK,UAAU,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAI,EAAU,EAAE,EAAU;IAC1C,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;QACnB,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACZ,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;GAEG;AACH,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import * as cp from 'node:child_process';\nimport { promises as fsPromises } from 'node:fs';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { PackageJson } from '@jsii/spec';\nimport * as fastGlob from 'fast-glob';\nimport * as semver from 'semver';\n\nimport { findDependencyDirectory, findUp, isBuiltinModule } from './find-utils';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, CompilationDependency } from './snippet';\nimport { mkDict, formatList, pathExists } from './util';\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst { intersect } = require('semver-intersect');\n\n/**\n * Collect the dependencies of a bunch of snippets together in one declaration\n *\n * We assume here the dependencies will not conflict.\n */\nexport function collectDependencies(snippets: TypeScriptSnippet[]) {\n const ret: Record<string, CompilationDependency> = {};\n for (const snippet of snippets) {\n for (const [name, source] of Object.entries(snippet.compilationDependencies ?? {})) {\n ret[name] = resolveConflict(name, source, ret[name]);\n }\n }\n return ret;\n}\n\n/**\n * Add transitive dependencies of concrete dependencies to the array\n *\n * This is necessary to prevent multiple copies of transitive dependencies on disk, which\n * jsii-based packages might not deal with very well.\n */\nexport async function expandWithTransitiveDependencies(deps: Record<string, CompilationDependency>) {\n const pathsSeen = new Set<string>();\n const queue = Object.values(deps).filter(isConcrete);\n\n let next = queue.shift();\n while (next) {\n await addDependenciesOf(next.resolvedDirectory);\n next = queue.shift();\n }\n\n async function addDependenciesOf(dir: string) {\n if (pathsSeen.has(dir)) {\n return;\n }\n pathsSeen.add(dir);\n try {\n const pj: PackageJson = JSON.parse(\n await fsPromises.readFile(path.join(dir, 'package.json'), { encoding: 'utf-8' }),\n );\n for (const [name, dep] of Object.entries(await resolveDependenciesFromPackageJson(pj, dir))) {\n if (!deps[name]) {\n deps[name] = dep;\n queue.push(dep);\n }\n }\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return;\n }\n throw e;\n }\n }\n}\n\n/**\n * Find the corresponding package directories for all dependencies in a package.json\n */\nexport async function resolveDependenciesFromPackageJson(packageJson: PackageJson | undefined, directory: string) {\n return mkDict(\n await Promise.all(\n Object.keys({ ...packageJson?.dependencies, ...packageJson?.peerDependencies })\n .filter((name) => !isBuiltinModule(name))\n .filter(\n (name) =>\n !packageJson?.bundledDependencies?.includes(name) && !packageJson?.bundleDependencies?.includes(name),\n )\n .map(\n async (name) =>\n [\n name,\n {\n type: 'concrete',\n resolvedDirectory: await fsPromises.realpath(await findDependencyDirectory(name, directory)),\n },\n ] as const,\n ),\n ),\n );\n}\n\nfunction resolveConflict(\n name: string,\n a: CompilationDependency,\n b: CompilationDependency | undefined,\n): CompilationDependency {\n if (!b) {\n return a;\n }\n\n if (a.type === 'concrete' && b.type === 'concrete') {\n if (b.resolvedDirectory !== a.resolvedDirectory) {\n throw new Error(`Dependency conflict: ${name} can be either ${a.resolvedDirectory} or ${b.resolvedDirectory}`);\n }\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'symbolic') {\n // Intersect the ranges\n return {\n type: 'symbolic',\n versionRange: myVersionIntersect(a.versionRange, b.versionRange),\n };\n }\n\n if (a.type === 'concrete' && b.type === 'symbolic') {\n const concreteVersion: string = JSON.parse(\n fs.readFileSync(path.join(a.resolvedDirectory, 'package.json'), 'utf-8'),\n ).version;\n\n if (!semver.satisfies(concreteVersion, b.versionRange, { includePrerelease: true })) {\n throw new Error(\n `Dependency conflict: ${name} expected to match ${b.versionRange} but found ${concreteVersion} at ${a.resolvedDirectory}`,\n );\n }\n\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'concrete') {\n // Reverse roles so we fall into the previous case\n return resolveConflict(name, b, a);\n }\n\n throw new Error('Cases should have been exhaustive');\n}\n\n/**\n * Check that the directory we were given has all the necessary dependencies in it\n *\n * It's a warning if this is not true, not an error.\n */\nexport async function validateAvailableDependencies(directory: string, deps: Record<string, CompilationDependency>) {\n logging.info(`Validating dependencies at ${directory}`);\n const failures = await Promise.all(\n Object.entries(deps).flatMap(async ([name, _dep]) => {\n try {\n await findDependencyDirectory(name, directory);\n return [];\n } catch {\n return [name];\n }\n }),\n );\n\n if (failures.length > 0) {\n logging.warn(\n `${directory}: packages necessary to compile examples missing from supplied directory: ${failures.join(', ')}`,\n );\n }\n}\n\n/**\n * Intersect two semver ranges\n *\n * The package we are using for this doesn't support all syntaxes yet.\n * Do some work on top.\n */\nfunction myVersionIntersect(a: string, b: string): string {\n if (a === '*') {\n return b;\n }\n if (b === '*') {\n return a;\n }\n\n try {\n return intersect(a, b);\n } catch (e: any) {\n throw new Error(`semver-intersect does not support either '${a}' or '${b}': ${e.message}`);\n }\n}\n\n/**\n * Prepare a temporary directory with symlinks to all the dependencies we need.\n *\n * - Symlinks the concrete dependencies\n * - Tries to first find the symbolic dependencies in a potential monorepo that might be present\n * (try both `lerna` and `yarn` monorepos).\n * - Installs the remaining symbolic dependencies using 'npm'.\n */\nexport async function prepareDependencyDirectory(deps: Record<string, CompilationDependency>): Promise<string> {\n const concreteDirs = Object.values(deps)\n .filter(isConcrete)\n .map((x) => x.resolvedDirectory);\n const monorepoPackages = await scanMonoRepos(concreteDirs);\n\n const tmpDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'rosetta'));\n logging.info(`Preparing dependency closure at ${tmpDir} (-vv for more details)`);\n\n // Resolved symbolic packages against monorepo\n const resolvedDeps = mkDict(\n Object.entries(deps).map(([name, dep]) => [\n name,\n dep.type === 'concrete'\n ? dep\n : ((monorepoPackages[name]\n ? { type: 'concrete', resolvedDirectory: monorepoPackages[name] }\n : dep) as CompilationDependency),\n ]),\n );\n\n const dependencies: Record<string, string> = {};\n for (const [name, dep] of Object.entries(resolvedDeps)) {\n if (isConcrete(dep)) {\n logging.debug(`${name} -> ${dep.resolvedDirectory}`);\n dependencies[name] = `file:${dep.resolvedDirectory}`;\n } else {\n logging.debug(`${name} @ ${dep.versionRange}`);\n dependencies[name] = dep.versionRange;\n }\n }\n\n await fsPromises.writeFile(\n path.join(tmpDir, 'package.json'),\n JSON.stringify(\n {\n name: 'examples',\n version: '0.0.1',\n private: true,\n dependencies,\n },\n undefined,\n 2,\n ),\n {\n encoding: 'utf-8',\n },\n );\n\n // Run NPM install on this package.json. We need to include --force for packages\n // that have a symbolic version in the symlinked dev tree (like \"0.0.0\"), but have\n // actual version range dependencies from externally installed packages (like \"^2.0.0\").\n cp.execSync(`npm install --force --loglevel error`, { cwd: tmpDir, encoding: 'utf-8' });\n\n return tmpDir;\n}\n\n/**\n * Map package name to directory\n */\nasync function scanMonoRepos(startingDirs: readonly string[]): Promise<Record<string, string>> {\n const globs = new Set<string>();\n for (const dir of startingDirs) {\n // eslint-disable-next-line no-await-in-loop\n setExtend(globs, await findMonoRepoGlobs(dir));\n }\n\n if (globs.size === 0) {\n return {};\n }\n\n logging.debug(`Monorepo package sources: ${Array.from(globs).join(', ')}`);\n\n const packageDirectories = await fastGlob(Array.from(globs).map(windowsToUnix), { onlyDirectories: true });\n const results = mkDict(\n (\n await Promise.all(\n packageDirectories.map(async (directory) => {\n const pjLocation = path.join(directory, 'package.json');\n return (await pathExists(pjLocation))\n ? [[JSON.parse(await fsPromises.readFile(pjLocation, 'utf-8')).name as string, directory] as const]\n : [];\n }),\n )\n ).flat(),\n );\n\n logging.debug(`Found ${Object.keys(results).length} packages in monorepo: ${formatList(Object.keys(results))}`);\n return results;\n}\n\nasync function findMonoRepoGlobs(startingDir: string): Promise<Set<string>> {\n const ret = new Set<string>();\n\n // Lerna monorepo\n const lernaJsonDir = await findUp(startingDir, async (dir) => pathExists(path.join(dir, 'lerna.json')));\n if (lernaJsonDir) {\n const lernaJson = JSON.parse(await fsPromises.readFile(path.join(lernaJsonDir, 'lerna.json'), 'utf-8'));\n for (const glob of lernaJson?.packages ?? []) {\n ret.add(path.join(lernaJsonDir, glob));\n }\n }\n\n // Yarn monorepo\n const yarnWsDir = await findUp(\n startingDir,\n async (dir) =>\n (await pathExists(path.join(dir, 'package.json'))) &&\n JSON.parse(await fsPromises.readFile(path.join(dir, 'package.json'), 'utf-8'))?.workspaces !== undefined,\n );\n if (yarnWsDir) {\n const yarnWs = JSON.parse(await fsPromises.readFile(path.join(yarnWsDir, 'package.json'), 'utf-8'));\n for (const glob of yarnWs.workspaces?.packages ?? []) {\n ret.add(path.join(yarnWsDir, glob));\n }\n }\n\n return ret;\n}\n\nfunction isConcrete(x: CompilationDependency): x is Extract<CompilationDependency, { type: 'concrete' }> {\n return x.type === 'concrete';\n}\n\nfunction setExtend<A>(xs: Set<A>, ys: Set<A>) {\n for (const y of ys) {\n xs.add(y);\n }\n return xs;\n}\n\n/**\n * Necessary for fastGlob\n */\nfunction windowsToUnix(x: string) {\n return x.replace(/\\\\/g, '/');\n}\n"]}
|
1
|
+
{"version":3,"file":"snippet-dependencies.js","sourceRoot":"","sources":["../src/snippet-dependencies.ts"],"names":[],"mappings":";;AAqBA,kDAQC;AAQD,4EAgCC;AAKD,gFAqBC;AAqDD,sEAkBC;AA+BD,gEAuDC;AA5PD,yCAAyC;AACzC,qCAAiD;AACjD,8BAA8B;AAC9B,8BAA8B;AAC9B,kCAAkC;AAElC,sCAAsC;AACtC,iCAAiC;AAEjC,6CAAgF;AAChF,qCAAqC;AAErC,iCAAwD;AACxD,iEAAiE;AACjE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAElD;;;;GAIG;AACH,SAAgB,mBAAmB,CAAC,Q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AAS,SAAS,CAAI,EAAU,EAAE,EAAU;IAC1C,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;QACnB,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACZ,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;GAEG;AACH,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import * as cp from 'node:child_process';\nimport { promises as fsPromises } from 'node:fs';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { PackageJson } from '@jsii/spec';\nimport * as fastGlob from 'fast-glob';\nimport * as semver from 'semver';\n\nimport { findDependencyDirectory, findUp, isBuiltinModule } from './find-utils';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, CompilationDependency } from './snippet';\nimport { mkDict, formatList, pathExists } from './util';\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst { intersect } = require('semver-intersect');\n\n/**\n * Collect the dependencies of a bunch of snippets together in one declaration\n *\n * We assume here the dependencies will not conflict.\n */\nexport function collectDependencies(snippets: TypeScriptSnippet[]) {\n const ret: Record<string, CompilationDependency> = {};\n for (const snippet of snippets) {\n for (const [name, source] of Object.entries(snippet.compilationDependencies ?? {})) {\n ret[name] = resolveConflict(name, source, ret[name]);\n }\n }\n return ret;\n}\n\n/**\n * Add transitive dependencies of concrete dependencies to the array\n *\n * This is necessary to prevent multiple copies of transitive dependencies on disk, which\n * jsii-based packages might not deal with very well.\n */\nexport async function expandWithTransitiveDependencies(deps: Record<string, CompilationDependency>) {\n const pathsSeen = new Set<string>();\n const queue = Object.values(deps).filter(isConcrete);\n\n let next = queue.shift();\n while (next) {\n await addDependenciesOf(next.resolvedDirectory);\n next = queue.shift();\n }\n\n async function addDependenciesOf(dir: string) {\n if (pathsSeen.has(dir)) {\n return;\n }\n pathsSeen.add(dir);\n try {\n const pj: PackageJson = JSON.parse(\n await fsPromises.readFile(path.join(dir, 'package.json'), { encoding: 'utf-8' }),\n );\n for (const [name, dep] of Object.entries(await resolveDependenciesFromPackageJson(pj, dir))) {\n if (!deps[name]) {\n deps[name] = dep;\n queue.push(dep);\n }\n }\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return;\n }\n throw e;\n }\n }\n}\n\n/**\n * Find the corresponding package directories for all dependencies in a package.json\n */\nexport async function resolveDependenciesFromPackageJson(packageJson: PackageJson | undefined, directory: string) {\n return mkDict(\n await Promise.all(\n Object.keys({ ...packageJson?.dependencies, ...packageJson?.peerDependencies })\n .filter((name) => !isBuiltinModule(name))\n .filter(\n (name) =>\n !packageJson?.bundledDependencies?.includes(name) && !packageJson?.bundleDependencies?.includes(name),\n )\n .map(\n async (name) =>\n [\n name,\n {\n type: 'concrete',\n resolvedDirectory: await fsPromises.realpath(await findDependencyDirectory(name, directory)),\n },\n ] as const,\n ),\n ),\n );\n}\n\nfunction resolveConflict(\n name: string,\n a: CompilationDependency,\n b: CompilationDependency | undefined,\n): CompilationDependency {\n if (!b) {\n return a;\n }\n\n if (a.type === 'concrete' && b.type === 'concrete') {\n if (b.resolvedDirectory !== a.resolvedDirectory) {\n throw new Error(`Dependency conflict: ${name} can be either ${a.resolvedDirectory} or ${b.resolvedDirectory}`);\n }\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'symbolic') {\n // Intersect the ranges\n return {\n type: 'symbolic',\n versionRange: myVersionIntersect(a.versionRange, b.versionRange),\n };\n }\n\n if (a.type === 'concrete' && b.type === 'symbolic') {\n const concreteVersion: string = JSON.parse(\n fs.readFileSync(path.join(a.resolvedDirectory, 'package.json'), 'utf-8'),\n ).version;\n\n if (!semver.satisfies(concreteVersion, b.versionRange, { includePrerelease: true })) {\n throw new Error(\n `Dependency conflict: ${name} expected to match ${b.versionRange} but found ${concreteVersion} at ${a.resolvedDirectory}`,\n );\n }\n\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'concrete') {\n // Reverse roles so we fall into the previous case\n return resolveConflict(name, b, a);\n }\n\n throw new Error('Cases should have been exhaustive');\n}\n\n/**\n * Check that the directory we were given has all the necessary dependencies in it\n *\n * It's a warning if this is not true, not an error.\n */\nexport async function validateAvailableDependencies(directory: string, deps: Record<string, CompilationDependency>) {\n logging.info(`Validating dependencies at ${directory}`);\n const failures = await Promise.all(\n Object.entries(deps).flatMap(async ([name, _dep]) => {\n try {\n await findDependencyDirectory(name, directory);\n return [];\n } catch {\n return [name];\n }\n }),\n );\n\n if (failures.length > 0) {\n logging.warn(\n `${directory}: packages necessary to compile examples missing from supplied directory: ${failures.join(', ')}`,\n );\n }\n}\n\n/**\n * Intersect two semver ranges\n *\n * The package we are using for this doesn't support all syntaxes yet.\n * Do some work on top.\n */\nfunction myVersionIntersect(a: string, b: string): string {\n if (a === '*') {\n return b;\n }\n if (b === '*') {\n return a;\n }\n\n try {\n return intersect(a, b);\n } catch (e: any) {\n throw new Error(`semver-intersect does not support either '${a}' or '${b}': ${e.message}`);\n }\n}\n\n/**\n * Prepare a temporary directory with symlinks to all the dependencies we need.\n *\n * - Symlinks the concrete dependencies\n * - Tries to first find the symbolic dependencies in a potential monorepo that might be present\n * (try both `lerna` and `yarn` monorepos).\n * - Installs the remaining symbolic dependencies using 'npm'.\n */\nexport async function prepareDependencyDirectory(deps: Record<string, CompilationDependency>): Promise<string> {\n const concreteDirs = Object.values(deps)\n .filter(isConcrete)\n .map((x) => x.resolvedDirectory);\n const monorepoPackages = await scanMonoRepos(concreteDirs);\n\n const tmpDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'rosetta'));\n logging.info(`Preparing dependency closure at ${tmpDir} (-vv for more details)`);\n\n // Resolved symbolic packages against monorepo\n const resolvedDeps = mkDict(\n Object.entries(deps).map(([name, dep]) => [\n name,\n dep.type === 'concrete'\n ? dep\n : ((monorepoPackages[name]\n ? { type: 'concrete', resolvedDirectory: monorepoPackages[name] }\n : dep) as CompilationDependency),\n ]),\n );\n\n const dependencies: Record<string, string> = {};\n for (const [name, dep] of Object.entries(resolvedDeps)) {\n if (isConcrete(dep)) {\n logging.debug(`${name} -> ${dep.resolvedDirectory}`);\n dependencies[name] = `file:${dep.resolvedDirectory}`;\n } else {\n logging.debug(`${name} @ ${dep.versionRange}`);\n dependencies[name] = dep.versionRange;\n }\n }\n\n await fsPromises.writeFile(\n path.join(tmpDir, 'package.json'),\n JSON.stringify(\n {\n name: 'examples',\n version: '0.0.1',\n private: true,\n dependencies,\n },\n undefined,\n 2,\n ),\n {\n encoding: 'utf-8',\n },\n );\n\n // Run NPM install on this package.json. We need to include --force for packages\n // that have a symbolic version in the symlinked dev tree (like \"0.0.0\"), but have\n // actual version range dependencies from externally installed packages (like \"^2.0.0\").\n cp.execSync(`npm install --force --loglevel error`, { cwd: tmpDir, encoding: 'utf-8' });\n\n return tmpDir;\n}\n\n/**\n * Map package name to directory\n */\nasync function scanMonoRepos(startingDirs: readonly string[]): Promise<Record<string, string>> {\n const globs = new Set<string>();\n for (const dir of startingDirs) {\n // eslint-disable-next-line no-await-in-loop\n setExtend(globs, await findMonoRepoGlobs(dir));\n }\n\n if (globs.size === 0) {\n return {};\n }\n\n logging.debug(`Monorepo package sources: ${Array.from(globs).join(', ')}`);\n\n const packageDirectories = await fastGlob(Array.from(globs).map(windowsToUnix), { onlyDirectories: true });\n const results = mkDict(\n (\n await Promise.all(\n packageDirectories.map(async (directory) => {\n const pjLocation = path.join(directory, 'package.json');\n return (await pathExists(pjLocation))\n ? [[JSON.parse(await fsPromises.readFile(pjLocation, 'utf-8')).name as string, directory] as const]\n : [];\n }),\n )\n ).flat(),\n );\n\n logging.debug(`Found ${Object.keys(results).length} packages in monorepo: ${formatList(Object.keys(results))}`);\n return results;\n}\n\nasync function findMonoRepoGlobs(startingDir: string): Promise<Set<string>> {\n const ret = new Set<string>();\n\n // Lerna monorepo\n const lernaJsonDir = await findUp(startingDir, async (dir) => pathExists(path.join(dir, 'lerna.json')));\n if (lernaJsonDir) {\n const lernaJson = JSON.parse(await fsPromises.readFile(path.join(lernaJsonDir, 'lerna.json'), 'utf-8'));\n for (const glob of lernaJson?.packages ?? []) {\n ret.add(path.join(lernaJsonDir, glob));\n }\n }\n\n // Yarn monorepo\n const yarnWsDir = await findUp(\n startingDir,\n async (dir) =>\n (await pathExists(path.join(dir, 'package.json'))) &&\n JSON.parse(await fsPromises.readFile(path.join(dir, 'package.json'), 'utf-8'))?.workspaces !== undefined,\n );\n if (yarnWsDir) {\n const yarnWs = JSON.parse(await fsPromises.readFile(path.join(yarnWsDir, 'package.json'), 'utf-8'));\n for (const glob of yarnWs.workspaces?.packages ?? []) {\n ret.add(path.join(yarnWsDir, glob));\n }\n }\n\n return ret;\n}\n\nfunction isConcrete(x: CompilationDependency): x is Extract<CompilationDependency, { type: 'concrete' }> {\n return x.type === 'concrete';\n}\n\nfunction setExtend<A>(xs: Set<A>, ys: Set<A>) {\n for (const y of ys) {\n xs.add(y);\n }\n return xs;\n}\n\n/**\n * Necessary for fastGlob\n */\nfunction windowsToUnix(x: string) {\n return x.replace(/\\\\/g, '/');\n}\n"]}
|
package/lib/snippet-selectors.js
CHANGED
@@ -1,6 +1,9 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.
|
3
|
+
exports.longest = longest;
|
4
|
+
exports.shortest = shortest;
|
5
|
+
exports.meanLength = meanLength;
|
6
|
+
exports.mean = mean;
|
4
7
|
class SnippetScore {
|
5
8
|
constructor(snippet, score) {
|
6
9
|
this.snippet = snippet;
|
@@ -20,7 +23,6 @@ function longest(snippets) {
|
|
20
23
|
}
|
21
24
|
return getMaxScore(snippetScores).snippet;
|
22
25
|
}
|
23
|
-
exports.longest = longest;
|
24
26
|
/**
|
25
27
|
* Returns the shortest available snippet.
|
26
28
|
*/
|
@@ -34,7 +36,6 @@ function shortest(snippets) {
|
|
34
36
|
}
|
35
37
|
return getMinScore(snippetScores).snippet;
|
36
38
|
}
|
37
|
-
exports.shortest = shortest;
|
38
39
|
/**
|
39
40
|
* Returns the snippet with the length closest to the mean length of the available snippets.
|
40
41
|
*/
|
@@ -49,7 +50,6 @@ function meanLength(snippets) {
|
|
49
50
|
}
|
50
51
|
return getMinScore(snippetScores).snippet;
|
51
52
|
}
|
52
|
-
exports.meanLength = meanLength;
|
53
53
|
/**
|
54
54
|
* Finds and returns the mean sparse vector of available snippets for each type.
|
55
55
|
*/
|
@@ -70,7 +70,6 @@ function mean(snippets) {
|
|
70
70
|
}
|
71
71
|
return getMinScore(snippetScores).snippet;
|
72
72
|
}
|
73
|
-
exports.mean = mean;
|
74
73
|
/**
|
75
74
|
* Given a list of Records, outputs a Record that averages all the items in each Record.
|
76
75
|
*/
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"snippet-selectors.js","sourceRoot":"","sources":["../src/snippet-selectors.ts"],"names":[],"mappings":"
|
1
|
+
{"version":3,"file":"snippet-selectors.js","sourceRoot":"","sources":["../src/snippet-selectors.ts"],"names":[],"mappings":";;AAWA,0BASC;AAKD,4BASC;AAKD,gCAWC;AAKD,oBAiBC;AApED,MAAM,YAAY;IAChB,YAAmC,OAA0B,EAAkB,KAAa;QAAzD,YAAO,GAAP,OAAO,CAAmB;QAAkB,UAAK,GAAL,KAAK,CAAQ;IAAG,CAAC;CACjG;AAED;;GAEG;AACH,SAAgB,OAAO,CAAC,QAA6B;IACnD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IACpD,CAAC;IACD,MAAM,aAAa,GAAmB,EAAE,CAAC;IACzC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,aAAa,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;IACxF,CAAC;IACD,OAA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,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { TranslatedSnippet } from './tablets/tablets';\n\nexport type SnippetSelector = (snippets: TranslatedSnippet[]) => TranslatedSnippet;\n\nclass SnippetScore {\n public constructor(public readonly snippet: TranslatedSnippet, public readonly score: number) {}\n}\n\n/**\n * Returns the longest available snippet.\n */\nexport function longest(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('longest: array cannot be empty');\n }\n const snippetScores: SnippetScore[] = [];\n for (const snippet of snippets) {\n snippetScores.push({ snippet: snippet, score: snippet.originalSource.source.length });\n }\n return getMaxScore(snippetScores).snippet;\n}\n\n/**\n * Returns the shortest available snippet.\n */\nexport function shortest(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('shortest: array cannot be empty');\n }\n const snippetScores: SnippetScore[] = [];\n for (const snippet of snippets) {\n snippetScores.push({ snippet: snippet, score: snippet.originalSource.source.length });\n }\n return getMinScore(snippetScores).snippet;\n}\n\n/**\n * Returns the snippet with the length closest to the mean length of the available snippets.\n */\nexport function meanLength(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('meanLength: array cannot be empty');\n }\n\n const meanLen = snippets.reduce((x, y) => x + y.originalSource.source.length, 0) / snippets.length;\n const snippetScores: SnippetScore[] = [];\n for (const snippet of snippets) {\n snippetScores.push({ snippet: snippet, score: Math.abs(snippet.originalSource.source.length - meanLen) });\n }\n return getMinScore(snippetScores).snippet;\n}\n\n/**\n * Finds and returns the mean sparse vector of available snippets for each type.\n */\nexport function mean(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('mean: array cannot be empty');\n }\n\n // Find mean counter.\n const counters: Array<Record<string, number>> = [];\n snippets.map((snippet) => {\n counters.push(snippet.snippet.syntaxKindCounter ?? {});\n });\n const meanCounter = findCenter(counters);\n // Find counter with closest euclidian distance.\n const snippetScores: SnippetScore[] = [];\n for (let i = 0; i < snippets.length; i++) {\n snippetScores.push({ snippet: snippets[i], score: euclideanDistance(meanCounter, counters[i]) });\n }\n return getMinScore(snippetScores).snippet;\n}\n\n/**\n * Given a list of Records, outputs a Record that averages all the items in each Record.\n */\nfunction findCenter(counters: Array<Record<string, number>>): Record<string, number> {\n const centerCounter: Record<string, number> = {};\n for (const counter of counters) {\n for (const [key, value] of Object.entries(counter)) {\n centerCounter[key] = value + (centerCounter[key] ?? 0);\n }\n }\n const total = counters.length;\n Object.entries(centerCounter).map(([key, value]) => {\n centerCounter[key] = value / total;\n });\n return centerCounter;\n}\n\n/**\n * Finds the euclidean distance between two sparse vectors.\n * !!! This function assumes that the center parameter is a superset of the counter parameter. !!!\n */\nfunction euclideanDistance(center: Record<string, number>, counter: Record<string, number>): number {\n const individualDistances: number[] = [];\n Object.entries(center).map(([key, value]) => {\n individualDistances.push(value - (counter[key] ?? 0));\n });\n return individualDistances.reduce((acc, curr) => acc + Math.sqrt(Math.pow(curr, 2)), 0);\n}\n\nfunction getMaxScore(snippetScores: SnippetScore[]): SnippetScore {\n return snippetScores.reduce((x, y) => {\n return x.score >= y.score ? x : y;\n });\n}\n\nfunction getMinScore(snippetScores: SnippetScore[]): SnippetScore {\n return snippetScores.reduce((x, y) => {\n return x.score <= y.score ? x : y;\n });\n}\n"]}
|
package/lib/snippet.js
CHANGED
@@ -1,6 +1,16 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.SnippetParameters = exports.
|
3
|
+
exports.SnippetParameters = exports.INITIALIZER_METHOD_NAME = void 0;
|
4
|
+
exports.formatLocation = formatLocation;
|
5
|
+
exports.renderApiLocation = renderApiLocation;
|
6
|
+
exports.typeScriptSnippetFromVisibleSource = typeScriptSnippetFromVisibleSource;
|
7
|
+
exports.typeScriptSnippetFromSource = typeScriptSnippetFromSource;
|
8
|
+
exports.typeScriptSnippetFromCompleteSource = typeScriptSnippetFromCompleteSource;
|
9
|
+
exports.updateParameters = updateParameters;
|
10
|
+
exports.completeSource = completeSource;
|
11
|
+
exports.parseKeyValueList = parseKeyValueList;
|
12
|
+
exports.parseMetadataLine = parseMetadataLine;
|
13
|
+
exports.renderMetadataline = renderMetadataline;
|
4
14
|
const visible_spans_1 = require("./typescript/visible-spans");
|
5
15
|
/**
|
6
16
|
* How to represent the initializer in a 'parameter' type.
|
@@ -22,7 +32,6 @@ function formatLocation(location) {
|
|
22
32
|
return renderApiLocation(location.api);
|
23
33
|
}
|
24
34
|
}
|
25
|
-
exports.formatLocation = formatLocation;
|
26
35
|
/**
|
27
36
|
* Render an API location to an unique string
|
28
37
|
*
|
@@ -45,7 +54,6 @@ function renderApiLocation(apiLoc) {
|
|
45
54
|
return `${apiLoc.fqn}#${apiLoc.methodName}!#${apiLoc.parameterName}`;
|
46
55
|
}
|
47
56
|
}
|
48
|
-
exports.renderApiLocation = renderApiLocation;
|
49
57
|
/**
|
50
58
|
* Construct a TypeScript snippet from visible source
|
51
59
|
*
|
@@ -69,7 +77,6 @@ function typeScriptSnippetFromVisibleSource(typeScriptSource, location, strict,
|
|
69
77
|
strict,
|
70
78
|
};
|
71
79
|
}
|
72
|
-
exports.typeScriptSnippetFromVisibleSource = typeScriptSnippetFromVisibleSource;
|
73
80
|
/**
|
74
81
|
* Construct a TypeScript snippet from literal source
|
75
82
|
*
|
@@ -78,7 +85,6 @@ exports.typeScriptSnippetFromVisibleSource = typeScriptSnippetFromVisibleSource;
|
|
78
85
|
function typeScriptSnippetFromSource(typeScriptSource, location, strict, parameters = {}) {
|
79
86
|
return typeScriptSnippetFromVisibleSource(typeScriptSource, location, strict, parameters);
|
80
87
|
}
|
81
|
-
exports.typeScriptSnippetFromSource = typeScriptSnippetFromSource;
|
82
88
|
/**
|
83
89
|
* Construct a TypeScript snippet from complete source
|
84
90
|
*
|
@@ -104,21 +110,18 @@ function typeScriptSnippetFromCompleteSource(typeScriptSource, location, strict,
|
|
104
110
|
strict,
|
105
111
|
};
|
106
112
|
}
|
107
|
-
exports.typeScriptSnippetFromCompleteSource = typeScriptSnippetFromCompleteSource;
|
108
113
|
function updateParameters(snippet, params) {
|
109
114
|
return {
|
110
115
|
...snippet,
|
111
116
|
parameters: Object.assign(Object.create(null), snippet.parameters ?? {}, params),
|
112
117
|
};
|
113
118
|
}
|
114
|
-
exports.updateParameters = updateParameters;
|
115
119
|
/**
|
116
120
|
* Get the complete (compilable) source of a snippet
|
117
121
|
*/
|
118
122
|
function completeSource(snippet) {
|
119
123
|
return snippet.completeSource ?? snippet.visibleSource;
|
120
124
|
}
|
121
|
-
exports.completeSource = completeSource;
|
122
125
|
/**
|
123
126
|
* Extract snippet parameters from the first line of the source if it's a compiler directive
|
124
127
|
*/
|
@@ -147,7 +150,6 @@ function parseKeyValueList(parameters) {
|
|
147
150
|
}
|
148
151
|
return ret;
|
149
152
|
}
|
150
|
-
exports.parseKeyValueList = parseKeyValueList;
|
151
153
|
function parseMetadataLine(metadata) {
|
152
154
|
return parseKeyValueList(parseMetadata(metadata));
|
153
155
|
function parseMetadata(md) {
|
@@ -158,7 +160,6 @@ function parseMetadataLine(metadata) {
|
|
158
160
|
.filter((s) => s !== '');
|
159
161
|
}
|
160
162
|
}
|
161
|
-
exports.parseMetadataLine = parseMetadataLine;
|
162
163
|
function renderMetadataline(metadata = {}) {
|
163
164
|
const line = Object.entries(metadata)
|
164
165
|
.filter(([key, _]) => !key.startsWith('$'))
|
@@ -166,7 +167,6 @@ function renderMetadataline(metadata = {}) {
|
|
166
167
|
.join(' ');
|
167
168
|
return line ? line : undefined;
|
168
169
|
}
|
169
|
-
exports.renderMetadataline = renderMetadataline;
|
170
170
|
/**
|
171
171
|
* Recognized snippet parameters
|
172
172
|
*/
|
package/lib/snippet.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"snippet.js","sourceRoot":"","sources":["../src/snippet.ts"],"names":[],"mappings":";;;AAAA,8DAAyE;AAuEzE;;;;;GAKG;AACU,QAAA,uBAAuB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AC;aACV,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;aACpB,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC;AAVD,8CAUC;AAED,SAAgB,kBAAkB,CAAC,WAAmC,EAAE;IACtE,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC;SAClC,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;SAC1C,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IAEb,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AACjC,CAAC;AAPD,gDAOC;AAED;;GAEG;AACH,IAAY,iBAgDX;AAhDD,WAAY,iBAAiB;IAC3B;;OAEG;IACH,wCAAmB,CAAA;IAEnB;;OAEG;IACH,6CAAwB,CAAA;IAExB;;;;;OAKG;IACH,4CAAuB,CAAA;IAEvB;;;;;;;;;;;OAWG;IACH,wCAAmB,CAAA;IAEnB;;;;;OAKG;IACH,sDAAiC,CAAA;IAEjC;;;;;OAKG;IACH,4DAAuC,CAAA;AACzC,CAAC,EAhDW,iBAAiB,iCAAjB,iBAAiB,QAgD5B","sourcesContent":["import { trimCompleteSourceToVisible } from './typescript/visible-spans';\n\n/**\n * A piece of TypeScript code found in an assembly, ready to be translated\n */\nexport interface TypeScriptSnippet {\n /**\n * The snippet code that ends up in the JSII assembly\n */\n readonly visibleSource: string;\n\n /**\n * Description of where the snippet was found\n */\n readonly location: SnippetLocation;\n\n /**\n * When enhanced with a fixture, the snippet's complete source code\n */\n readonly completeSource?: string;\n\n /**\n * Parameters for the conversion\n */\n readonly parameters?: Record<string, string>;\n\n /**\n * Whether this snippet must be processed as if `--strict` was always supplied.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * Dependencies necessary to compile this snippet\n *\n * Value is a regular { name -> semver } map like NPM's `dependencies`,\n * `devDependencies` etc.\n *\n * @default none\n */\n readonly compilationDependencies?: Record<string, CompilationDependency>;\n}\n\nexport type CompilationDependency =\n | { readonly type: 'concrete'; readonly resolvedDirectory: string }\n | { readonly type: 'symbolic'; readonly versionRange: string };\n\n/**\n * Description of a location where the snippet is found\n *\n * The location does not necessarily indicate an exact source file,\n * but it will generally refer to a location that can contain one or more\n * snippets.\n */\nexport interface SnippetLocation {\n /**\n * The jsii API with which this snippet is associated\n */\n readonly api: ApiLocation;\n\n /**\n * The API field in which the snippet is found, if any\n *\n * Absence of this field is appropriate for source files (or tests),\n * but for Markdown files 'field' should really be set to a Markdown\n * location.\n */\n readonly field?: FieldLocation;\n}\n\n/**\n * How to represent the initializer in a 'parameter' type.\n *\n * (Don't feel like making everyone's `case` statement worse by adding an\n * 'initializer-parameter' variant).\n */\nexport const INITIALIZER_METHOD_NAME = '<initializer>';\n\nexport type ApiLocation =\n | { readonly api: 'file'; readonly fileName: string }\n | { readonly api: 'moduleReadme'; readonly moduleFqn: string }\n | { readonly api: 'type'; readonly fqn: string }\n | { readonly api: 'initializer'; readonly fqn: string }\n | { readonly api: 'member'; readonly fqn: string; readonly memberName: string }\n | {\n readonly api: 'parameter';\n readonly fqn: string;\n readonly methodName: string | typeof INITIALIZER_METHOD_NAME;\n readonly parameterName: string;\n };\n\nexport type FieldLocation = { readonly field: 'markdown'; readonly line: number } | { readonly field: 'example' };\n\n/**\n * Render an API location to a human readable representation\n */\nexport function formatLocation(location: SnippetLocation): string {\n switch (location.field?.field) {\n case 'example':\n return `${renderApiLocation(location.api)}-example`;\n case 'markdown':\n return `${renderApiLocation(location.api)}-L${location.field.line}`;\n case undefined:\n return renderApiLocation(location.api);\n }\n}\n\n/**\n * Render an API location to an unique string\n *\n * This function is used in hashing examples for reuse, and so the formatting\n * here should not be changed lightly.\n */\nexport function renderApiLocation(apiLoc: ApiLocation): string {\n switch (apiLoc.api) {\n case 'file':\n return apiLoc.fileName;\n case 'moduleReadme':\n return `${apiLoc.moduleFqn}-README`;\n case 'type':\n return apiLoc.fqn;\n case 'initializer':\n return `${apiLoc.fqn}#initializer`;\n case 'member':\n return `${apiLoc.fqn}#${apiLoc.memberName}`;\n case 'parameter':\n return `${apiLoc.fqn}#${apiLoc.methodName}!#${apiLoc.parameterName}`;\n }\n}\n\n/**\n * Construct a TypeScript snippet from visible source\n *\n * Will parse parameters from a directive in the given source, but will not\n * interpret `/// !show` and `/// !hide` directives.\n *\n * `/// !show` and `/// !hide` directives WILL affect what gets displayed by\n * the translator, but they will NOT affect the snippet's cache key (i.e. the\n * cache key will be based on the full source given here).\n *\n * Use this if you are looking up a snippet in a tablet, which has been translated\n * previously using a fixture.\n */\nexport function typeScriptSnippetFromVisibleSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const visibleSource = source.trimRight();\n\n return {\n visibleSource,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\n/**\n * Construct a TypeScript snippet from literal source\n *\n * @deprecated Use `typeScriptSnippetFromVisibleSource`\n */\nexport function typeScriptSnippetFromSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n return typeScriptSnippetFromVisibleSource(typeScriptSource, location, strict, parameters);\n}\n\n/**\n * Construct a TypeScript snippet from complete source\n *\n * Will parse parameters from a directive in the given source, and will\n * interpret `/// !show` and `/// !hide` directives.\n *\n * The snippet's cache key will be based on the source that remains after\n * these directives are processed.\n *\n * Use this if you are building a snippet to be translated, and take care\n * to store the return object's `visibleSource` in the assembly (not the original\n * source you passed in).\n */\nexport function typeScriptSnippetFromCompleteSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const completeSrc = source.trimRight();\n\n const visibleSource = trimCompleteSourceToVisible(completeSrc);\n\n return {\n visibleSource,\n completeSource: visibleSource !== completeSrc ? completeSrc : undefined,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\nexport function updateParameters(snippet: TypeScriptSnippet, params: Record<string, string>): TypeScriptSnippet {\n return {\n ...snippet,\n parameters: Object.assign(Object.create(null), snippet.parameters ?? {}, params),\n };\n}\n\n/**\n * Get the complete (compilable) source of a snippet\n */\nexport function completeSource(snippet: TypeScriptSnippet) {\n return snippet.completeSource ?? snippet.visibleSource;\n}\n\n/**\n * Extract snippet parameters from the first line of the source if it's a compiler directive\n */\nfunction parametersFromSourceDirectives(source: string): [string, Record<string, string>] {\n const [firstLine, ...rest] = source.split('\\n');\n // Also extract parameters from an initial line starting with '/// ' (getting rid of that line).\n const m = /[/]{3}(.*)$/.exec(firstLine);\n if (m) {\n return [rest.join('\\n'), parseMetadataLine(m[1])];\n }\n\n return [source, {}];\n}\n\n/**\n * Parse a set of 'param param=value' directives into an object\n */\nexport function parseKeyValueList(parameters: string[]): Record<string, string> {\n const ret: Record<string, string> = {};\n for (const param of parameters) {\n const parts = param.split('=', 2);\n if (parts.length === 2) {\n ret[parts[0]] = parts[1];\n } else {\n ret[parts[0]] = '';\n }\n }\n return ret;\n}\n\nexport function parseMetadataLine(metadata: string): Record<string, string> {\n return parseKeyValueList(parseMetadata(metadata));\n\n function parseMetadata(md: string): string[] {\n return md\n .trim()\n .split(' ')\n .map((s) => s.trim())\n .filter((s) => s !== '');\n }\n}\n\nexport function renderMetadataline(metadata: Record<string, string> = {}): string | undefined {\n const line = Object.entries(metadata)\n .filter(([key, _]) => !key.startsWith('$'))\n .map(([key, value]) => (value !== '' ? `${key}=${value}` : key))\n .join(' ');\n\n return line ? line : undefined;\n}\n\n/**\n * Recognized snippet parameters\n */\nexport enum SnippetParameters {\n /**\n * Use fixture with the given name (author parameter)\n */\n FIXTURE = 'fixture',\n\n /**\n * Don't use a fixture (author parameter)\n */\n NO_FIXTURE = 'nofixture',\n\n /**\n * Snippet was extracted from this literate file (backwards compatibility)\n *\n * Parameter attached by 'jsii'; load the given file instead of any fixture,\n * process as usual.\n */\n LITERATE_SOURCE = 'lit',\n\n /**\n * This snippet has been infused\n *\n * This means it has been copied from a different location, and potentially\n * even from a different assembly. If so, we can't expect it to compile in\n * the future, and if doesn't, we ignore the errors.\n *\n * N.B: this shouldn't make a difference in normal operation, as the `infuse`\n * command will duplicate the translation to the target tablet. This only\n * matters if we remove the tablet and try to re-extract an assembly with\n * infused examples from somewher else.\n */\n INFUSED = 'infused',\n\n /**\n * What directory to resolve fixtures in for this snippet (system parameter)\n *\n * Attached during processing, should not be used by authors. Does NOT imply\n * anything about the directory where we pretend to compile this file.\n */\n $PROJECT_DIRECTORY = '$directory',\n\n /**\n * What directory to pretend the file is in (system parameter)\n *\n * Attached when compiling a literate file, as they compile in\n * the location where they are stored.\n */\n $COMPILATION_DIRECTORY = '$compilation',\n}\n"]}
|
1
|
+
{"version":3,"file":"snippet.js","sourceRoot":"","sources":["../src/snippet.ts"],"names":[],"mappings":";;;AAiGA,wCASC;AAQD,8CAeC;AAeD,gFAeC;AAOD,kEAOC;AAeD,kFAkBC;AAED,4CAKC;AAKD,wCAEC;AAmBD,8CAWC;AAED,8CAUC;AAED,gDAOC;AA/QD,8DAAyE;AAuEzE;;;;;GAKG;AACU,QAAA,uBAAuB,GAAG,eAAe,CAAC;AAiBvD;;GAEG;AACH,SAAgB,cAAc,CAAC,QAAyB;IACtD,QAAQ,QAAQ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AgB,kBAAkB,CAAC,WAAmC,EAAE;IACtE,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC;SAClC,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;SAC1C,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IAEb,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AACjC,CAAC;AAED;;GAEG;AACH,IAAY,iBAgDX;AAhDD,WAAY,iBAAiB;IAC3B;;OAEG;IACH,wCAAmB,CAAA;IAEnB;;OAEG;IACH,6CAAwB,CAAA;IAExB;;;;;OAKG;IACH,4CAAuB,CAAA;IAEvB;;;;;;;;;;;OAWG;IACH,wCAAmB,CAAA;IAEnB;;;;;OAKG;IACH,sDAAiC,CAAA;IAEjC;;;;;OAKG;IACH,4DAAuC,CAAA;AACzC,CAAC,EAhDW,iBAAiB,iCAAjB,iBAAiB,QAgD5B","sourcesContent":["import { trimCompleteSourceToVisible } from './typescript/visible-spans';\n\n/**\n * A piece of TypeScript code found in an assembly, ready to be translated\n */\nexport interface TypeScriptSnippet {\n /**\n * The snippet code that ends up in the JSII assembly\n */\n readonly visibleSource: string;\n\n /**\n * Description of where the snippet was found\n */\n readonly location: SnippetLocation;\n\n /**\n * When enhanced with a fixture, the snippet's complete source code\n */\n readonly completeSource?: string;\n\n /**\n * Parameters for the conversion\n */\n readonly parameters?: Record<string, string>;\n\n /**\n * Whether this snippet must be processed as if `--strict` was always supplied.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * Dependencies necessary to compile this snippet\n *\n * Value is a regular { name -> semver } map like NPM's `dependencies`,\n * `devDependencies` etc.\n *\n * @default none\n */\n readonly compilationDependencies?: Record<string, CompilationDependency>;\n}\n\nexport type CompilationDependency =\n | { readonly type: 'concrete'; readonly resolvedDirectory: string }\n | { readonly type: 'symbolic'; readonly versionRange: string };\n\n/**\n * Description of a location where the snippet is found\n *\n * The location does not necessarily indicate an exact source file,\n * but it will generally refer to a location that can contain one or more\n * snippets.\n */\nexport interface SnippetLocation {\n /**\n * The jsii API with which this snippet is associated\n */\n readonly api: ApiLocation;\n\n /**\n * The API field in which the snippet is found, if any\n *\n * Absence of this field is appropriate for source files (or tests),\n * but for Markdown files 'field' should really be set to a Markdown\n * location.\n */\n readonly field?: FieldLocation;\n}\n\n/**\n * How to represent the initializer in a 'parameter' type.\n *\n * (Don't feel like making everyone's `case` statement worse by adding an\n * 'initializer-parameter' variant).\n */\nexport const INITIALIZER_METHOD_NAME = '<initializer>';\n\nexport type ApiLocation =\n | { readonly api: 'file'; readonly fileName: string }\n | { readonly api: 'moduleReadme'; readonly moduleFqn: string }\n | { readonly api: 'type'; readonly fqn: string }\n | { readonly api: 'initializer'; readonly fqn: string }\n | { readonly api: 'member'; readonly fqn: string; readonly memberName: string }\n | {\n readonly api: 'parameter';\n readonly fqn: string;\n readonly methodName: string | typeof INITIALIZER_METHOD_NAME;\n readonly parameterName: string;\n };\n\nexport type FieldLocation = { readonly field: 'markdown'; readonly line: number } | { readonly field: 'example' };\n\n/**\n * Render an API location to a human readable representation\n */\nexport function formatLocation(location: SnippetLocation): string {\n switch (location.field?.field) {\n case 'example':\n return `${renderApiLocation(location.api)}-example`;\n case 'markdown':\n return `${renderApiLocation(location.api)}-L${location.field.line}`;\n case undefined:\n return renderApiLocation(location.api);\n }\n}\n\n/**\n * Render an API location to an unique string\n *\n * This function is used in hashing examples for reuse, and so the formatting\n * here should not be changed lightly.\n */\nexport function renderApiLocation(apiLoc: ApiLocation): string {\n switch (apiLoc.api) {\n case 'file':\n return apiLoc.fileName;\n case 'moduleReadme':\n return `${apiLoc.moduleFqn}-README`;\n case 'type':\n return apiLoc.fqn;\n case 'initializer':\n return `${apiLoc.fqn}#initializer`;\n case 'member':\n return `${apiLoc.fqn}#${apiLoc.memberName}`;\n case 'parameter':\n return `${apiLoc.fqn}#${apiLoc.methodName}!#${apiLoc.parameterName}`;\n }\n}\n\n/**\n * Construct a TypeScript snippet from visible source\n *\n * Will parse parameters from a directive in the given source, but will not\n * interpret `/// !show` and `/// !hide` directives.\n *\n * `/// !show` and `/// !hide` directives WILL affect what gets displayed by\n * the translator, but they will NOT affect the snippet's cache key (i.e. the\n * cache key will be based on the full source given here).\n *\n * Use this if you are looking up a snippet in a tablet, which has been translated\n * previously using a fixture.\n */\nexport function typeScriptSnippetFromVisibleSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const visibleSource = source.trimRight();\n\n return {\n visibleSource,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\n/**\n * Construct a TypeScript snippet from literal source\n *\n * @deprecated Use `typeScriptSnippetFromVisibleSource`\n */\nexport function typeScriptSnippetFromSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n return typeScriptSnippetFromVisibleSource(typeScriptSource, location, strict, parameters);\n}\n\n/**\n * Construct a TypeScript snippet from complete source\n *\n * Will parse parameters from a directive in the given source, and will\n * interpret `/// !show` and `/// !hide` directives.\n *\n * The snippet's cache key will be based on the source that remains after\n * these directives are processed.\n *\n * Use this if you are building a snippet to be translated, and take care\n * to store the return object's `visibleSource` in the assembly (not the original\n * source you passed in).\n */\nexport function typeScriptSnippetFromCompleteSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const completeSrc = source.trimRight();\n\n const visibleSource = trimCompleteSourceToVisible(completeSrc);\n\n return {\n visibleSource,\n completeSource: visibleSource !== completeSrc ? completeSrc : undefined,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\nexport function updateParameters(snippet: TypeScriptSnippet, params: Record<string, string>): TypeScriptSnippet {\n return {\n ...snippet,\n parameters: Object.assign(Object.create(null), snippet.parameters ?? {}, params),\n };\n}\n\n/**\n * Get the complete (compilable) source of a snippet\n */\nexport function completeSource(snippet: TypeScriptSnippet) {\n return snippet.completeSource ?? snippet.visibleSource;\n}\n\n/**\n * Extract snippet parameters from the first line of the source if it's a compiler directive\n */\nfunction parametersFromSourceDirectives(source: string): [string, Record<string, string>] {\n const [firstLine, ...rest] = source.split('\\n');\n // Also extract parameters from an initial line starting with '/// ' (getting rid of that line).\n const m = /[/]{3}(.*)$/.exec(firstLine);\n if (m) {\n return [rest.join('\\n'), parseMetadataLine(m[1])];\n }\n\n return [source, {}];\n}\n\n/**\n * Parse a set of 'param param=value' directives into an object\n */\nexport function parseKeyValueList(parameters: string[]): Record<string, string> {\n const ret: Record<string, string> = {};\n for (const param of parameters) {\n const parts = param.split('=', 2);\n if (parts.length === 2) {\n ret[parts[0]] = parts[1];\n } else {\n ret[parts[0]] = '';\n }\n }\n return ret;\n}\n\nexport function parseMetadataLine(metadata: string): Record<string, string> {\n return parseKeyValueList(parseMetadata(metadata));\n\n function parseMetadata(md: string): string[] {\n return md\n .trim()\n .split(' ')\n .map((s) => s.trim())\n .filter((s) => s !== '');\n }\n}\n\nexport function renderMetadataline(metadata: Record<string, string> = {}): string | undefined {\n const line = Object.entries(metadata)\n .filter(([key, _]) => !key.startsWith('$'))\n .map(([key, value]) => (value !== '' ? `${key}=${value}` : key))\n .join(' ');\n\n return line ? line : undefined;\n}\n\n/**\n * Recognized snippet parameters\n */\nexport enum SnippetParameters {\n /**\n * Use fixture with the given name (author parameter)\n */\n FIXTURE = 'fixture',\n\n /**\n * Don't use a fixture (author parameter)\n */\n NO_FIXTURE = 'nofixture',\n\n /**\n * Snippet was extracted from this literate file (backwards compatibility)\n *\n * Parameter attached by 'jsii'; load the given file instead of any fixture,\n * process as usual.\n */\n LITERATE_SOURCE = 'lit',\n\n /**\n * This snippet has been infused\n *\n * This means it has been copied from a different location, and potentially\n * even from a different assembly. If so, we can't expect it to compile in\n * the future, and if doesn't, we ignore the errors.\n *\n * N.B: this shouldn't make a difference in normal operation, as the `infuse`\n * command will duplicate the translation to the target tablet. This only\n * matters if we remove the tablet and try to re-extract an assembly with\n * infused examples from somewher else.\n */\n INFUSED = 'infused',\n\n /**\n * What directory to resolve fixtures in for this snippet (system parameter)\n *\n * Attached during processing, should not be used by authors. Does NOT imply\n * anything about the directory where we pretend to compile this file.\n */\n $PROJECT_DIRECTORY = '$directory',\n\n /**\n * What directory to pretend the file is in (system parameter)\n *\n * Attached when compiling a literate file, as they compile in\n * the location where they are stored.\n */\n $COMPILATION_DIRECTORY = '$compilation',\n}\n"]}
|
package/lib/strict.js
CHANGED
@@ -1,8 +1,7 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.enforcesStrictMode =
|
3
|
+
exports.enforcesStrictMode = enforcesStrictMode;
|
4
4
|
function enforcesStrictMode(assembly) {
|
5
5
|
return !!assembly.metadata?.jsii?.rosetta?.strict;
|
6
6
|
}
|
7
|
-
exports.enforcesStrictMode = enforcesStrictMode;
|
8
7
|
//# sourceMappingURL=strict.js.map
|
package/lib/strict.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"strict.js","sourceRoot":"","sources":["../src/strict.ts"],"names":[],"mappings":"
|
1
|
+
{"version":3,"file":"strict.js","sourceRoot":"","sources":["../src/strict.ts"],"names":[],"mappings":";;AAEA,gDAEC;AAFD,SAAgB,kBAAkB,CAAC,QAAkB;IACnD,OAAO,CAAC,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC;AACpD,CAAC","sourcesContent":["import { Assembly } from '@jsii/spec';\n\nexport function enforcesStrictMode(assembly: Assembly): boolean {\n return !!assembly.metadata?.jsii?.rosetta?.strict;\n}\n"]}
|
package/lib/support.js
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.emitSupportPolicyInformation =
|
3
|
+
exports.emitSupportPolicyInformation = emitSupportPolicyInformation;
|
4
4
|
const node_fs_1 = require("node:fs");
|
5
5
|
const node_https_1 = require("node:https");
|
6
6
|
const node_path_1 = require("node:path");
|
@@ -59,7 +59,6 @@ async function emitSupportPolicyInformation() {
|
|
59
59
|
veryVisibleMessage(chalk.bgYellow.black, `The ${typescript_1.versionMajorMinor} release line of jsii will reach End-of-Support soon, on ${endOfSupportDate.toISOString()}.`, `We strongly recommend you upgrade to the current release line (${data.current}) at your earliest convenience.`, ...alternatives);
|
60
60
|
}
|
61
61
|
}
|
62
|
-
exports.emitSupportPolicyInformation = emitSupportPolicyInformation;
|
63
62
|
/**
|
64
63
|
* Downloads the latest `releases.json` document from 'https://raw.githubusercontent.com/aws/jsii-rosetta/main/releases.json'
|
65
64
|
* if possible, or falls back to the built-in version of that file if that fails in any way.
|
package/lib/support.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"support.js","sourceRoot":"","sources":["../src/support.ts"],"names":[],"mappings":";;;AAAA,qCAAuC;AACvC,2CAAiC;AACjC,yCAAiC;AACjC,+BAA+B;AAC/B,2CAA+C;AAE/C,MAAM,eAAe,GAAG,8BAA8B,CAAC;AACvD,MAAM,qBAAqB,GAAG,UAAa,CAAC;AAuB5C;;;;;;;;GAQG;AACI,KAAK,UAAU,4BAA4B;IAChD,IAAI,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,CAAC;QACjC,OA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,CAAC,OAAO,EAAE,IAAI,IAAI,CAAC,IAAc,CAAC,CAAC,CAAC,CAAC,CAAC;IACjH,CAAC,CAAqB,CAAC;AACzB,CAAC;AAED,SAAS,kBAAkB,CAAC,SAAsB,EAAE,GAAG,KAAwB;IAC7E,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACpE,CAAC;IAED,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;IAC9C,MAAM,MAAM,GAAG,SAAS,CAAC,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAEvD,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACtB,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACtB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACtB,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AACxB,CAAC","sourcesContent":["import { readFileSync } from 'node:fs';\nimport { get } from 'node:https';\nimport { join } from 'node:path';\nimport * as chalk from 'chalk';\nimport { versionMajorMinor } from 'typescript';\n\nconst SILENCE_ENV_VAR = 'JSII_SILENCE_SUPPORT_WARNING';\nconst THIRTY_DAYS_IN_MILLIS = 2_592_000_000;\n\n/** @internal */\nexport interface ReleasesDocument {\n /**\n * The release line that occupies the 'Current' stage.\n */\n readonly current: ReleaseLine;\n /**\n * Release lines currently in 'Maintenance' with the date at which they are\n * planned to go into the 'End-of-Support' stage. This date should always be\n * set a minimum of 6 months in the future when a release line is added to the\n * list.\n */\n readonly maintenance: { readonly [release: ReleaseLine]: Date };\n /**\n * Release lines that are currently out-of-support. This is semantically\n * equivalent to being in the `maintenance` list with a past date, but offers\n * slightly faster look-up.\n */\n readonly endOfSupport?: readonly ReleaseLine[];\n}\n\n/**\n * Checks whether the current release line is close to End-of-Support (within\n * 30 days), or already in End-of-Support, and if that is the case, emits a\n * warning to call the user to action.\n *\n * It is possible for users to opt out of these notifications by setting the\n * `JSII_SILENCE_SUPPORT_WARNING` environment variable to any truthy value (that\n * is, any non-empty value).\n */\nexport async function emitSupportPolicyInformation() {\n if (process.env[SILENCE_ENV_VAR]) {\n return;\n }\n\n const data = await getReleasesDocument();\n\n if (data.current == versionMajorMinor) {\n // Current release is not close to deprecation\n return;\n }\n\n const endOfSupportDate = data.endOfSupport?.includes(versionMajorMinor)\n ? new Date(0)\n : data.maintenance[versionMajorMinor];\n if (endOfSupportDate == null) {\n // Don't know the status, so don't say anything...\n return;\n }\n\n const now = new Date();\n const inThirtyDays = new Date(now.getTime() + THIRTY_DAYS_IN_MILLIS);\n const alternatives = Object.entries(data.maintenance)\n .flatMap(([release, dateStr]) => {\n const date = new Date(dateStr);\n if (date <= inThirtyDays) {\n return [];\n }\n return [{ release, date }];\n })\n .reduce((acc, { release, date }) => {\n if (acc.length === 0) {\n acc.push('', 'Other actively supported release lines include:');\n }\n acc.push(`- ${release} (planned End-of-Support date: ${date.toISOString()})`);\n return acc;\n }, new Array<string>());\n if (endOfSupportDate <= now) {\n // End-of-Support already!\n veryVisibleMessage(\n chalk.bgRed.white.bold,\n `The ${versionMajorMinor} release line of jsii has reached End-of-Support.`,\n `We strongly recommend you upgrade to the current release line (${data.current}) at your earliest convenience.`,\n ...alternatives,\n );\n } else if (endOfSupportDate <= inThirtyDays) {\n // End-of-Support within 30 days!\n veryVisibleMessage(\n chalk.bgYellow.black,\n `The ${versionMajorMinor} release line of jsii will reach End-of-Support soon, on ${endOfSupportDate.toISOString()}.`,\n `We strongly recommend you upgrade to the current release line (${data.current}) at your earliest convenience.`,\n ...alternatives,\n );\n }\n}\n\n/**\n * Downloads the latest `releases.json` document from 'https://raw.githubusercontent.com/aws/jsii-rosetta/main/releases.json'\n * if possible, or falls back to the built-in version of that file if that fails in any way.\n */\nasync function getReleasesDocument(): Promise<ReleasesDocument> {\n const downloaded = await new Promise<string | undefined>((ok, ko) => {\n const request = get(\n new URL('https://raw.githubusercontent.com/aws/jsii-rosetta/main/releases.json'),\n (response) => {\n if (response.statusCode === 404) {\n return ok(undefined);\n }\n if (response.statusCode !== 200) {\n return ko(`received error response: HTTP ${response.statusCode} - ${response.statusMessage}`);\n }\n response.once('error', ko);\n const chunks = new Array<Buffer>();\n response.on('data', (chunk) => chunks.push(Buffer.from(chunk)));\n response.once('end', () => ok(Buffer.concat(chunks).toString('utf-8')));\n },\n );\n request.once('abort', () => ko('request aborted'));\n request.once('timeout', () => ko('request timed out'));\n request.once('error', ko);\n request.end();\n }).catch((cause) => {\n if (process.env.JSII_DEBUG) {\n console.error(`Could not download releases.json from GitHub: ${cause}`);\n }\n undefined;\n });\n\n return JSON.parse(downloaded ?? readFileSync(join(__dirname, '..', 'releases.json'), 'utf-8'), (key, value) => {\n if (key !== 'maintenance') {\n return value;\n }\n return Object.fromEntries(Object.entries(value).map(([release, date]) => [release, new Date(date as string)]));\n }) as ReleasesDocument;\n}\n\nfunction veryVisibleMessage(formatter: chalk.Chalk, ...lines: readonly string[]): void {\n if (lines.length === 0) {\n throw new Error(`At least one line of message must be provided!`);\n }\n\n const len = Math.max(...lines.map((line) => line.length));\n const border = formatter('!'.repeat(len + 8));\n const spacer = formatter(`!! ${' '.repeat(len)} !!`);\n\n console.error(border);\n console.error(spacer);\n for (const line of lines) {\n console.error(formatter(`!! ${line.padEnd(len, ' ')} !!`));\n }\n console.error(spacer);\n console.error(border);\n}\n\ntype ReleaseLine = `${number}.${number}`;\n"]}
|
1
|
+
{"version":3,"file":"support.js","sourceRoot":"","sources":["../src/support.ts"],"names":[],"mappings":";;AAuCA,oEAsDC;AA7FD,qCAAuC;AACvC,2CAAiC;AACjC,yCAAiC;AACjC,+BAA+B;AAC/B,2CAA+C;AAE/C,MAAM,eAAe,GAAG,8BAA8B,CAAC;AACvD,MAAM,qBAAqB,GAAG,UAAa,CAAC;AAuB5C;;;;;;;;GAQG;AACI,KAAK,UAAU,4BAA4B;IAChD,IAAI,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,CAAC;QACjC,OAAO;IACT,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,mBAAmB,EAAE,CAAC;IAEzC,IAAI,IAAI,CAAC,OAAO,IAAI,8BAAiB,EAAE,CAAC;QACtC,8CAA8C;QAC9C,OAAO;IACT,CAAC;IAED,MAAM,gBAAgB,GAAG,IAAI,CAAC,YAAY,EAAE,QAAQ,CAAC,8BAAiB,CAAC;QACrE,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC;QACb,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,8BAAiB,CAAC,CAAC;IACxC,IAAI,gBAAgB,IAAI,IAAI,EAAE,CAAC;QAC7B,kDAAkD;QAClD,OAAO;IACT,CAAC;IAED,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;IACvB,MAAM,YAAY,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,qBAAqB,CAAC,CAAC;IACrE,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC;SAClD,OAAO,CAAC,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,EAAE;QAC9B,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC;QAC/B,IAAI,IAAI,IAAI,YAAY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AI,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACtB,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AACxB,CAAC","sourcesContent":["import { readFileSync } from 'node:fs';\nimport { get } from 'node:https';\nimport { join } from 'node:path';\nimport * as chalk from 'chalk';\nimport { versionMajorMinor } from 'typescript';\n\nconst SILENCE_ENV_VAR = 'JSII_SILENCE_SUPPORT_WARNING';\nconst THIRTY_DAYS_IN_MILLIS = 2_592_000_000;\n\n/** @internal */\nexport interface ReleasesDocument {\n /**\n * The release line that occupies the 'Current' stage.\n */\n readonly current: ReleaseLine;\n /**\n * Release lines currently in 'Maintenance' with the date at which they are\n * planned to go into the 'End-of-Support' stage. This date should always be\n * set a minimum of 6 months in the future when a release line is added to the\n * list.\n */\n readonly maintenance: { readonly [release: ReleaseLine]: Date };\n /**\n * Release lines that are currently out-of-support. This is semantically\n * equivalent to being in the `maintenance` list with a past date, but offers\n * slightly faster look-up.\n */\n readonly endOfSupport?: readonly ReleaseLine[];\n}\n\n/**\n * Checks whether the current release line is close to End-of-Support (within\n * 30 days), or already in End-of-Support, and if that is the case, emits a\n * warning to call the user to action.\n *\n * It is possible for users to opt out of these notifications by setting the\n * `JSII_SILENCE_SUPPORT_WARNING` environment variable to any truthy value (that\n * is, any non-empty value).\n */\nexport async function emitSupportPolicyInformation() {\n if (process.env[SILENCE_ENV_VAR]) {\n return;\n }\n\n const data = await getReleasesDocument();\n\n if (data.current == versionMajorMinor) {\n // Current release is not close to deprecation\n return;\n }\n\n const endOfSupportDate = data.endOfSupport?.includes(versionMajorMinor)\n ? new Date(0)\n : data.maintenance[versionMajorMinor];\n if (endOfSupportDate == null) {\n // Don't know the status, so don't say anything...\n return;\n }\n\n const now = new Date();\n const inThirtyDays = new Date(now.getTime() + THIRTY_DAYS_IN_MILLIS);\n const alternatives = Object.entries(data.maintenance)\n .flatMap(([release, dateStr]) => {\n const date = new Date(dateStr);\n if (date <= inThirtyDays) {\n return [];\n }\n return [{ release, date }];\n })\n .reduce((acc, { release, date }) => {\n if (acc.length === 0) {\n acc.push('', 'Other actively supported release lines include:');\n }\n acc.push(`- ${release} (planned End-of-Support date: ${date.toISOString()})`);\n return acc;\n }, new Array<string>());\n if (endOfSupportDate <= now) {\n // End-of-Support already!\n veryVisibleMessage(\n chalk.bgRed.white.bold,\n `The ${versionMajorMinor} release line of jsii has reached End-of-Support.`,\n `We strongly recommend you upgrade to the current release line (${data.current}) at your earliest convenience.`,\n ...alternatives,\n );\n } else if (endOfSupportDate <= inThirtyDays) {\n // End-of-Support within 30 days!\n veryVisibleMessage(\n chalk.bgYellow.black,\n `The ${versionMajorMinor} release line of jsii will reach End-of-Support soon, on ${endOfSupportDate.toISOString()}.`,\n `We strongly recommend you upgrade to the current release line (${data.current}) at your earliest convenience.`,\n ...alternatives,\n );\n }\n}\n\n/**\n * Downloads the latest `releases.json` document from 'https://raw.githubusercontent.com/aws/jsii-rosetta/main/releases.json'\n * if possible, or falls back to the built-in version of that file if that fails in any way.\n */\nasync function getReleasesDocument(): Promise<ReleasesDocument> {\n const downloaded = await new Promise<string | undefined>((ok, ko) => {\n const request = get(\n new URL('https://raw.githubusercontent.com/aws/jsii-rosetta/main/releases.json'),\n (response) => {\n if (response.statusCode === 404) {\n return ok(undefined);\n }\n if (response.statusCode !== 200) {\n return ko(`received error response: HTTP ${response.statusCode} - ${response.statusMessage}`);\n }\n response.once('error', ko);\n const chunks = new Array<Buffer>();\n response.on('data', (chunk) => chunks.push(Buffer.from(chunk)));\n response.once('end', () => ok(Buffer.concat(chunks).toString('utf-8')));\n },\n );\n request.once('abort', () => ko('request aborted'));\n request.once('timeout', () => ko('request timed out'));\n request.once('error', ko);\n request.end();\n }).catch((cause) => {\n if (process.env.JSII_DEBUG) {\n console.error(`Could not download releases.json from GitHub: ${cause}`);\n }\n undefined;\n });\n\n return JSON.parse(downloaded ?? readFileSync(join(__dirname, '..', 'releases.json'), 'utf-8'), (key, value) => {\n if (key !== 'maintenance') {\n return value;\n }\n return Object.fromEntries(Object.entries(value).map(([release, date]) => [release, new Date(date as string)]));\n }) as ReleasesDocument;\n}\n\nfunction veryVisibleMessage(formatter: chalk.Chalk, ...lines: readonly string[]): void {\n if (lines.length === 0) {\n throw new Error(`At least one line of message must be provided!`);\n }\n\n const len = Math.max(...lines.map((line) => line.length));\n const border = formatter('!'.repeat(len + 8));\n const spacer = formatter(`!! ${' '.repeat(len)} !!`);\n\n console.error(border);\n console.error(spacer);\n for (const line of lines) {\n console.error(formatter(`!! ${line.padEnd(len, ' ')} !!`));\n }\n console.error(spacer);\n console.error(border);\n}\n\ntype ReleaseLine = `${number}.${number}`;\n"]}
|
package/lib/tablets/key.js
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.snippetKey =
|
3
|
+
exports.snippetKey = snippetKey;
|
4
4
|
const crypto = require("node:crypto");
|
5
5
|
const record_references_version_1 = require("../languages/record-references-version");
|
6
6
|
const snippet_1 = require("../snippet");
|
@@ -16,5 +16,4 @@ function snippetKey(snippet) {
|
|
16
16
|
h.update(snippet.visibleSource);
|
17
17
|
return h.digest('hex');
|
18
18
|
}
|
19
|
-
exports.snippetKey = snippetKey;
|
20
19
|
//# sourceMappingURL=key.js.map
|
package/lib/tablets/key.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"key.js","sourceRoot":"","sources":["../../src/tablets/key.ts"],"names":[],"mappings":"
|
1
|
+
{"version":3,"file":"key.js","sourceRoot":"","sources":["../../src/tablets/key.ts"],"names":[],"mappings":";;AAQA,gCAQC;AAhBD,sCAAsC;AAEtC,sFAAmF;AACnF,wCAAkE;AAElE;;GAEG;AACH,SAAgB,UAAU,CAAC,OAA0B;IACnD,MAAM,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;IACtC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,qDAAyB,CAAC,CAAC,CAAC;IAC5C,8DAA8D;IAC9D,CAAC,CAAC,MAAM,CAAC,IAAA,2BAAiB,EAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IAClD,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACd,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;IAChC,OAAO,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import * as crypto from 'node:crypto';\n\nimport { RECORD_REFERENCES_VERSION } from '../languages/record-references-version';\nimport { TypeScriptSnippet, renderApiLocation } from '../snippet';\n\n/**\n * Determine the key for a code block\n */\nexport function snippetKey(snippet: TypeScriptSnippet) {\n const h = crypto.createHash('sha256');\n h.update(String(RECORD_REFERENCES_VERSION));\n // Mix in API location to distinguish between similar snippets\n h.update(renderApiLocation(snippet.location.api));\n h.update(':');\n h.update(snippet.visibleSource);\n return h.digest('hex');\n}\n"]}
|
package/lib/translate.js
CHANGED
@@ -6,7 +6,10 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
6
6
|
};
|
7
7
|
var _Translator_diagnostics;
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
9
|
-
exports.
|
9
|
+
exports.SnippetTranslator = exports.Translator = void 0;
|
10
|
+
exports.translateTypeScript = translateTypeScript;
|
11
|
+
exports.makeRosettaDiagnostic = makeRosettaDiagnostic;
|
12
|
+
exports.rosettaDiagFromTypescript = rosettaDiagFromTypescript;
|
10
13
|
const node_util_1 = require("node:util");
|
11
14
|
const ts = require("typescript");
|
12
15
|
const languages_1 = require("./languages");
|
@@ -32,7 +35,6 @@ function translateTypeScript(source, visitor, options = {}) {
|
|
32
35
|
diagnostics: translator.diagnostics.map(rosettaDiagFromTypescript),
|
33
36
|
};
|
34
37
|
}
|
35
|
-
exports.translateTypeScript = translateTypeScript;
|
36
38
|
/**
|
37
39
|
* Translate one or more TypeScript snippets into other languages
|
38
40
|
*
|
@@ -95,7 +97,6 @@ _Translator_diagnostics = new WeakMap();
|
|
95
97
|
function makeRosettaDiagnostic(isError, formattedMessage) {
|
96
98
|
return { isError, formattedMessage, isFromStrictAssembly: false };
|
97
99
|
}
|
98
|
-
exports.makeRosettaDiagnostic = makeRosettaDiagnostic;
|
99
100
|
/**
|
100
101
|
* Translate a single TypeScript snippet
|
101
102
|
*/
|
@@ -197,7 +198,6 @@ function rosettaDiagFromTypescript(diag) {
|
|
197
198
|
formattedMessage: ts.formatDiagnosticsWithColorAndContext([diag], DIAG_HOST),
|
198
199
|
};
|
199
200
|
}
|
200
|
-
exports.rosettaDiagFromTypescript = rosettaDiagFromTypescript;
|
201
201
|
const DIAG_HOST = {
|
202
202
|
getCurrentDirectory() {
|
203
203
|
return '.';
|
package/lib/translate.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"translate.js","sourceRoot":"","sources":["../src/translate.ts"],"names":[],"mappings":";;;;;;;;;AAAA,yCAAoC;AACpC,iCAAiC;AAEjC,2CAA+D;AAC/D,qEAAwE;AACxE,iEAAgF;AAChF,qCAAqC;AACrC,qCAAsC;AACtC,yCAAyE;AACzE,uCAAiG;AACjG,+DAAkF;AAClF,uCAA2C;AAC3C,6CAAwD;AACxD,+CAAsD;AACtD,0EAAqE;AACrE,0DAAiF;AACjF,8DAAmD;AACnD,iCAAmF;AAEnF,SAAgB,mBAAmB,CACjC,MAAY,EACZ,OAAwB,EACxB,UAAoC,EAAE;IAEtC,MAAM,UAAU,GAAG,IAAI,iBAAiB,CACtC,EAAE,aAAa,EAAE,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,EAAE,GAAG,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,EAAE,EAAE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BAA6B,CAAC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC,CAAC;IACrG,CAAC;CACF;AAhHD,8CAgHC;AAED;;GAEG;AACH,SAAS,wBAAwB,CAAC,KAA+B,EAAE,YAAmB;IACpF,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,KAAK,KAAK,SAAS,IAAI,YAAY,CAAC,gBAAgB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AACxH,CAAC;AAED;;GAEG;AACH,SAAgB,yBAAyB,CAAC,IAAmB;IAC3D,OAAO;QACL,OAAO,EAAE,IAAI,CAAC,QAAQ,KAAK,EAAE,CAAC,kBAAkB,CAAC,KAAK;QACtD,oBAAoB,EAAE,IAAA,wBAAiB,EAAC,IAAI,CAAC;QAC7C,gBAAgB,EAAE,EAAE,CAAC,oCAAoC,CAAC,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC;KAC7E,CAAC;AACJ,CAAC;AAND,8DAMC;AAED,MAAM,SAAS,GAAG;IAChB,mBAAmB;QACjB,OAAO,GAAG,CAAC;IACb,CAAC;IACD,oBAAoB,CAAC,QAAgB;QACnC,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,UAAU;QACR,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAC;AAEF;;;GAGG;AACH,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;AAClC,CAAC","sourcesContent":["import { inspect } from 'node:util';\nimport * as ts from 'typescript';\n\nimport { TARGET_LANGUAGES, TargetLanguage } from './languages';\nimport { RecordReferencesVisitor } from './languages/record-references';\nimport { supportsTransitiveSubmoduleAccess } from './languages/target-language';\nimport * as logging from './logging';\nimport { renderTree } from './o-tree';\nimport { AstRenderer, AstHandler, AstRendererOptions } from './renderer';\nimport { TypeScriptSnippet, completeSource, SnippetParameters, formatLocation } from './snippet';\nimport { SubmoduleReference, SubmoduleReferenceMap } from './submodule-reference';\nimport { snippetKey } from './tablets/key';\nimport { ORIGINAL_SNIPPET_KEY } from './tablets/schema';\nimport { TranslatedSnippet } from './tablets/tablets';\nimport { SyntaxKindCounter } from './typescript/syntax-kind-counter';\nimport { TypeScriptCompiler, CompilationResult } from './typescript/ts-compiler';\nimport { Spans } from './typescript/visible-spans';\nimport { annotateStrictDiagnostic, File, hasStrictBranding, mkDict } from './util';\n\nexport function translateTypeScript(\n source: File,\n visitor: AstHandler<any>,\n options: SnippetTranslatorOptions = {},\n): TranslateResult {\n const translator = new SnippetTranslator(\n { visibleSource: source.contents, location: { api: { api: 'file', fileName: source.fileName } } },\n options,\n );\n const translated = translator.renderUsing(visitor);\n\n return {\n translation: translated,\n diagnostics: translator.diagnostics.map(rosettaDiagFromTypescript),\n };\n}\n\n/**\n * Translate one or more TypeScript snippets into other languages\n *\n * Can be configured to fully typecheck the samples, or perform only syntactical\n * translation.\n */\nexport class Translator {\n private readonly compiler = new TypeScriptCompiler();\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n #diagnostics: ts.Diagnostic[] = [];\n\n public constructor(private readonly includeCompilerDiagnostics: boolean) {}\n\n public translate(snip: TypeScriptSnippet, languages: readonly TargetLanguage[] = Object.values(TargetLanguage)) {\n logging.debug(`Translating ${snippetKey(snip)} ${inspect(snip.parameters ?? {})}`);\n const translator = this.translatorFor(snip);\n\n const translations = mkDict(\n languages.flatMap((lang, idx, array) => {\n if (array.slice(0, idx).includes(lang)) {\n // This language was duplicated in the request... we'll skip that here...\n return [];\n }\n const languageConverterFactory = TARGET_LANGUAGES[lang];\n const translated = translator.renderUsing(languageConverterFactory.createVisitor());\n return [[lang, { source: translated, version: languageConverterFactory.version }] as const];\n }),\n );\n\n if (snip.parameters?.infused === undefined) {\n this.#diagnostics.push(...translator.diagnostics);\n }\n\n return TranslatedSnippet.fromSchema({\n translations: {\n ...translations,\n [ORIGINAL_SNIPPET_KEY]: { source: snip.visibleSource, version: '0' },\n },\n location: snip.location,\n didCompile: translator.didSuccessfullyCompile,\n fqnsReferenced: translator.fqnsReferenced(),\n fullSource: completeSource(snip),\n syntaxKindCounter: translator.syntaxKindCounter(),\n });\n }\n\n public get diagnostics(): readonly RosettaDiagnostic[] {\n return ts.sortAndDeduplicateDiagnostics(this.#diagnostics).map(rosettaDiagFromTypescript);\n }\n\n /**\n * Return the snippet translator for the given snippet\n *\n * We used to cache these, but each translator holds on to quite a bit of memory,\n * so we don't do that anymore.\n */\n public translatorFor(snippet: TypeScriptSnippet) {\n const translator = new SnippetTranslator(snippet, {\n compiler: this.compiler,\n includeCompilerDiagnostics: this.includeCompilerDiagnostics,\n });\n return translator;\n }\n}\n\nexport interface SnippetTranslatorOptions extends AstRendererOptions {\n /**\n * Re-use the given compiler if given\n */\n readonly compiler?: TypeScriptCompiler;\n\n /**\n * Include compiler errors in return diagnostics\n *\n * If false, only translation diagnostics will be returned.\n *\n * @default false\n */\n readonly includeCompilerDiagnostics?: boolean;\n}\n\nexport interface TranslateResult {\n translation: string;\n diagnostics: readonly RosettaDiagnostic[];\n}\n\n/**\n * A translation of a TypeScript diagnostic into a data-only representation for Rosetta\n *\n * We cannot use the original `ts.Diagnostic` since it holds on to way too much\n * state (the source file and by extension the entire parse tree), which grows\n * too big to be properly serialized by a worker and also takes too much memory.\n *\n * Reduce it down to only the information we need.\n */\nexport interface RosettaDiagnostic {\n /**\n * If this is an error diagnostic or not\n */\n readonly isError: boolean;\n\n /**\n * If the diagnostic was emitted from an assembly that has its 'strict' flag set\n */\n readonly isFromStrictAssembly: boolean;\n\n /**\n * The formatted message, ready to be printed (will have colors and newlines in it)\n *\n * Ends in a newline.\n */\n readonly formattedMessage: string;\n}\n\nexport function makeRosettaDiagnostic(isError: boolean, formattedMessage: string): RosettaDiagnostic {\n return { isError, formattedMessage, isFromStrictAssembly: false };\n}\n\n/**\n * Translate a single TypeScript snippet\n */\nexport class SnippetTranslator {\n public readonly translateDiagnostics: ts.Diagnostic[] = [];\n public readonly compileDiagnostics: ts.Diagnostic[] = [];\n private readonly visibleSpans: Spans;\n private readonly compilation!: CompilationResult;\n private readonly tryCompile: boolean;\n private readonly submoduleReferences: SubmoduleReferenceMap;\n\n public constructor(snippet: TypeScriptSnippet, private readonly options: SnippetTranslatorOptions = {}) {\n const compiler = options.compiler ?? new TypeScriptCompiler();\n const source = completeSource(snippet);\n const fakeCurrentDirectory = snippet.parameters?.[SnippetParameters.$COMPILATION_DIRECTORY] ?? process.cwd();\n this.compilation = compiler.compileInMemory(\n removeSlashes(formatLocation(snippet.location)),\n source,\n fakeCurrentDirectory,\n );\n\n // Respect '/// !hide' and '/// !show' directives\n this.visibleSpans = Spans.visibleSpansFromSource(source);\n\n // Find submodule references on explicit imports\n this.submoduleReferences = SubmoduleReference.inSourceFile(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n );\n\n // This makes it about 5x slower, so only do it on demand\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n this.tryCompile = (options.includeCompilerDiagnostics || snippet.strict) ?? false;\n if (this.tryCompile) {\n const program = this.compilation.program;\n const diagnostics = [\n ...neverThrowing(program.getGlobalDiagnostics)(),\n ...neverThrowing(program.getSyntacticDiagnostics)(this.compilation.rootFile),\n ...neverThrowing(program.getDeclarationDiagnostics)(this.compilation.rootFile),\n ...neverThrowing(program.getSemanticDiagnostics)(this.compilation.rootFile),\n ];\n if (snippet.strict) {\n // In a strict assembly, so we'll need to brand all diagnostics here...\n for (const diag of diagnostics) {\n annotateStrictDiagnostic(diag);\n }\n }\n this.compileDiagnostics.push(...diagnostics);\n }\n\n /**\n * Intercepts all exceptions thrown by the wrapped call, and logs them to\n * console.error instead of re-throwing, then returns an empty array. This\n * is here to avoid compiler crashes due to broken code examples that cause\n * the TypeScript compiler to hit a \"Debug Failure\".\n */\n function neverThrowing<A extends unknown[], R>(call: (...args: A) => readonly R[]): (...args: A) => readonly R[] {\n return (...args: A) => {\n try {\n return call(...args);\n } catch (err: any) {\n const isExpectedTypescriptError = err.message.includes('Debug Failure');\n\n if (!isExpectedTypescriptError) {\n console.error(`Failed to execute ${call.name}: ${err}`);\n }\n\n return [];\n }\n };\n }\n }\n\n /**\n * Returns a boolean if compilation was attempted, and undefined if it was not.\n */\n public get didSuccessfullyCompile() {\n return this.tryCompile ? this.compileDiagnostics.length === 0 : undefined;\n }\n\n public renderUsing(visitor: AstHandler<any>) {\n const converter = new AstRenderer(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n visitor,\n this.options,\n // If we support transitive submodule access, don't provide a submodule reference map.\n supportsTransitiveSubmoduleAccess(visitor.language) ? undefined : this.submoduleReferences,\n );\n const converted = converter.convert(this.compilation.rootFile);\n this.translateDiagnostics.push(...filterVisibleDiagnostics(converter.diagnostics, this.visibleSpans));\n return renderTree(converted, { indentChar: visitor.indentChar, visibleSpans: this.visibleSpans });\n }\n\n public syntaxKindCounter(): Partial<Record<ts.SyntaxKind, number>> {\n const kindCounter = new SyntaxKindCounter(this.visibleSpans);\n return kindCounter.countKinds(this.compilation.rootFile);\n }\n\n public fqnsReferenced() {\n const visitor = new RecordReferencesVisitor(this.visibleSpans);\n const converter = new AstRenderer(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n visitor,\n this.options,\n this.submoduleReferences,\n );\n converter.convert(this.compilation.rootFile);\n return visitor.fqnsReferenced();\n }\n\n public get diagnostics(): readonly ts.Diagnostic[] {\n return ts.sortAndDeduplicateDiagnostics(this.compileDiagnostics.concat(this.translateDiagnostics));\n }\n}\n\n/**\n * Hide diagnostics that are rosetta-sourced if they are reported against a non-visible span\n */\nfunction filterVisibleDiagnostics(diags: readonly ts.Diagnostic[], visibleSpans: Spans): ts.Diagnostic[] {\n return diags.filter((d) => d.source !== 'rosetta' || d.start === undefined || visibleSpans.containsPosition(d.start));\n}\n\n/**\n * Turn TypeScript diagnostics into Rosetta diagnostics\n */\nexport function rosettaDiagFromTypescript(diag: ts.Diagnostic): RosettaDiagnostic {\n return {\n isError: diag.category === ts.DiagnosticCategory.Error,\n isFromStrictAssembly: hasStrictBranding(diag),\n formattedMessage: ts.formatDiagnosticsWithColorAndContext([diag], DIAG_HOST),\n };\n}\n\nconst DIAG_HOST = {\n getCurrentDirectory() {\n return '.';\n },\n getCanonicalFileName(fileName: string) {\n return fileName;\n },\n getNewLine() {\n return '\\n';\n },\n};\n\n/**\n * Remove slashes from a \"where\" description, as the TS compiler will interpret it as a directory\n * and we can't have that for compiling literate files\n */\nfunction removeSlashes(x: string) {\n return x.replace(/\\/|\\\\/g, '.');\n}\n"]}
|
1
|
+
{"version":3,"file":"translate.js","sourceRoot":"","sources":["../src/translate.ts"],"names":[],"mappings":";;;;;;;;;AAmBA,kDAeC;AAoHD,sDAEC;AAiID,8DAMC;AA/RD,yCAAoC;AACpC,iCAAiC;AAEjC,2CAA+D;AAC/D,qEAAwE;AACxE,iEAAgF;AAChF,qCAAqC;AACrC,qCAAsC;AACtC,yCAAyE;AACzE,uCAAiG;AACjG,+DAAkF;AAClF,uCAA2C;AAC3C,6CAAwD;AACxD,+CAAsD;AACtD,0EAAqE;AACrE,0DAAiF;AACjF,8DAAmD;AACnD,iCAAmF;AAEnF,SAAgB,mBAAmB,CACjC,MAAY,EACZ,OAAwB,EACxB,UAAoC,EAAE;IAEtC,MAAM,UAAU,GAAG,IAAI,iBAAiB,CACtC,EAAE,aAAa,EAAE,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,EAAE,GAAG,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,EAAE,EAAE,EACjG,OAAO,CACR,CAAC;IACF,MAAM,UAAU,GAAG,UAAU,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAEnD,OAAO;QACL,WAAW,EAAE,UAAU;QACvB,WAAW,EAAE,UAAU,CAAC,W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pF,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,KAAK,KAAK,SAAS,IAAI,YAAY,CAAC,gBAAgB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AACxH,CAAC;AAED;;GAEG;AACH,SAAgB,yBAAyB,CAAC,IAAmB;IAC3D,OAAO;QACL,OAAO,EAAE,IAAI,CAAC,QAAQ,KAAK,EAAE,CAAC,kBAAkB,CAAC,KAAK;QACtD,oBAAoB,EAAE,IAAA,wBAAiB,EAAC,IAAI,CAAC;QAC7C,gBAAgB,EAAE,EAAE,CAAC,oCAAoC,CAAC,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC;KAC7E,CAAC;AACJ,CAAC;AAED,MAAM,SAAS,GAAG;IAChB,mBAAmB;QACjB,OAAO,GAAG,CAAC;IACb,CAAC;IACD,oBAAoB,CAAC,QAAgB;QACnC,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,UAAU;QACR,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAC;AAEF;;;GAGG;AACH,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;AAClC,CAAC","sourcesContent":["import { inspect } from 'node:util';\nimport * as ts from 'typescript';\n\nimport { TARGET_LANGUAGES, TargetLanguage } from './languages';\nimport { RecordReferencesVisitor } from './languages/record-references';\nimport { supportsTransitiveSubmoduleAccess } from './languages/target-language';\nimport * as logging from './logging';\nimport { renderTree } from './o-tree';\nimport { AstRenderer, AstHandler, AstRendererOptions } from './renderer';\nimport { TypeScriptSnippet, completeSource, SnippetParameters, formatLocation } from './snippet';\nimport { SubmoduleReference, SubmoduleReferenceMap } from './submodule-reference';\nimport { snippetKey } from './tablets/key';\nimport { ORIGINAL_SNIPPET_KEY } from './tablets/schema';\nimport { TranslatedSnippet } from './tablets/tablets';\nimport { SyntaxKindCounter } from './typescript/syntax-kind-counter';\nimport { TypeScriptCompiler, CompilationResult } from './typescript/ts-compiler';\nimport { Spans } from './typescript/visible-spans';\nimport { annotateStrictDiagnostic, File, hasStrictBranding, mkDict } from './util';\n\nexport function translateTypeScript(\n source: File,\n visitor: AstHandler<any>,\n options: SnippetTranslatorOptions = {},\n): TranslateResult {\n const translator = new SnippetTranslator(\n { visibleSource: source.contents, location: { api: { api: 'file', fileName: source.fileName } } },\n options,\n );\n const translated = translator.renderUsing(visitor);\n\n return {\n translation: translated,\n diagnostics: translator.diagnostics.map(rosettaDiagFromTypescript),\n };\n}\n\n/**\n * Translate one or more TypeScript snippets into other languages\n *\n * Can be configured to fully typecheck the samples, or perform only syntactical\n * translation.\n */\nexport class Translator {\n private readonly compiler = new TypeScriptCompiler();\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n #diagnostics: ts.Diagnostic[] = [];\n\n public constructor(private readonly includeCompilerDiagnostics: boolean) {}\n\n public translate(snip: TypeScriptSnippet, languages: readonly TargetLanguage[] = Object.values(TargetLanguage)) {\n logging.debug(`Translating ${snippetKey(snip)} ${inspect(snip.parameters ?? {})}`);\n const translator = this.translatorFor(snip);\n\n const translations = mkDict(\n languages.flatMap((lang, idx, array) => {\n if (array.slice(0, idx).includes(lang)) {\n // This language was duplicated in the request... we'll skip that here...\n return [];\n }\n const languageConverterFactory = TARGET_LANGUAGES[lang];\n const translated = translator.renderUsing(languageConverterFactory.createVisitor());\n return [[lang, { source: translated, version: languageConverterFactory.version }] as const];\n }),\n );\n\n if (snip.parameters?.infused === undefined) {\n this.#diagnostics.push(...translator.diagnostics);\n }\n\n return TranslatedSnippet.fromSchema({\n translations: {\n ...translations,\n [ORIGINAL_SNIPPET_KEY]: { source: snip.visibleSource, version: '0' },\n },\n location: snip.location,\n didCompile: translator.didSuccessfullyCompile,\n fqnsReferenced: translator.fqnsReferenced(),\n fullSource: completeSource(snip),\n syntaxKindCounter: translator.syntaxKindCounter(),\n });\n }\n\n public get diagnostics(): readonly RosettaDiagnostic[] {\n return ts.sortAndDeduplicateDiagnostics(this.#diagnostics).map(rosettaDiagFromTypescript);\n }\n\n /**\n * Return the snippet translator for the given snippet\n *\n * We used to cache these, but each translator holds on to quite a bit of memory,\n * so we don't do that anymore.\n */\n public translatorFor(snippet: TypeScriptSnippet) {\n const translator = new SnippetTranslator(snippet, {\n compiler: this.compiler,\n includeCompilerDiagnostics: this.includeCompilerDiagnostics,\n });\n return translator;\n }\n}\n\nexport interface SnippetTranslatorOptions extends AstRendererOptions {\n /**\n * Re-use the given compiler if given\n */\n readonly compiler?: TypeScriptCompiler;\n\n /**\n * Include compiler errors in return diagnostics\n *\n * If false, only translation diagnostics will be returned.\n *\n * @default false\n */\n readonly includeCompilerDiagnostics?: boolean;\n}\n\nexport interface TranslateResult {\n translation: string;\n diagnostics: readonly RosettaDiagnostic[];\n}\n\n/**\n * A translation of a TypeScript diagnostic into a data-only representation for Rosetta\n *\n * We cannot use the original `ts.Diagnostic` since it holds on to way too much\n * state (the source file and by extension the entire parse tree), which grows\n * too big to be properly serialized by a worker and also takes too much memory.\n *\n * Reduce it down to only the information we need.\n */\nexport interface RosettaDiagnostic {\n /**\n * If this is an error diagnostic or not\n */\n readonly isError: boolean;\n\n /**\n * If the diagnostic was emitted from an assembly that has its 'strict' flag set\n */\n readonly isFromStrictAssembly: boolean;\n\n /**\n * The formatted message, ready to be printed (will have colors and newlines in it)\n *\n * Ends in a newline.\n */\n readonly formattedMessage: string;\n}\n\nexport function makeRosettaDiagnostic(isError: boolean, formattedMessage: string): RosettaDiagnostic {\n return { isError, formattedMessage, isFromStrictAssembly: false };\n}\n\n/**\n * Translate a single TypeScript snippet\n */\nexport class SnippetTranslator {\n public readonly translateDiagnostics: ts.Diagnostic[] = [];\n public readonly compileDiagnostics: ts.Diagnostic[] = [];\n private readonly visibleSpans: Spans;\n private readonly compilation!: CompilationResult;\n private readonly tryCompile: boolean;\n private readonly submoduleReferences: SubmoduleReferenceMap;\n\n public constructor(snippet: TypeScriptSnippet, private readonly options: SnippetTranslatorOptions = {}) {\n const compiler = options.compiler ?? new TypeScriptCompiler();\n const source = completeSource(snippet);\n const fakeCurrentDirectory = snippet.parameters?.[SnippetParameters.$COMPILATION_DIRECTORY] ?? process.cwd();\n this.compilation = compiler.compileInMemory(\n removeSlashes(formatLocation(snippet.location)),\n source,\n fakeCurrentDirectory,\n );\n\n // Respect '/// !hide' and '/// !show' directives\n this.visibleSpans = Spans.visibleSpansFromSource(source);\n\n // Find submodule references on explicit imports\n this.submoduleReferences = SubmoduleReference.inSourceFile(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n );\n\n // This makes it about 5x slower, so only do it on demand\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n this.tryCompile = (options.includeCompilerDiagnostics || snippet.strict) ?? false;\n if (this.tryCompile) {\n const program = this.compilation.program;\n const diagnostics = [\n ...neverThrowing(program.getGlobalDiagnostics)(),\n ...neverThrowing(program.getSyntacticDiagnostics)(this.compilation.rootFile),\n ...neverThrowing(program.getDeclarationDiagnostics)(this.compilation.rootFile),\n ...neverThrowing(program.getSemanticDiagnostics)(this.compilation.rootFile),\n ];\n if (snippet.strict) {\n // In a strict assembly, so we'll need to brand all diagnostics here...\n for (const diag of diagnostics) {\n annotateStrictDiagnostic(diag);\n }\n }\n this.compileDiagnostics.push(...diagnostics);\n }\n\n /**\n * Intercepts all exceptions thrown by the wrapped call, and logs them to\n * console.error instead of re-throwing, then returns an empty array. This\n * is here to avoid compiler crashes due to broken code examples that cause\n * the TypeScript compiler to hit a \"Debug Failure\".\n */\n function neverThrowing<A extends unknown[], R>(call: (...args: A) => readonly R[]): (...args: A) => readonly R[] {\n return (...args: A) => {\n try {\n return call(...args);\n } catch (err: any) {\n const isExpectedTypescriptError = err.message.includes('Debug Failure');\n\n if (!isExpectedTypescriptError) {\n console.error(`Failed to execute ${call.name}: ${err}`);\n }\n\n return [];\n }\n };\n }\n }\n\n /**\n * Returns a boolean if compilation was attempted, and undefined if it was not.\n */\n public get didSuccessfullyCompile() {\n return this.tryCompile ? this.compileDiagnostics.length === 0 : undefined;\n }\n\n public renderUsing(visitor: AstHandler<any>) {\n const converter = new AstRenderer(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n visitor,\n this.options,\n // If we support transitive submodule access, don't provide a submodule reference map.\n supportsTransitiveSubmoduleAccess(visitor.language) ? undefined : this.submoduleReferences,\n );\n const converted = converter.convert(this.compilation.rootFile);\n this.translateDiagnostics.push(...filterVisibleDiagnostics(converter.diagnostics, this.visibleSpans));\n return renderTree(converted, { indentChar: visitor.indentChar, visibleSpans: this.visibleSpans });\n }\n\n public syntaxKindCounter(): Partial<Record<ts.SyntaxKind, number>> {\n const kindCounter = new SyntaxKindCounter(this.visibleSpans);\n return kindCounter.countKinds(this.compilation.rootFile);\n }\n\n public fqnsReferenced() {\n const visitor = new RecordReferencesVisitor(this.visibleSpans);\n const converter = new AstRenderer(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n visitor,\n this.options,\n this.submoduleReferences,\n );\n converter.convert(this.compilation.rootFile);\n return visitor.fqnsReferenced();\n }\n\n public get diagnostics(): readonly ts.Diagnostic[] {\n return ts.sortAndDeduplicateDiagnostics(this.compileDiagnostics.concat(this.translateDiagnostics));\n }\n}\n\n/**\n * Hide diagnostics that are rosetta-sourced if they are reported against a non-visible span\n */\nfunction filterVisibleDiagnostics(diags: readonly ts.Diagnostic[], visibleSpans: Spans): ts.Diagnostic[] {\n return diags.filter((d) => d.source !== 'rosetta' || d.start === undefined || visibleSpans.containsPosition(d.start));\n}\n\n/**\n * Turn TypeScript diagnostics into Rosetta diagnostics\n */\nexport function rosettaDiagFromTypescript(diag: ts.Diagnostic): RosettaDiagnostic {\n return {\n isError: diag.category === ts.DiagnosticCategory.Error,\n isFromStrictAssembly: hasStrictBranding(diag),\n formattedMessage: ts.formatDiagnosticsWithColorAndContext([diag], DIAG_HOST),\n };\n}\n\nconst DIAG_HOST = {\n getCurrentDirectory() {\n return '.';\n },\n getCanonicalFileName(fileName: string) {\n return fileName;\n },\n getNewLine() {\n return '\\n';\n },\n};\n\n/**\n * Remove slashes from a \"where\" description, as the TS compiler will interpret it as a directory\n * and we can't have that for compiling literate files\n */\nfunction removeSlashes(x: string) {\n return x.replace(/\\/|\\\\/g, '.');\n}\n"]}
|
package/lib/translate_all.js
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.translateAll =
|
3
|
+
exports.translateAll = translateAll;
|
4
4
|
const os = require("node:os");
|
5
5
|
const path = require("node:path");
|
6
6
|
const workerpool = require("workerpool");
|
@@ -46,7 +46,6 @@ async function translateAll(snippets, includeCompilerDiagnostics) {
|
|
46
46
|
void pool.terminate();
|
47
47
|
}
|
48
48
|
}
|
49
|
-
exports.translateAll = translateAll;
|
50
49
|
function batchSnippets(snippets, includeCompilerDiagnostics, batchSize = 10) {
|
51
50
|
const ret = [];
|
52
51
|
for (let i = 0; i < snippets.length; i += batchSize) {
|