jsii-rosetta 5.4.32-dev.2 → 5.5.0
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +2 -2
- 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 +3 -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 +4 -4
- package/releases.json +4 -3
@@ -1,6 +1,10 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.
|
3
|
+
exports.collectDependencies = collectDependencies;
|
4
|
+
exports.expandWithTransitiveDependencies = expandWithTransitiveDependencies;
|
5
|
+
exports.resolveDependenciesFromPackageJson = resolveDependenciesFromPackageJson;
|
6
|
+
exports.validateAvailableDependencies = validateAvailableDependencies;
|
7
|
+
exports.prepareDependencyDirectory = prepareDependencyDirectory;
|
4
8
|
const cp = require("node:child_process");
|
5
9
|
const node_fs_1 = require("node:fs");
|
6
10
|
const fs = require("node:fs");
|
@@ -27,7 +31,6 @@ function collectDependencies(snippets) {
|
|
27
31
|
}
|
28
32
|
return ret;
|
29
33
|
}
|
30
|
-
exports.collectDependencies = collectDependencies;
|
31
34
|
/**
|
32
35
|
* Add transitive dependencies of concrete dependencies to the array
|
33
36
|
*
|
@@ -64,7 +67,6 @@ async function expandWithTransitiveDependencies(deps) {
|
|
64
67
|
}
|
65
68
|
}
|
66
69
|
}
|
67
|
-
exports.expandWithTransitiveDependencies = expandWithTransitiveDependencies;
|
68
70
|
/**
|
69
71
|
* Find the corresponding package directories for all dependencies in a package.json
|
70
72
|
*/
|
@@ -80,7 +82,6 @@ async function resolveDependenciesFromPackageJson(packageJson, directory) {
|
|
80
82
|
},
|
81
83
|
])));
|
82
84
|
}
|
83
|
-
exports.resolveDependenciesFromPackageJson = resolveDependenciesFromPackageJson;
|
84
85
|
function resolveConflict(name, a, b) {
|
85
86
|
if (!b) {
|
86
87
|
return a;
|
@@ -131,7 +132,6 @@ async function validateAvailableDependencies(directory, deps) {
|
|
131
132
|
logging.warn(`${directory}: packages necessary to compile examples missing from supplied directory: ${failures.join(', ')}`);
|
132
133
|
}
|
133
134
|
}
|
134
|
-
exports.validateAvailableDependencies = validateAvailableDependencies;
|
135
135
|
/**
|
136
136
|
* Intersect two semver ranges
|
137
137
|
*
|
@@ -201,7 +201,6 @@ async function prepareDependencyDirectory(deps) {
|
|
201
201
|
cp.execSync(`npm install --force --loglevel error`, { cwd: tmpDir, encoding: 'utf-8' });
|
202
202
|
return tmpDir;
|
203
203
|
}
|
204
|
-
exports.prepareDependencyDirectory = prepareDependencyDirectory;
|
205
204
|
/**
|
206
205
|
* Map package name to directory
|
207
206
|
*/
|
@@ -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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E,CAAC;YACrD,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC;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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,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC;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"]}
|
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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,CAAC,EAAE,CAAC,EAAE,EAAE;QACnC,OAAO,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC,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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SourceToVisible } 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;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AAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;aACpB,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC;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;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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f,CAAC;QACD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,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,O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AC;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"]}
|
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 '.';
|