jsii-rosetta 5.2.7 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +50 -43
  2. package/lib/commands/coverage.js.map +1 -1
  3. package/lib/commands/extract.js.map +1 -1
  4. package/lib/commands/infuse.js.map +1 -1
  5. package/lib/commands/read.js.map +1 -1
  6. package/lib/commands/transliterate.js.map +1 -1
  7. package/lib/find-utils.js.map +1 -1
  8. package/lib/fixtures.js.map +1 -1
  9. package/lib/jsii/assemblies.js.map +1 -1
  10. package/lib/jsii/fingerprinting.js.map +1 -1
  11. package/lib/jsii/jsii-types.js.map +1 -1
  12. package/lib/jsii/jsii-utils.js +1 -1
  13. package/lib/jsii/jsii-utils.js.map +1 -1
  14. package/lib/jsii/packages.js.map +1 -1
  15. package/lib/languages/csharp.js +1 -1
  16. package/lib/languages/csharp.js.map +1 -1
  17. package/lib/languages/default.js.map +1 -1
  18. package/lib/languages/go.js +1 -1
  19. package/lib/languages/go.js.map +1 -1
  20. package/lib/languages/java.js +1 -1
  21. package/lib/languages/java.js.map +1 -1
  22. package/lib/languages/python.js.map +1 -1
  23. package/lib/languages/record-references.js.map +1 -1
  24. package/lib/languages/target-language.js.map +1 -1
  25. package/lib/logging.js.map +1 -1
  26. package/lib/main.js.map +1 -1
  27. package/lib/markdown/escapes.js.map +1 -1
  28. package/lib/markdown/markdown-renderer.js.map +1 -1
  29. package/lib/markdown/markdown.js.map +1 -1
  30. package/lib/markdown/replace-typescript-transform.js.map +1 -1
  31. package/lib/markdown/structure-renderer.js.map +1 -1
  32. package/lib/markdown/xml-comment-renderer.js.map +1 -1
  33. package/lib/o-tree.js.map +1 -1
  34. package/lib/renderer.js.map +1 -1
  35. package/lib/rosetta-reader.js.map +1 -1
  36. package/lib/rosetta-translator.js.map +1 -1
  37. package/lib/snippet-dependencies.js.map +1 -1
  38. package/lib/snippet-selectors.js.map +1 -1
  39. package/lib/snippet.js.map +1 -1
  40. package/lib/submodule-reference.js.map +1 -1
  41. package/lib/support.js.map +1 -1
  42. package/lib/tablets/tablets.js.map +1 -1
  43. package/lib/translate.js.map +1 -1
  44. package/lib/translate_all.js.map +1 -1
  45. package/lib/translate_all_worker.js.map +1 -1
  46. package/lib/typescript/ast-utils.js.map +1 -1
  47. package/lib/typescript/imports.js +1 -1
  48. package/lib/typescript/imports.js.map +1 -1
  49. package/lib/typescript/syntax-kind-counter.js.map +1 -1
  50. package/lib/typescript/ts-compiler.js +2 -2
  51. package/lib/typescript/ts-compiler.js.map +1 -1
  52. package/lib/typescript/types.js.map +1 -1
  53. package/lib/typescript/visible-spans.js.map +1 -1
  54. package/lib/util.js.map +1 -1
  55. package/package.json +8 -6
  56. package/releases.json +4 -2
@@ -1 +1 @@
1
- {"version":3,"file":"submodule-reference.js","sourceRoot":"","sources":["../src/submodule-reference.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAOjC,MAAa,kBAAkB;IACtB,MAAM,CAAC,YAAY,CAAC,UAAyB,EAAE,WAA2B;QAC/E,MAAM,kBAAkB,GAAG,UAAU,CAAC,UAAU;aAC7C,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC;aAC9C,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,mBAAmB,CAAC,IAA4B,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC;QAEjG,OAAO,kBAAkB,CAAC,MAAM,CAAC,UAAU,EAAE,WAAW,EAAE,IAAI,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC;IACzF,CAAC;IAEO,MAAM,CAAC,MAAM,CACnB,IAAa,EACb,WAA2B,EAC3B,kBAA0C,EAC1C,MAAM,IAAI,GAAG,EAGV;QAKH,IAAI,EAAE,CAAC,0BAA0B,CAAC,IAAI,CAAC,EAAE;YACvC,MAAM,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,GA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moduleReferenceMap = ReadonlyMap<\n ts.PropertyAccessExpression | ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n SubmoduleReference\n>;\n\nexport class SubmoduleReference {\n public static inSourceFile(sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker): SubmoduleReferenceMap {\n const importDeclarations = sourceFile.statements\n .filter((stmt) => ts.isImportDeclaration(stmt))\n .flatMap((stmt) => importedSymbolsFrom(stmt as ts.ImportDeclaration, sourceFile, typeChecker));\n\n return SubmoduleReference.inNode(sourceFile, typeChecker, new Set(importDeclarations));\n }\n\n private static inNode(\n node: ts.Node,\n typeChecker: ts.TypeChecker,\n importDeclarations: ReadonlySet<ts.Symbol>,\n map = new Map<\n ts.PropertyAccessExpression | ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n SubmoduleReference\n >(),\n ): Map<\n ts.PropertyAccessExpression | ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n SubmoduleReference\n > {\n if (ts.isPropertyAccessExpression(node)) {\n const [head, ...tail] = propertyPath(node);\n const symbol = typeChecker.getSymbolAtLocation(head.name);\n if (symbol && importDeclarations.has(symbol)) {\n // This is a reference within an imported namespace, so we need to record that...\n const firstNonNamespace = tail.findIndex((item) => !isLikelyNamespace(item.name, typeChecker));\n if (firstNonNamespace < 0) {\n map.set(node.expression, new SubmoduleReference(symbol, node.expression, []));\n } else {\n const tailEnd = tail[firstNonNamespace].expression;\n const path = tail.slice(0, firstNonNamespace).map((item) => item.name);\n map.set(tailEnd, new SubmoduleReference(symbol, tailEnd, path));\n }\n }\n\n return map;\n }\n\n // Faster than ||-ing a bung of if statements to avoid traversing uninteresting nodes...\n switch (node.kind) {\n case ts.SyntaxKind.ImportDeclaration:\n case ts.SyntaxKind.ExportDeclaration:\n break;\n default:\n for (const child of node.getChildren()) {\n map = SubmoduleReference.inNode(child, typeChecker, importDeclarations, map);\n }\n }\n\n return map;\n }\n\n private constructor(\n public readonly root: ts.Symbol,\n public readonly submoduleChain: ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n public readonly path: readonly ts.Node[],\n ) {}\n\n public get lastNode(): ts.Node {\n if (this.path.length === 0) {\n const node = this.root.valueDeclaration ?? this.root.declarations![0];\n return ts.isNamespaceImport(node) || ts.isImportSpecifier(node) ? node.name : node;\n }\n return this.path[this.path.length - 1];\n }\n\n public toString(): string {\n return `${this.constructor.name}<root=${this.root.name}, path=${JSON.stringify(\n this.path.map((item) => item.getText(item.getSourceFile())),\n )}>`;\n }\n}\n\n/**\n * Determines what symbols are imported by the given TypeScript import\n * delcaration, in the context of the specified file, using the provided type\n * checker.\n *\n * @param decl an import declaration.\n * @param sourceFile the source file that contains the import declaration.\n * @param typeChecker a TypeChecker instance valid for the provided source file.\n *\n * @returns the (possibly empty) list of symbols imported by this declaration.\n */\nfunction importedSymbolsFrom(\n decl: ts.ImportDeclaration,\n sourceFile: ts.SourceFile,\n typeChecker: ts.TypeChecker,\n): ts.Symbol[] {\n const { importClause } = decl;\n\n if (importClause == null) {\n // This is a \"for side effects\" import, which isn't relevant for our business here...\n return [];\n }\n\n const { name, namedBindings } = importClause;\n const imports = new Array<ts.Symbol>();\n\n if (name != null) {\n const symbol = typeChecker.getSymbolAtLocation(name);\n if (symbol == null) {\n throw new Error(`No symbol was defined for node ${name.getText(sourceFile)}`);\n }\n imports.push(symbol);\n }\n if (namedBindings != null) {\n if (ts.isNamespaceImport(namedBindings)) {\n const { name: bindingName } = namedBindings;\n const symbol = typeChecker.getSymbolAtLocation(bindingName);\n if (symbol == null) {\n throw new Error(`No symbol was defined for node ${bindingName.getText(sourceFile)}`);\n }\n imports.push(symbol);\n } else {\n for (const specifier of namedBindings.elements) {\n const { name: specifierName } = specifier;\n const symbol = typeChecker.getSymbolAtLocation(specifierName);\n if (symbol == null) {\n throw new Error(`No symbol was defined for node ${specifierName.getText(sourceFile)}`);\n }\n imports.push(symbol);\n }\n }\n }\n\n return imports;\n}\n\ninterface PathEntry {\n readonly name: ts.Identifier | ts.PrivateIdentifier | ts.LeftHandSideExpression;\n readonly expression: ts.LeftHandSideExpression;\n}\n\nfunction propertyPath(node: ts.PropertyAccessExpression): readonly PathEntry[] {\n const { expression, name } = node;\n if (!ts.isPropertyAccessExpression(expression)) {\n return [\n { name: expression, expression },\n { name, expression },\n ];\n }\n return [...propertyPath(expression), { name, expression }];\n}\n\n/**\n * A heuristic to determine whether the provided node likely refers to some\n * namespace.\n *\n * @param node the node to be checked.\n * @param typeChecker a type checker that can obtain symbols for this node.\n *\n * @returns true if the node likely refers to a namespace name.\n */\nfunction isLikelyNamespace(node: ts.Node, typeChecker: ts.TypeChecker): boolean {\n if (!ts.isIdentifier(node)) {\n return false;\n }\n\n // If the identifier was bound to a symbol, we can inspect the declarations of\n // it to validate they are all module or namespace declarations.\n const symbol = typeChecker.getSymbolAtLocation(node);\n if (symbol != null) {\n return (\n symbol.declarations!.length > 0 &&\n symbol.declarations!.every(\n (decl) => ts.isModuleDeclaration(decl) || ts.isNamespaceExport(decl) || ts.isNamespaceImport(decl),\n )\n );\n }\n\n // We understand this is likely a namespace if the name does not start with\n // upper-case letter.\n return !startsWithUpperCase(node.text);\n}\n\nfunction startsWithUpperCase(text: string): boolean {\n return text.length > 0 && text[0] === text[0].toUpperCase();\n}\n"]}
1
+ {"version":3,"file":"submodule-reference.js","sourceRoot":"","sources":["../src/submodule-reference.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAOjC,MAAa,kBAAkB;IACtB,MAAM,CAAC,YAAY,CAAC,UAAyB,EAAE,WAA2B;QAC/E,MAAM,kBAAkB,GAAG,UAAU,CAAC,UAAU;aAC7C,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC;aAC9C,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,mBAAmB,CAAC,IAA4B,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC;QAEjG,OAAO,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YAC/B,MAAM,CAAC,YAAa,CAAC,KAAK,CACxB,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,mBAAmB,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,iBAAiB,CAAC,IAAI,CAAC,CACnG,CACF,CAAC;IACJ,CAAC;IAED,2EAA2E;IAC3E,qBAAqB;IACrB,OAAO,CAAC,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzC,CAAC;AAED,SAAS,mBAAmB,CAAC,IAAY;IACvC,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;AAC9D,CAAC","sourcesContent":["import * as ts from 'typescript';\n\nexport type SubmoduleReferenceMap = ReadonlyMap<\n ts.PropertyAccessExpression | ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n SubmoduleReference\n>;\n\nexport class SubmoduleReference {\n public static inSourceFile(sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker): SubmoduleReferenceMap {\n const importDeclarations = sourceFile.statements\n .filter((stmt) => ts.isImportDeclaration(stmt))\n .flatMap((stmt) => importedSymbolsFrom(stmt as ts.ImportDeclaration, sourceFile, typeChecker));\n\n return SubmoduleReference.inNode(sourceFile, typeChecker, new Set(importDeclarations));\n }\n\n private static inNode(\n node: ts.Node,\n typeChecker: ts.TypeChecker,\n importDeclarations: ReadonlySet<ts.Symbol>,\n map = new Map<\n ts.PropertyAccessExpression | ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n SubmoduleReference\n >(),\n ): Map<\n ts.PropertyAccessExpression | ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n SubmoduleReference\n > {\n if (ts.isPropertyAccessExpression(node)) {\n const [head, ...tail] = propertyPath(node);\n const symbol = typeChecker.getSymbolAtLocation(head.name);\n if (symbol && importDeclarations.has(symbol)) {\n // This is a reference within an imported namespace, so we need to record that...\n const firstNonNamespace = tail.findIndex((item) => !isLikelyNamespace(item.name, typeChecker));\n if (firstNonNamespace < 0) {\n map.set(node.expression, new SubmoduleReference(symbol, node.expression, []));\n } else {\n const tailEnd = tail[firstNonNamespace].expression;\n const path = tail.slice(0, firstNonNamespace).map((item) => item.name);\n map.set(tailEnd, new SubmoduleReference(symbol, tailEnd, path));\n }\n }\n\n return map;\n }\n\n // Faster than ||-ing a bung of if statements to avoid traversing uninteresting nodes...\n switch (node.kind) {\n case ts.SyntaxKind.ImportDeclaration:\n case ts.SyntaxKind.ExportDeclaration:\n break;\n default:\n for (const child of node.getChildren()) {\n map = SubmoduleReference.inNode(child, typeChecker, importDeclarations, map);\n }\n }\n\n return map;\n }\n\n private constructor(\n public readonly root: ts.Symbol,\n public readonly submoduleChain: ts.LeftHandSideExpression | ts.Identifier | ts.PrivateIdentifier,\n public readonly path: readonly ts.Node[],\n ) {}\n\n public get lastNode(): ts.Node {\n if (this.path.length === 0) {\n const node = this.root.valueDeclaration ?? this.root.declarations![0];\n return ts.isNamespaceImport(node) || ts.isImportSpecifier(node) ? node.name : node;\n }\n return this.path[this.path.length - 1];\n }\n\n public toString(): string {\n return `${this.constructor.name}<root=${this.root.name}, path=${JSON.stringify(\n this.path.map((item) => item.getText(item.getSourceFile())),\n )}>`;\n }\n}\n\n/**\n * Determines what symbols are imported by the given TypeScript import\n * delcaration, in the context of the specified file, using the provided type\n * checker.\n *\n * @param decl an import declaration.\n * @param sourceFile the source file that contains the import declaration.\n * @param typeChecker a TypeChecker instance valid for the provided source file.\n *\n * @returns the (possibly empty) list of symbols imported by this declaration.\n */\nfunction importedSymbolsFrom(\n decl: ts.ImportDeclaration,\n sourceFile: ts.SourceFile,\n typeChecker: ts.TypeChecker,\n): ts.Symbol[] {\n const { importClause } = decl;\n\n if (importClause == null) {\n // This is a \"for side effects\" import, which isn't relevant for our business here...\n return [];\n }\n\n const { name, namedBindings } = importClause;\n const imports = new Array<ts.Symbol>();\n\n if (name != null) {\n const symbol = typeChecker.getSymbolAtLocation(name);\n if (symbol == null) {\n throw new Error(`No symbol was defined for node ${name.getText(sourceFile)}`);\n }\n imports.push(symbol);\n }\n if (namedBindings != null) {\n if (ts.isNamespaceImport(namedBindings)) {\n const { name: bindingName } = namedBindings;\n const symbol = typeChecker.getSymbolAtLocation(bindingName);\n if (symbol == null) {\n throw new Error(`No symbol was defined for node ${bindingName.getText(sourceFile)}`);\n }\n imports.push(symbol);\n } else {\n for (const specifier of namedBindings.elements) {\n const { name: specifierName } = specifier;\n const symbol = typeChecker.getSymbolAtLocation(specifierName);\n if (symbol == null) {\n throw new Error(`No symbol was defined for node ${specifierName.getText(sourceFile)}`);\n }\n imports.push(symbol);\n }\n }\n }\n\n return imports;\n}\n\ninterface PathEntry {\n readonly name: ts.Identifier | ts.PrivateIdentifier | ts.LeftHandSideExpression;\n readonly expression: ts.LeftHandSideExpression;\n}\n\nfunction propertyPath(node: ts.PropertyAccessExpression): readonly PathEntry[] {\n const { expression, name } = node;\n if (!ts.isPropertyAccessExpression(expression)) {\n return [\n { name: expression, expression },\n { name, expression },\n ];\n }\n return [...propertyPath(expression), { name, expression }];\n}\n\n/**\n * A heuristic to determine whether the provided node likely refers to some\n * namespace.\n *\n * @param node the node to be checked.\n * @param typeChecker a type checker that can obtain symbols for this node.\n *\n * @returns true if the node likely refers to a namespace name.\n */\nfunction isLikelyNamespace(node: ts.Node, typeChecker: ts.TypeChecker): boolean {\n if (!ts.isIdentifier(node)) {\n return false;\n }\n\n // If the identifier was bound to a symbol, we can inspect the declarations of\n // it to validate they are all module or namespace declarations.\n const symbol = typeChecker.getSymbolAtLocation(node);\n if (symbol != null) {\n return (\n symbol.declarations!.length > 0 &&\n symbol.declarations!.every(\n (decl) => ts.isModuleDeclaration(decl) || ts.isNamespaceExport(decl) || ts.isNamespaceImport(decl),\n )\n );\n }\n\n // We understand this is likely a namespace if the name does not start with\n // upper-case letter.\n return !startsWithUpperCase(node.text);\n}\n\nfunction startsWithUpperCase(text: string): boolean {\n return text.length > 0 && text[0] === text[0].toUpperCase();\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"support.js","sourceRoot":"","sources":["../src/support.ts"],"names":[],"mappings":";;;AAAA,qCAAuC;AACvC,2CAAiC;AACjC,yCAAiC;AACjC,+BAA+B;AAC/B,2CAA+C;AAE/C,MAAM,eAAe,GAAG,8BAA8B,CAAC;AACvD,MAAM,qBAAqB,GAAG,UAAa,CAAC;AAuB5C;;;;;;;;GAQG;AACI,KAAK,UAAU,4BAA4B;IAChD,IAAI,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE;QAChC,OAAO;KACR;IAED,MAAM,IAAI,GAAG,MAAM,mBAAmB,EAAE,CAAC;IAEzC,IAAI,IAAI,CAAC,OAAO,IAAI,8BAAiB,EAAE;QACrC,8CAA8C;QAC9C,OAAO;KACR;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;QAC5B,kDAAkD;QAClD,OAAO;KACR;IAED,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;IACvB,MAAM,YAAY,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,qBAAqB,CAAC,CAAC;IACrE,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC;SAClD,OAAO,CAAC,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,EAAE;QAC9B,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC;QAC/B,IAAI,IAAI,IAAI,YAAY,EAAE;YACxB,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AC,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":";;;AAAA,qCAAuC;AACvC,2CAAiC;AACjC,yCAAiC;AACjC,+BAA+B;AAC/B,2CAA+C;AAE/C,MAAM,eAAe,GAAG,8BAA8B,CAAC;AACvD,MAAM,qBAAqB,GAAG,UAAa,CAAC;AA4B5C;;;;;;;;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,GAA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AC9C,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 /**\n * The release line that occupies the 'Current' stage.\n */\n readonly currentMinVersionNumber: VersionNumber;\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}`;\ntype VersionNumber = `${number}.${number}.${number}`;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tablets.js","sourceRoot":"","sources":["../../src/tablets/tablets.ts"],"names":[],"mappings":";;;AAAA,qCAA0F;AAC1F,kCAAkC;AAElC,kCAAkC;AAElC,+BAAmC;AACnC,qCAAuF;AACvF,kCAA2C;AAE3C,sCAAsC;AACtC,wCAAgF;AAChF,kCAA6C;AAE7C,oGAAoG;AACpG,MAAM,YAAY,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAE3D;;GAEG;AACU,QAAA,mBAAmB,GAAG,iBAAi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C,CAAC,MAAM;YACrE,QAAQ,EAAE,IAAI,CAAC,OAAO,CAAC,QAAQ;SAChC,CAAC;IACJ,CAAC;CACF;AA5GD,8CA4GC;AAQD,KAAK,UAAU,SAAS,CAAC,QAAgB;IACvC,MAAM,QAAQ,GAAG,MAAM,kBAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IAC9C,IAAI;QACF,8EAA8E;QAC9E,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAC5E,OAAO,SAAS,IAAI,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;KACzF;YAAS;QACR,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;KACxB;AACH,CAAC","sourcesContent":["import { createReadStream, createWriteStream, existsSync, promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport { Readable, Writable } from 'node:stream';\nimport * as zlib from 'node:zlib';\n\nimport { snippetKey } from './key';\nimport { TabletSchema, TranslatedSnippetSchema, ORIGINAL_SNIPPET_KEY } from './schema';\nimport { parse, stringify } from '../json';\nimport { TargetLanguage } from '../languages';\nimport * as logging from '../logging';\nimport { TypeScriptSnippet, SnippetLocation, completeSource } from '../snippet';\nimport { mapValues, Mutable } from '../util';\n\n// eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-var-requires\nconst TOOL_VERSION = require('../../package.json').version;\n\n/**\n * The default name of the tablet file\n */\nexport const DEFAULT_TABLET_NAME = '.jsii.tabl.json';\n\n/**\n * The default name of the compressed tablet file\n */\nexport const DEFAULT_TABLET_NAME_COMPRESSED = '.jsii.tabl.json.gz';\n\nexport const CURRENT_SCHEMA_VERSION = '2';\n\n/**\n * A tablet containing various snippets in multiple languages\n */\nexport class LanguageTablet {\n /**\n * Load a tablet from a file\n */\n public static async fromFile(filename: string) {\n const ret = new LanguageTablet();\n await ret.load(filename);\n return ret;\n }\n\n /**\n * Load a tablet from a file that may not exist\n *\n * Will return an empty tablet if the file does not exist\n */\n public static async fromOptionalFile(filename: string) {\n const ret = new LanguageTablet();\n if (existsSync(filename)) {\n try {\n await ret.load(filename);\n } catch (e: any) {\n logging.warn(`${filename}: ${e}`);\n }\n }\n return ret;\n }\n\n /**\n * Whether or not the LanguageTablet was loaded with a compressed source.\n * This gets used to determine if it should be compressed when saved.\n */\n public compressedSource = false;\n\n private readonly snippets: Record<string, TranslatedSnippet> = {};\n\n /**\n * Add one or more snippets to this tablet\n */\n public addSnippets(...snippets: TranslatedSnippet[]) {\n for (const snippet of snippets) {\n const existingSnippet = this.snippets[snippet.key];\n this.snippets[snippet.key] = existingSnippet ? existingSnippet.mergeTranslations(snippet) : snippet;\n }\n }\n\n /**\n * Add one snippet to this tablet\n *\n * @deprecated use addSnippets instead\n */\n public addSnippet(snippet: TranslatedSnippet) {\n this.addSnippets(snippet);\n }\n\n public get snippetKeys() {\n return Object.keys(this.snippets);\n }\n\n /**\n * Add all snippets from the given tablets into this one\n */\n public addTablets(...tablets: LanguageTablet[]) {\n for (const tablet of tablets) {\n for (const snippet of Object.values(tablet.snippets)) {\n this.addSnippet(snippet);\n }\n }\n }\n\n /**\n * Add all snippets from the given tablet into this one\n *\n * @deprecated Use `addTablets()` instead.\n */\n public addTablet(tablet: LanguageTablet) {\n this.addTablets(tablet);\n }\n\n public tryGetSnippet(key: string): TranslatedSnippet | undefined {\n return this.snippets[key];\n }\n\n /**\n * Look up a single translation of a source snippet\n *\n * @deprecated Use `lookupTranslationBySource` instead.\n */\n public lookup(typeScriptSource: TypeScriptSnippet, language: TargetLanguage): Translation | undefined {\n return this.lookupTranslationBySource(typeScriptSource, language);\n }\n\n /**\n * Look up a single translation of a source snippet\n */\n public lookupTranslationBySource(\n typeScriptSource: TypeScriptSnippet,\n language: TargetLanguage,\n ): Translation | undefined {\n const snippet = this.snippets[snippetKey(typeScriptSource)];\n return snippet?.get(language);\n }\n\n /**\n * Lookup the translated verion of a TypeScript snippet\n */\n public lookupBySource(typeScriptSource: TypeScriptSnippet): TranslatedSnippet | undefined {\n return this.snippets[snippetKey(typeScriptSource)];\n }\n\n /**\n * Load the tablet from a file. Will automatically detect if the file is\n * compressed and decompress accordingly.\n */\n public async load(filename: string) {\n let readStream: Readable;\n if (await isGzipped(filename)) {\n const gunzip = zlib.createGunzip();\n createReadStream(filename).pipe(gunzip, { end: true });\n readStream = gunzip;\n this.compressedSource = true;\n } else {\n readStream = createReadStream(filename);\n }\n\n const obj: TabletSchema = await parse(readStream);\n\n if (!obj.toolVersion || !obj.snippets) {\n throw new Error(`File '${filename}' does not seem to be a Tablet file`);\n }\n\n if (obj.version !== CURRENT_SCHEMA_VERSION) {\n // If we're ever changing the schema version in a backwards incompatible way,\n // do upconversion here.\n throw new Error(\n `Tablet file '${filename}' has schema version '${obj.version}', this program expects '${CURRENT_SCHEMA_VERSION}'`,\n );\n }\n\n Object.assign(this.snippets, mapValues(obj.snippets, TranslatedSnippet.fromSchema));\n }\n\n public get count() {\n return Object.keys(this.snippets).length;\n }\n\n public get translatedSnippets() {\n return Object.values(this.snippets);\n }\n\n /**\n * Saves the tablet schema to a file. If the compress option is passed, then\n * the schema will be gzipped before writing to the file.\n */\n public async save(filename: string, compress = false): Promise<void> {\n await fs.mkdir(path.dirname(filename), { recursive: true });\n\n const writeStream: Writable = createWriteStream(filename, { flags: 'w' });\n const gzip = compress ? zlib.createGzip() : undefined;\n\n return stringify(this.toSchema(), ...(gzip ? [gzip] : []), writeStream);\n }\n\n private toSchema(): TabletSchema {\n return {\n version: CURRENT_SCHEMA_VERSION,\n toolVersion: TOOL_VERSION,\n snippets: mapValues(this.snippets, (s) => s.snippet),\n };\n }\n}\n\n/**\n * Mutable operations on an underlying TranslatedSnippetSchema\n */\nexport class TranslatedSnippet {\n public static fromSchema(schema: TranslatedSnippetSchema) {\n if (!schema.translations[ORIGINAL_SNIPPET_KEY]) {\n throw new Error(`Input schema must have '${ORIGINAL_SNIPPET_KEY}' key set in translations`);\n }\n return new TranslatedSnippet(schema);\n }\n\n public static fromTypeScript(original: TypeScriptSnippet, didCompile?: boolean) {\n return new TranslatedSnippet({\n translations: {\n [ORIGINAL_SNIPPET_KEY]: { source: original.visibleSource, version: '0' },\n },\n didCompile: didCompile,\n location: original.location,\n fullSource: completeSource(original),\n });\n }\n\n public readonly snippet: TranslatedSnippetSchema;\n\n private readonly _snippet: Mutable<TranslatedSnippetSchema>;\n private _key?: string;\n\n private constructor(snippet: TranslatedSnippetSchema) {\n this._snippet = { ...snippet };\n this.snippet = this._snippet;\n }\n\n public get key() {\n if (this._key === undefined) {\n this._key = snippetKey(this.asTypescriptSnippet());\n }\n return this._key;\n }\n\n public get originalSource(): Translation {\n return {\n source: this.snippet.translations[ORIGINAL_SNIPPET_KEY].source,\n language: 'typescript',\n didCompile: this.snippet.didCompile,\n };\n }\n\n public addTranslation(language: TargetLanguage, translation: string, version: string): Translation {\n this.snippet.translations[language] = { source: translation, version };\n\n return {\n source: translation,\n language,\n didCompile: this.snippet.didCompile,\n };\n }\n\n public fqnsReferenced() {\n return this._snippet.fqnsReferenced ?? [];\n }\n\n public addSyntaxKindCounter(syntaxKindCounter: Record<string, number>) {\n if (!this._snippet.syntaxKindCounter) {\n this._snippet.syntaxKindCounter = {};\n }\n for (const [key, value] of Object.entries(syntaxKindCounter)) {\n const x = this._snippet.syntaxKindCounter[key] ?? 0;\n this._snippet.syntaxKindCounter[key] = value + x;\n }\n }\n\n public get languages(): TargetLanguage[] {\n return Object.keys(this.snippet.translations).filter((x) => x !== ORIGINAL_SNIPPET_KEY) as TargetLanguage[];\n }\n\n public get(language: TargetLanguage): Translation | undefined {\n const t = this.snippet.translations[language];\n return t && { source: t.source, language, didCompile: this.snippet.didCompile };\n }\n\n public mergeTranslations(other: TranslatedSnippet) {\n return new TranslatedSnippet({\n ...this.snippet,\n translations: { ...this.snippet.translations, ...other.snippet.translations },\n });\n }\n\n public withFingerprint(fp: string) {\n return new TranslatedSnippet({\n ...this.snippet,\n fqnsFingerprint: fp,\n });\n }\n\n public withLocation(location: SnippetLocation) {\n return new TranslatedSnippet({\n ...this.snippet,\n location,\n });\n }\n\n public toJSON() {\n return this._snippet;\n }\n\n private asTypescriptSnippet(): TypeScriptSnippet {\n return {\n visibleSource: this.snippet.translations[ORIGINAL_SNIPPET_KEY].source,\n location: this.snippet.location,\n };\n }\n}\n\nexport interface Translation {\n source: string;\n language: string;\n didCompile?: boolean;\n}\n\nasync function isGzipped(filename: string) {\n const openFile = await fs.open(filename, 'r');\n try {\n // Assumes that we can always read 3 bytes if there's that many in the file...\n const { bytesRead, buffer } = await openFile.read(Buffer.alloc(4), 0, 3, 0);\n return bytesRead >= 3 && buffer[0] === 0x1f && buffer[1] === 0x8b && buffer[2] === 0x08;\n } finally {\n await openFile.close();\n }\n}\n"]}
1
+ {"version":3,"file":"tablets.js","sourceRoot":"","sources":["../../src/tablets/tablets.ts"],"names":[],"mappings":";;;AAAA,qCAA0F;AAC1F,kCAAkC;AAElC,kCAAkC;AAElC,+BAAmC;AACnC,qCAAuF;AACvF,kCAA2C;AAE3C,sCAAsC;AACtC,wCAAgF;AAChF,kCAA6C;AAE7C,oGAAoG;AACpG,MAAM,YAAY,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAE3D;;GAEG;AACU,QAAA,mBAAmB,GAAG,iBAAiB,CAAC;AAErD;;GAEG;AACU,QAAA,8BAA8B,GAAG,oBAAoB,CAAC;AAEtD,QAAA,sBAAsB,GAAG,GAAG,CAAC;AAE1C;;GAEG;AACH,MAAa,cAAc;IAA3B;QA2BE;;;WAGG;QACI,qBAAgB,GAAG,KAAK,CAAC;QAEf,aAAQ,GAAsC,EAAE,CAAC;IAwIp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CAAC,QAAQ;SAChC,CAAC;IACJ,CAAC;CACF;AA5GD,8CA4GC;AAQD,KAAK,UAAU,SAAS,CAAC,QAAgB;IACvC,MAAM,QAAQ,GAAG,MAAM,kBAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IAC9C,IAAI,CAAC;QACH,8EAA8E;QAC9E,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAC5E,OAAO,SAAS,IAAI,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;IAC1F,CAAC;YAAS,CAAC;QACT,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;AACH,CAAC","sourcesContent":["import { createReadStream, createWriteStream, existsSync, promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport { Readable, Writable } from 'node:stream';\nimport * as zlib from 'node:zlib';\n\nimport { snippetKey } from './key';\nimport { TabletSchema, TranslatedSnippetSchema, ORIGINAL_SNIPPET_KEY } from './schema';\nimport { parse, stringify } from '../json';\nimport { TargetLanguage } from '../languages';\nimport * as logging from '../logging';\nimport { TypeScriptSnippet, SnippetLocation, completeSource } from '../snippet';\nimport { mapValues, Mutable } from '../util';\n\n// eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-var-requires\nconst TOOL_VERSION = require('../../package.json').version;\n\n/**\n * The default name of the tablet file\n */\nexport const DEFAULT_TABLET_NAME = '.jsii.tabl.json';\n\n/**\n * The default name of the compressed tablet file\n */\nexport const DEFAULT_TABLET_NAME_COMPRESSED = '.jsii.tabl.json.gz';\n\nexport const CURRENT_SCHEMA_VERSION = '2';\n\n/**\n * A tablet containing various snippets in multiple languages\n */\nexport class LanguageTablet {\n /**\n * Load a tablet from a file\n */\n public static async fromFile(filename: string) {\n const ret = new LanguageTablet();\n await ret.load(filename);\n return ret;\n }\n\n /**\n * Load a tablet from a file that may not exist\n *\n * Will return an empty tablet if the file does not exist\n */\n public static async fromOptionalFile(filename: string) {\n const ret = new LanguageTablet();\n if (existsSync(filename)) {\n try {\n await ret.load(filename);\n } catch (e: any) {\n logging.warn(`${filename}: ${e}`);\n }\n }\n return ret;\n }\n\n /**\n * Whether or not the LanguageTablet was loaded with a compressed source.\n * This gets used to determine if it should be compressed when saved.\n */\n public compressedSource = false;\n\n private readonly snippets: Record<string, TranslatedSnippet> = {};\n\n /**\n * Add one or more snippets to this tablet\n */\n public addSnippets(...snippets: TranslatedSnippet[]) {\n for (const snippet of snippets) {\n const existingSnippet = this.snippets[snippet.key];\n this.snippets[snippet.key] = existingSnippet ? existingSnippet.mergeTranslations(snippet) : snippet;\n }\n }\n\n /**\n * Add one snippet to this tablet\n *\n * @deprecated use addSnippets instead\n */\n public addSnippet(snippet: TranslatedSnippet) {\n this.addSnippets(snippet);\n }\n\n public get snippetKeys() {\n return Object.keys(this.snippets);\n }\n\n /**\n * Add all snippets from the given tablets into this one\n */\n public addTablets(...tablets: LanguageTablet[]) {\n for (const tablet of tablets) {\n for (const snippet of Object.values(tablet.snippets)) {\n this.addSnippet(snippet);\n }\n }\n }\n\n /**\n * Add all snippets from the given tablet into this one\n *\n * @deprecated Use `addTablets()` instead.\n */\n public addTablet(tablet: LanguageTablet) {\n this.addTablets(tablet);\n }\n\n public tryGetSnippet(key: string): TranslatedSnippet | undefined {\n return this.snippets[key];\n }\n\n /**\n * Look up a single translation of a source snippet\n *\n * @deprecated Use `lookupTranslationBySource` instead.\n */\n public lookup(typeScriptSource: TypeScriptSnippet, language: TargetLanguage): Translation | undefined {\n return this.lookupTranslationBySource(typeScriptSource, language);\n }\n\n /**\n * Look up a single translation of a source snippet\n */\n public lookupTranslationBySource(\n typeScriptSource: TypeScriptSnippet,\n language: TargetLanguage,\n ): Translation | undefined {\n const snippet = this.snippets[snippetKey(typeScriptSource)];\n return snippet?.get(language);\n }\n\n /**\n * Lookup the translated verion of a TypeScript snippet\n */\n public lookupBySource(typeScriptSource: TypeScriptSnippet): TranslatedSnippet | undefined {\n return this.snippets[snippetKey(typeScriptSource)];\n }\n\n /**\n * Load the tablet from a file. Will automatically detect if the file is\n * compressed and decompress accordingly.\n */\n public async load(filename: string) {\n let readStream: Readable;\n if (await isGzipped(filename)) {\n const gunzip = zlib.createGunzip();\n createReadStream(filename).pipe(gunzip, { end: true });\n readStream = gunzip;\n this.compressedSource = true;\n } else {\n readStream = createReadStream(filename);\n }\n\n const obj: TabletSchema = await parse(readStream);\n\n if (!obj.toolVersion || !obj.snippets) {\n throw new Error(`File '${filename}' does not seem to be a Tablet file`);\n }\n\n if (obj.version !== CURRENT_SCHEMA_VERSION) {\n // If we're ever changing the schema version in a backwards incompatible way,\n // do upconversion here.\n throw new Error(\n `Tablet file '${filename}' has schema version '${obj.version}', this program expects '${CURRENT_SCHEMA_VERSION}'`,\n );\n }\n\n Object.assign(this.snippets, mapValues(obj.snippets, TranslatedSnippet.fromSchema));\n }\n\n public get count() {\n return Object.keys(this.snippets).length;\n }\n\n public get translatedSnippets() {\n return Object.values(this.snippets);\n }\n\n /**\n * Saves the tablet schema to a file. If the compress option is passed, then\n * the schema will be gzipped before writing to the file.\n */\n public async save(filename: string, compress = false): Promise<void> {\n await fs.mkdir(path.dirname(filename), { recursive: true });\n\n const writeStream: Writable = createWriteStream(filename, { flags: 'w' });\n const gzip = compress ? zlib.createGzip() : undefined;\n\n return stringify(this.toSchema(), ...(gzip ? [gzip] : []), writeStream);\n }\n\n private toSchema(): TabletSchema {\n return {\n version: CURRENT_SCHEMA_VERSION,\n toolVersion: TOOL_VERSION,\n snippets: mapValues(this.snippets, (s) => s.snippet),\n };\n }\n}\n\n/**\n * Mutable operations on an underlying TranslatedSnippetSchema\n */\nexport class TranslatedSnippet {\n public static fromSchema(schema: TranslatedSnippetSchema) {\n if (!schema.translations[ORIGINAL_SNIPPET_KEY]) {\n throw new Error(`Input schema must have '${ORIGINAL_SNIPPET_KEY}' key set in translations`);\n }\n return new TranslatedSnippet(schema);\n }\n\n public static fromTypeScript(original: TypeScriptSnippet, didCompile?: boolean) {\n return new TranslatedSnippet({\n translations: {\n [ORIGINAL_SNIPPET_KEY]: { source: original.visibleSource, version: '0' },\n },\n didCompile: didCompile,\n location: original.location,\n fullSource: completeSource(original),\n });\n }\n\n public readonly snippet: TranslatedSnippetSchema;\n\n private readonly _snippet: Mutable<TranslatedSnippetSchema>;\n private _key?: string;\n\n private constructor(snippet: TranslatedSnippetSchema) {\n this._snippet = { ...snippet };\n this.snippet = this._snippet;\n }\n\n public get key() {\n if (this._key === undefined) {\n this._key = snippetKey(this.asTypescriptSnippet());\n }\n return this._key;\n }\n\n public get originalSource(): Translation {\n return {\n source: this.snippet.translations[ORIGINAL_SNIPPET_KEY].source,\n language: 'typescript',\n didCompile: this.snippet.didCompile,\n };\n }\n\n public addTranslation(language: TargetLanguage, translation: string, version: string): Translation {\n this.snippet.translations[language] = { source: translation, version };\n\n return {\n source: translation,\n language,\n didCompile: this.snippet.didCompile,\n };\n }\n\n public fqnsReferenced() {\n return this._snippet.fqnsReferenced ?? [];\n }\n\n public addSyntaxKindCounter(syntaxKindCounter: Record<string, number>) {\n if (!this._snippet.syntaxKindCounter) {\n this._snippet.syntaxKindCounter = {};\n }\n for (const [key, value] of Object.entries(syntaxKindCounter)) {\n const x = this._snippet.syntaxKindCounter[key] ?? 0;\n this._snippet.syntaxKindCounter[key] = value + x;\n }\n }\n\n public get languages(): TargetLanguage[] {\n return Object.keys(this.snippet.translations).filter((x) => x !== ORIGINAL_SNIPPET_KEY) as TargetLanguage[];\n }\n\n public get(language: TargetLanguage): Translation | undefined {\n const t = this.snippet.translations[language];\n return t && { source: t.source, language, didCompile: this.snippet.didCompile };\n }\n\n public mergeTranslations(other: TranslatedSnippet) {\n return new TranslatedSnippet({\n ...this.snippet,\n translations: { ...this.snippet.translations, ...other.snippet.translations },\n });\n }\n\n public withFingerprint(fp: string) {\n return new TranslatedSnippet({\n ...this.snippet,\n fqnsFingerprint: fp,\n });\n }\n\n public withLocation(location: SnippetLocation) {\n return new TranslatedSnippet({\n ...this.snippet,\n location,\n });\n }\n\n public toJSON() {\n return this._snippet;\n }\n\n private asTypescriptSnippet(): TypeScriptSnippet {\n return {\n visibleSource: this.snippet.translations[ORIGINAL_SNIPPET_KEY].source,\n location: this.snippet.location,\n };\n }\n}\n\nexport interface Translation {\n source: string;\n language: string;\n didCompile?: boolean;\n}\n\nasync function isGzipped(filename: string) {\n const openFile = await fs.open(filename, 'r');\n try {\n // Assumes that we can always read 3 bytes if there's that many in the file...\n const { bytesRead, buffer } = await openFile.read(Buffer.alloc(4), 0, 3, 0);\n return bytesRead >= 3 && buffer[0] === 0x1f && buffer[1] === 0x8b && buffer[2] === 0x08;\n } finally {\n await openFile.close();\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"translate.js","sourceRoot":"","sources":["../src/translate.ts"],"names":[],"mappings":";;;;;;;;;AAAA,yCAAoC;AACpC,iCAAiC;AAEjC,2CAA+D;AAC/D,qEAAwE;AACxE,iEAAgF;AAChF,qCAAqC;AACrC,qCAAsC;AACtC,yCAAyE;AACzE,uCAAiG;AACjG,+DAAkF;AAClF,uCAA2C;AAC3C,6CAAwD;AACxD,+CAAsD;AACtD,0EAAqE;AACrE,0DAAiF;AACjF,8DAAmD;AACnD,iCAAmF;AAEnF,SAAgB,mBAAmB,CACjC,MAAY,EACZ,OAAwB,EACxB,UAAoC,EAAE;IAEtC,MAAM,UAAU,GAAG,IAAI,iBAAiB,CACtC,EAAE,aAAa,EAAE,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,EAAE,GAAG,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EA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AAC;IACrG,CAAC;CACF;AAhHD,8CAgHC;AAED;;GAEG;AACH,SAAS,wBAAwB,CAAC,KAA+B,EAAE,YAAmB;IACpF,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,KAAK,KAAK,SAAS,IAAI,YAAY,CAAC,gBAAgB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AACxH,CAAC;AAED;;GAEG;AACH,SAAgB,yBAAyB,CAAC,IAAmB;IAC3D,OAAO;QACL,OAAO,EAAE,IAAI,CAAC,QAAQ,KAAK,EAAE,CAAC,kBAAkB,CAAC,KAAK;QACtD,oBAAoB,EAAE,IAAA,wBAAiB,EAAC,IAAI,CAAC;QAC7C,gBAAgB,EAAE,EAAE,CAAC,oCAAoC,CAAC,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC;KAC7E,CAAC;AACJ,CAAC;AAND,8DAMC;AAED,MAAM,SAAS,GAAG;IAChB,mBAAmB;QACjB,OAAO,GAAG,CAAC;IACb,CAAC;IACD,oBAAoB,CAAC,QAAgB;QACnC,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,UAAU;QACR,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAC;AAEF;;;GAGG;AACH,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;AAClC,CAAC","sourcesContent":["import { inspect } from 'node:util';\nimport * as ts from 'typescript';\n\nimport { TARGET_LANGUAGES, TargetLanguage } from './languages';\nimport { RecordReferencesVisitor } from './languages/record-references';\nimport { supportsTransitiveSubmoduleAccess } from './languages/target-language';\nimport * as logging from './logging';\nimport { renderTree } from './o-tree';\nimport { AstRenderer, AstHandler, AstRendererOptions } from './renderer';\nimport { TypeScriptSnippet, completeSource, SnippetParameters, formatLocation } from './snippet';\nimport { SubmoduleReference, SubmoduleReferenceMap } from './submodule-reference';\nimport { snippetKey } from './tablets/key';\nimport { ORIGINAL_SNIPPET_KEY } from './tablets/schema';\nimport { TranslatedSnippet } from './tablets/tablets';\nimport { SyntaxKindCounter } from './typescript/syntax-kind-counter';\nimport { TypeScriptCompiler, CompilationResult } from './typescript/ts-compiler';\nimport { Spans } from './typescript/visible-spans';\nimport { annotateStrictDiagnostic, File, hasStrictBranding, mkDict } from './util';\n\nexport function translateTypeScript(\n source: File,\n visitor: AstHandler<any>,\n options: SnippetTranslatorOptions = {},\n): TranslateResult {\n const translator = new SnippetTranslator(\n { visibleSource: source.contents, location: { api: { api: 'file', fileName: source.fileName } } },\n options,\n );\n const translated = translator.renderUsing(visitor);\n\n return {\n translation: translated,\n diagnostics: translator.diagnostics.map(rosettaDiagFromTypescript),\n };\n}\n\n/**\n * Translate one or more TypeScript snippets into other languages\n *\n * Can be configured to fully typecheck the samples, or perform only syntactical\n * translation.\n */\nexport class Translator {\n private readonly compiler = new TypeScriptCompiler();\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n #diagnostics: ts.Diagnostic[] = [];\n\n public constructor(private readonly includeCompilerDiagnostics: boolean) {}\n\n public translate(snip: TypeScriptSnippet, languages: readonly TargetLanguage[] = Object.values(TargetLanguage)) {\n logging.debug(`Translating ${snippetKey(snip)} ${inspect(snip.parameters ?? {})}`);\n const translator = this.translatorFor(snip);\n\n const translations = mkDict(\n languages.flatMap((lang, idx, array) => {\n if (array.slice(0, idx).includes(lang)) {\n // This language was duplicated in the request... we'll skip that here...\n return [];\n }\n const languageConverterFactory = TARGET_LANGUAGES[lang];\n const translated = translator.renderUsing(languageConverterFactory.createVisitor());\n return [[lang, { source: translated, version: languageConverterFactory.version }] as const];\n }),\n );\n\n if (snip.parameters?.infused === undefined) {\n this.#diagnostics.push(...translator.diagnostics);\n }\n\n return TranslatedSnippet.fromSchema({\n translations: {\n ...translations,\n [ORIGINAL_SNIPPET_KEY]: { source: snip.visibleSource, version: '0' },\n },\n location: snip.location,\n didCompile: translator.didSuccessfullyCompile,\n fqnsReferenced: translator.fqnsReferenced(),\n fullSource: completeSource(snip),\n syntaxKindCounter: translator.syntaxKindCounter(),\n });\n }\n\n public get diagnostics(): readonly RosettaDiagnostic[] {\n return ts.sortAndDeduplicateDiagnostics(this.#diagnostics).map(rosettaDiagFromTypescript);\n }\n\n /**\n * Return the snippet translator for the given snippet\n *\n * We used to cache these, but each translator holds on to quite a bit of memory,\n * so we don't do that anymore.\n */\n public translatorFor(snippet: TypeScriptSnippet) {\n const translator = new SnippetTranslator(snippet, {\n compiler: this.compiler,\n includeCompilerDiagnostics: this.includeCompilerDiagnostics,\n });\n return translator;\n }\n}\n\nexport interface SnippetTranslatorOptions extends AstRendererOptions {\n /**\n * Re-use the given compiler if given\n */\n readonly compiler?: TypeScriptCompiler;\n\n /**\n * Include compiler errors in return diagnostics\n *\n * If false, only translation diagnostics will be returned.\n *\n * @default false\n */\n readonly includeCompilerDiagnostics?: boolean;\n}\n\nexport interface TranslateResult {\n translation: string;\n diagnostics: readonly RosettaDiagnostic[];\n}\n\n/**\n * A translation of a TypeScript diagnostic into a data-only representation for Rosetta\n *\n * We cannot use the original `ts.Diagnostic` since it holds on to way too much\n * state (the source file and by extension the entire parse tree), which grows\n * too big to be properly serialized by a worker and also takes too much memory.\n *\n * Reduce it down to only the information we need.\n */\nexport interface RosettaDiagnostic {\n /**\n * If this is an error diagnostic or not\n */\n readonly isError: boolean;\n\n /**\n * If the diagnostic was emitted from an assembly that has its 'strict' flag set\n */\n readonly isFromStrictAssembly: boolean;\n\n /**\n * The formatted message, ready to be printed (will have colors and newlines in it)\n *\n * Ends in a newline.\n */\n readonly formattedMessage: string;\n}\n\nexport function makeRosettaDiagnostic(isError: boolean, formattedMessage: string): RosettaDiagnostic {\n return { isError, formattedMessage, isFromStrictAssembly: false };\n}\n\n/**\n * Translate a single TypeScript snippet\n */\nexport class SnippetTranslator {\n public readonly translateDiagnostics: ts.Diagnostic[] = [];\n public readonly compileDiagnostics: ts.Diagnostic[] = [];\n private readonly visibleSpans: Spans;\n private readonly compilation!: CompilationResult;\n private readonly tryCompile: boolean;\n private readonly submoduleReferences: SubmoduleReferenceMap;\n\n public constructor(snippet: TypeScriptSnippet, private readonly options: SnippetTranslatorOptions = {}) {\n const compiler = options.compiler ?? new TypeScriptCompiler();\n const source = completeSource(snippet);\n const fakeCurrentDirectory = snippet.parameters?.[SnippetParameters.$COMPILATION_DIRECTORY] ?? process.cwd();\n this.compilation = compiler.compileInMemory(\n removeSlashes(formatLocation(snippet.location)),\n source,\n fakeCurrentDirectory,\n );\n\n // Respect '/// !hide' and '/// !show' directives\n this.visibleSpans = Spans.visibleSpansFromSource(source);\n\n // Find submodule references on explicit imports\n this.submoduleReferences = SubmoduleReference.inSourceFile(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n );\n\n // This makes it about 5x slower, so only do it on demand\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n this.tryCompile = (options.includeCompilerDiagnostics || snippet.strict) ?? false;\n if (this.tryCompile) {\n const program = this.compilation.program;\n const diagnostics = [\n ...neverThrowing(program.getGlobalDiagnostics)(),\n ...neverThrowing(program.getSyntacticDiagnostics)(this.compilation.rootFile),\n ...neverThrowing(program.getDeclarationDiagnostics)(this.compilation.rootFile),\n ...neverThrowing(program.getSemanticDiagnostics)(this.compilation.rootFile),\n ];\n if (snippet.strict) {\n // In a strict assembly, so we'll need to brand all diagnostics here...\n for (const diag of diagnostics) {\n annotateStrictDiagnostic(diag);\n }\n }\n this.compileDiagnostics.push(...diagnostics);\n }\n\n /**\n * Intercepts all exceptions thrown by the wrapped call, and logs them to\n * console.error instead of re-throwing, then returns an empty array. This\n * is here to avoid compiler crashes due to broken code examples that cause\n * the TypeScript compiler to hit a \"Debug Failure\".\n */\n function neverThrowing<A extends unknown[], R>(call: (...args: A) => readonly R[]): (...args: A) => readonly R[] {\n return (...args: A) => {\n try {\n return call(...args);\n } catch (err: any) {\n const isExpectedTypescriptError = err.message.includes('Debug Failure');\n\n if (!isExpectedTypescriptError) {\n console.error(`Failed to execute ${call.name}: ${err}`);\n }\n\n return [];\n }\n };\n }\n }\n\n /**\n * Returns a boolean if compilation was attempted, and undefined if it was not.\n */\n public get didSuccessfullyCompile() {\n return this.tryCompile ? this.compileDiagnostics.length === 0 : undefined;\n }\n\n public renderUsing(visitor: AstHandler<any>) {\n const converter = new AstRenderer(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n visitor,\n this.options,\n // If we support transitive submodule access, don't provide a submodule reference map.\n supportsTransitiveSubmoduleAccess(visitor.language) ? undefined : this.submoduleReferences,\n );\n const converted = converter.convert(this.compilation.rootFile);\n this.translateDiagnostics.push(...filterVisibleDiagnostics(converter.diagnostics, this.visibleSpans));\n return renderTree(converted, { indentChar: visitor.indentChar, visibleSpans: this.visibleSpans });\n }\n\n public syntaxKindCounter(): Partial<Record<ts.SyntaxKind, number>> {\n const kindCounter = new SyntaxKindCounter(this.visibleSpans);\n return kindCounter.countKinds(this.compilation.rootFile);\n }\n\n public fqnsReferenced() {\n const visitor = new RecordReferencesVisitor(this.visibleSpans);\n const converter = new AstRenderer(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n visitor,\n this.options,\n this.submoduleReferences,\n );\n converter.convert(this.compilation.rootFile);\n return visitor.fqnsReferenced();\n }\n\n public get diagnostics(): readonly ts.Diagnostic[] {\n return ts.sortAndDeduplicateDiagnostics(this.compileDiagnostics.concat(this.translateDiagnostics));\n }\n}\n\n/**\n * Hide diagnostics that are rosetta-sourced if they are reported against a non-visible span\n */\nfunction filterVisibleDiagnostics(diags: readonly ts.Diagnostic[], visibleSpans: Spans): ts.Diagnostic[] {\n return diags.filter((d) => d.source !== 'rosetta' || d.start === undefined || visibleSpans.containsPosition(d.start));\n}\n\n/**\n * Turn TypeScript diagnostics into Rosetta diagnostics\n */\nexport function rosettaDiagFromTypescript(diag: ts.Diagnostic): RosettaDiagnostic {\n return {\n isError: diag.category === ts.DiagnosticCategory.Error,\n isFromStrictAssembly: hasStrictBranding(diag),\n formattedMessage: ts.formatDiagnosticsWithColorAndContext([diag], DIAG_HOST),\n };\n}\n\nconst DIAG_HOST = {\n getCurrentDirectory() {\n return '.';\n },\n getCanonicalFileName(fileName: string) {\n return fileName;\n },\n getNewLine() {\n return '\\n';\n },\n};\n\n/**\n * Remove slashes from a \"where\" description, as the TS compiler will interpret it as a directory\n * and we can't have that for compiling literate files\n */\nfunction removeSlashes(x: string) {\n return x.replace(/\\/|\\\\/g, '.');\n}\n"]}
1
+ {"version":3,"file":"translate.js","sourceRoot":"","sources":["../src/translate.ts"],"names":[],"mappings":";;;;;;;;;AAAA,yCAAoC;AACpC,iCAAiC;AAEjC,2CAA+D;AAC/D,qEAAwE;AACxE,iEAAgF;AAChF,qCAAqC;AACrC,qCAAsC;AACtC,yCAAyE;AACzE,uCAAiG;AACjG,+DAAkF;AAClF,uCAA2C;AAC3C,6CAAwD;AACxD,+CAAsD;AACtD,0EAAqE;AACrE,0DAAiF;AACjF,8DAAmD;AACnD,iCAAmF;AAEnF,SAAgB,mBAAmB,CACjC,MAAY,EACZ,OAAwB,EACxB,UAAoC,EAAE;IAEtC,MAAM,UAAU,GAAG,IAAI,iBAAiB,CACtC,EAAE,aAAa,EAAE,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,EAAE,GAAG,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,EAAE,EAAE,EACjG,OAAO,CACR,CAAC;IACF,MAAM,UAAU,GAAG,UAAU,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAEnD,OAAO;QACL,WAAW,EAAE,UAAU;QACvB,WAAW,EAAE,UAAU,CAAC,WAAW,CAAC,GAAG,CAAC,yBAAyB,CAAC;KACnE,CAAC;AACJ,CAAC;AAfD,kDAeC;AAED;;;;;GAKG;AACH,MAAa,UAAU;IAKrB,YAAoC,0BAAmC;QAA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AAC,KAAK,KAAK,SAAS,IAAI,YAAY,CAAC,gBAAgB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;AACxH,CAAC;AAED;;GAEG;AACH,SAAgB,yBAAyB,CAAC,IAAmB;IAC3D,OAAO;QACL,OAAO,EAAE,IAAI,CAAC,QAAQ,KAAK,EAAE,CAAC,kBAAkB,CAAC,KAAK;QACtD,oBAAoB,EAAE,IAAA,wBAAiB,EAAC,IAAI,CAAC;QAC7C,gBAAgB,EAAE,EAAE,CAAC,oCAAoC,CAAC,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC;KAC7E,CAAC;AACJ,CAAC;AAND,8DAMC;AAED,MAAM,SAAS,GAAG;IAChB,mBAAmB;QACjB,OAAO,GAAG,CAAC;IACb,CAAC;IACD,oBAAoB,CAAC,QAAgB;QACnC,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,UAAU;QACR,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAC;AAEF;;;GAGG;AACH,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;AAClC,CAAC","sourcesContent":["import { inspect } from 'node:util';\nimport * as ts from 'typescript';\n\nimport { TARGET_LANGUAGES, TargetLanguage } from './languages';\nimport { RecordReferencesVisitor } from './languages/record-references';\nimport { supportsTransitiveSubmoduleAccess } from './languages/target-language';\nimport * as logging from './logging';\nimport { renderTree } from './o-tree';\nimport { AstRenderer, AstHandler, AstRendererOptions } from './renderer';\nimport { TypeScriptSnippet, completeSource, SnippetParameters, formatLocation } from './snippet';\nimport { SubmoduleReference, SubmoduleReferenceMap } from './submodule-reference';\nimport { snippetKey } from './tablets/key';\nimport { ORIGINAL_SNIPPET_KEY } from './tablets/schema';\nimport { TranslatedSnippet } from './tablets/tablets';\nimport { SyntaxKindCounter } from './typescript/syntax-kind-counter';\nimport { TypeScriptCompiler, CompilationResult } from './typescript/ts-compiler';\nimport { Spans } from './typescript/visible-spans';\nimport { annotateStrictDiagnostic, File, hasStrictBranding, mkDict } from './util';\n\nexport function translateTypeScript(\n source: File,\n visitor: AstHandler<any>,\n options: SnippetTranslatorOptions = {},\n): TranslateResult {\n const translator = new SnippetTranslator(\n { visibleSource: source.contents, location: { api: { api: 'file', fileName: source.fileName } } },\n options,\n );\n const translated = translator.renderUsing(visitor);\n\n return {\n translation: translated,\n diagnostics: translator.diagnostics.map(rosettaDiagFromTypescript),\n };\n}\n\n/**\n * Translate one or more TypeScript snippets into other languages\n *\n * Can be configured to fully typecheck the samples, or perform only syntactical\n * translation.\n */\nexport class Translator {\n private readonly compiler = new TypeScriptCompiler();\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n #diagnostics: ts.Diagnostic[] = [];\n\n public constructor(private readonly includeCompilerDiagnostics: boolean) {}\n\n public translate(snip: TypeScriptSnippet, languages: readonly TargetLanguage[] = Object.values(TargetLanguage)) {\n logging.debug(`Translating ${snippetKey(snip)} ${inspect(snip.parameters ?? {})}`);\n const translator = this.translatorFor(snip);\n\n const translations = mkDict(\n languages.flatMap((lang, idx, array) => {\n if (array.slice(0, idx).includes(lang)) {\n // This language was duplicated in the request... we'll skip that here...\n return [];\n }\n const languageConverterFactory = TARGET_LANGUAGES[lang];\n const translated = translator.renderUsing(languageConverterFactory.createVisitor());\n return [[lang, { source: translated, version: languageConverterFactory.version }] as const];\n }),\n );\n\n if (snip.parameters?.infused === undefined) {\n this.#diagnostics.push(...translator.diagnostics);\n }\n\n return TranslatedSnippet.fromSchema({\n translations: {\n ...translations,\n [ORIGINAL_SNIPPET_KEY]: { source: snip.visibleSource, version: '0' },\n },\n location: snip.location,\n didCompile: translator.didSuccessfullyCompile,\n fqnsReferenced: translator.fqnsReferenced(),\n fullSource: completeSource(snip),\n syntaxKindCounter: translator.syntaxKindCounter(),\n });\n }\n\n public get diagnostics(): readonly RosettaDiagnostic[] {\n return ts.sortAndDeduplicateDiagnostics(this.#diagnostics).map(rosettaDiagFromTypescript);\n }\n\n /**\n * Return the snippet translator for the given snippet\n *\n * We used to cache these, but each translator holds on to quite a bit of memory,\n * so we don't do that anymore.\n */\n public translatorFor(snippet: TypeScriptSnippet) {\n const translator = new SnippetTranslator(snippet, {\n compiler: this.compiler,\n includeCompilerDiagnostics: this.includeCompilerDiagnostics,\n });\n return translator;\n }\n}\n\nexport interface SnippetTranslatorOptions extends AstRendererOptions {\n /**\n * Re-use the given compiler if given\n */\n readonly compiler?: TypeScriptCompiler;\n\n /**\n * Include compiler errors in return diagnostics\n *\n * If false, only translation diagnostics will be returned.\n *\n * @default false\n */\n readonly includeCompilerDiagnostics?: boolean;\n}\n\nexport interface TranslateResult {\n translation: string;\n diagnostics: readonly RosettaDiagnostic[];\n}\n\n/**\n * A translation of a TypeScript diagnostic into a data-only representation for Rosetta\n *\n * We cannot use the original `ts.Diagnostic` since it holds on to way too much\n * state (the source file and by extension the entire parse tree), which grows\n * too big to be properly serialized by a worker and also takes too much memory.\n *\n * Reduce it down to only the information we need.\n */\nexport interface RosettaDiagnostic {\n /**\n * If this is an error diagnostic or not\n */\n readonly isError: boolean;\n\n /**\n * If the diagnostic was emitted from an assembly that has its 'strict' flag set\n */\n readonly isFromStrictAssembly: boolean;\n\n /**\n * The formatted message, ready to be printed (will have colors and newlines in it)\n *\n * Ends in a newline.\n */\n readonly formattedMessage: string;\n}\n\nexport function makeRosettaDiagnostic(isError: boolean, formattedMessage: string): RosettaDiagnostic {\n return { isError, formattedMessage, isFromStrictAssembly: false };\n}\n\n/**\n * Translate a single TypeScript snippet\n */\nexport class SnippetTranslator {\n public readonly translateDiagnostics: ts.Diagnostic[] = [];\n public readonly compileDiagnostics: ts.Diagnostic[] = [];\n private readonly visibleSpans: Spans;\n private readonly compilation!: CompilationResult;\n private readonly tryCompile: boolean;\n private readonly submoduleReferences: SubmoduleReferenceMap;\n\n public constructor(snippet: TypeScriptSnippet, private readonly options: SnippetTranslatorOptions = {}) {\n const compiler = options.compiler ?? new TypeScriptCompiler();\n const source = completeSource(snippet);\n const fakeCurrentDirectory = snippet.parameters?.[SnippetParameters.$COMPILATION_DIRECTORY] ?? process.cwd();\n this.compilation = compiler.compileInMemory(\n removeSlashes(formatLocation(snippet.location)),\n source,\n fakeCurrentDirectory,\n );\n\n // Respect '/// !hide' and '/// !show' directives\n this.visibleSpans = Spans.visibleSpansFromSource(source);\n\n // Find submodule references on explicit imports\n this.submoduleReferences = SubmoduleReference.inSourceFile(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n );\n\n // This makes it about 5x slower, so only do it on demand\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n this.tryCompile = (options.includeCompilerDiagnostics || snippet.strict) ?? false;\n if (this.tryCompile) {\n const program = this.compilation.program;\n const diagnostics = [\n ...neverThrowing(program.getGlobalDiagnostics)(),\n ...neverThrowing(program.getSyntacticDiagnostics)(this.compilation.rootFile),\n ...neverThrowing(program.getDeclarationDiagnostics)(this.compilation.rootFile),\n ...neverThrowing(program.getSemanticDiagnostics)(this.compilation.rootFile),\n ];\n if (snippet.strict) {\n // In a strict assembly, so we'll need to brand all diagnostics here...\n for (const diag of diagnostics) {\n annotateStrictDiagnostic(diag);\n }\n }\n this.compileDiagnostics.push(...diagnostics);\n }\n\n /**\n * Intercepts all exceptions thrown by the wrapped call, and logs them to\n * console.error instead of re-throwing, then returns an empty array. This\n * is here to avoid compiler crashes due to broken code examples that cause\n * the TypeScript compiler to hit a \"Debug Failure\".\n */\n function neverThrowing<A extends unknown[], R>(call: (...args: A) => readonly R[]): (...args: A) => readonly R[] {\n return (...args: A) => {\n try {\n return call(...args);\n } catch (err: any) {\n const isExpectedTypescriptError = err.message.includes('Debug Failure');\n\n if (!isExpectedTypescriptError) {\n console.error(`Failed to execute ${call.name}: ${err}`);\n }\n\n return [];\n }\n };\n }\n }\n\n /**\n * Returns a boolean if compilation was attempted, and undefined if it was not.\n */\n public get didSuccessfullyCompile() {\n return this.tryCompile ? this.compileDiagnostics.length === 0 : undefined;\n }\n\n public renderUsing(visitor: AstHandler<any>) {\n const converter = new AstRenderer(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n visitor,\n this.options,\n // If we support transitive submodule access, don't provide a submodule reference map.\n supportsTransitiveSubmoduleAccess(visitor.language) ? undefined : this.submoduleReferences,\n );\n const converted = converter.convert(this.compilation.rootFile);\n this.translateDiagnostics.push(...filterVisibleDiagnostics(converter.diagnostics, this.visibleSpans));\n return renderTree(converted, { indentChar: visitor.indentChar, visibleSpans: this.visibleSpans });\n }\n\n public syntaxKindCounter(): Partial<Record<ts.SyntaxKind, number>> {\n const kindCounter = new SyntaxKindCounter(this.visibleSpans);\n return kindCounter.countKinds(this.compilation.rootFile);\n }\n\n public fqnsReferenced() {\n const visitor = new RecordReferencesVisitor(this.visibleSpans);\n const converter = new AstRenderer(\n this.compilation.rootFile,\n this.compilation.program.getTypeChecker(),\n visitor,\n this.options,\n this.submoduleReferences,\n );\n converter.convert(this.compilation.rootFile);\n return visitor.fqnsReferenced();\n }\n\n public get diagnostics(): readonly ts.Diagnostic[] {\n return ts.sortAndDeduplicateDiagnostics(this.compileDiagnostics.concat(this.translateDiagnostics));\n }\n}\n\n/**\n * Hide diagnostics that are rosetta-sourced if they are reported against a non-visible span\n */\nfunction filterVisibleDiagnostics(diags: readonly ts.Diagnostic[], visibleSpans: Spans): ts.Diagnostic[] {\n return diags.filter((d) => d.source !== 'rosetta' || d.start === undefined || visibleSpans.containsPosition(d.start));\n}\n\n/**\n * Turn TypeScript diagnostics into Rosetta diagnostics\n */\nexport function rosettaDiagFromTypescript(diag: ts.Diagnostic): RosettaDiagnostic {\n return {\n isError: diag.category === ts.DiagnosticCategory.Error,\n isFromStrictAssembly: hasStrictBranding(diag),\n formattedMessage: ts.formatDiagnosticsWithColorAndContext([diag], DIAG_HOST),\n };\n}\n\nconst DIAG_HOST = {\n getCurrentDirectory() {\n return '.';\n },\n getCanonicalFileName(fileName: string) {\n return fileName;\n },\n getNewLine() {\n return '\\n';\n },\n};\n\n/**\n * Remove slashes from a \"where\" description, as the TS compiler will interpret it as a directory\n * and we can't have that for compiling literate files\n */\nfunction removeSlashes(x: string) {\n return x.replace(/\\/|\\\\/g, '.');\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"translate_all.js","sourceRoot":"","sources":["../src/translate_all.ts"],"names":[],"mappings":";;;AAAA,8BAA8B;AAC9B,kCAAkC;AAClC,yCAAyC;AAEzC,qCAAqC;AAErC,+CAAsD;AAItD;;;;;;;;;GASG;AACI,KAAK,UAAU,YAAY,CAChC,QAA6B,EAC7B,0BAAmC;IAEnC,6EAA6E;IAC7E,6EAA6E;IAC7E,qDAAqD;IACrD,2FAA2F;IAC3F,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,6BAA6B;QACjD,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC;QACrD,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,eAAe,UAAU,CAAC,MAAM,mBAAmB,CAAC,UAAU,CAAC,CAAC;IAE7E,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,yBAAyB,CAAC,EAAE;QAC5E,UAAU,EAAE,CAAC;KACd,CAAC,CAAC;IAEH,IAAI;QACF,MAAM,QAAQ,GAAG,aAAa,CAAC,UAAU,EAAE,0BAA0B,CAAC,CAAC;QAEvE,MAAM,SAAS,GAA6B,MAAM,OAAO,CAAC,GAAG,CAC3D,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAClE,CAAC;QAEF,MAAM,WAAW,GAAG,IAAI,KAAK,EAAqB,CAAC;QACnD,MAAM,kBAAkB,GAAG,IAAI,KAAK,EAAqB,CAAC;QAE1D,kBAAkB;QAClB,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE;YAChC,WAAW,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,CAAC;YAC1C,kBAAkB,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,iBAAiB,CAAC,GAAG,CAAC,2BAAiB,CAAC,UAAU,CAAC,CAAC,CAAC;SAC1F;QACD,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,CAAC;KAC5C;YAAS;QACR,yBAAyB;QACzB,KAAK,IAAI,CAAC,SAAS,EAAE,CAAC;KACvB;AACH,CAAC;AAtCD,oCAsCC;AAED,SAAS,aAAa,CACpB,QAA6B,EAC7B,0BAAmC,EACnC,SAAS,GAAG,EAAE;IAEd,MAAM,GAAG,GAAG,EAAE,CAAC;IAEf,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,SAAS,EAAE;QACnD,GAAG,CAAC,IAAI,CAAC;YACP,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC;YAC1C,0BAA0B;SAC3B,CAAC,CAAC;KACJ;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as workerpool from 'workerpool';\n\nimport * as logging from './logging';\nimport { TypeScriptSnippet } from './snippet';\nimport { TranslatedSnippet } from './tablets/tablets';\nimport { RosettaDiagnostic } from './translate';\nimport type { TranslateBatchRequest, TranslateBatchResponse } from './translate_all_worker';\n\n/**\n * Divide the work evenly over all processors by running 'translate_all_worker' in Worker Threads, then combine results\n *\n * The workers are fed small queues of work each. We used to divide the entire queue into N\n * but since the work is divided unevenly that led to some workers stopping early, idling while\n * waiting for more work.\n *\n * Never include 'translate_all_worker' directly, only do TypeScript type references (so that in\n * the script we may assume that 'worker_threads' successfully imports).\n */\nexport async function translateAll(\n snippets: TypeScriptSnippet[],\n includeCompilerDiagnostics: boolean,\n): Promise<TranslateAllResult> {\n // Use about half the advertised cores because hyperthreading doesn't seem to\n // help that much, or we become I/O-bound at some point. On my machine, using\n // more than half the cores actually makes it slower.\n // Cap to a reasonable top-level limit to prevent thrash on machines with many, many cores.\n const N = process.env.JSII_ROSETTA_MAX_WORKER_COUNT\n ? parseInt(process.env.JSII_ROSETTA_MAX_WORKER_COUNT)\n : Math.min(16, Math.max(1, Math.ceil(os.cpus().length / 2)));\n const snippetArr = Array.from(snippets);\n logging.info(`Translating ${snippetArr.length} snippets using ${N} workers`);\n\n const pool = workerpool.pool(path.join(__dirname, 'translate_all_worker.js'), {\n maxWorkers: N,\n });\n\n try {\n const requests = batchSnippets(snippetArr, includeCompilerDiagnostics);\n\n const responses: TranslateBatchResponse[] = await Promise.all(\n requests.map((request) => pool.exec('translateBatch', [request])),\n );\n\n const diagnostics = new Array<RosettaDiagnostic>();\n const translatedSnippets = new Array<TranslatedSnippet>();\n\n // Combine results\n for (const response of responses) {\n diagnostics.push(...response.diagnostics);\n translatedSnippets.push(...response.translatedSchemas.map(TranslatedSnippet.fromSchema));\n }\n return { diagnostics, translatedSnippets };\n } finally {\n // Not waiting on purpose\n void pool.terminate();\n }\n}\n\nfunction batchSnippets(\n snippets: TypeScriptSnippet[],\n includeCompilerDiagnostics: boolean,\n batchSize = 10,\n): TranslateBatchRequest[] {\n const ret = [];\n\n for (let i = 0; i < snippets.length; i += batchSize) {\n ret.push({\n snippets: snippets.slice(i, i + batchSize),\n includeCompilerDiagnostics,\n });\n }\n\n return ret;\n}\n\nexport interface TranslateAllResult {\n translatedSnippets: TranslatedSnipp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,GAAG,IAAI,KAAK,EAAqB,CAAC;QACnD,MAAM,kBAAkB,GAAG,IAAI,KAAK,EAAqB,CAAC;QAE1D,kBAAkB;QAClB,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;YACjC,WAAW,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,CAAC;YAC1C,kBAAkB,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,iBAAiB,CAAC,GAAG,CAAC,2BAAiB,CAAC,UAAU,CAAC,CAAC,CAAC;QAC3F,CAAC;QACD,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,CAAC;IAC7C,CAAC;YAAS,CAAC;QACT,yBAAyB;QACzB,KAAK,IAAI,CAAC,SAAS,EAAE,CAAC;IACxB,CAAC;AACH,CAAC;AAtCD,oCAsCC;AAED,SAAS,aAAa,CACpB,QAA6B,EAC7B,0BAAmC,EACnC,SAAS,GAAG,EAAE;IAEd,MAAM,GAAG,GAAG,EAAE,CAAC;IAEf,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,SAAS,EAAE,CAAC;QACpD,GAAG,CAAC,IAAI,CAAC;YACP,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC;YAC1C,0BAA0B;SAC3B,CAAC,CAAC;IACL,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as workerpool from 'workerpool';\n\nimport * as logging from './logging';\nimport { TypeScriptSnippet } from './snippet';\nimport { TranslatedSnippet } from './tablets/tablets';\nimport { RosettaDiagnostic } from './translate';\nimport type { TranslateBatchRequest, TranslateBatchResponse } from './translate_all_worker';\n\n/**\n * Divide the work evenly over all processors by running 'translate_all_worker' in Worker Threads, then combine results\n *\n * The workers are fed small queues of work each. We used to divide the entire queue into N\n * but since the work is divided unevenly that led to some workers stopping early, idling while\n * waiting for more work.\n *\n * Never include 'translate_all_worker' directly, only do TypeScript type references (so that in\n * the script we may assume that 'worker_threads' successfully imports).\n */\nexport async function translateAll(\n snippets: TypeScriptSnippet[],\n includeCompilerDiagnostics: boolean,\n): Promise<TranslateAllResult> {\n // Use about half the advertised cores because hyperthreading doesn't seem to\n // help that much, or we become I/O-bound at some point. On my machine, using\n // more than half the cores actually makes it slower.\n // Cap to a reasonable top-level limit to prevent thrash on machines with many, many cores.\n const N = process.env.JSII_ROSETTA_MAX_WORKER_COUNT\n ? parseInt(process.env.JSII_ROSETTA_MAX_WORKER_COUNT)\n : Math.min(16, Math.max(1, Math.ceil(os.cpus().length / 2)));\n const snippetArr = Array.from(snippets);\n logging.info(`Translating ${snippetArr.length} snippets using ${N} workers`);\n\n const pool = workerpool.pool(path.join(__dirname, 'translate_all_worker.js'), {\n maxWorkers: N,\n });\n\n try {\n const requests = batchSnippets(snippetArr, includeCompilerDiagnostics);\n\n const responses: TranslateBatchResponse[] = await Promise.all(\n requests.map((request) => pool.exec('translateBatch', [request])),\n );\n\n const diagnostics = new Array<RosettaDiagnostic>();\n const translatedSnippets = new Array<TranslatedSnippet>();\n\n // Combine results\n for (const response of responses) {\n diagnostics.push(...response.diagnostics);\n translatedSnippets.push(...response.translatedSchemas.map(TranslatedSnippet.fromSchema));\n }\n return { diagnostics, translatedSnippets };\n } finally {\n // Not waiting on purpose\n void pool.terminate();\n }\n}\n\nfunction batchSnippets(\n snippets: TypeScriptSnippet[],\n includeCompilerDiagnostics: boolean,\n batchSize = 10,\n): TranslateBatchRequest[] {\n const ret = [];\n\n for (let i = 0; i < snippets.length; i += batchSize) {\n ret.push({\n snippets: snippets.slice(i, i + batchSize),\n includeCompilerDiagnostics,\n });\n }\n\n return ret;\n}\n\nexport interface TranslateAllResult {\n translatedSnippets: TranslatedSnippet[];\n diagnostics: RosettaDiagnostic[];\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"translate_all_worker.js","sourceRoot":"","sources":["../src/translate_all_worker.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,yCAAyC;AAKzC,2CAAmF;AAcnF,SAAS,cAAc,CAAC,OAA8B;IACpD,MAAM,MAAM,GAAG,0BAA0B,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,0BAA0B,CAAC,CAAC;IAEhG,OAAO;QACL,iBAAiB,EAAE,MAAM,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;QAClE,WAAW,EAAE,MAAM,CAAC,WAAW;KAChC,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,SAAgB,0BAA0B,CACxC,QAA6B,EAC7B,0BAAmC;IAEnC,MAAM,kBAAkB,GAAG,IAAI,KAAK,EAAqB,CAAC;IAE1D,MAAM,QAAQ,GAAG,IAAI,KAAK,EAAqB,CAAC;IAEhD,MAAM,UAAU,GAAG,IAAI,sBAAU,CAAC,0BAA0B,CAAC,CAAC;IAC9D,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE;QAC5B,IAAI;YACF,kBAAkB,CAAC,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;SACtD;QAAC,OAAO,CAAM,EAAE;YACf,QAAQ,CAAC,IAAI,CACX,IAAA,iCAAqB,EAAC,IAAI,EAAE,uCAAuC,CAAC,KAAK,CAAC,CAAC,KAAK,KAAK,KAAK,CAAC,cAAc,EAAE,CAAC,CAC7G,CAAC;SACH;KACF;IAED,OAAO;QACL,kBAAkB;QAClB,WAAW,EAAE,CAAC,GAAG,UAAU,CAAC,WAAW,EAAE,GAAG,QAAQ,CAAC;KACtD,CAAC;AACJ,CAAC;AAvBD,gEAuBC;AAED,UAAU,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC","sourcesContent":["/**\n * Pool worker for extract.ts\n */\nimport * as workerpool from 'workerpool';\n\nimport { TypeScriptSnippet } from './snippet';\nimport { TranslatedSnippetSchema } from './tablets/schema';\nimport { TranslatedSnippet } from './tablets/tablets';\nimport { RosettaDiagnostic, Translator, makeRosettaDiagnostic } from './translate';\nimport { TranslateAllResult } from './translate_all';\n\nexport interface TranslateBatchRequest {\n readonly snippets: TypeScriptSnippet[];\n readonly includeCompilerDiagnostics: boolean;\n}\n\nexport interface TranslateBatchResponse {\n // Cannot be 'TranslatedSnippet' because needs to be serializable\n readonly translatedSchemas: TranslatedSnippetSchema[];\n readonly diagnostics: RosettaDiagnostic[];\n}\n\nfunction translateBatch(request: TranslateBatchRequest): TranslateBatchResponse {\n const result = singleThreadedTranslateAll(request.snippets, request.includeCompilerDiagnostics);\n\n return {\n translatedSchemas: result.translatedSnippets.map((s) => s.snippet),\n diagnostics: result.diagnostics,\n };\n}\n\n/**\n * Translate the given snippets using a single compiler\n */\nexport function singleThreadedTranslateAll(\n snippets: TypeScriptSnippet[],\n includeCompilerDiagnostics: boolean,\n): TranslateAllResult {\n const translatedSnippets = new Array<TranslatedSnippet>();\n\n const failures = new Array<RosettaDiagnostic>();\n\n const translator = new Translator(includeCompilerDiagnostics);\n for (const block of snippets) {\n try {\n translatedSnippets.push(translator.translate(block));\n } catch (e: any) {\n failures.push(\n makeRosettaDiagnostic(true, `rosetta: error translating snippet: ${e}\\n${e.stack}\\n${block.completeSource}`),\n );\n }\n }\n\n return {\n translatedSnippets,\n diagnostics: [...translator.diagnostics, ...failures],\n };\n}\n\nworkerpool.worker({ translateBatch });\n"]}
1
+ {"version":3,"file":"translate_all_worker.js","sourceRoot":"","sources":["../src/translate_all_worker.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,yCAAyC;AAKzC,2CAAmF;AAcnF,SAAS,cAAc,CAAC,OAA8B;IACpD,MAAM,MAAM,GAAG,0BAA0B,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,0BAA0B,CAAC,CAAC;IAEhG,OAAO;QACL,iBAAiB,EAAE,MAAM,CAAC,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;QAClE,WAAW,EAAE,MAAM,CAAC,WAAW;KAChC,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,SAAgB,0BAA0B,CACxC,QAA6B,EAC7B,0BAAmC;IAEnC,MAAM,kBAAkB,GAAG,IAAI,KAAK,EAAqB,CAAC;IAE1D,MAAM,QAAQ,GAAG,IAAI,KAAK,EAAqB,CAAC;IAEhD,MAAM,UAAU,GAAG,IAAI,sBAAU,CAAC,0BAA0B,CAAC,CAAC;IAC9D,KAAK,MAAM,KAAK,IAAI,QAAQ,EAAE,CAAC;QAC7B,IAAI,CAAC;YACH,kBAAkB,CAAC,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;QACvD,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,QAAQ,CAAC,IAAI,CACX,IAAA,iCAAqB,EAAC,IAAI,EAAE,uCAAuC,CAAC,KAAK,CAAC,CAAC,KAAK,KAAK,KAAK,CAAC,cAAc,EAAE,CAAC,CAC7G,CAAC;QACJ,CAAC;IACH,CAAC;IAED,OAAO;QACL,kBAAkB;QAClB,WAAW,EAAE,CAAC,GAAG,UAAU,CAAC,WAAW,EAAE,GAAG,QAAQ,CAAC;KACtD,CAAC;AACJ,CAAC;AAvBD,gEAuBC;AAED,UAAU,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC","sourcesContent":["/**\n * Pool worker for extract.ts\n */\nimport * as workerpool from 'workerpool';\n\nimport { TypeScriptSnippet } from './snippet';\nimport { TranslatedSnippetSchema } from './tablets/schema';\nimport { TranslatedSnippet } from './tablets/tablets';\nimport { RosettaDiagnostic, Translator, makeRosettaDiagnostic } from './translate';\nimport { TranslateAllResult } from './translate_all';\n\nexport interface TranslateBatchRequest {\n readonly snippets: TypeScriptSnippet[];\n readonly includeCompilerDiagnostics: boolean;\n}\n\nexport interface TranslateBatchResponse {\n // Cannot be 'TranslatedSnippet' because needs to be serializable\n readonly translatedSchemas: TranslatedSnippetSchema[];\n readonly diagnostics: RosettaDiagnostic[];\n}\n\nfunction translateBatch(request: TranslateBatchRequest): TranslateBatchResponse {\n const result = singleThreadedTranslateAll(request.snippets, request.includeCompilerDiagnostics);\n\n return {\n translatedSchemas: result.translatedSnippets.map((s) => s.snippet),\n diagnostics: result.diagnostics,\n };\n}\n\n/**\n * Translate the given snippets using a single compiler\n */\nexport function singleThreadedTranslateAll(\n snippets: TypeScriptSnippet[],\n includeCompilerDiagnostics: boolean,\n): TranslateAllResult {\n const translatedSnippets = new Array<TranslatedSnippet>();\n\n const failures = new Array<RosettaDiagnostic>();\n\n const translator = new Translator(includeCompilerDiagnostics);\n for (const block of snippets) {\n try {\n translatedSnippets.push(translator.translate(block));\n } catch (e: any) {\n failures.push(\n makeRosettaDiagnostic(true, `rosetta: error translating snippet: ${e}\\n${e.stack}\\n${block.completeSource}`),\n );\n }\n }\n\n return {\n translatedSnippets,\n diagnostics: [...translator.diagnostics, ...failures],\n };\n}\n\nworkerpool.worker({ translateBatch });\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ast-utils.js","sourceRoot":"","sources":["../../src/typescript/ast-utils.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAIjC,SAAgB,mBAAmB,CAAC,OAAe,EAAE,SAAkB;IACrE,IAAI,SAAS,EAAE;QACb,qDAAqD;QACrD,2EAA2E;QAC3E,wCAAwC;QACxC,OAAO,OAAO;aACX,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;aAChC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,8BAA8B;aACtD,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,+BAA+B;aACvD,OAAO,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC,CAAC,gCAAgC;KACtE;IACD,kCAAkC;IAClC,OAAO,OA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F,CAAC;AAHD,oDAGC;AAED,SAAgB,6BAA6B,CAAC,IAAa;IACzD,OAAO,IAAI,IAAI,CAAC,EAAE,CAAC,kBAAkB,CAAC,IAAI,CAAC,EAAE;QAC3C,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC;KACpB;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AALD,sEAKC","sourcesContent":["import * as ts from 'typescript';\n\nimport { AstRenderer } from '../renderer';\n\nexport function stripCommentMarkers(comment: string, multiline: boolean) {\n if (multiline) {\n // The text *must* start with '/*' and end with '*/'.\n // Strip leading '*' from every remaining line (first line because of '**',\n // other lines because of continuations.\n return comment\n .substring(2, comment.length - 2)\n .replace(/^[ \\t]+/g, '') // Strip all leading whitepace\n .replace(/[ \\t]+$/g, '') // Strip all trailing whitepace\n .replace(/^[ \\t]*\\*[ \\t]?/gm, ''); // Strip \"* \" from start of line\n }\n // The text *must* start with '//'\n return comment.replace(/^[/]{2}[ \\t]?/gm, '');\n}\n\nexport function stringFromLiteral(expr: ts.Expression) {\n if (ts.isStringLiteral(expr)) {\n return expr.text;\n }\n return '???';\n}\n\n/**\n * All types of nodes that can be captured using `nodeOfType`, and the type of Node they map to\n */\nexport type CapturableNodes = {\n [ts.SyntaxKind.ImportDeclaration]: ts.ImportDeclaration;\n [ts.SyntaxKind.VariableDeclaration]: ts.VariableDeclaration;\n [ts.SyntaxKind.ExternalModuleReference]: ts.ExternalModuleReference;\n [ts.SyntaxKind.NamespaceImport]: ts.NamespaceImport;\n [ts.SyntaxKind.NamedImports]: ts.NamedImports;\n [ts.SyntaxKind.ImportSpecifier]: ts.ImportSpecifier;\n [ts.SyntaxKind.StringLiteral]: ts.StringLiteral;\n};\n\nexport type AstMatcher<A> = (nodes?: ts.Node[]) => A | undefined;\n\n/**\n * Return AST children of the given node\n *\n * Difference with node.getChildren():\n *\n * - node.getChildren() must take a SourceFile (will fail if it doesn't get it)\n * and returns a mix of abstract and concrete syntax nodes.\n * - This function function will ONLY return abstract syntax nodes.\n */\nexport function nodeChildren(node: ts.Node): ts.Node[] {\n const ret = new Array<ts.Node>();\n node.forEachChild((n) => {\n ret.push(n);\n });\n return ret;\n}\n\n/**\n * Match a single node of a given type\n *\n * Capture name is first so that the IDE can detect eagerly that we're falling into\n * that overload and properly autocomplete the recognized node types from CapturableNodes.\n *\n * Looks like SyntaxList nodes appear in the printed AST, but they don't actually appear\n */\nexport function nodeOfType<A>(syntaxKind: ts.SyntaxKind, children?: AstMatcher<A>): AstMatcher<A>;\n// eslint-disable-next-line max-len\nexport function nodeOfType<S extends keyof CapturableNodes, N extends string, A>(\n capture: N,\n capturableNodeType: S,\n children?: AstMatcher<A>,\n): AstMatcher<Omit<A, N> & { [key in N]: CapturableNodes[S] }>;\n// eslint-disable-next-line max-len\nexport function nodeOfType<S extends keyof CapturableNodes, N extends string, A>(\n syntaxKindOrCaptureName: ts.SyntaxKind | N,\n nodeTypeOrChildren?: S | AstMatcher<A>,\n children?: AstMatcher<A>,\n): AstMatcher<A> | AstMatcher<A & { [key in N]: CapturableNodes[S] }> {\n const capturing = typeof syntaxKindOrCaptureName === 'string'; // Determine which overload we're in (SyntaxKind is a number)\n\n const realNext = (capturing ? children : (nodeTypeOrChildren as AstMatcher<A>)) ?? DONE;\n const realCapture = capturing ? syntaxKindOrCaptureName : undefined;\n const realSyntaxKind = capturing ? nodeTypeOrChildren : syntaxKindOrCaptureName;\n\n return (nodes) => {\n for (const node of nodes ?? []) {\n if (node.kind === realSyntaxKind) {\n const ret = realNext(nodeChildren(node));\n if (!ret) {\n continue;\n }\n\n if (realCapture) {\n return Object.assign(ret, {\n [realCapture]: node as CapturableNodes[S],\n }) as any;\n }\n return ret;\n }\n }\n return undefined;\n };\n}\n\nexport function anyNode(): AstMatcher<Record<string, unknown>>;\nexport function anyNode<A>(children: AstMatcher<A>): AstMatcher<A>;\nexport function anyNode<A>(children?: AstMatcher<A>): AstMatcher<A> | AstMatcher<any> {\n const realNext = children ?? DONE;\n return (nodes) => {\n for (const node of nodes ?? []) {\n const m = realNext(nodeChildren(node));\n if (m) {\n return m;\n }\n }\n return undefined;\n };\n}\n\n// Does not capture deeper because how would we even represent that?\nexport function allOfType<S extends keyof CapturableNodes, N extends string, A>(\n s: S,\n name: N,\n children?: AstMatcher<A>,\n): AstMatcher<{ [key in N]: Array<CapturableNodes[S]> }> {\n type ArrayType = Array<CapturableNodes[S]>;\n type ReturnType = { [key in N]: ArrayType };\n const realNext = children ?? DONE;\n\n return (nodes) => {\n let ret: ReturnType | undefined;\n for (const node of nodes ?? []) {\n if (node.kind === s) {\n if (realNext(nodeChildren(node))) {\n if (!ret) {\n ret = { [name]: new Array<CapturableNodes[S]>() } as ReturnType;\n }\n ret[name].push(node as any);\n }\n }\n }\n return ret;\n };\n}\n\nexport const DONE: AstMatcher<Record<string, unknown>> = () => ({});\n\n/**\n * Run a matcher against a node and return (or invoke a callback with) the accumulated bindings\n */\nexport function matchAst<A>(node: ts.Node, matcher: AstMatcher<A>): A | undefined;\nexport function matchAst<A>(node: ts.Node, matcher: AstMatcher<A>, cb: (bindings: A) => void): boolean;\nexport function matchAst<A>(\n node: ts.Node,\n matcher: AstMatcher<A>,\n cb?: (bindings: A) => void,\n): boolean | A | undefined {\n const matched = matcher([node]);\n if (cb) {\n if (matched) {\n cb(matched);\n }\n return !!matched;\n }\n return matched;\n}\n\n/**\n * Count the newlines in a given piece of string that aren't in comment blocks\n */\nexport function countNakedNewlines(str: string) {\n let ret = 0;\n for (const s of scanText(str, 0, str.length).filter((r) => r.type === 'other' || r.type === 'blockcomment')) {\n if (s.type === 'other') {\n // Count newlines in non-comments\n for (let i = s.pos; i < s.end; i++) {\n if (str[i] === '\\n') {\n ret++;\n }\n }\n } else {\n // Discount newlines at the end of block comments\n if (s.hasTrailingNewLine) {\n ret--;\n }\n }\n }\n return ret;\n}\n\nexport function repeatNewlines(str: string) {\n return '\\n'.repeat(Math.min(2, countNakedNewlines(str)));\n}\n\nconst WHITESPACE = [' ', '\\t', '\\r', '\\n'];\n\n/**\n * Extract single-line and multi-line comments from the given string\n *\n * Rewritten because I can't get ts.getLeadingComments and ts.getTrailingComments to do what I want.\n */\nexport function extractComments(text: string, start: number): ts.CommentRange[] {\n return scanText(text, start)\n .filter((s) => s.type === 'blockcomment' || s.type === 'linecomment')\n .map(commentRangeFromTextRange);\n}\n\nexport function commentRangeFromTextRange(rng: TextRange): ts.CommentRange {\n return {\n kind: rng.type === 'blockcomment' ? ts.SyntaxKind.MultiLineCommentTrivia : ts.SyntaxKind.SingleLineCommentTrivia,\n pos: rng.pos,\n end: rng.end,\n hasTrailingNewLine: rng.type !== 'blockcomment' && rng.hasTrailingNewLine,\n };\n}\n\ninterface TextRange {\n pos: number;\n end: number;\n type: 'linecomment' | 'blockcomment' | 'other' | 'directive';\n hasTrailingNewLine: boolean;\n}\n\n/**\n * Extract spans of comments and non-comments out of the string\n *\n * Stop at 'end' when given, or the first non-whitespace character in a\n * non-comment if not given.\n */\nexport function scanText(text: string, start: number, end?: number): TextRange[] {\n const ret: TextRange[] = [];\n\n let pos = start;\n const stopAtCode = end === undefined;\n if (end === undefined) {\n end = text.length;\n }\n while (pos < end) {\n const ch = text[pos];\n\n if (WHITESPACE.includes(ch)) {\n pos++;\n continue;\n }\n\n if (ch === '/' && text[pos + 1] === '/') {\n accumulateTextBlock();\n scanSinglelineComment();\n continue;\n }\n\n if (ch === '/' && text[pos + 1] === '*') {\n accumulateTextBlock();\n scanMultilineComment();\n continue;\n }\n\n // Non-whitespace, non-comment, must be regular token. End if we're not scanning\n // to a particular location, otherwise continue.\n if (stopAtCode) {\n break;\n }\n\n pos++;\n }\n\n accumulateTextBlock();\n\n return ret;\n\n function scanMultilineComment() {\n const endOfComment = findNext('*/', pos + 2);\n ret.push({\n type: 'blockcomment',\n hasTrailingNewLine: ['\\n', '\\r'].includes(text[endOfComment + 2]),\n pos,\n end: endOfComment + 2,\n });\n pos = endOfComment + 2;\n start = pos;\n }\n\n function scanSinglelineComment() {\n const nl = Math.min(findNext('\\r', pos + 2), findNext('\\n', pos + 2));\n\n if (text[pos + 2] === '/') {\n // Special /// comment\n ret.push({\n type: 'directive',\n hasTrailingNewLine: true,\n pos: pos + 1,\n end: nl,\n });\n } else {\n // Regular // comment\n ret.push({\n type: 'linecomment',\n hasTrailingNewLine: true,\n pos,\n end: nl,\n });\n }\n pos = nl + 1;\n start = pos;\n }\n\n function accumulateTextBlock() {\n if (pos - start > 0) {\n ret.push({\n type: 'other',\n hasTrailingNewLine: false,\n pos: start,\n end: pos,\n });\n start = pos;\n }\n }\n\n function findNext(sub: string, startPos: number) {\n const f = text.indexOf(sub, startPos);\n if (f === -1) {\n return text.length;\n }\n return f;\n }\n}\n\nconst VOID_SHOW_KEYWORD = 'show';\n\nexport function extractMaskingVoidExpression(node: ts.Node): ts.VoidExpression | undefined {\n const expr = extractVoidExpression(node);\n if (!expr) {\n return undefined;\n }\n if (ts.isStringLiteral(expr.expression) && expr.expression.text === VOID_SHOW_KEYWORD) {\n return undefined;\n }\n return expr;\n}\n\nexport function extractShowingVoidExpression(node: ts.Node): ts.VoidExpression | undefined {\n const expr = extractVoidExpression(node);\n if (!expr) {\n return undefined;\n }\n if (ts.isStringLiteral(expr.expression) && expr.expression.text === VOID_SHOW_KEYWORD) {\n return expr;\n }\n return undefined;\n}\n\n/**\n * Return the string argument to a void expression if it exists\n */\nexport function voidExpressionString(node: ts.VoidExpression): string | undefined {\n if (ts.isStringLiteral(node.expression)) {\n return node.expression.text;\n }\n return undefined;\n}\n\n/**\n * We use void directives as pragmas. Extract the void directives here\n */\nexport function extractVoidExpression(node: ts.Node): ts.VoidExpression | undefined {\n if (ts.isVoidExpression(node)) {\n return node;\n }\n if (ts.isExpressionStatement(node)) {\n return extractVoidExpression(node.expression);\n }\n if (ts.isParenthesizedExpression(node)) {\n return extractVoidExpression(node.expression);\n }\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.CommaToken) {\n return extractVoidExpression(node.left);\n }\n return undefined;\n}\n\nexport function quoteStringLiteral(x: string) {\n return x.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\nexport function visibility(\n x:\n | ts.AccessorDeclaration\n | ts.FunctionLikeDeclaration\n | ts.GetAccessorDeclaration\n | ts.PropertyDeclaration\n | ts.PropertySignature\n | ts.SetAccessorDeclaration,\n) {\n const flags = ts.getCombinedModifierFlags(x);\n if (flags & ts.ModifierFlags.Private) {\n return 'private';\n }\n if (flags & ts.ModifierFlags.Protected) {\n return 'protected';\n }\n return 'public';\n}\n\nfunction hasFlag<T extends ts.Declaration>(flag: ts.ModifierFlags) {\n return (x: T) => {\n const flags = ts.getCombinedModifierFlags(x);\n return (flags & flag) !== 0;\n };\n}\n\nexport const isReadOnly = hasFlag<\n | ts.AccessorDeclaration\n | ts.FunctionLikeDeclaration\n | ts.GetAccessorDeclaration\n | ts.PropertyDeclaration\n | ts.PropertySignature\n | ts.SetAccessorDeclaration\n>(ts.ModifierFlags.Readonly);\nexport const isExported = hasFlag(ts.ModifierFlags.Export);\nexport const isPrivate = hasFlag(ts.ModifierFlags.Private);\nexport const isProtected = hasFlag(ts.ModifierFlags.Private);\nexport function isPublic(x: ts.Declaration) {\n // In TypeScript, anything not explicitly marked private or protected is public.\n return !isPrivate(x) && !isProtected(x);\n}\nexport const isStatic = hasFlag(ts.ModifierFlags.Static);\n\n/**\n * Return the super() call from a method body if found\n */\nexport function findSuperCall(\n node: ts.Block | ts.Expression | undefined,\n renderer: AstRenderer<any>,\n): ts.SuperCall | undefined {\n if (node === undefined) {\n return undefined;\n }\n if (ts.isCallExpression(node)) {\n if (renderer.textOf(node.expression) === 'super') {\n return node as unknown as ts.SuperCall;\n }\n }\n if (ts.isExpressionStatement(node)) {\n return findSuperCall(node.expression, renderer);\n }\n if (ts.isBlock(node)) {\n for (const statement of node.statements) {\n if (ts.isExpressionStatement(statement)) {\n const s = findSuperCall(statement.expression, renderer);\n if (s) {\n return s;\n }\n }\n }\n }\n return undefined;\n}\n\n/**\n * Return the names of all private property declarations\n */\nexport function privatePropertyNames(members: readonly ts.ClassElement[], renderer: AstRenderer<any>): string[] {\n const props = members.filter((m) => ts.isPropertyDeclaration(m)) as ts.PropertyDeclaration[];\n return props.filter((m) => visibility(m) === 'private').map((m) => renderer.textOf(m.name));\n}\n\nexport function findEnclosingClassDeclaration(node: ts.Node): ts.ClassDeclaration | undefined {\n while (node && !ts.isClassDeclaration(node)) {\n node = node.parent;\n }\n return node;\n}\n"]}
1
+ {"version":3,"file":"ast-utils.js","sourceRoot":"","sources":["../../src/typescript/ast-utils.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAIjC,SAAgB,mBAAmB,CAAC,OAAe,EAAE,SAAkB;IACrE,IAAI,SAAS,EAAE,CAAC;QACd,qDAAqD;QACrD,2EAA2E;QAC3E,wCAAwC;QACxC,OAAO,OAAO;aACX,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;aAChC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,8BAA8B;aACtD,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,+BAA+B;aACvD,OAAO,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC,CAAC,gCAAgC;IACvE,CAAC;IACD,kCAAkC;IAClC,OAAO,OAAO,CAAC,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC;AAChD,CAAC;AAbD,kDAaC;AAED,SAAgB,iBAAiB,CAAC,IAAmB;IACnD,IAAI,EAAE,CAAC,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AALD,8CAKC;AAiBD;;;;;;;;GAQG;AACH,SAAgB,YAAY,CAAC,IAAa;IACxC,MAAM,GAAG,GAAG,IAAI,KAAK,EAAW,CAAC;IACjC,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,EA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,UAAU,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;AAC9F,CAAC;AAHD,oDAGC;AAED,SAAgB,6BAA6B,CAAC,IAAa;IACzD,OAAO,IAAI,IAAI,CAAC,EAAE,CAAC,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAAC;QAC5C,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AALD,sEAKC","sourcesContent":["import * as ts from 'typescript';\n\nimport { AstRenderer } from '../renderer';\n\nexport function stripCommentMarkers(comment: string, multiline: boolean) {\n if (multiline) {\n // The text *must* start with '/*' and end with '*/'.\n // Strip leading '*' from every remaining line (first line because of '**',\n // other lines because of continuations.\n return comment\n .substring(2, comment.length - 2)\n .replace(/^[ \\t]+/g, '') // Strip all leading whitepace\n .replace(/[ \\t]+$/g, '') // Strip all trailing whitepace\n .replace(/^[ \\t]*\\*[ \\t]?/gm, ''); // Strip \"* \" from start of line\n }\n // The text *must* start with '//'\n return comment.replace(/^[/]{2}[ \\t]?/gm, '');\n}\n\nexport function stringFromLiteral(expr: ts.Expression) {\n if (ts.isStringLiteral(expr)) {\n return expr.text;\n }\n return '???';\n}\n\n/**\n * All types of nodes that can be captured using `nodeOfType`, and the type of Node they map to\n */\nexport type CapturableNodes = {\n [ts.SyntaxKind.ImportDeclaration]: ts.ImportDeclaration;\n [ts.SyntaxKind.VariableDeclaration]: ts.VariableDeclaration;\n [ts.SyntaxKind.ExternalModuleReference]: ts.ExternalModuleReference;\n [ts.SyntaxKind.NamespaceImport]: ts.NamespaceImport;\n [ts.SyntaxKind.NamedImports]: ts.NamedImports;\n [ts.SyntaxKind.ImportSpecifier]: ts.ImportSpecifier;\n [ts.SyntaxKind.StringLiteral]: ts.StringLiteral;\n};\n\nexport type AstMatcher<A> = (nodes?: ts.Node[]) => A | undefined;\n\n/**\n * Return AST children of the given node\n *\n * Difference with node.getChildren():\n *\n * - node.getChildren() must take a SourceFile (will fail if it doesn't get it)\n * and returns a mix of abstract and concrete syntax nodes.\n * - This function function will ONLY return abstract syntax nodes.\n */\nexport function nodeChildren(node: ts.Node): ts.Node[] {\n const ret = new Array<ts.Node>();\n node.forEachChild((n) => {\n ret.push(n);\n });\n return ret;\n}\n\n/**\n * Match a single node of a given type\n *\n * Capture name is first so that the IDE can detect eagerly that we're falling into\n * that overload and properly autocomplete the recognized node types from CapturableNodes.\n *\n * Looks like SyntaxList nodes appear in the printed AST, but they don't actually appear\n */\nexport function nodeOfType<A>(syntaxKind: ts.SyntaxKind, children?: AstMatcher<A>): AstMatcher<A>;\n// eslint-disable-next-line max-len\nexport function nodeOfType<S extends keyof CapturableNodes, N extends string, A>(\n capture: N,\n capturableNodeType: S,\n children?: AstMatcher<A>,\n): AstMatcher<Omit<A, N> & { [key in N]: CapturableNodes[S] }>;\n// eslint-disable-next-line max-len\nexport function nodeOfType<S extends keyof CapturableNodes, N extends string, A>(\n syntaxKindOrCaptureName: ts.SyntaxKind | N,\n nodeTypeOrChildren?: S | AstMatcher<A>,\n children?: AstMatcher<A>,\n): AstMatcher<A> | AstMatcher<A & { [key in N]: CapturableNodes[S] }> {\n const capturing = typeof syntaxKindOrCaptureName === 'string'; // Determine which overload we're in (SyntaxKind is a number)\n\n const realNext = (capturing ? children : (nodeTypeOrChildren as AstMatcher<A>)) ?? DONE;\n const realCapture = capturing ? syntaxKindOrCaptureName : undefined;\n const realSyntaxKind = capturing ? nodeTypeOrChildren : syntaxKindOrCaptureName;\n\n return (nodes) => {\n for (const node of nodes ?? []) {\n if (node.kind === realSyntaxKind) {\n const ret = realNext(nodeChildren(node));\n if (!ret) {\n continue;\n }\n\n if (realCapture) {\n return Object.assign(ret, {\n [realCapture]: node as CapturableNodes[S],\n }) as any;\n }\n return ret;\n }\n }\n return undefined;\n };\n}\n\nexport function anyNode(): AstMatcher<Record<string, unknown>>;\nexport function anyNode<A>(children: AstMatcher<A>): AstMatcher<A>;\nexport function anyNode<A>(children?: AstMatcher<A>): AstMatcher<A> | AstMatcher<any> {\n const realNext = children ?? DONE;\n return (nodes) => {\n for (const node of nodes ?? []) {\n const m = realNext(nodeChildren(node));\n if (m) {\n return m;\n }\n }\n return undefined;\n };\n}\n\n// Does not capture deeper because how would we even represent that?\nexport function allOfType<S extends keyof CapturableNodes, N extends string, A>(\n s: S,\n name: N,\n children?: AstMatcher<A>,\n): AstMatcher<{ [key in N]: Array<CapturableNodes[S]> }> {\n type ArrayType = Array<CapturableNodes[S]>;\n type ReturnType = { [key in N]: ArrayType };\n const realNext = children ?? DONE;\n\n return (nodes) => {\n let ret: ReturnType | undefined;\n for (const node of nodes ?? []) {\n if (node.kind === s) {\n if (realNext(nodeChildren(node))) {\n if (!ret) {\n ret = { [name]: new Array<CapturableNodes[S]>() } as ReturnType;\n }\n ret[name].push(node as any);\n }\n }\n }\n return ret;\n };\n}\n\nexport const DONE: AstMatcher<Record<string, unknown>> = () => ({});\n\n/**\n * Run a matcher against a node and return (or invoke a callback with) the accumulated bindings\n */\nexport function matchAst<A>(node: ts.Node, matcher: AstMatcher<A>): A | undefined;\nexport function matchAst<A>(node: ts.Node, matcher: AstMatcher<A>, cb: (bindings: A) => void): boolean;\nexport function matchAst<A>(\n node: ts.Node,\n matcher: AstMatcher<A>,\n cb?: (bindings: A) => void,\n): boolean | A | undefined {\n const matched = matcher([node]);\n if (cb) {\n if (matched) {\n cb(matched);\n }\n return !!matched;\n }\n return matched;\n}\n\n/**\n * Count the newlines in a given piece of string that aren't in comment blocks\n */\nexport function countNakedNewlines(str: string) {\n let ret = 0;\n for (const s of scanText(str, 0, str.length).filter((r) => r.type === 'other' || r.type === 'blockcomment')) {\n if (s.type === 'other') {\n // Count newlines in non-comments\n for (let i = s.pos; i < s.end; i++) {\n if (str[i] === '\\n') {\n ret++;\n }\n }\n } else {\n // Discount newlines at the end of block comments\n if (s.hasTrailingNewLine) {\n ret--;\n }\n }\n }\n return ret;\n}\n\nexport function repeatNewlines(str: string) {\n return '\\n'.repeat(Math.min(2, countNakedNewlines(str)));\n}\n\nconst WHITESPACE = [' ', '\\t', '\\r', '\\n'];\n\n/**\n * Extract single-line and multi-line comments from the given string\n *\n * Rewritten because I can't get ts.getLeadingComments and ts.getTrailingComments to do what I want.\n */\nexport function extractComments(text: string, start: number): ts.CommentRange[] {\n return scanText(text, start)\n .filter((s) => s.type === 'blockcomment' || s.type === 'linecomment')\n .map(commentRangeFromTextRange);\n}\n\nexport function commentRangeFromTextRange(rng: TextRange): ts.CommentRange {\n return {\n kind: rng.type === 'blockcomment' ? ts.SyntaxKind.MultiLineCommentTrivia : ts.SyntaxKind.SingleLineCommentTrivia,\n pos: rng.pos,\n end: rng.end,\n hasTrailingNewLine: rng.type !== 'blockcomment' && rng.hasTrailingNewLine,\n };\n}\n\ninterface TextRange {\n pos: number;\n end: number;\n type: 'linecomment' | 'blockcomment' | 'other' | 'directive';\n hasTrailingNewLine: boolean;\n}\n\n/**\n * Extract spans of comments and non-comments out of the string\n *\n * Stop at 'end' when given, or the first non-whitespace character in a\n * non-comment if not given.\n */\nexport function scanText(text: string, start: number, end?: number): TextRange[] {\n const ret: TextRange[] = [];\n\n let pos = start;\n const stopAtCode = end === undefined;\n if (end === undefined) {\n end = text.length;\n }\n while (pos < end) {\n const ch = text[pos];\n\n if (WHITESPACE.includes(ch)) {\n pos++;\n continue;\n }\n\n if (ch === '/' && text[pos + 1] === '/') {\n accumulateTextBlock();\n scanSinglelineComment();\n continue;\n }\n\n if (ch === '/' && text[pos + 1] === '*') {\n accumulateTextBlock();\n scanMultilineComment();\n continue;\n }\n\n // Non-whitespace, non-comment, must be regular token. End if we're not scanning\n // to a particular location, otherwise continue.\n if (stopAtCode) {\n break;\n }\n\n pos++;\n }\n\n accumulateTextBlock();\n\n return ret;\n\n function scanMultilineComment() {\n const endOfComment = findNext('*/', pos + 2);\n ret.push({\n type: 'blockcomment',\n hasTrailingNewLine: ['\\n', '\\r'].includes(text[endOfComment + 2]),\n pos,\n end: endOfComment + 2,\n });\n pos = endOfComment + 2;\n start = pos;\n }\n\n function scanSinglelineComment() {\n const nl = Math.min(findNext('\\r', pos + 2), findNext('\\n', pos + 2));\n\n if (text[pos + 2] === '/') {\n // Special /// comment\n ret.push({\n type: 'directive',\n hasTrailingNewLine: true,\n pos: pos + 1,\n end: nl,\n });\n } else {\n // Regular // comment\n ret.push({\n type: 'linecomment',\n hasTrailingNewLine: true,\n pos,\n end: nl,\n });\n }\n pos = nl + 1;\n start = pos;\n }\n\n function accumulateTextBlock() {\n if (pos - start > 0) {\n ret.push({\n type: 'other',\n hasTrailingNewLine: false,\n pos: start,\n end: pos,\n });\n start = pos;\n }\n }\n\n function findNext(sub: string, startPos: number) {\n const f = text.indexOf(sub, startPos);\n if (f === -1) {\n return text.length;\n }\n return f;\n }\n}\n\nconst VOID_SHOW_KEYWORD = 'show';\n\nexport function extractMaskingVoidExpression(node: ts.Node): ts.VoidExpression | undefined {\n const expr = extractVoidExpression(node);\n if (!expr) {\n return undefined;\n }\n if (ts.isStringLiteral(expr.expression) && expr.expression.text === VOID_SHOW_KEYWORD) {\n return undefined;\n }\n return expr;\n}\n\nexport function extractShowingVoidExpression(node: ts.Node): ts.VoidExpression | undefined {\n const expr = extractVoidExpression(node);\n if (!expr) {\n return undefined;\n }\n if (ts.isStringLiteral(expr.expression) && expr.expression.text === VOID_SHOW_KEYWORD) {\n return expr;\n }\n return undefined;\n}\n\n/**\n * Return the string argument to a void expression if it exists\n */\nexport function voidExpressionString(node: ts.VoidExpression): string | undefined {\n if (ts.isStringLiteral(node.expression)) {\n return node.expression.text;\n }\n return undefined;\n}\n\n/**\n * We use void directives as pragmas. Extract the void directives here\n */\nexport function extractVoidExpression(node: ts.Node): ts.VoidExpression | undefined {\n if (ts.isVoidExpression(node)) {\n return node;\n }\n if (ts.isExpressionStatement(node)) {\n return extractVoidExpression(node.expression);\n }\n if (ts.isParenthesizedExpression(node)) {\n return extractVoidExpression(node.expression);\n }\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.CommaToken) {\n return extractVoidExpression(node.left);\n }\n return undefined;\n}\n\nexport function quoteStringLiteral(x: string) {\n return x.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\nexport function visibility(\n x:\n | ts.AccessorDeclaration\n | ts.FunctionLikeDeclaration\n | ts.GetAccessorDeclaration\n | ts.PropertyDeclaration\n | ts.PropertySignature\n | ts.SetAccessorDeclaration,\n) {\n const flags = ts.getCombinedModifierFlags(x);\n if (flags & ts.ModifierFlags.Private) {\n return 'private';\n }\n if (flags & ts.ModifierFlags.Protected) {\n return 'protected';\n }\n return 'public';\n}\n\nfunction hasFlag<T extends ts.Declaration>(flag: ts.ModifierFlags) {\n return (x: T) => {\n const flags = ts.getCombinedModifierFlags(x);\n return (flags & flag) !== 0;\n };\n}\n\nexport const isReadOnly = hasFlag<\n | ts.AccessorDeclaration\n | ts.FunctionLikeDeclaration\n | ts.GetAccessorDeclaration\n | ts.PropertyDeclaration\n | ts.PropertySignature\n | ts.SetAccessorDeclaration\n>(ts.ModifierFlags.Readonly);\nexport const isExported = hasFlag(ts.ModifierFlags.Export);\nexport const isPrivate = hasFlag(ts.ModifierFlags.Private);\nexport const isProtected = hasFlag(ts.ModifierFlags.Private);\nexport function isPublic(x: ts.Declaration) {\n // In TypeScript, anything not explicitly marked private or protected is public.\n return !isPrivate(x) && !isProtected(x);\n}\nexport const isStatic = hasFlag(ts.ModifierFlags.Static);\n\n/**\n * Return the super() call from a method body if found\n */\nexport function findSuperCall(\n node: ts.Block | ts.Expression | undefined,\n renderer: AstRenderer<any>,\n): ts.SuperCall | undefined {\n if (node === undefined) {\n return undefined;\n }\n if (ts.isCallExpression(node)) {\n if (renderer.textOf(node.expression) === 'super') {\n return node as unknown as ts.SuperCall;\n }\n }\n if (ts.isExpressionStatement(node)) {\n return findSuperCall(node.expression, renderer);\n }\n if (ts.isBlock(node)) {\n for (const statement of node.statements) {\n if (ts.isExpressionStatement(statement)) {\n const s = findSuperCall(statement.expression, renderer);\n if (s) {\n return s;\n }\n }\n }\n }\n return undefined;\n}\n\n/**\n * Return the names of all private property declarations\n */\nexport function privatePropertyNames(members: readonly ts.ClassElement[], renderer: AstRenderer<any>): string[] {\n const props = members.filter((m) => ts.isPropertyDeclaration(m)) as ts.PropertyDeclaration[];\n return props.filter((m) => visibility(m) === 'private').map((m) => renderer.textOf(m.name));\n}\n\nexport function findEnclosingClassDeclaration(node: ts.Node): ts.ClassDeclaration | undefined {\n while (node && !ts.isClassDeclaration(node)) {\n node = node.parent;\n }\n return node;\n}\n"]}
@@ -58,7 +58,7 @@ function analyzeImportDeclaration(node, context, submoduleReferences) {
58
58
  moduleSymbol,
59
59
  imports: {
60
60
  import: 'full',
61
- alias: undefined,
61
+ alias: undefined, // No alias exists in the source text for this...
62
62
  sourceName: context.textOf(submoduleChain),
63
63
  },
64
64
  },
@@ -1 +1 @@
1
- {"version":3,"file":"imports.js","sourceRoot":"","sources":["../../src/typescript/imports.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAEjC,2CAAiF;AACjF,mDAAwF;AAGxF,kCAA+B;AA0C/B,SAAgB,mBAAmB,CAAC,IAAgC,EAAE,OAAyB;IAC7F,IAAI,UAAU,GAAG,KAAK,CAAC;IACvB,IAAA,oBAAQ,EAAC,IAAI,CAAC,eAAe,EAAE,IAAA,sBAAU,EAAC,KAAK,EAAE,EAAE,CAAC,UAAU,CAAC,uBAAuB,CAAC,EAAE,CAAC,QAAQ,EAAE,EAAE;QACpG,UAAU,GAAG,IAAA,6BAAiB,EAAC,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC1D,CAAC,CAAC,CAAC;IAEH,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAE7C,OAA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,IAAI,mBAAmB,IAAI,IAAI,EAAE;QAC/B,OAAO;YACL,IAAI;YACJ,WAAW;YACX,OAAO,EAAE,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE;YAC1C,YAAY,EAAE,IAAA,WAAI,EAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,yBAAY,CAAC;SAChE,CAAC;KACH;IAED,OAAO;QACL;YACE,IAAI;YACJ,WAAW;YACX,OAAO,EAAE,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE;YAC1C,YAAY,EAAE,IAAA,WAAI,EAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,yBAAY,CAAC;SAChE;QACD,GAAG,YAAY;KAChB,CAAC;AACJ,CAAC;AApJD,4DAoJC","sourcesContent":["import * as ts from 'typescript';\n\nimport { allOfType, matchAst, nodeOfType, stringFromLiteral } from './ast-utils';\nimport { JsiiSymbol, parentSymbol, lookupJsiiSymbolFromNode } from '../jsii/jsii-utils';\nimport { AstRenderer } from '../renderer';\nimport { SubmoduleReferenceMap } from '../submodule-reference';\nimport { fmap } from '../util';\n\n/**\n * Our own unification of import statements\n */\nexport interface ImportStatement {\n readonly node: ts.Node;\n readonly packageName: string;\n readonly imports: FullImport | SelectiveImport;\n readonly moduleSymbol?: JsiiSymbol;\n}\n\nexport type FullImport = {\n readonly import: 'full';\n /**\n * The name of the namespace prefix in the source code. Used to strip the\n * prefix in certain languages (e.g: Java).\n */\n readonly sourceName: string;\n /**\n * The name under which this module is imported. Undefined if the module is\n * not aliased (could be the case for namepsace/submodule imports).\n */\n readonly alias?: string;\n};\n\nexport type SelectiveImport = {\n readonly import: 'selective';\n readonly elements: ImportBinding[];\n};\n\nexport interface ImportBinding {\n readonly sourceName: string;\n\n readonly alias?: string;\n\n /**\n * The JSII Symbol the import refers to\n */\n readonly importedSymbol?: JsiiSymbol;\n}\n\nexport function analyzeImportEquals(node: ts.ImportEqualsDeclaration, context: AstRenderer<any>): ImportStatement {\n let moduleName = '???';\n matchAst(node.moduleReference, nodeOfType('ref', ts.SyntaxKind.ExternalModuleReference), (bindings) => {\n moduleName = stringFromLiteral(bindings.ref.expression);\n });\n\n const sourceName = context.textOf(node.name);\n\n return {\n node,\n packageName: moduleName,\n moduleSymbol: lookupJsiiSymbolFromNode(context.typeChecker, node.name),\n imports: { import: 'full', alias: sourceName, sourceName },\n };\n}\n\nexport function analyzeImportDeclaration(node: ts.ImportDeclaration, context: AstRenderer<any>): ImportStatement;\nexport function analyzeImportDeclaration(\n node: ts.ImportDeclaration,\n context: AstRenderer<any>,\n submoduleReferences: SubmoduleReferenceMap,\n): ImportStatement[];\nexport function analyzeImportDeclaration(\n node: ts.ImportDeclaration,\n context: AstRenderer<any>,\n submoduleReferences?: SubmoduleReferenceMap,\n): ImportStatement | ImportStatement[] {\n const packageName = stringFromLiteral(node.moduleSpecifier);\n\n const starBindings = matchAst(\n node,\n nodeOfType(\n ts.SyntaxKind.ImportDeclaration,\n nodeOfType(ts.SyntaxKind.ImportClause, nodeOfType('namespace', ts.SyntaxKind.NamespaceImport)),\n ),\n );\n\n if (starBindings) {\n const sourceName = context.textOf(starBindings.namespace.name);\n const bareImport: ImportStatement = {\n node,\n packageName,\n moduleSymbol: lookupJsiiSymbolFromNode(context.typeChecker, starBindings.namespace.name),\n imports: {\n import: 'full',\n alias: sourceName,\n sourceName,\n },\n };\n if (submoduleReferences == null) {\n return bareImport;\n }\n\n const rootSymbol = context.typeChecker.getSymbolAtLocation(starBindings.namespace.name);\n const refs = rootSymbol && Array.from(submoduleReferences.values()).filter((ref) => ref.root === rootSymbol);\n // No submodule reference, or only 1 where the path is empty (this is used to signal the use of the bare import so it's not erased)\n if (refs == null || refs.length === 0 || (refs.length === 1 && refs[0].path.length === 0)) {\n return [bareImport];\n }\n\n return refs.flatMap(({ lastNode, path, root, submoduleChain }, idx, array): ImportStatement[] => {\n if (\n array\n .slice(0, idx)\n .some(\n (other) => other.root === root && context.textOf(other.submoduleChain) === context.textOf(submoduleChain),\n )\n ) {\n // This would be a duplicate, so we're skipping it\n return [];\n }\n\n const moduleSymbol = lookupJsiiSymbolFromNode(context.typeChecker, lastNode);\n return [\n {\n node,\n packageName: [packageName, ...path.map((n) => context.textOf(n))].join('/'),\n moduleSymbol,\n imports: {\n import: 'full',\n alias: undefined, // No alias exists in the source text for this...\n sourceName: context.textOf(submoduleChain),\n },\n },\n ];\n });\n }\n\n const namedBindings = matchAst(\n node,\n nodeOfType(\n ts.SyntaxKind.ImportDeclaration,\n nodeOfType(\n ts.SyntaxKind.ImportClause,\n nodeOfType(ts.SyntaxKind.NamedImports, allOfType(ts.SyntaxKind.ImportSpecifier, 'specifiers')),\n ),\n ),\n );\n\n const extraImports = new Array<ImportStatement>();\n const elements: ImportBinding[] = (namedBindings?.specifiers ?? []).flatMap(\n ({ name, propertyName }): ImportBinding[] => {\n // regular import { name }\n // renamed import { propertyName as name }\n const directBinding = {\n sourceName: context.textOf(propertyName ?? name),\n alias: propertyName && context.textOf(name),\n importedSymbol: lookupJsiiSymbolFromNode(context.typeChecker, propertyName ?? name),\n } as const;\n\n if (submoduleReferences != null) {\n const symbol = context.typeChecker.getSymbolAtLocation(name);\n let omitDirectBinding = false;\n for (const match of Array.from(submoduleReferences.values()).filter((ref) => ref.root === symbol)) {\n if (match.path.length === 0) {\n // This is a namespace binding that is used as-is (not via a transitive path). It needs to be preserved.\n omitDirectBinding = false;\n continue;\n }\n const subPackageName = [packageName, ...match.path.map((n) => n.getText(n.getSourceFile()))].join('/');\n const importedSymbol = lookupJsiiSymbolFromNode(context.typeChecker, match.lastNode);\n const moduleSymbol = fmap(importedSymbol, parentSymbol);\n const importStatement =\n extraImports.find((stmt) => {\n if (moduleSymbol != null) {\n return stmt.moduleSymbol === moduleSymbol;\n }\n return stmt.packageName === subPackageName;\n }) ??\n extraImports[\n extraImports.push({\n moduleSymbol,\n node: match.lastNode,\n packageName: subPackageName,\n imports: { import: 'selective', elements: [] },\n }) - 1\n ];\n\n (importStatement.imports as SelectiveImport).elements.push({\n sourceName: context.textOf(match.submoduleChain),\n importedSymbol,\n });\n }\n if (omitDirectBinding) {\n return [];\n }\n }\n\n return [directBinding];\n },\n );\n\n if (submoduleReferences == null) {\n return {\n node,\n packageName,\n imports: { import: 'selective', elements },\n moduleSymbol: fmap(elements?.[0]?.importedSymbol, parentSymbol),\n };\n }\n\n return [\n {\n node,\n packageName,\n imports: { import: 'selective', elements },\n moduleSymbol: fmap(elements?.[0]?.importedSymbol, parentSymbol),\n },\n ...extraImports,\n ];\n}\n"]}
1
+ {"version":3,"file":"imports.js","sourceRoot":"","sources":["../../src/typescript/imports.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAEjC,2CAAiF;AACjF,mDAAwF;AAGxF,kCAA+B;AA0C/B,SAAgB,mBAAmB,CAAC,IAAgC,EAAE,OAAyB;IAC7F,IAAI,UAAU,GAAG,KAAK,CAAC;IACvB,IAAA,oBAAQ,EAAC,IAAI,CAAC,eAAe,EAAE,IAAA,sBAAU,EAAC,KAAK,EAAE,EAAE,CAAC,UAAU,CAAC,uBAAuB,CAAC,EAAE,CAAC,QAAQ,EAAE,EAAE;QACpG,UAAU,GAAG,IAAA,6BAAiB,EAAC,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC1D,CAAC,CAAC,CAAC;IAEH,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAE7C,OAAO;QACL,IAAI;QACJ,WAAW,EAAE,UAAU;QACvB,YAAY,EAAE,IAAA,qCAAwB,EAAC,OAAO,CAAC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC;QACtE,OAAO,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE;KAC3D,CAAC;AACJ,CAAC;AAdD,kDAcC;AAQD,SAAgB,wBAAwB,CACtC,IAA0B,EAC1B,OAAyB,EAC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,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,yBAAY,CAAC;SAChE,CAAC;IACJ,CAAC;IAED,OAAO;QACL;YACE,IAAI;YACJ,WAAW;YACX,OAAO,EAAE,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE;YAC1C,YAAY,EAAE,IAAA,WAAI,EAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,yBAAY,CAAC;SAChE;QACD,GAAG,YAAY;KAChB,CAAC;AACJ,CAAC;AApJD,4DAoJC","sourcesContent":["import * as ts from 'typescript';\n\nimport { allOfType, matchAst, nodeOfType, stringFromLiteral } from './ast-utils';\nimport { JsiiSymbol, parentSymbol, lookupJsiiSymbolFromNode } from '../jsii/jsii-utils';\nimport { AstRenderer } from '../renderer';\nimport { SubmoduleReferenceMap } from '../submodule-reference';\nimport { fmap } from '../util';\n\n/**\n * Our own unification of import statements\n */\nexport interface ImportStatement {\n readonly node: ts.Node;\n readonly packageName: string;\n readonly imports: FullImport | SelectiveImport;\n readonly moduleSymbol?: JsiiSymbol;\n}\n\nexport type FullImport = {\n readonly import: 'full';\n /**\n * The name of the namespace prefix in the source code. Used to strip the\n * prefix in certain languages (e.g: Java).\n */\n readonly sourceName: string;\n /**\n * The name under which this module is imported. Undefined if the module is\n * not aliased (could be the case for namepsace/submodule imports).\n */\n readonly alias?: string;\n};\n\nexport type SelectiveImport = {\n readonly import: 'selective';\n readonly elements: ImportBinding[];\n};\n\nexport interface ImportBinding {\n readonly sourceName: string;\n\n readonly alias?: string;\n\n /**\n * The JSII Symbol the import refers to\n */\n readonly importedSymbol?: JsiiSymbol;\n}\n\nexport function analyzeImportEquals(node: ts.ImportEqualsDeclaration, context: AstRenderer<any>): ImportStatement {\n let moduleName = '???';\n matchAst(node.moduleReference, nodeOfType('ref', ts.SyntaxKind.ExternalModuleReference), (bindings) => {\n moduleName = stringFromLiteral(bindings.ref.expression);\n });\n\n const sourceName = context.textOf(node.name);\n\n return {\n node,\n packageName: moduleName,\n moduleSymbol: lookupJsiiSymbolFromNode(context.typeChecker, node.name),\n imports: { import: 'full', alias: sourceName, sourceName },\n };\n}\n\nexport function analyzeImportDeclaration(node: ts.ImportDeclaration, context: AstRenderer<any>): ImportStatement;\nexport function analyzeImportDeclaration(\n node: ts.ImportDeclaration,\n context: AstRenderer<any>,\n submoduleReferences: SubmoduleReferenceMap,\n): ImportStatement[];\nexport function analyzeImportDeclaration(\n node: ts.ImportDeclaration,\n context: AstRenderer<any>,\n submoduleReferences?: SubmoduleReferenceMap,\n): ImportStatement | ImportStatement[] {\n const packageName = stringFromLiteral(node.moduleSpecifier);\n\n const starBindings = matchAst(\n node,\n nodeOfType(\n ts.SyntaxKind.ImportDeclaration,\n nodeOfType(ts.SyntaxKind.ImportClause, nodeOfType('namespace', ts.SyntaxKind.NamespaceImport)),\n ),\n );\n\n if (starBindings) {\n const sourceName = context.textOf(starBindings.namespace.name);\n const bareImport: ImportStatement = {\n node,\n packageName,\n moduleSymbol: lookupJsiiSymbolFromNode(context.typeChecker, starBindings.namespace.name),\n imports: {\n import: 'full',\n alias: sourceName,\n sourceName,\n },\n };\n if (submoduleReferences == null) {\n return bareImport;\n }\n\n const rootSymbol = context.typeChecker.getSymbolAtLocation(starBindings.namespace.name);\n const refs = rootSymbol && Array.from(submoduleReferences.values()).filter((ref) => ref.root === rootSymbol);\n // No submodule reference, or only 1 where the path is empty (this is used to signal the use of the bare import so it's not erased)\n if (refs == null || refs.length === 0 || (refs.length === 1 && refs[0].path.length === 0)) {\n return [bareImport];\n }\n\n return refs.flatMap(({ lastNode, path, root, submoduleChain }, idx, array): ImportStatement[] => {\n if (\n array\n .slice(0, idx)\n .some(\n (other) => other.root === root && context.textOf(other.submoduleChain) === context.textOf(submoduleChain),\n )\n ) {\n // This would be a duplicate, so we're skipping it\n return [];\n }\n\n const moduleSymbol = lookupJsiiSymbolFromNode(context.typeChecker, lastNode);\n return [\n {\n node,\n packageName: [packageName, ...path.map((n) => context.textOf(n))].join('/'),\n moduleSymbol,\n imports: {\n import: 'full',\n alias: undefined, // No alias exists in the source text for this...\n sourceName: context.textOf(submoduleChain),\n },\n },\n ];\n });\n }\n\n const namedBindings = matchAst(\n node,\n nodeOfType(\n ts.SyntaxKind.ImportDeclaration,\n nodeOfType(\n ts.SyntaxKind.ImportClause,\n nodeOfType(ts.SyntaxKind.NamedImports, allOfType(ts.SyntaxKind.ImportSpecifier, 'specifiers')),\n ),\n ),\n );\n\n const extraImports = new Array<ImportStatement>();\n const elements: ImportBinding[] = (namedBindings?.specifiers ?? []).flatMap(\n ({ name, propertyName }): ImportBinding[] => {\n // regular import { name }\n // renamed import { propertyName as name }\n const directBinding = {\n sourceName: context.textOf(propertyName ?? name),\n alias: propertyName && context.textOf(name),\n importedSymbol: lookupJsiiSymbolFromNode(context.typeChecker, propertyName ?? name),\n } as const;\n\n if (submoduleReferences != null) {\n const symbol = context.typeChecker.getSymbolAtLocation(name);\n let omitDirectBinding = false;\n for (const match of Array.from(submoduleReferences.values()).filter((ref) => ref.root === symbol)) {\n if (match.path.length === 0) {\n // This is a namespace binding that is used as-is (not via a transitive path). It needs to be preserved.\n omitDirectBinding = false;\n continue;\n }\n const subPackageName = [packageName, ...match.path.map((n) => n.getText(n.getSourceFile()))].join('/');\n const importedSymbol = lookupJsiiSymbolFromNode(context.typeChecker, match.lastNode);\n const moduleSymbol = fmap(importedSymbol, parentSymbol);\n const importStatement =\n extraImports.find((stmt) => {\n if (moduleSymbol != null) {\n return stmt.moduleSymbol === moduleSymbol;\n }\n return stmt.packageName === subPackageName;\n }) ??\n extraImports[\n extraImports.push({\n moduleSymbol,\n node: match.lastNode,\n packageName: subPackageName,\n imports: { import: 'selective', elements: [] },\n }) - 1\n ];\n\n (importStatement.imports as SelectiveImport).elements.push({\n sourceName: context.textOf(match.submoduleChain),\n importedSymbol,\n });\n }\n if (omitDirectBinding) {\n return [];\n }\n }\n\n return [directBinding];\n },\n );\n\n if (submoduleReferences == null) {\n return {\n node,\n packageName,\n imports: { import: 'selective', elements },\n moduleSymbol: fmap(elements?.[0]?.importedSymbol, parentSymbol),\n };\n }\n\n return [\n {\n node,\n packageName,\n imports: { import: 'selective', elements },\n moduleSymbol: fmap(elements?.[0]?.importedSymbol, parentSymbol),\n },\n ...extraImports,\n ];\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"syntax-kind-counter.js","sourceRoot":"","sources":["../../src/typescript/syntax-kind-counter.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAIjC,MAAa,iBAAiB;IAG5B,YAAoC,YAAmB;QAAnB,iBAAY,GAAZ,YAAY,CAAO;QACrD,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;IACpB,CAAC;IAEM,UAAU,CAAC,UAAyB;QACzC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QAC3B,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAEO,SAAS,CAAC,IAAa;QAC7B,IAAI,IAAI,CAAC,YAAY,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE;YAC/C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;SAC9D;QAED,2GAA2G;QAC3G,sDAAsD;QACtD,2EAA2E;QAC3E,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAClD,CAAC;CACF;AAtBD,8CAsBC","sourcesContent":["import * as ts from 'typescript';\n\nimport { Spans } from './visible-spans';\n\nexport class SyntaxKindCounter {\n private readonly counter: Partial<Record<ts.SyntaxKind, number>>;\n\n public constructor(private readonly visibleSpans: Spans) {\n this.counter = {};\n }\n\n public countKinds(sourceFile: ts.SourceFile): Partial<Record<ts.SyntaxKind, number>> {\n this.countNode(sourceFile);\n return this.counter;\n }\n\n private countNode(node: ts.Node) {\n if (this.visibleSpans.containsStartOfNode(node)) {\n this.counter[node.kind] = (this.counter[node.kind] ?? 0) + 1;\n }\n\n // The two recursive options produce differing results. `ts.forEachChild()` ignores some unimportant kinds.\n // `node.getChildren()` goes through all syntax kinds.\n // see: https://basarat.gitbook.io/typescript/overview/ast/ast-tip-children\n ts.forEachChild(node, (x) => this.countNode(x));\n }\n}\n"]}
1
+ {"version":3,"file":"syntax-kind-counter.js","sourceRoot":"","sources":["../../src/typescript/syntax-kind-counter.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAIjC,MAAa,iBAAiB;IAG5B,YAAoC,YAAmB;QAAnB,iBAAY,GAAZ,YAAY,CAAO;QACrD,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;IACpB,CAAC;IAEM,UAAU,CAAC,UAAyB;QACzC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QAC3B,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAEO,SAAS,CAAC,IAAa;QAC7B,IAAI,IAAI,CAAC,YAAY,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,CAAC;YAChD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;QAC/D,CAAC;QAED,2GAA2G;QAC3G,sDAAsD;QACtD,2EAA2E;QAC3E,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAClD,CAAC;CACF;AAtBD,8CAsBC","sourcesContent":["import * as ts from 'typescript';\n\nimport { Spans } from './visible-spans';\n\nexport class SyntaxKindCounter {\n private readonly counter: Partial<Record<ts.SyntaxKind, number>>;\n\n public constructor(private readonly visibleSpans: Spans) {\n this.counter = {};\n }\n\n public countKinds(sourceFile: ts.SourceFile): Partial<Record<ts.SyntaxKind, number>> {\n this.countNode(sourceFile);\n return this.counter;\n }\n\n private countNode(node: ts.Node) {\n if (this.visibleSpans.containsStartOfNode(node)) {\n this.counter[node.kind] = (this.counter[node.kind] ?? 0) + 1;\n }\n\n // The two recursive options produce differing results. `ts.forEachChild()` ignores some unimportant kinds.\n // `node.getChildren()` goes through all syntax kinds.\n // see: https://basarat.gitbook.io/typescript/overview/ast/ast-tip-children\n ts.forEachChild(node, (x) => this.countNode(x));\n }\n}\n"]}
@@ -66,8 +66,8 @@ exports.STANDARD_COMPILER_OPTIONS = {
66
66
  noImplicitAny: true,
67
67
  noImplicitReturns: true,
68
68
  noImplicitThis: true,
69
- noUnusedLocals: false,
70
- noUnusedParameters: false,
69
+ noUnusedLocals: false, // Important, becomes super annoying without this
70
+ noUnusedParameters: false, // Important, becomes super annoying without this
71
71
  resolveJsonModule: true,
72
72
  strict: true,
73
73
  strictNullChecks: true,
@@ -1 +1 @@
1
- {"version":3,"file":"ts-compiler.js","sourceRoot":"","sources":["../../src/typescript/ts-compiler.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAEjC,MAAa,kBAAkB;IAA/B;QACmB,aAAQ,GAAG,EAAE,CAAC,kBAAkB,CAAC,iCAAyB,EAAE,IAAI,CAAC,CAAC;QAEnF;;WAEG;QACc,cAAS,GAAG,IAAI,GAAG,EAAqC,CAAC;IAqD5E,CAAC;IAnDQ,0BAA0B,CAC/B,UAAkB,EAClB,cAAsB,EACtB,gBAAyB;QAEzB,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,MAAM,UAAU,GAAG,EAAE,CAAC,gBAAgB,CAAC,UAAU,EAAE,cAAc,EAAE,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;QAE3F,OAAO;YACL,GAAG,QAAQ;YACX,UAAU,EAAE,CAAC,QAAQ,EAAE,EAAE,CACvB,Q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AAC,QAAQ,CAAC;YACrB,OAAO,EAAE,iCAAyB;YAClC,IAAI,EAAE,IAAI,CAAC,0BAA0B,CAAC,QAAQ,EAAE,QAAQ,EAAE,gBAAgB,CAAC;SAC5E,CAAC,CAAC;QAEH,MAAM,QAAQ,GAAG,OAAO,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QACjD,IAAI,QAAQ,IAAI,IAAI,EAAE;YACpB,MAAM,IAAI,KAAK,CAAC,2CAA2C,QAAQ,EAAE,CAAC,CAAC;SACxE;QAED,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IAC/B,CAAC;CACF;AA3DD,gDA2DC;AAOY,QAAA,yBAAyB,GAAuB;IAC3D,YAAY,EAAE,IAAI;IAClB,OAAO,EAAE,MAAM;IACf,WAAW,EAAE,IAAI;IACjB,cAAc,EAAE,IAAI;IACpB,sBAAsB,EAAE,IAAI;IAC5B,eAAe,EAAE,IAAI;IACrB,aAAa,EAAE,IAAI;IACnB,GAAG,EAAE,CAAC,iBAAiB,CAAC;IACxB,MAAM,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ;IAC9B,aAAa,EAAE,IAAI;IACnB,0BAA0B,EAAE,IAAI;IAChC,aAAa,EAAE,IAAI;IACnB,iBAAiB,EAAE,IAAI;IACvB,cAAc,EAAE,IAAI;IACpB,cAAc,EAAE,KAAK;IACrB,kBAAkB,EAAE,KAAK;IACzB,iBAAiB,EAAE,IAAI;IACvB,MAAM,EAAE,IAAI;IACZ,gBAAgB,EAAE,IAAI;IACtB,4BAA4B,EAAE,IAAI;IAClC,aAAa,EAAE,IAAI;IACnB,MAAM,EAAE,EAAE,CAAC,YAAY,CAAC,MAAM;IAC9B,qBAAqB;IACrB,WAAW,EAAE,IAAI;IACjB,eAAe,EAAE,cAAc;CAChC,CAAC","sourcesContent":["import * as ts from 'typescript';\n\nexport class TypeScriptCompiler {\n private readonly realHost = ts.createCompilerHost(STANDARD_COMPILER_OPTIONS, true);\n\n /**\n * A compiler-scoped cache to avoid having to re-parse the same library files for every compilation\n */\n private readonly fileCache = new Map<string, ts.SourceFile | undefined>();\n\n public createInMemoryCompilerHost(\n sourcePath: string,\n sourceContents: string,\n currentDirectory?: string,\n ): ts.CompilerHost {\n const realHost = this.realHost;\n const sourceFile = ts.createSourceFile(sourcePath, sourceContents, ts.ScriptTarget.Latest);\n\n return {\n ...realHost,\n fileExists: (filePath) =>\n filePath === sourcePath || this.fileCache.has(filePath) || realHost.fileExists(filePath),\n getCurrentDirectory: currentDirectory != null ? () => currentDirectory : realHost.getCurrentDirectory,\n getSourceFile: (fileName, languageVersion, onError, shouldCreateNewSourceFile) => {\n if (fileName === sourcePath) {\n return sourceFile;\n }\n\n const existing = this.fileCache.get(fileName);\n if (existing) {\n return existing;\n }\n\n const parsed = realHost.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);\n this.fileCache.set(fileName, parsed);\n return parsed;\n },\n readFile: (filePath) => (filePath === sourcePath ? sourceContents : realHost.readFile(filePath)),\n writeFile: () => void undefined,\n };\n }\n\n public compileInMemory(filename: string, contents: string, currentDirectory?: string): CompilationResult {\n if (!filename.endsWith('.ts')) {\n // Necessary or the TypeScript compiler won't compile the file.\n filename += '.ts';\n }\n\n const program = ts.createProgram({\n rootNames: [filename],\n options: STANDARD_COMPILER_OPTIONS,\n host: this.createInMemoryCompilerHost(filename, contents, currentDirectory),\n });\n\n const rootFile = program.getSourceFile(filename);\n if (rootFile == null) {\n throw new Error(`Oopsie -- couldn't find root file back: ${filename}`);\n }\n\n return { program, rootFile };\n }\n}\n\nexport interface CompilationResult {\n program: ts.Program;\n rootFile: ts.SourceFile;\n}\n\nexport const STANDARD_COMPILER_OPTIONS: ts.CompilerOptions = {\n alwaysStrict: true,\n charset: 'utf8',\n declaration: true,\n declarationMap: true,\n experimentalDecorators: true,\n inlineSourceMap: true,\n inlineSources: true,\n lib: ['lib.es2020.d.ts'],\n module: ts.ModuleKind.CommonJS,\n noEmitOnError: true,\n noFallthroughCasesInSwitch: true,\n noImplicitAny: true,\n noImplicitReturns: true,\n noImplicitThis: true,\n noUnusedLocals: false, // Important, becomes super annoying without this\n noUnusedParameters: false, // Important, becomes super annoying without this\n resolveJsonModule: true,\n strict: true,\n strictNullChecks: true,\n strictPropertyInitialization: true,\n stripInternal: true,\n target: ts.ScriptTarget.ES2020,\n // Incremental builds\n incremental: true,\n tsBuildInfoFile: '.tsbuildinfo',\n};\n"]}
1
+ {"version":3,"file":"ts-compiler.js","sourceRoot":"","sources":["../../src/typescript/ts-compiler.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAEjC,MAAa,kBAAkB;IAA/B;QACmB,aAAQ,GAAG,EAAE,CAAC,kBAAkB,CAAC,iCAAyB,EAAE,IAAI,CAAC,CAAC;QAEnF;;WAEG;QACc,cAAS,GAAG,IAAI,GAAG,EAAqC,CAAC;IAqD5E,CAAC;IAnDQ,0BAA0B,CAC/B,UAAkB,EAClB,cAAsB,EACtB,gBAAyB;QAEzB,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,MAAM,UAAU,GAAG,EAAE,CAAC,gBAAgB,CAAC,UAAU,EAAE,cAAc,EAAE,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;QAE3F,OAAO;YACL,GAAG,QAAQ;YACX,UAAU,EAAE,CAAC,QAAQ,EAAE,EAAE,CACvB,QAAQ,KAAK,UAAU,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,UAAU,CAAC,QAAQ,CAAC;YAC1F,mBAAmB,EAAE,gBAAgB,IAAI,IAAI,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,gBAAgB,CAAC,CAAC,CAAC,QAAQ,CAAC,mBAAmB;YACrG,aAAa,EAAE,CAAC,QAAQ,EAAE,eAAe,EAAE,OAAO,EAAE,yBAAyB,EAAE,EAAE;gBAC/E,IAAI,QAAQ,KAAK,UAAU,EAAE,CAAC;oB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ED,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IAC/B,CAAC;CACF;AA3DD,gDA2DC;AAOY,QAAA,yBAAyB,GAAuB;IAC3D,YAAY,EAAE,IAAI;IAClB,OAAO,EAAE,MAAM;IACf,WAAW,EAAE,IAAI;IACjB,cAAc,EAAE,IAAI;IACpB,sBAAsB,EAAE,IAAI;IAC5B,eAAe,EAAE,IAAI;IACrB,aAAa,EAAE,IAAI;IACnB,GAAG,EAAE,CAAC,iBAAiB,CAAC;IACxB,MAAM,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ;IAC9B,aAAa,EAAE,IAAI;IACnB,0BAA0B,EAAE,IAAI;IAChC,aAAa,EAAE,IAAI;IACnB,iBAAiB,EAAE,IAAI;IACvB,cAAc,EAAE,IAAI;IACpB,cAAc,EAAE,KAAK,EAAE,iDAAiD;IACxE,kBAAkB,EAAE,KAAK,EAAE,iDAAiD;IAC5E,iBAAiB,EAAE,IAAI;IACvB,MAAM,EAAE,IAAI;IACZ,gBAAgB,EAAE,IAAI;IACtB,4BAA4B,EAAE,IAAI;IAClC,aAAa,EAAE,IAAI;IACnB,MAAM,EAAE,EAAE,CAAC,YAAY,CAAC,MAAM;IAC9B,qBAAqB;IACrB,WAAW,EAAE,IAAI;IACjB,eAAe,EAAE,cAAc;CAChC,CAAC","sourcesContent":["import * as ts from 'typescript';\n\nexport class TypeScriptCompiler {\n private readonly realHost = ts.createCompilerHost(STANDARD_COMPILER_OPTIONS, true);\n\n /**\n * A compiler-scoped cache to avoid having to re-parse the same library files for every compilation\n */\n private readonly fileCache = new Map<string, ts.SourceFile | undefined>();\n\n public createInMemoryCompilerHost(\n sourcePath: string,\n sourceContents: string,\n currentDirectory?: string,\n ): ts.CompilerHost {\n const realHost = this.realHost;\n const sourceFile = ts.createSourceFile(sourcePath, sourceContents, ts.ScriptTarget.Latest);\n\n return {\n ...realHost,\n fileExists: (filePath) =>\n filePath === sourcePath || this.fileCache.has(filePath) || realHost.fileExists(filePath),\n getCurrentDirectory: currentDirectory != null ? () => currentDirectory : realHost.getCurrentDirectory,\n getSourceFile: (fileName, languageVersion, onError, shouldCreateNewSourceFile) => {\n if (fileName === sourcePath) {\n return sourceFile;\n }\n\n const existing = this.fileCache.get(fileName);\n if (existing) {\n return existing;\n }\n\n const parsed = realHost.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);\n this.fileCache.set(fileName, parsed);\n return parsed;\n },\n readFile: (filePath) => (filePath === sourcePath ? sourceContents : realHost.readFile(filePath)),\n writeFile: () => void undefined,\n };\n }\n\n public compileInMemory(filename: string, contents: string, currentDirectory?: string): CompilationResult {\n if (!filename.endsWith('.ts')) {\n // Necessary or the TypeScript compiler won't compile the file.\n filename += '.ts';\n }\n\n const program = ts.createProgram({\n rootNames: [filename],\n options: STANDARD_COMPILER_OPTIONS,\n host: this.createInMemoryCompilerHost(filename, contents, currentDirectory),\n });\n\n const rootFile = program.getSourceFile(filename);\n if (rootFile == null) {\n throw new Error(`Oopsie -- couldn't find root file back: ${filename}`);\n }\n\n return { program, rootFile };\n }\n}\n\nexport interface CompilationResult {\n program: ts.Program;\n rootFile: ts.SourceFile;\n}\n\nexport const STANDARD_COMPILER_OPTIONS: ts.CompilerOptions = {\n alwaysStrict: true,\n charset: 'utf8',\n declaration: true,\n declarationMap: true,\n experimentalDecorators: true,\n inlineSourceMap: true,\n inlineSources: true,\n lib: ['lib.es2020.d.ts'],\n module: ts.ModuleKind.CommonJS,\n noEmitOnError: true,\n noFallthroughCasesInSwitch: true,\n noImplicitAny: true,\n noImplicitReturns: true,\n noImplicitThis: true,\n noUnusedLocals: false, // Important, becomes super annoying without this\n noUnusedParameters: false, // Important, becomes super annoying without this\n resolveJsonModule: true,\n strict: true,\n strictNullChecks: true,\n strictPropertyInitialization: true,\n stripInternal: true,\n target: ts.ScriptTarget.ES2020,\n // Incremental builds\n incremental: true,\n tsBuildInfoFile: '.tsbuildinfo',\n};\n"]}