jsii-rosetta 5.9.6-dev.2 → 5.9.6

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.
@@ -5,6 +5,7 @@ const node_fs_1 = require("node:fs");
5
5
  const node_path_1 = require("node:path");
6
6
  const spec_1 = require("@jsii/spec");
7
7
  const extract_1 = require("./extract");
8
+ const assemblies_1 = require("../jsii/assemblies");
8
9
  const target_language_1 = require("../languages/target-language");
9
10
  const logging_1 = require("../logging");
10
11
  const rosetta_reader_1 = require("../rosetta-reader");
@@ -88,7 +89,7 @@ async function transliterateAssembly(assemblyLocations, targetLanguages, options
88
89
  async function loadAssemblies(directories, rosetta) {
89
90
  const result = new Map();
90
91
  for (const directory of directories) {
91
- const loader = () => (0, spec_1.loadAssemblyFromPath)(directory);
92
+ const loader = () => (0, spec_1.loadAssemblyFromPath)(directory, false, assemblies_1.SUPPORTED_ASSEMBLY_FEATURES);
92
93
  // eslint-disable-next-line no-await-in-loop
93
94
  await rosetta.addAssembly(loader(), directory);
94
95
  result.set(directory, loader);
@@ -1 +1 @@
1
- {"version":3,"file":"transliterate.js","sourceRoot":"","sources":["../../src/commands/transliterate.ts"],"names":[],"mappings":";;AA+DA,sDAqEC;AApID,qCAAyC;AACzC,yCAAoC;AACpC,qCAAkG;AAElG,uCAA4C;AAE5C,kEAA0D;AAC1D,wCAAmC;AACnC,sDAA4E;AAC5E,wCAA6E;AA0C7E;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,qBAAqB,CACzC,iBAAoC,EACpC,eAA0C,EAC1C,UAAwC,EAAE;IAE1C,uDAAuD;IACvD,EAAE;IACF,+EAA+E;IAC/E,mFAAmF;IACnF,4CAA4C;IAC5C,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAA,yBAAe,EAAC,iBAAiB,EAAE;QAC1D,0BAA0B,EAAE,IAAI;QAChC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,aAAa,EAAE,OAAO,CAAC,M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C","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { Assembly, Docs, SPEC_FILE_NAME, Type, TypeKind, loadAssemblyFromPath } from '@jsii/spec';\n\nimport { extractSnippets } from './extract';\nimport { TargetLanguage } from '../languages';\nimport { targetName } from '../languages/target-language';\nimport { debug } from '../logging';\nimport { RosettaTabletReader, UnknownSnippetMode } from '../rosetta-reader';\nimport { typeScriptSnippetFromVisibleSource, ApiLocation } from '../snippet';\nimport { Mutable } from '../util';\n\nexport interface TransliterateAssemblyOptions {\n /**\n * Whether to ignore any missing fixture files or literate markdown documents\n * referenced by the assembly, instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Whether transliteration should fail upon failing to compile an example that\n * required live transliteration.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * A pre-build translation tablet (as produced by `jsii-rosetta extract`).\n *\n * @default - Only the default tablet (`.jsii.tabl.json`) files will be used.\n */\n readonly tablet?: string;\n\n /**\n * A directory to output translated assemblies to\n *\n * @default - assembly location\n */\n readonly outdir?: string;\n\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.FAIL\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n}\n\n/**\n * Prepares transliterated versions of the designated assemblies into the\n * selected target languages.\n *\n * @param assemblyLocations the directories which contain assemblies to\n * transliterate.\n * @param targetLanguages the languages into which to transliterate.\n * @param tabletLocation an optional Rosetta tablet file to source\n * pre-transliterated snippets from.\n *\n * @experimental\n */\nexport async function transliterateAssembly(\n assemblyLocations: readonly string[],\n targetLanguages: readonly TargetLanguage[],\n options: TransliterateAssemblyOptions = {},\n): Promise<void> {\n // Start by doing an 'extract' for all these assemblies\n //\n // This will locate all examples that haven't been translated yet and translate\n // them. Importantly: it will translate them in parallel, which is going to improve\n // performance a lot. We ignore diagnostics.\n const { tablet } = await extractSnippets(assemblyLocations, {\n includeCompilerDiagnostics: true,\n loose: options.loose,\n cacheFromFile: options.tablet,\n writeToImplicitTablets: false,\n allowDirtyTranslations: true,\n });\n\n // Now do a regular \"tablet reader\" cycle, expecting everything to be translated already,\n // and therefore it doesn't matter that we do this all in a single-threaded loop.\n const rosetta = new RosettaTabletReader({\n unknownSnippets: options?.unknownSnippets ?? UnknownSnippetMode.FAIL,\n targetLanguages,\n prefixDisclaimer: true,\n });\n // Put in the same caching tablet here\n if (options.tablet) {\n await rosetta.loadTabletFromFile(options.tablet);\n }\n // Any fresh translations we just came up with\n rosetta.addTablet(tablet);\n\n const assemblies = await loadAssemblies(assemblyLocations, rosetta);\n\n for (const [location, loadAssembly] of assemblies.entries()) {\n for (const language of targetLanguages) {\n const now = new Date().getTime();\n const result = loadAssembly();\n\n if (result.targets?.[targetName(language)] == null) {\n // This language is not supported by the assembly, so we skip it...\n continue;\n }\n\n if (result.readme?.markdown) {\n result.readme.markdown = rosetta.translateSnippetsInMarkdown(\n { api: 'moduleReadme', moduleFqn: result.name },\n result.readme.markdown,\n language,\n true /* strict */,\n );\n }\n for (const type of Object.values(result.types ?? {})) {\n transliterateType(type, rosetta, language);\n }\n // eslint-disable-next-line no-await-in-loop\n await fs.writeFile(\n resolve(options?.outdir ?? location, `${SPEC_FILE_NAME}.${language}`),\n JSON.stringify(result, null, 2),\n );\n const then = new Date().getTime();\n debug(`Done transliterating ${result.name}@${result.version} to ${language} after ${then - now} milliseconds`);\n }\n }\n\n rosetta.printDiagnostics(process.stderr, process.stderr.isTTY);\n if (rosetta.hasErrors && options.strict) {\n throw new Error('Strict mode is enabled and some examples failed compilation!');\n }\n}\n\n/**\n * Given a set of directories containing `.jsii` assemblies, load all the\n * assemblies into the provided `Rosetta` instance and return a map of\n * directories to assembly-loading functions (the function re-loads the original\n * assembly from disk on each invocation).\n *\n * @param directories the assembly-containing directories to traverse.\n * @param rosetta the `Rosetta` instance in which to load assemblies.\n *\n * @returns a map of directories to a function that loads the `.jsii` assembly\n * contained therein from disk.\n */\nasync function loadAssemblies(\n directories: readonly string[],\n rosetta: RosettaTabletReader,\n): Promise<ReadonlyMap<string, AssemblyLoader>> {\n const result = new Map<string, AssemblyLoader>();\n\n for (const directory of directories) {\n const loader = () => loadAssemblyFromPath(directory);\n // eslint-disable-next-line no-await-in-loop\n await rosetta.addAssembly(loader(), directory);\n result.set(directory, loader);\n }\n\n return result;\n}\n\ntype AssemblyLoader = () => Mutable<Assembly>;\n\nfunction transliterateType(type: Type, rosetta: RosettaTabletReader, language: TargetLanguage): void {\n transliterateDocs({ api: 'type', fqn: type.fqn }, type.docs);\n switch (type.kind) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore 7029\n case TypeKind.Class:\n if (type.initializer) {\n transliterateDocs({ api: 'initializer', fqn: type.fqn }, type.initializer.docs);\n }\n\n // fallthrough\n case TypeKind.Interface:\n for (const method of type.methods ?? []) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: method.name }, method.docs);\n for (const parameter of method.parameters ?? []) {\n transliterateDocs(\n { api: 'parameter', fqn: type.fqn, methodName: method.name, parameterName: parameter.name },\n parameter.docs,\n );\n }\n }\n for (const property of type.properties ?? []) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: property.name }, property.docs);\n }\n break;\n\n case TypeKind.Enum:\n for (const member of type.members) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: member.name }, member.docs);\n }\n break;\n\n default:\n throw new Error(`Unsupported type kind: ${(type as any).kind}`);\n }\n\n function transliterateDocs(api: ApiLocation, docs: Docs | undefined) {\n if (docs?.remarks) {\n docs.remarks = rosetta.translateSnippetsInMarkdown(api, docs.remarks, language, true /* strict */);\n }\n\n if (docs?.example) {\n const location = { api, field: { field: 'example' } } as const;\n const snippet = typeScriptSnippetFromVisibleSource(docs.example, location, true /* strict */);\n const translation = rosetta.translateSnippet(snippet, language);\n if (translation != null) {\n docs.example = translation.source;\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"transliterate.js","sourceRoot":"","sources":["../../src/commands/transliterate.ts"],"names":[],"mappings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EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QACrG,CAAC;QAED,IAAI,IAAI,EAAE,OAAO,EAAE,CAAC;YAClB,MAAM,QAAQ,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,EAAW,CAAC;YAC/D,MAAM,OAAO,GAAG,IAAA,4CAAkC,EAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;YAC9F,MAAM,WAAW,GAAG,OAAO,CAAC,gBAAgB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAChE,IAAI,WAAW,IAAI,IAAI,EAAE,CAAC;gBACxB,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC,MAAM,CAAC;YACpC,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { Assembly, Docs, SPEC_FILE_NAME, Type, TypeKind, loadAssemblyFromPath } from '@jsii/spec';\n\nimport { extractSnippets } from './extract';\nimport { SUPPORTED_ASSEMBLY_FEATURES } from '../jsii/assemblies';\nimport { TargetLanguage } from '../languages';\nimport { targetName } from '../languages/target-language';\nimport { debug } from '../logging';\nimport { RosettaTabletReader, UnknownSnippetMode } from '../rosetta-reader';\nimport { typeScriptSnippetFromVisibleSource, ApiLocation } from '../snippet';\nimport { Mutable } from '../util';\n\nexport interface TransliterateAssemblyOptions {\n /**\n * Whether to ignore any missing fixture files or literate markdown documents\n * referenced by the assembly, instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Whether transliteration should fail upon failing to compile an example that\n * required live transliteration.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * A pre-build translation tablet (as produced by `jsii-rosetta extract`).\n *\n * @default - Only the default tablet (`.jsii.tabl.json`) files will be used.\n */\n readonly tablet?: string;\n\n /**\n * A directory to output translated assemblies to\n *\n * @default - assembly location\n */\n readonly outdir?: string;\n\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.FAIL\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n}\n\n/**\n * Prepares transliterated versions of the designated assemblies into the\n * selected target languages.\n *\n * @param assemblyLocations the directories which contain assemblies to\n * transliterate.\n * @param targetLanguages the languages into which to transliterate.\n * @param tabletLocation an optional Rosetta tablet file to source\n * pre-transliterated snippets from.\n *\n * @experimental\n */\nexport async function transliterateAssembly(\n assemblyLocations: readonly string[],\n targetLanguages: readonly TargetLanguage[],\n options: TransliterateAssemblyOptions = {},\n): Promise<void> {\n // Start by doing an 'extract' for all these assemblies\n //\n // This will locate all examples that haven't been translated yet and translate\n // them. Importantly: it will translate them in parallel, which is going to improve\n // performance a lot. We ignore diagnostics.\n const { tablet } = await extractSnippets(assemblyLocations, {\n includeCompilerDiagnostics: true,\n loose: options.loose,\n cacheFromFile: options.tablet,\n writeToImplicitTablets: false,\n allowDirtyTranslations: true,\n });\n\n // Now do a regular \"tablet reader\" cycle, expecting everything to be translated already,\n // and therefore it doesn't matter that we do this all in a single-threaded loop.\n const rosetta = new RosettaTabletReader({\n unknownSnippets: options?.unknownSnippets ?? UnknownSnippetMode.FAIL,\n targetLanguages,\n prefixDisclaimer: true,\n });\n // Put in the same caching tablet here\n if (options.tablet) {\n await rosetta.loadTabletFromFile(options.tablet);\n }\n // Any fresh translations we just came up with\n rosetta.addTablet(tablet);\n\n const assemblies = await loadAssemblies(assemblyLocations, rosetta);\n\n for (const [location, loadAssembly] of assemblies.entries()) {\n for (const language of targetLanguages) {\n const now = new Date().getTime();\n const result = loadAssembly();\n\n if (result.targets?.[targetName(language)] == null) {\n // This language is not supported by the assembly, so we skip it...\n continue;\n }\n\n if (result.readme?.markdown) {\n result.readme.markdown = rosetta.translateSnippetsInMarkdown(\n { api: 'moduleReadme', moduleFqn: result.name },\n result.readme.markdown,\n language,\n true /* strict */,\n );\n }\n for (const type of Object.values(result.types ?? {})) {\n transliterateType(type, rosetta, language);\n }\n // eslint-disable-next-line no-await-in-loop\n await fs.writeFile(\n resolve(options?.outdir ?? location, `${SPEC_FILE_NAME}.${language}`),\n JSON.stringify(result, null, 2),\n );\n const then = new Date().getTime();\n debug(`Done transliterating ${result.name}@${result.version} to ${language} after ${then - now} milliseconds`);\n }\n }\n\n rosetta.printDiagnostics(process.stderr, process.stderr.isTTY);\n if (rosetta.hasErrors && options.strict) {\n throw new Error('Strict mode is enabled and some examples failed compilation!');\n }\n}\n\n/**\n * Given a set of directories containing `.jsii` assemblies, load all the\n * assemblies into the provided `Rosetta` instance and return a map of\n * directories to assembly-loading functions (the function re-loads the original\n * assembly from disk on each invocation).\n *\n * @param directories the assembly-containing directories to traverse.\n * @param rosetta the `Rosetta` instance in which to load assemblies.\n *\n * @returns a map of directories to a function that loads the `.jsii` assembly\n * contained therein from disk.\n */\nasync function loadAssemblies(\n directories: readonly string[],\n rosetta: RosettaTabletReader,\n): Promise<ReadonlyMap<string, AssemblyLoader>> {\n const result = new Map<string, AssemblyLoader>();\n\n for (const directory of directories) {\n const loader = () => loadAssemblyFromPath(directory, false, SUPPORTED_ASSEMBLY_FEATURES);\n // eslint-disable-next-line no-await-in-loop\n await rosetta.addAssembly(loader(), directory);\n result.set(directory, loader);\n }\n\n return result;\n}\n\ntype AssemblyLoader = () => Mutable<Assembly>;\n\nfunction transliterateType(type: Type, rosetta: RosettaTabletReader, language: TargetLanguage): void {\n transliterateDocs({ api: 'type', fqn: type.fqn }, type.docs);\n switch (type.kind) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore 7029\n case TypeKind.Class:\n if (type.initializer) {\n transliterateDocs({ api: 'initializer', fqn: type.fqn }, type.initializer.docs);\n }\n\n // fallthrough\n case TypeKind.Interface:\n for (const method of type.methods ?? []) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: method.name }, method.docs);\n for (const parameter of method.parameters ?? []) {\n transliterateDocs(\n { api: 'parameter', fqn: type.fqn, methodName: method.name, parameterName: parameter.name },\n parameter.docs,\n );\n }\n }\n for (const property of type.properties ?? []) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: property.name }, property.docs);\n }\n break;\n\n case TypeKind.Enum:\n for (const member of type.members) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: member.name }, member.docs);\n }\n break;\n\n default:\n throw new Error(`Unsupported type kind: ${(type as any).kind}`);\n }\n\n function transliterateDocs(api: ApiLocation, docs: Docs | undefined) {\n if (docs?.remarks) {\n docs.remarks = rosetta.translateSnippetsInMarkdown(api, docs.remarks, language, true /* strict */);\n }\n\n if (docs?.example) {\n const location = { api, field: { field: 'example' } } as const;\n const snippet = typeScriptSnippetFromVisibleSource(docs.example, location, true /* strict */);\n const translation = rosetta.translateSnippet(snippet, language);\n if (translation != null) {\n docs.example = translation.source;\n }\n }\n }\n}\n"]}
@@ -1,6 +1,15 @@
1
1
  import * as spec from '@jsii/spec';
2
2
  import { TypeScriptSnippet, ApiLocation } from '../snippet';
3
3
  import { LanguageTablet } from '../tablets/tablets';
4
+ /**
5
+ * The Assembly features jsii-rosetta supports
6
+ *
7
+ * In actual fact, Rosetta doesn't do much with the Assembly, just crawl all
8
+ * API documentations, so basically most new features would be supported... but
9
+ * we technically should advertise a known list here anyway since we don't
10
+ * know what future extension are going to be.
11
+ */
12
+ export declare const SUPPORTED_ASSEMBLY_FEATURES: spec.JsiiFeature[];
4
13
  /**
5
14
  * The JSDoc tag users can use to associate non-visible metadata with an example
6
15
  *
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EXAMPLE_METADATA_JSDOCTAG = void 0;
3
+ exports.EXAMPLE_METADATA_JSDOCTAG = exports.SUPPORTED_ASSEMBLY_FEATURES = void 0;
4
4
  exports.loadAssemblies = loadAssemblies;
5
5
  exports.loadAllDefaultTablets = loadAllDefaultTablets;
6
6
  exports.guessTabletLocation = guessTabletLocation;
@@ -21,6 +21,15 @@ const snippet_dependencies_1 = require("../snippet-dependencies");
21
21
  const strict_1 = require("../strict");
22
22
  const tablets_1 = require("../tablets/tablets");
23
23
  const util_1 = require("../util");
24
+ /**
25
+ * The Assembly features jsii-rosetta supports
26
+ *
27
+ * In actual fact, Rosetta doesn't do much with the Assembly, just crawl all
28
+ * API documentations, so basically most new features would be supported... but
29
+ * we technically should advertise a known list here anyway since we don't
30
+ * know what future extension are going to be.
31
+ */
32
+ exports.SUPPORTED_ASSEMBLY_FEATURES = ['intersection-types'];
24
33
  /**
25
34
  * The JSDoc tag users can use to associate non-visible metadata with an example
26
35
  *
@@ -48,7 +57,7 @@ function loadAssemblies(assemblyLocations, validateAssemblies) {
48
57
  }
49
58
  const directory = path.dirname(location);
50
59
  const pjLocation = path.join(directory, 'package.json');
51
- const assembly = (0, spec_1.loadAssemblyFromFile)(location, validateAssemblies);
60
+ const assembly = (0, spec_1.loadAssemblyFromFile)(location, validateAssemblies, exports.SUPPORTED_ASSEMBLY_FEATURES);
52
61
  const packageJson = fs.existsSync(pjLocation) ? JSON.parse(fs.readFileSync(pjLocation, 'utf-8')) : undefined;
53
62
  return { assembly, directory, packageJson };
54
63
  }
@@ -210,7 +219,7 @@ function findTypeLookupAssembly(startingDirectory) {
210
219
  function loadLookupAssembly(directory) {
211
220
  try {
212
221
  const packageJson = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf-8'));
213
- const assembly = (0, spec_1.loadAssemblyFromPath)(directory);
222
+ const assembly = (0, spec_1.loadAssemblyFromPath)(directory, false, exports.SUPPORTED_ASSEMBLY_FEATURES);
214
223
  const symbolIdMap = (0, util_1.mkDict)([
215
224
  ...Object.values(assembly.types ?? {}).map((type) => [type.symbolId ?? '', type.fqn]),
216
225
  ...Object.entries(assembly.submodules ?? {}).map(([fqn, mod]) => [mod.symbolId ?? '', fqn]),
@@ -1 +1 @@
1
- {"version":3,"file":"assemblies.js","sourceRoot":"","sources":["../../src/jsii/assemblies.ts"],"names":[],"mappings":";;;AAsDA,wCA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D,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,MAAM,CAAC,uBAAuB,EAAE,MAAM,IAAA,yDAAkC,EAAC,GAAG,CAAC,WAAW,EAAE,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;IAEjH,MAAM,CAAC,MAAM,CACX,uBAAuB,EACvB,IAAA,aAAM,EACJ,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,EAAE,WAAW,EAAE,mBAAmB,IAAI,EAAE,CAAC,CAAC,GAAG,CACzE,CAAC,CAAC,IAAI,EAAE,YAAY,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,YAAY,EAAE,CAAU,CAC9E,CACF,CACF,CAAC;IAEF,OAAO;QACL,GAAG,OAAO;QACV,uBAAuB;KACxB,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,QAAQ,CAAC,MAAsB;IACtC,OAAO,MAAM,CAAC,WAAW,EAAE,WAAW,EAAE,MAAM,IAAI,IAAA,2BAAkB,EAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACxF,CAAC","sourcesContent":["import { promises as fsPromises } from 'node:fs';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { loadAssemblyFromFile, loadAssemblyFromPath, findAssemblyFile } from '@jsii/spec';\nimport * as spec from '@jsii/spec';\nimport { fixturize } from '../fixtures';\nimport { extractTypescriptSnippetsFromMarkdown } from '../markdown/extract-snippets';\nimport {\n TypeScriptSnippet,\n updateParameters,\n SnippetParameters,\n ApiLocation,\n parseMetadataLine,\n CompilationDependency,\n INITIALIZER_METHOD_NAME,\n typeScriptSnippetFromVisibleSource,\n} from '../snippet';\nimport { resolveDependenciesFromPackageJson } from '../snippet-dependencies';\nimport { enforcesStrictMode } from '../strict';\nimport { LanguageTablet, DEFAULT_TABLET_NAME, DEFAULT_TABLET_NAME_COMPRESSED } from '../tablets/tablets';\nimport { fmap, mkDict, pathExists, sortBy } from '../util';\n\n/**\n * The JSDoc tag users can use to associate non-visible metadata with an example\n *\n * In a Markdown section, metadata goes after the code block fence, where it will\n * be attached to the example but invisible.\n *\n * ```ts metadata=goes here\n *\n * But in doc comments, '@example' already delineates the example, and any metadata\n * in there added by the '///' tags becomes part of the visible code (there is no\n * place to put hidden information).\n *\n * We introduce the '@exampleMetadata' tag to put that additional information.\n */\nexport const EXAMPLE_METADATA_JSDOCTAG = 'exampleMetadata';\n\ninterface RosettaPackageJson extends spec.PackageJson {\n readonly jsiiRosetta?: {\n readonly strict?: boolean;\n readonly exampleDependencies?: Record<string, string>;\n };\n}\n\nexport interface LoadedAssembly {\n readonly assembly: spec.Assembly;\n readonly directory: string;\n readonly packageJson?: RosettaPackageJson;\n}\n\n/**\n * Load assemblies by filename or directory\n */\nexport function loadAssemblies(\n assemblyLocations: readonly string[],\n validateAssemblies: boolean,\n): readonly LoadedAssembly[] {\n return assemblyLocations.map(loadAssembly);\n\n function loadAssembly(location: string): LoadedAssembly {\n const stat = fs.statSync(location);\n if (stat.isDirectory()) {\n return loadAssembly(findAssemblyFile(location));\n }\n\n const directory = path.dirname(location);\n const pjLocation = path.join(directory, 'package.json');\n\n const assembly = loadAssemblyFromFile(location, validateAssemblies);\n const packageJson = fs.existsSync(pjLocation) ? JSON.parse(fs.readFileSync(pjLocation, 'utf-8')) : undefined;\n\n return { assembly, directory, packageJson };\n }\n}\n\n/**\n * Load the default tablets for every assembly, if available\n *\n * Returns a map of { directory -> tablet }.\n */\nexport async function loadAllDefaultTablets(asms: readonly LoadedAssembly[]): Promise<Record<string, LanguageTablet>> {\n return mkDict(\n await Promise.all(\n asms.map(\n async (a) => [a.directory, await LanguageTablet.fromOptionalFile(guessTabletLocation(a.directory))] as const,\n ),\n ),\n );\n}\n\n/**\n * Returns the location of the tablet file, either .jsii.tabl.json or .jsii.tabl.json.gz.\n * Assumes that a tablet exists in the directory and if not, the ensuing behavior is\n * handled by the caller of this function.\n */\nexport function guessTabletLocation(directory: string) {\n return compressedTabletExists(directory)\n ? path.join(directory, DEFAULT_TABLET_NAME_COMPRESSED)\n : path.join(directory, DEFAULT_TABLET_NAME);\n}\n\nexport function compressedTabletExists(directory: string) {\n return fs.existsSync(path.join(directory, DEFAULT_TABLET_NAME_COMPRESSED));\n}\n\nexport type AssemblySnippetSource =\n | { type: 'markdown'; markdown: string; location: ApiLocation }\n | { type: 'example'; source: string; metadata?: { [key: string]: string }; location: ApiLocation };\n\n/**\n * Return all markdown and example snippets from the given assembly\n */\nexport function allSnippetSources(assembly: spec.Assembly): AssemblySnippetSource[] {\n const ret: AssemblySnippetSource[] = [];\n\n if (assembly.readme) {\n ret.push({\n type: 'markdown',\n markdown: assembly.readme.markdown,\n location: { api: 'moduleReadme', moduleFqn: assembly.name },\n });\n }\n\n for (const [submoduleFqn, submodule] of Object.entries(assembly.submodules ?? {})) {\n if (submodule.readme) {\n ret.push({\n type: 'markdown',\n markdown: submodule.readme.markdown,\n location: { api: 'moduleReadme', moduleFqn: submoduleFqn },\n });\n }\n }\n\n if (assembly.types) {\n for (const type of Object.values(assembly.types)) {\n emitDocs(type.docs, { api: 'type', fqn: type.fqn });\n\n if (spec.isEnumType(type)) {\n for (const m of type.members) emitDocs(m.docs, { api: 'member', fqn: type.fqn, memberName: m.name });\n }\n if (spec.isClassType(type)) {\n emitDocsForCallable(type.initializer, type.fqn);\n }\n if (spec.isClassOrInterfaceType(type)) {\n for (const m of type.methods ?? []) emitDocsForCallable(m, type.fqn, m.name);\n for (const m of type.properties ?? []) emitDocs(m.docs, { api: 'member', fqn: type.fqn, memberName: m.name });\n }\n }\n }\n\n return ret;\n\n function emitDocsForCallable(callable: spec.Callable | undefined, fqn: string, memberName?: string) {\n if (!callable) {\n return;\n }\n emitDocs(callable.docs, memberName ? { api: 'member', fqn, memberName } : { api: 'initializer', fqn });\n\n for (const parameter of callable.parameters ?? []) {\n emitDocs(parameter.docs, {\n api: 'parameter',\n fqn: fqn,\n methodName: memberName ?? INITIALIZER_METHOD_NAME,\n parameterName: parameter.name,\n });\n }\n }\n\n function emitDocs(docs: spec.Docs | undefined, location: ApiLocation) {\n if (!docs) {\n return;\n }\n\n if (docs.remarks) {\n ret.push({\n type: 'markdown',\n markdown: docs.remarks,\n location,\n });\n }\n if (docs.example) {\n ret.push({\n type: 'example',\n source: docs.example,\n metadata: fmap(docs.custom?.[EXAMPLE_METADATA_JSDOCTAG], parseMetadataLine),\n location,\n });\n }\n }\n}\n\nexport async function allTypeScriptSnippets(\n assemblies: readonly LoadedAssembly[],\n loose = false,\n): Promise<TypeScriptSnippet[]> {\n const sources = assemblies\n .flatMap((loaded) => allSnippetSources(loaded.assembly).map((source) => ({ source, loaded })))\n .flatMap(({ source, loaded }) => {\n switch (source.type) {\n case 'example':\n return [\n {\n snippet: updateParameters(\n typeScriptSnippetFromVisibleSource(\n source.source,\n { api: source.location, field: { field: 'example' } },\n isStrict(loaded),\n ),\n source.metadata ?? {},\n ),\n loaded,\n },\n ];\n case 'markdown':\n return extractTypescriptSnippetsFromMarkdown(source.markdown, source.location, isStrict(loaded)).map(\n (snippet) => ({ snippet, loaded }),\n );\n }\n });\n\n const fixtures = [];\n for (let { snippet, loaded } of sources) {\n const isInfused = snippet.parameters?.infused != null;\n\n // Ignore fixturization errors if requested on this command, or if the snippet was infused\n const ignoreFixtureErrors = loose || isInfused;\n\n // Also if the snippet was infused: switch off 'strict' mode if it was set\n if (isInfused) {\n snippet = { ...snippet, strict: false };\n }\n\n snippet = await withDependencies(loaded, withProjectDirectory(loaded.directory, snippet));\n fixtures.push(fixturize(snippet, ignoreFixtureErrors));\n }\n\n return fixtures;\n}\n\nexport interface TypeLookupAssembly {\n readonly packageJson: any;\n readonly assembly: spec.Assembly;\n readonly directory: string;\n readonly symbolIdMap: Record<string, string>;\n}\n\nconst MAX_ASM_CACHE = 3;\nconst ASM_CACHE: TypeLookupAssembly[] = [];\n\n/**\n * Recursively searches for a .jsii file in the directory.\n * When file is found, checks cache to see if we already\n * stored the assembly in memory. If not, we synchronously\n * load the assembly into memory.\n */\nexport function findTypeLookupAssembly(startingDirectory: string): TypeLookupAssembly | undefined {\n const pjLocation = findPackageJsonLocation(path.resolve(startingDirectory));\n if (!pjLocation) {\n return undefined;\n }\n const directory = path.dirname(pjLocation);\n\n const fromCache = ASM_CACHE.find((c) => c.directory === directory);\n if (fromCache) {\n return fromCache;\n }\n\n const loaded = loadLookupAssembly(directory);\n if (!loaded) {\n return undefined;\n }\n\n while (ASM_CACHE.length >= MAX_ASM_CACHE) {\n ASM_CACHE.pop();\n }\n ASM_CACHE.unshift(loaded);\n return loaded;\n}\n\nfunction loadLookupAssembly(directory: string): TypeLookupAssembly | undefined {\n try {\n const packageJson = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf-8'));\n const assembly: spec.Assembly = loadAssemblyFromPath(directory);\n const symbolIdMap = mkDict([\n ...Object.values(assembly.types ?? {}).map((type) => [type.symbolId ?? '', type.fqn] as const),\n ...Object.entries(assembly.submodules ?? {}).map(([fqn, mod]) => [mod.symbolId ?? '', fqn] as const),\n ]);\n\n return {\n packageJson,\n assembly,\n directory,\n symbolIdMap,\n };\n } catch {\n return undefined;\n }\n}\n\nfunction findPackageJsonLocation(currentPath: string): string | undefined {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const candidate = path.join(currentPath, 'package.json');\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n\n const parentPath = path.resolve(currentPath, '..');\n if (parentPath === currentPath) {\n return undefined;\n }\n currentPath = parentPath;\n }\n}\n\n/**\n * Find the jsii [sub]module that contains the given FQN\n *\n * @returns `undefined` if the type is a member of the assembly root.\n */\nexport function findContainingSubmodule(assembly: spec.Assembly, fqn: string): string | undefined {\n const submoduleNames = Object.keys(assembly.submodules ?? {});\n sortBy(submoduleNames, (s) => [-s.length]); // Longest first\n for (const s of submoduleNames) {\n if (fqn.startsWith(`${s}.`)) {\n return s;\n }\n }\n return undefined;\n}\n\nfunction withProjectDirectory(dir: string, snippet: TypeScriptSnippet) {\n return updateParameters(snippet, {\n [SnippetParameters.$PROJECT_DIRECTORY]: dir,\n });\n}\n\n/**\n * Return a TypeScript snippet with dependencies added\n *\n * The dependencies will be taken from the package.json, and will consist of:\n *\n * - The package itself\n * - The package's dependencies and peerDependencies (but NOT devDependencies). Will\n * symlink to the files on disk.\n * - Any additional dependencies declared in `jsiiRosetta.exampleDependencies`.\n */\nasync function withDependencies(asm: LoadedAssembly, snippet: TypeScriptSnippet): Promise<TypeScriptSnippet> {\n const compilationDependencies: Record<string, CompilationDependency> = {};\n\n if (await pathExists(path.join(asm.directory, 'package.json'))) {\n compilationDependencies[asm.assembly.name] = {\n type: 'concrete',\n resolvedDirectory: await fsPromises.realpath(asm.directory),\n };\n }\n\n Object.assign(compilationDependencies, await resolveDependenciesFromPackageJson(asm.packageJson, asm.directory));\n\n Object.assign(\n compilationDependencies,\n mkDict(\n Object.entries(asm.packageJson?.jsiiRosetta?.exampleDependencies ?? {}).map(\n ([name, versionRange]) => [name, { type: 'symbolic', versionRange }] as const,\n ),\n ),\n );\n\n return {\n ...snippet,\n compilationDependencies,\n };\n}\n\n/**\n * Whether samples in the assembly should be treated as strict\n *\n * True if the strict flag is found in the package.json (modern) or the assembly itself (legacy).\n */\nfunction isStrict(loaded: LoadedAssembly) {\n return loaded.packageJson?.jsiiRosetta?.strict ?? enforcesStrictMode(loaded.assembly);\n}\n"]}
1
+ {"version":3,"file":"assemblies.js","sourceRoot":"","sources":["../../src/jsii/assemblies.ts"],"names":[],"mappings":";;;AAgEA,wCAoBC;AAOD,sDAQC;AAOD,kDAIC;AAED,wDAEC;AASD,8CA6EC;AAED,sDA8CC;AAkBD,wDAsBC;AA2CD,0DASC;AApVD,qCAAiD;AACjD,8BAA8B;AAC9B,kCAAkC;AAClC,qCAA0F;AAC1F,mCAAmC;AACnC,0CAAwC;AACxC,mEAAqF;AACrF,wCASoB;AACpB,kEAA6E;AAC7E,sCAA+C;AAC/C,gDAAyG;AACzG,kCAA2D;AAE3D;;;;;;;GA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,uBAAuB,EACvB,IAAA,aAAM,EACJ,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,EAAE,WAAW,EAAE,mBAAmB,IAAI,EAAE,CAAC,CAAC,GAAG,CACzE,CAAC,CAAC,IAAI,EAAE,YAAY,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,YAAY,EAAE,CAAU,CAC9E,CACF,CACF,CAAC;IAEF,OAAO;QACL,GAAG,OAAO;QACV,uBAAuB;KACxB,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,QAAQ,CAAC,MAAsB;IACtC,OAAO,MAAM,CAAC,WAAW,EAAE,WAAW,EAAE,MAAM,IAAI,IAAA,2BAAkB,EAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACxF,CAAC","sourcesContent":["import { promises as fsPromises } from 'node:fs';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { loadAssemblyFromFile, loadAssemblyFromPath, findAssemblyFile } from '@jsii/spec';\nimport * as spec from '@jsii/spec';\nimport { fixturize } from '../fixtures';\nimport { extractTypescriptSnippetsFromMarkdown } from '../markdown/extract-snippets';\nimport {\n TypeScriptSnippet,\n updateParameters,\n SnippetParameters,\n ApiLocation,\n parseMetadataLine,\n CompilationDependency,\n INITIALIZER_METHOD_NAME,\n typeScriptSnippetFromVisibleSource,\n} from '../snippet';\nimport { resolveDependenciesFromPackageJson } from '../snippet-dependencies';\nimport { enforcesStrictMode } from '../strict';\nimport { LanguageTablet, DEFAULT_TABLET_NAME, DEFAULT_TABLET_NAME_COMPRESSED } from '../tablets/tablets';\nimport { fmap, mkDict, pathExists, sortBy } from '../util';\n\n/**\n * The Assembly features jsii-rosetta supports\n *\n * In actual fact, Rosetta doesn't do much with the Assembly, just crawl all\n * API documentations, so basically most new features would be supported... but\n * we technically should advertise a known list here anyway since we don't\n * know what future extension are going to be.\n */\nexport const SUPPORTED_ASSEMBLY_FEATURES: spec.JsiiFeature[] = ['intersection-types'];\n\n/**\n * The JSDoc tag users can use to associate non-visible metadata with an example\n *\n * In a Markdown section, metadata goes after the code block fence, where it will\n * be attached to the example but invisible.\n *\n * ```ts metadata=goes here\n *\n * But in doc comments, '@example' already delineates the example, and any metadata\n * in there added by the '///' tags becomes part of the visible code (there is no\n * place to put hidden information).\n *\n * We introduce the '@exampleMetadata' tag to put that additional information.\n */\nexport const EXAMPLE_METADATA_JSDOCTAG = 'exampleMetadata';\n\ninterface RosettaPackageJson extends spec.PackageJson {\n readonly jsiiRosetta?: {\n readonly strict?: boolean;\n readonly exampleDependencies?: Record<string, string>;\n };\n}\n\nexport interface LoadedAssembly {\n readonly assembly: spec.Assembly;\n readonly directory: string;\n readonly packageJson?: RosettaPackageJson;\n}\n\n/**\n * Load assemblies by filename or directory\n */\nexport function loadAssemblies(\n assemblyLocations: readonly string[],\n validateAssemblies: boolean,\n): readonly LoadedAssembly[] {\n return assemblyLocations.map(loadAssembly);\n\n function loadAssembly(location: string): LoadedAssembly {\n const stat = fs.statSync(location);\n if (stat.isDirectory()) {\n return loadAssembly(findAssemblyFile(location));\n }\n\n const directory = path.dirname(location);\n const pjLocation = path.join(directory, 'package.json');\n\n const assembly = loadAssemblyFromFile(location, validateAssemblies, SUPPORTED_ASSEMBLY_FEATURES);\n const packageJson = fs.existsSync(pjLocation) ? JSON.parse(fs.readFileSync(pjLocation, 'utf-8')) : undefined;\n\n return { assembly, directory, packageJson };\n }\n}\n\n/**\n * Load the default tablets for every assembly, if available\n *\n * Returns a map of { directory -> tablet }.\n */\nexport async function loadAllDefaultTablets(asms: readonly LoadedAssembly[]): Promise<Record<string, LanguageTablet>> {\n return mkDict(\n await Promise.all(\n asms.map(\n async (a) => [a.directory, await LanguageTablet.fromOptionalFile(guessTabletLocation(a.directory))] as const,\n ),\n ),\n );\n}\n\n/**\n * Returns the location of the tablet file, either .jsii.tabl.json or .jsii.tabl.json.gz.\n * Assumes that a tablet exists in the directory and if not, the ensuing behavior is\n * handled by the caller of this function.\n */\nexport function guessTabletLocation(directory: string) {\n return compressedTabletExists(directory)\n ? path.join(directory, DEFAULT_TABLET_NAME_COMPRESSED)\n : path.join(directory, DEFAULT_TABLET_NAME);\n}\n\nexport function compressedTabletExists(directory: string) {\n return fs.existsSync(path.join(directory, DEFAULT_TABLET_NAME_COMPRESSED));\n}\n\nexport type AssemblySnippetSource =\n | { type: 'markdown'; markdown: string; location: ApiLocation }\n | { type: 'example'; source: string; metadata?: { [key: string]: string }; location: ApiLocation };\n\n/**\n * Return all markdown and example snippets from the given assembly\n */\nexport function allSnippetSources(assembly: spec.Assembly): AssemblySnippetSource[] {\n const ret: AssemblySnippetSource[] = [];\n\n if (assembly.readme) {\n ret.push({\n type: 'markdown',\n markdown: assembly.readme.markdown,\n location: { api: 'moduleReadme', moduleFqn: assembly.name },\n });\n }\n\n for (const [submoduleFqn, submodule] of Object.entries(assembly.submodules ?? {})) {\n if (submodule.readme) {\n ret.push({\n type: 'markdown',\n markdown: submodule.readme.markdown,\n location: { api: 'moduleReadme', moduleFqn: submoduleFqn },\n });\n }\n }\n\n if (assembly.types) {\n for (const type of Object.values(assembly.types)) {\n emitDocs(type.docs, { api: 'type', fqn: type.fqn });\n\n if (spec.isEnumType(type)) {\n for (const m of type.members) emitDocs(m.docs, { api: 'member', fqn: type.fqn, memberName: m.name });\n }\n if (spec.isClassType(type)) {\n emitDocsForCallable(type.initializer, type.fqn);\n }\n if (spec.isClassOrInterfaceType(type)) {\n for (const m of type.methods ?? []) emitDocsForCallable(m, type.fqn, m.name);\n for (const m of type.properties ?? []) emitDocs(m.docs, { api: 'member', fqn: type.fqn, memberName: m.name });\n }\n }\n }\n\n return ret;\n\n function emitDocsForCallable(callable: spec.Callable | undefined, fqn: string, memberName?: string) {\n if (!callable) {\n return;\n }\n emitDocs(callable.docs, memberName ? { api: 'member', fqn, memberName } : { api: 'initializer', fqn });\n\n for (const parameter of callable.parameters ?? []) {\n emitDocs(parameter.docs, {\n api: 'parameter',\n fqn: fqn,\n methodName: memberName ?? INITIALIZER_METHOD_NAME,\n parameterName: parameter.name,\n });\n }\n }\n\n function emitDocs(docs: spec.Docs | undefined, location: ApiLocation) {\n if (!docs) {\n return;\n }\n\n if (docs.remarks) {\n ret.push({\n type: 'markdown',\n markdown: docs.remarks,\n location,\n });\n }\n if (docs.example) {\n ret.push({\n type: 'example',\n source: docs.example,\n metadata: fmap(docs.custom?.[EXAMPLE_METADATA_JSDOCTAG], parseMetadataLine),\n location,\n });\n }\n }\n}\n\nexport async function allTypeScriptSnippets(\n assemblies: readonly LoadedAssembly[],\n loose = false,\n): Promise<TypeScriptSnippet[]> {\n const sources = assemblies\n .flatMap((loaded) => allSnippetSources(loaded.assembly).map((source) => ({ source, loaded })))\n .flatMap(({ source, loaded }) => {\n switch (source.type) {\n case 'example':\n return [\n {\n snippet: updateParameters(\n typeScriptSnippetFromVisibleSource(\n source.source,\n { api: source.location, field: { field: 'example' } },\n isStrict(loaded),\n ),\n source.metadata ?? {},\n ),\n loaded,\n },\n ];\n case 'markdown':\n return extractTypescriptSnippetsFromMarkdown(source.markdown, source.location, isStrict(loaded)).map(\n (snippet) => ({ snippet, loaded }),\n );\n }\n });\n\n const fixtures = [];\n for (let { snippet, loaded } of sources) {\n const isInfused = snippet.parameters?.infused != null;\n\n // Ignore fixturization errors if requested on this command, or if the snippet was infused\n const ignoreFixtureErrors = loose || isInfused;\n\n // Also if the snippet was infused: switch off 'strict' mode if it was set\n if (isInfused) {\n snippet = { ...snippet, strict: false };\n }\n\n snippet = await withDependencies(loaded, withProjectDirectory(loaded.directory, snippet));\n fixtures.push(fixturize(snippet, ignoreFixtureErrors));\n }\n\n return fixtures;\n}\n\nexport interface TypeLookupAssembly {\n readonly packageJson: any;\n readonly assembly: spec.Assembly;\n readonly directory: string;\n readonly symbolIdMap: Record<string, string>;\n}\n\nconst MAX_ASM_CACHE = 3;\nconst ASM_CACHE: TypeLookupAssembly[] = [];\n\n/**\n * Recursively searches for a .jsii file in the directory.\n * When file is found, checks cache to see if we already\n * stored the assembly in memory. If not, we synchronously\n * load the assembly into memory.\n */\nexport function findTypeLookupAssembly(startingDirectory: string): TypeLookupAssembly | undefined {\n const pjLocation = findPackageJsonLocation(path.resolve(startingDirectory));\n if (!pjLocation) {\n return undefined;\n }\n const directory = path.dirname(pjLocation);\n\n const fromCache = ASM_CACHE.find((c) => c.directory === directory);\n if (fromCache) {\n return fromCache;\n }\n\n const loaded = loadLookupAssembly(directory);\n if (!loaded) {\n return undefined;\n }\n\n while (ASM_CACHE.length >= MAX_ASM_CACHE) {\n ASM_CACHE.pop();\n }\n ASM_CACHE.unshift(loaded);\n return loaded;\n}\n\nfunction loadLookupAssembly(directory: string): TypeLookupAssembly | undefined {\n try {\n const packageJson = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf-8'));\n const assembly: spec.Assembly = loadAssemblyFromPath(directory, false, SUPPORTED_ASSEMBLY_FEATURES);\n const symbolIdMap = mkDict([\n ...Object.values(assembly.types ?? {}).map((type) => [type.symbolId ?? '', type.fqn] as const),\n ...Object.entries(assembly.submodules ?? {}).map(([fqn, mod]) => [mod.symbolId ?? '', fqn] as const),\n ]);\n\n return {\n packageJson,\n assembly,\n directory,\n symbolIdMap,\n };\n } catch {\n return undefined;\n }\n}\n\nfunction findPackageJsonLocation(currentPath: string): string | undefined {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const candidate = path.join(currentPath, 'package.json');\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n\n const parentPath = path.resolve(currentPath, '..');\n if (parentPath === currentPath) {\n return undefined;\n }\n currentPath = parentPath;\n }\n}\n\n/**\n * Find the jsii [sub]module that contains the given FQN\n *\n * @returns `undefined` if the type is a member of the assembly root.\n */\nexport function findContainingSubmodule(assembly: spec.Assembly, fqn: string): string | undefined {\n const submoduleNames = Object.keys(assembly.submodules ?? {});\n sortBy(submoduleNames, (s) => [-s.length]); // Longest first\n for (const s of submoduleNames) {\n if (fqn.startsWith(`${s}.`)) {\n return s;\n }\n }\n return undefined;\n}\n\nfunction withProjectDirectory(dir: string, snippet: TypeScriptSnippet) {\n return updateParameters(snippet, {\n [SnippetParameters.$PROJECT_DIRECTORY]: dir,\n });\n}\n\n/**\n * Return a TypeScript snippet with dependencies added\n *\n * The dependencies will be taken from the package.json, and will consist of:\n *\n * - The package itself\n * - The package's dependencies and peerDependencies (but NOT devDependencies). Will\n * symlink to the files on disk.\n * - Any additional dependencies declared in `jsiiRosetta.exampleDependencies`.\n */\nasync function withDependencies(asm: LoadedAssembly, snippet: TypeScriptSnippet): Promise<TypeScriptSnippet> {\n const compilationDependencies: Record<string, CompilationDependency> = {};\n\n if (await pathExists(path.join(asm.directory, 'package.json'))) {\n compilationDependencies[asm.assembly.name] = {\n type: 'concrete',\n resolvedDirectory: await fsPromises.realpath(asm.directory),\n };\n }\n\n Object.assign(compilationDependencies, await resolveDependenciesFromPackageJson(asm.packageJson, asm.directory));\n\n Object.assign(\n compilationDependencies,\n mkDict(\n Object.entries(asm.packageJson?.jsiiRosetta?.exampleDependencies ?? {}).map(\n ([name, versionRange]) => [name, { type: 'symbolic', versionRange }] as const,\n ),\n ),\n );\n\n return {\n ...snippet,\n compilationDependencies,\n };\n}\n\n/**\n * Whether samples in the assembly should be treated as strict\n *\n * True if the strict flag is found in the package.json (modern) or the assembly itself (legacy).\n */\nfunction isStrict(loaded: LoadedAssembly) {\n return loaded.packageJson?.jsiiRosetta?.strict ?? enforcesStrictMode(loaded.assembly);\n}\n"]}
@@ -62,6 +62,10 @@ export interface RosettaOptions {
62
62
  */
63
63
  export declare class RosettaTabletReader {
64
64
  private readonly options;
65
+ /**
66
+ * The assembly features that the current version of `jsii-rosetta` supports.
67
+ */
68
+ static get supportedAssemblyFeatures(): spec.JsiiFeature[];
65
69
  /**
66
70
  * Newly translated samples
67
71
  *
@@ -39,6 +39,12 @@ var UnknownSnippetMode;
39
39
  * when the second one is not necessary.
40
40
  */
41
41
  class RosettaTabletReader {
42
+ /**
43
+ * The assembly features that the current version of `jsii-rosetta` supports.
44
+ */
45
+ static get supportedAssemblyFeatures() {
46
+ return assemblies_1.SUPPORTED_ASSEMBLY_FEATURES;
47
+ }
42
48
  constructor(options = {}) {
43
49
  this.options = options;
44
50
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"rosetta-reader.js","sourceRoot":"","sources":["../src/rosetta-reader.ts"],"names":[],"mappings":";;;AAEA,kDAA+E;AAE/E,qCAAqC;AACrC,kDAAwD;AACxD,oEAAgE;AAChE,0FAAqF;AAErF,uCAMmB;AACnB,uCAA2C;AAC3C,+CAAgE;AAChE,2CAAyC;AACzC,iCAAoE;AAEpE,IAAY,kBAeX;AAfD,WAAY,kBAAkB;IAC5B;;OAEG;IACH,2CAAqB,CAAA;IAErB;;OAEG;IACH,6CAAuB,CAAA;IAEvB;;OAEG;IACH,mCAAa,CAAA;AACf,CAAC,EAfW,kBAAkB,kCAAlB,kBAAkB,QAe7B;AAsCD;;;;;;;;;;;GAWG;AACH,MAAa,mBAAmB;IAgB9B,YAAoC,UAA0B,EAAE;QAA5B,YAAO,GAAP,OAAO,CAAqB;QAfhE;;;;;WAKG;QACa,eAAU,GAAG,IAAI,wBAAc,EAAE,CAAC;QAEjC,kBAAa,GAAqB,EAAE,CAAC;QACrC,sBAAiB,GAAG,IAAI,GAAG,EAA6B,CAAC;QAOxE,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC;QAC7B,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,IAAI,kBAAkB,CAAC,QAAQ,CAAC;QAC9E,IAAI,CAAC,UAAU,GAAG,IAAI,sBAAU,CAAC,OAAO,CAAC,0BAA0B,IAAI,KAAK,CAAC,CAAC;QAC9E,IAAI,CAAC,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,IAAI,KAAK,CAAC;IAC7D,CAAC;IAED;;OAEG;IACH,IAAW,WAAW;QACpB,OAAO,IAAI,CAAC,UAAU,CAAC,WAAW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G,IAAA,mBAAY,EAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QACnD,MAAM,UAAU,GAAG,gFAAgF,CAAC;QACpG,OAAO;YACL,GAAG,WAAW;YACd,MAAM,EAAE,GAAG,OAAO,IAAI,UAAU,KAAK,WAAW,CAAC,MAAM,EAAE;SAC1D,CAAC;IACJ,CAAC;CACF;AA5OD,kDA4OC;AAED,SAAS,EAAE,CAAC,CAAc;IACxB,OAAO,CAAC,CAAC;AACX,CAAC;AAED;;;;GAIG;AACH,MAAa,OAAQ,SAAQ,mBAAmB;CAAG;AAAnD,0BAAmD","sourcesContent":["import * as spec from '@jsii/spec';\n\nimport { allTypeScriptSnippets, guessTabletLocation } from './jsii/assemblies';\nimport { TargetLanguage } from './languages';\nimport * as logging from './logging';\nimport { transformMarkdown } from './markdown/markdown';\nimport { MarkdownRenderer } from './markdown/markdown-renderer';\nimport { ReplaceTypeScriptTransform } from './markdown/replace-typescript-transform';\nimport { CodeBlock } from './markdown/types';\nimport {\n SnippetParameters,\n TypeScriptSnippet,\n updateParameters,\n ApiLocation,\n typeScriptSnippetFromSource,\n} from './snippet';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, Translation } from './tablets/tablets';\nimport { Translator } from './translate';\nimport { commentToken, pathExists, printDiagnostics } from './util';\n\nexport enum UnknownSnippetMode {\n /**\n * Return the snippet as given (untranslated)\n */\n VERBATIM = 'verbatim',\n\n /**\n * Live-translate the snippet as best as we can\n */\n TRANSLATE = 'translate',\n\n /**\n * Throw an error if this occurs\n */\n FAIL = 'fail',\n}\n\nexport interface RosettaOptions {\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.VERBATIM\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n\n /**\n * Target languages to use for live conversion\n *\n * @default All languages\n */\n readonly targetLanguages?: readonly TargetLanguage[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Whether this Rosetta should operate in \"loose\" mode, where missing literate\n * source files and missing fixtures are ignored instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Adds a disclaimer to start of snippet if it did not compile.\n *\n * @default false\n */\n readonly prefixDisclaimer?: boolean;\n}\n\n/**\n * Entry point class for consumers of Rosetta tablets (primarily: pacmak)\n *\n * Rosetta can work in one of two modes:\n *\n * 1. Live translation of snippets.\n * 2. Read translations from a pre-translated tablet (prepared using `jsii-rosetta extract` command).\n *\n * The second method affords more control over the precise circumstances of\n * sample compilation and is recommended, but the first method will do\n * when the second one is not necessary.\n */\nexport class RosettaTabletReader {\n /**\n * Newly translated samples\n *\n * In case live translation has been enabled, all samples that have been translated on-the-fly\n * are added to this tablet.\n */\n public readonly liveTablet = new LanguageTablet();\n\n private readonly loadedTablets: LanguageTablet[] = [];\n private readonly extractedSnippets = new Map<string, TypeScriptSnippet>();\n private readonly translator: Translator;\n private readonly loose: boolean;\n private readonly unknownSnippets: UnknownSnippetMode;\n private readonly _prefixDisclaimer: boolean;\n\n public constructor(private readonly options: RosettaOptions = {}) {\n this.loose = !!options.loose;\n this.unknownSnippets = options.unknownSnippets ?? UnknownSnippetMode.VERBATIM;\n this.translator = new Translator(options.includeCompilerDiagnostics ?? false);\n this._prefixDisclaimer = options.prefixDisclaimer ?? false;\n }\n\n /**\n * Diagnostics encountered while doing live translation\n */\n public get diagnostics() {\n return this.translator.diagnostics;\n }\n\n /**\n * Load a tablet as a source for translateable snippets\n *\n * Note: the snippets loaded from this tablet will NOT be validated for\n * their fingerprints or translator versions! If a matching snippet is found\n * in the tablet, it will always be returned, whether or not it is stale.\n */\n public async loadTabletFromFile(tabletFile: string) {\n const tablet = new LanguageTablet();\n await tablet.load(tabletFile);\n this.addTablet(tablet);\n }\n\n /**\n * Directly add a tablet to the list of tablets to load translations from\n */\n public addTablet(tablet: LanguageTablet) {\n this.loadedTablets.push(tablet);\n }\n\n /**\n * Add an assembly\n *\n * If a default tablet file is found in the assembly's directory, it will be\n * loaded (and assumed to contain a complete list of translated snippets for\n * this assembly already).\n *\n * Otherwise, if live conversion is enabled, the snippets in the assembly\n * become available for live translation later. This is necessary because we probably\n * need to fixturize snippets for successful compilation, and the information\n * pacmak sends our way later on is not going to be enough to do that.\n */\n public async addAssembly(assembly: spec.Assembly, assemblyDir: string) {\n const defaultTablet = guessTabletLocation(assemblyDir);\n if (await pathExists(defaultTablet)) {\n try {\n await this.loadTabletFromFile(defaultTablet);\n return;\n } catch (e: any) {\n logging.warn(`Error loading ${defaultTablet}: ${e.message}. Skipped.`);\n }\n }\n\n // Inventarize the snippets from this assembly, but only if there's a chance\n // we're going to need them.\n if (this.unknownSnippets === UnknownSnippetMode.TRANSLATE) {\n for (const tsnip of await allTypeScriptSnippets([{ assembly, directory: assemblyDir }], this.loose)) {\n this.extractedSnippets.set(snippetKey(tsnip), tsnip);\n }\n }\n }\n\n /**\n * Translate the given snippet for the given target language\n *\n * This will either:\n *\n * - Find an existing translation in a tablet and return that, if available.\n * - Otherwise, find a fixturized version of this snippet in an assembly that\n * was loaded beforehand, and translate it on-the-fly. Finding the fixture\n * will be based on the snippet key, which consists of a hash of the\n * visible source and the API location.\n * - Otherwise, translate the snippet as-is (without fixture information).\n *\n * This will do and store a full conversion of the given snippet, even if it only\n * returns one language. Subsequent retrievals for the same snippet in other\n * languages will reuse the translation from cache.\n *\n * If you are calling this for the side effect of adding translations to the live\n * tablet, you only need to do that for one language.\n */\n public translateSnippet(source: TypeScriptSnippet, targetLang: TargetLanguage): Translation | undefined {\n // Look for it in loaded tablets (or previous conversions)\n for (const tab of this.allTablets) {\n const ret = tab.lookup(source, targetLang);\n if (ret !== undefined) {\n return this.prefixDisclaimer(ret, this._prefixDisclaimer);\n }\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.VERBATIM) {\n return this.prefixDisclaimer(\n {\n language: targetLang,\n source: source.visibleSource,\n },\n this._prefixDisclaimer,\n );\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.FAIL) {\n const message = [\n 'The following snippet was not found in any of the loaded tablets:',\n source.visibleSource,\n `Location: ${JSON.stringify(source.location)}`,\n `Language: ${targetLang}`,\n ].join('\\n');\n throw new Error(message);\n }\n\n if (this.options.targetLanguages && !this.options.targetLanguages.includes(targetLang)) {\n throw new Error(\n `Rosetta configured for live conversion to ${this.options.targetLanguages.join(\n ', ',\n )}, but requested ${targetLang}`,\n );\n }\n\n // See if we can find a fixturized version of this snippet. If so, use that do the live\n // conversion.\n const extracted = this.extractedSnippets.get(snippetKey(source));\n if (extracted !== undefined) {\n const snippet = this.translator.translate(extracted, this.options.targetLanguages);\n this.liveTablet.addSnippet(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n // Try to live-convert it as-is.\n const snippet = this.translator.translate(source, this.options.targetLanguages);\n this.liveTablet.addSnippet(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n /**\n * Translate a snippet found in the \"@ example\" section of a jsii assembly\n *\n * Behaves exactly like `translateSnippet`, so see that method for documentation.\n */\n public translateExample(\n apiLocation: ApiLocation,\n example: string,\n targetLang: TargetLanguage,\n strict: boolean,\n compileDirectory = process.cwd(),\n ): Translation {\n const location = { api: apiLocation, field: { field: 'example' } } as const;\n\n const snippet = typeScriptSnippetFromSource(example, location, strict, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n });\n\n const translated = this.translateSnippet(snippet, targetLang);\n\n return translated ?? { language: 'typescript', source: example };\n }\n\n /**\n * Translate all TypeScript snippets found in a block of Markdown text\n *\n * For each snippet, behaves exactly like `translateSnippet`, so see that\n * method for documentation.\n */\n public translateSnippetsInMarkdown(\n apiLocation: ApiLocation,\n markdown: string,\n targetLang: TargetLanguage,\n strict: boolean,\n translationToCodeBlock: (x: Translation) => CodeBlock = id,\n compileDirectory = process.cwd(),\n ): string {\n return transformMarkdown(\n markdown,\n new MarkdownRenderer(),\n new ReplaceTypeScriptTransform(apiLocation, strict, (tsSnip) => {\n const translated = this.translateSnippet(\n updateParameters(tsSnip, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n }),\n targetLang,\n );\n if (!translated) {\n return undefined;\n }\n\n return translationToCodeBlock(translated);\n }),\n );\n }\n\n public printDiagnostics(stream: NodeJS.WritableStream, colors = true) {\n printDiagnostics(this.diagnostics, stream, colors);\n }\n\n public get hasErrors() {\n return this.diagnostics.some((d) => d.isError);\n }\n\n private get allTablets(): LanguageTablet[] {\n return [...this.loadedTablets, this.liveTablet];\n }\n\n /**\n * Adds a disclaimer to the front of the example if the prefixDisclaimer\n * flag is set and we know it does not compile.\n */\n private prefixDisclaimer(translation: Translation | undefined, prefixDisclaimer: boolean): Translation | undefined {\n if (!prefixDisclaimer || translation?.didCompile !== false) {\n return translation;\n }\n const comment = commentToken(translation.language);\n const disclaimer = 'Example automatically generated from non-compiling source. May contain errors.';\n return {\n ...translation,\n source: `${comment} ${disclaimer}\\n${translation.source}`,\n };\n }\n}\n\nfunction id(x: Translation) {\n return x;\n}\n\n/**\n * Backwards compatibility\n *\n * @deprecated use RosettaTabletReader instead\n */\nexport class Rosetta extends RosettaTabletReader {}\n"]}
1
+ {"version":3,"file":"rosetta-reader.js","sourceRoot":"","sources":["../src/rosetta-reader.ts"],"names":[],"mappings":";;;AAEA,kDAA4G;AAE5G,qCAAqC;AACrC,kDAAwD;AACxD,oEAAgE;AAChE,0FAAqF;AAErF,uCAMmB;AACnB,uCAA2C;AAC3C,+CAAgE;AAChE,2CAAyC;AACzC,iCAAoE;AAEpE,IAAY,kBAeX;AAfD,WAAY,kBAAkB;IAC5B;;OAEG;IACH,2CAAqB,CAAA;IAErB;;OAEG;IACH,6CAAuB,CAAA;IAEvB;;OAEG;IACH,mCAAa,CAAA;AACf,CAAC,EAfW,kBAAkB,kCAAlB,kBAAkB,QAe7B;AAsCD;;;;;;;;;;;GAWG;AACH,MAAa,mBAAmB;IAC9B;;OAEG;IACI,MAAM,KAAK,yBAAyB;QACz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UAAU,CAAC,CAAC;QAC5C,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;IAEM,gBAAgB,CAAC,MAA6B,EAAE,MAAM,GAAG,IAAI;QAClE,IAAA,uBAAgB,EAAC,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACrD,CAAC;IAED,IAAW,SAAS;QAClB,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IACjD,CAAC;IAED,IAAY,UAAU;QACpB,OAAO,CAAC,GAAG,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAClD,CAAC;IAED;;;OAGG;IACK,gBAAgB,CAAC,WAAoC,EAAE,gBAAyB;QACtF,IAAI,CAAC,gBAAgB,IAAI,WAAW,EAAE,UAAU,KAAK,KAAK,EAAE,CAAC;YAC3D,OAAO,WAAW,CAAC;QACrB,CAAC;QACD,MAAM,OAAO,GAAG,IAAA,mBAAY,EAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QACnD,MAAM,UAAU,GAAG,gFAAgF,CAAC;QACpG,OAAO;YACL,GAAG,WAAW;YACd,MAAM,EAAE,GAAG,OAAO,IAAI,UAAU,KAAK,WAAW,CAAC,MAAM,EAAE;SAC1D,CAAC;IACJ,CAAC;CACF;AAnPD,kDAmPC;AAED,SAAS,EAAE,CAAC,CAAc;IACxB,OAAO,CAAC,CAAC;AACX,CAAC;AAED;;;;GAIG;AACH,MAAa,OAAQ,SAAQ,mBAAmB;CAAG;AAAnD,0BAAmD","sourcesContent":["import * as spec from '@jsii/spec';\n\nimport { allTypeScriptSnippets, guessTabletLocation, SUPPORTED_ASSEMBLY_FEATURES } from './jsii/assemblies';\nimport { TargetLanguage } from './languages';\nimport * as logging from './logging';\nimport { transformMarkdown } from './markdown/markdown';\nimport { MarkdownRenderer } from './markdown/markdown-renderer';\nimport { ReplaceTypeScriptTransform } from './markdown/replace-typescript-transform';\nimport { CodeBlock } from './markdown/types';\nimport {\n SnippetParameters,\n TypeScriptSnippet,\n updateParameters,\n ApiLocation,\n typeScriptSnippetFromSource,\n} from './snippet';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, Translation } from './tablets/tablets';\nimport { Translator } from './translate';\nimport { commentToken, pathExists, printDiagnostics } from './util';\n\nexport enum UnknownSnippetMode {\n /**\n * Return the snippet as given (untranslated)\n */\n VERBATIM = 'verbatim',\n\n /**\n * Live-translate the snippet as best as we can\n */\n TRANSLATE = 'translate',\n\n /**\n * Throw an error if this occurs\n */\n FAIL = 'fail',\n}\n\nexport interface RosettaOptions {\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.VERBATIM\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n\n /**\n * Target languages to use for live conversion\n *\n * @default All languages\n */\n readonly targetLanguages?: readonly TargetLanguage[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Whether this Rosetta should operate in \"loose\" mode, where missing literate\n * source files and missing fixtures are ignored instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Adds a disclaimer to start of snippet if it did not compile.\n *\n * @default false\n */\n readonly prefixDisclaimer?: boolean;\n}\n\n/**\n * Entry point class for consumers of Rosetta tablets (primarily: pacmak)\n *\n * Rosetta can work in one of two modes:\n *\n * 1. Live translation of snippets.\n * 2. Read translations from a pre-translated tablet (prepared using `jsii-rosetta extract` command).\n *\n * The second method affords more control over the precise circumstances of\n * sample compilation and is recommended, but the first method will do\n * when the second one is not necessary.\n */\nexport class RosettaTabletReader {\n /**\n * The assembly features that the current version of `jsii-rosetta` supports.\n */\n public static get supportedAssemblyFeatures(): spec.JsiiFeature[] {\n return SUPPORTED_ASSEMBLY_FEATURES;\n }\n\n /**\n * Newly translated samples\n *\n * In case live translation has been enabled, all samples that have been translated on-the-fly\n * are added to this tablet.\n */\n public readonly liveTablet = new LanguageTablet();\n\n private readonly loadedTablets: LanguageTablet[] = [];\n private readonly extractedSnippets = new Map<string, TypeScriptSnippet>();\n private readonly translator: Translator;\n private readonly loose: boolean;\n private readonly unknownSnippets: UnknownSnippetMode;\n private readonly _prefixDisclaimer: boolean;\n\n public constructor(private readonly options: RosettaOptions = {}) {\n this.loose = !!options.loose;\n this.unknownSnippets = options.unknownSnippets ?? UnknownSnippetMode.VERBATIM;\n this.translator = new Translator(options.includeCompilerDiagnostics ?? false);\n this._prefixDisclaimer = options.prefixDisclaimer ?? false;\n }\n\n /**\n * Diagnostics encountered while doing live translation\n */\n public get diagnostics() {\n return this.translator.diagnostics;\n }\n\n /**\n * Load a tablet as a source for translateable snippets\n *\n * Note: the snippets loaded from this tablet will NOT be validated for\n * their fingerprints or translator versions! If a matching snippet is found\n * in the tablet, it will always be returned, whether or not it is stale.\n */\n public async loadTabletFromFile(tabletFile: string) {\n const tablet = new LanguageTablet();\n await tablet.load(tabletFile);\n this.addTablet(tablet);\n }\n\n /**\n * Directly add a tablet to the list of tablets to load translations from\n */\n public addTablet(tablet: LanguageTablet) {\n this.loadedTablets.push(tablet);\n }\n\n /**\n * Add an assembly\n *\n * If a default tablet file is found in the assembly's directory, it will be\n * loaded (and assumed to contain a complete list of translated snippets for\n * this assembly already).\n *\n * Otherwise, if live conversion is enabled, the snippets in the assembly\n * become available for live translation later. This is necessary because we probably\n * need to fixturize snippets for successful compilation, and the information\n * pacmak sends our way later on is not going to be enough to do that.\n */\n public async addAssembly(assembly: spec.Assembly, assemblyDir: string) {\n const defaultTablet = guessTabletLocation(assemblyDir);\n if (await pathExists(defaultTablet)) {\n try {\n await this.loadTabletFromFile(defaultTablet);\n return;\n } catch (e: any) {\n logging.warn(`Error loading ${defaultTablet}: ${e.message}. Skipped.`);\n }\n }\n\n // Inventarize the snippets from this assembly, but only if there's a chance\n // we're going to need them.\n if (this.unknownSnippets === UnknownSnippetMode.TRANSLATE) {\n for (const tsnip of await allTypeScriptSnippets([{ assembly, directory: assemblyDir }], this.loose)) {\n this.extractedSnippets.set(snippetKey(tsnip), tsnip);\n }\n }\n }\n\n /**\n * Translate the given snippet for the given target language\n *\n * This will either:\n *\n * - Find an existing translation in a tablet and return that, if available.\n * - Otherwise, find a fixturized version of this snippet in an assembly that\n * was loaded beforehand, and translate it on-the-fly. Finding the fixture\n * will be based on the snippet key, which consists of a hash of the\n * visible source and the API location.\n * - Otherwise, translate the snippet as-is (without fixture information).\n *\n * This will do and store a full conversion of the given snippet, even if it only\n * returns one language. Subsequent retrievals for the same snippet in other\n * languages will reuse the translation from cache.\n *\n * If you are calling this for the side effect of adding translations to the live\n * tablet, you only need to do that for one language.\n */\n public translateSnippet(source: TypeScriptSnippet, targetLang: TargetLanguage): Translation | undefined {\n // Look for it in loaded tablets (or previous conversions)\n for (const tab of this.allTablets) {\n const ret = tab.lookup(source, targetLang);\n if (ret !== undefined) {\n return this.prefixDisclaimer(ret, this._prefixDisclaimer);\n }\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.VERBATIM) {\n return this.prefixDisclaimer(\n {\n language: targetLang,\n source: source.visibleSource,\n },\n this._prefixDisclaimer,\n );\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.FAIL) {\n const message = [\n 'The following snippet was not found in any of the loaded tablets:',\n source.visibleSource,\n `Location: ${JSON.stringify(source.location)}`,\n `Language: ${targetLang}`,\n ].join('\\n');\n throw new Error(message);\n }\n\n if (this.options.targetLanguages && !this.options.targetLanguages.includes(targetLang)) {\n throw new Error(\n `Rosetta configured for live conversion to ${this.options.targetLanguages.join(\n ', ',\n )}, but requested ${targetLang}`,\n );\n }\n\n // See if we can find a fixturized version of this snippet. If so, use that do the live\n // conversion.\n const extracted = this.extractedSnippets.get(snippetKey(source));\n if (extracted !== undefined) {\n const snippet = this.translator.translate(extracted, this.options.targetLanguages);\n this.liveTablet.addSnippet(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n // Try to live-convert it as-is.\n const snippet = this.translator.translate(source, this.options.targetLanguages);\n this.liveTablet.addSnippet(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n /**\n * Translate a snippet found in the \"@ example\" section of a jsii assembly\n *\n * Behaves exactly like `translateSnippet`, so see that method for documentation.\n */\n public translateExample(\n apiLocation: ApiLocation,\n example: string,\n targetLang: TargetLanguage,\n strict: boolean,\n compileDirectory = process.cwd(),\n ): Translation {\n const location = { api: apiLocation, field: { field: 'example' } } as const;\n\n const snippet = typeScriptSnippetFromSource(example, location, strict, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n });\n\n const translated = this.translateSnippet(snippet, targetLang);\n\n return translated ?? { language: 'typescript', source: example };\n }\n\n /**\n * Translate all TypeScript snippets found in a block of Markdown text\n *\n * For each snippet, behaves exactly like `translateSnippet`, so see that\n * method for documentation.\n */\n public translateSnippetsInMarkdown(\n apiLocation: ApiLocation,\n markdown: string,\n targetLang: TargetLanguage,\n strict: boolean,\n translationToCodeBlock: (x: Translation) => CodeBlock = id,\n compileDirectory = process.cwd(),\n ): string {\n return transformMarkdown(\n markdown,\n new MarkdownRenderer(),\n new ReplaceTypeScriptTransform(apiLocation, strict, (tsSnip) => {\n const translated = this.translateSnippet(\n updateParameters(tsSnip, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n }),\n targetLang,\n );\n if (!translated) {\n return undefined;\n }\n\n return translationToCodeBlock(translated);\n }),\n );\n }\n\n public printDiagnostics(stream: NodeJS.WritableStream, colors = true) {\n printDiagnostics(this.diagnostics, stream, colors);\n }\n\n public get hasErrors() {\n return this.diagnostics.some((d) => d.isError);\n }\n\n private get allTablets(): LanguageTablet[] {\n return [...this.loadedTablets, this.liveTablet];\n }\n\n /**\n * Adds a disclaimer to the front of the example if the prefixDisclaimer\n * flag is set and we know it does not compile.\n */\n private prefixDisclaimer(translation: Translation | undefined, prefixDisclaimer: boolean): Translation | undefined {\n if (!prefixDisclaimer || translation?.didCompile !== false) {\n return translation;\n }\n const comment = commentToken(translation.language);\n const disclaimer = 'Example automatically generated from non-compiling source. May contain errors.';\n return {\n ...translation,\n source: `${comment} ${disclaimer}\\n${translation.source}`,\n };\n }\n}\n\nfunction id(x: Translation) {\n return x;\n}\n\n/**\n * Backwards compatibility\n *\n * @deprecated use RosettaTabletReader instead\n */\nexport class Rosetta extends RosettaTabletReader {}\n"]}
package/package.json CHANGED
@@ -56,7 +56,7 @@
56
56
  "eslint-plugin-unicorn": "^56.0.1",
57
57
  "fs-monkey": "^1.1.0",
58
58
  "jest": "^29.7.0",
59
- "memfs": "^4.43.0",
59
+ "memfs": "^4.46.0",
60
60
  "mock-fs": "^5.5.0",
61
61
  "prettier": "^2.8.8",
62
62
  "projen": "^0.96.3",
@@ -88,7 +88,7 @@
88
88
  "publishConfig": {
89
89
  "access": "public"
90
90
  },
91
- "version": "5.9.6-dev.2",
91
+ "version": "5.9.6",
92
92
  "types": "lib/index.d.ts",
93
93
  "exports": {
94
94
  ".": "./lib/index.js",