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.
- package/README.md +50 -43
- package/lib/commands/coverage.js.map +1 -1
- package/lib/commands/extract.js.map +1 -1
- package/lib/commands/infuse.js.map +1 -1
- package/lib/commands/read.js.map +1 -1
- package/lib/commands/transliterate.js.map +1 -1
- package/lib/find-utils.js.map +1 -1
- package/lib/fixtures.js.map +1 -1
- package/lib/jsii/assemblies.js.map +1 -1
- package/lib/jsii/fingerprinting.js.map +1 -1
- package/lib/jsii/jsii-types.js.map +1 -1
- package/lib/jsii/jsii-utils.js +1 -1
- package/lib/jsii/jsii-utils.js.map +1 -1
- package/lib/jsii/packages.js.map +1 -1
- package/lib/languages/csharp.js +1 -1
- package/lib/languages/csharp.js.map +1 -1
- package/lib/languages/default.js.map +1 -1
- package/lib/languages/go.js +1 -1
- package/lib/languages/go.js.map +1 -1
- package/lib/languages/java.js +1 -1
- package/lib/languages/java.js.map +1 -1
- package/lib/languages/python.js.map +1 -1
- package/lib/languages/record-references.js.map +1 -1
- package/lib/languages/target-language.js.map +1 -1
- package/lib/logging.js.map +1 -1
- package/lib/main.js.map +1 -1
- package/lib/markdown/escapes.js.map +1 -1
- package/lib/markdown/markdown-renderer.js.map +1 -1
- package/lib/markdown/markdown.js.map +1 -1
- package/lib/markdown/replace-typescript-transform.js.map +1 -1
- package/lib/markdown/structure-renderer.js.map +1 -1
- package/lib/markdown/xml-comment-renderer.js.map +1 -1
- package/lib/o-tree.js.map +1 -1
- package/lib/renderer.js.map +1 -1
- package/lib/rosetta-reader.js.map +1 -1
- package/lib/rosetta-translator.js.map +1 -1
- package/lib/snippet-dependencies.js.map +1 -1
- package/lib/snippet-selectors.js.map +1 -1
- package/lib/snippet.js.map +1 -1
- package/lib/submodule-reference.js.map +1 -1
- package/lib/support.js.map +1 -1
- package/lib/tablets/tablets.js.map +1 -1
- package/lib/translate.js.map +1 -1
- package/lib/translate_all.js.map +1 -1
- package/lib/translate_all_worker.js.map +1 -1
- package/lib/typescript/ast-utils.js.map +1 -1
- package/lib/typescript/imports.js +1 -1
- package/lib/typescript/imports.js.map +1 -1
- package/lib/typescript/syntax-kind-counter.js.map +1 -1
- package/lib/typescript/ts-compiler.js +2 -2
- package/lib/typescript/ts-compiler.js.map +1 -1
- package/lib/typescript/types.js.map +1 -1
- package/lib/typescript/visible-spans.js.map +1 -1
- package/lib/util.js.map +1 -1
- package/package.json +8 -6
- package/releases.json +4 -2
package/lib/renderer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.js","sourceRoot":"","sources":["../src/renderer.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAGjC,qCAAiE;AAEjE,sDAOgC;AAChC,kDAAsG;AACtG,8CAAgF;AAEhF;;;;;;;GAOG;AACH,MAAa,WAAW;IAItB,YACmB,UAAyB,EAC1B,WAA2B,EAC1B,OAAsB,EACtB,UAA8B,EAAE,EACjC,sBAA6C,IAAI,GAAG,EAAE;QAJrD,eAAU,GAAV,UAAU,CAAe;QAC1B,gBAAW,GAAX,WAAW,CAAgB;QAC1B,YAAO,GAAP,OAAO,CAAe;QACtB,YAAO,GAAP,OAAO,CAAyB;QACjC,wBAAmB,GAAnB,mBAAmB,CAAmC;QARxD,gBAAW,GAAG,IAAI,KAAK,EAAiB,CAAC;QAUvD,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;IAC/C,CAAC;IAED;;OAEG;IACI,aAAa,CAAC,aAAyB;QAC5C,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,cAAc,EAAE,aAAa,CAAC,CAAC;QAEjF,yEAAyE;QACzE,+BAA+B;QAC/B,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;YACxC,cAAc,EAAE,UAAU;SAC3B,CAAC,CAAC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EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,CAAC;QAEzC,IAAI,CAAC,OAAO,EAAE;YACZ,MAAM,OAAO,GAAG,IAAA,wCAA4B,EAAC,IAAI,CAAC,CAAC;YACnD,IAAI,OAAO,EAAE;gBACX,OAAO,GAAG,IAAI,CAAC;aAChB;SACF;KACF;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,YAAY,CAAI,CAAgB;IACvC,OAAO,CAAC,KAAK,SAAS,CAAC;AACzB,CAAC;AAmBD,SAAS,6BAA6B,CAAC,GAAoB,EAAE,QAA0B;IACrF,OAAO;QACL,kBAAkB,EAAE,GAAG,CAAC,kBAAkB;QAC1C,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,GAAG,EAAE,GAAG,CAAC,GAAG;QACZ,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC;QACvC,UAAU,EAAE,QAAQ,CAAC,gBAAgB,CAAC,GAAG,CAAC,GAAG,CAAC;KAC/C,CAAC;AACJ,CAAC","sourcesContent":["import * as ts from 'typescript';\n\nimport { TargetLanguage } from './languages';\nimport { NO_SYNTAX, OTree, UnknownSyntax, Span } from './o-tree';\nimport { SubmoduleReference, SubmoduleReferenceMap } from './submodule-reference';\nimport {\n commentRangeFromTextRange,\n extractMaskingVoidExpression,\n extractShowingVoidExpression,\n nodeChildren,\n repeatNewlines,\n scanText,\n} from './typescript/ast-utils';\nimport { analyzeImportDeclaration, analyzeImportEquals, ImportStatement } from './typescript/imports';\nimport { typeOfExpression, inferredTypeOfExpression } from './typescript/types';\n\n/**\n * Render a TypeScript AST to some other representation (encoded in OTrees)\n *\n * Dispatch the actual conversion to a specific handler which will get the\n * appropriate method called for particular AST nodes. The handler may use\n * context to modify its own operations when traversing the tree hierarchy,\n * the type of which should be expressed via the C parameter.\n */\nexport class AstRenderer<C> {\n public readonly diagnostics = new Array<ts.Diagnostic>();\n public readonly currentContext: C;\n\n public constructor(\n private readonly sourceFile: ts.SourceFile,\n public readonly typeChecker: ts.TypeChecker,\n private readonly handler: AstHandler<C>,\n private readonly options: AstRendererOptions = {},\n public readonly submoduleReferences: SubmoduleReferenceMap = new Map(),\n ) {\n this.currentContext = handler.defaultContext;\n }\n\n /**\n * Merge the new context with the current context and create a new Converter from it\n */\n public updateContext(contextUpdate: Partial<C>): AstRenderer<C> {\n const newContext = this.handler.mergeContext(this.currentContext, contextUpdate);\n\n // Use prototypal inheritance to create a version of 'this' in which only\n // 'currentContext' is updated.\n return Object.assign(Object.create(this), {\n currentContext: newContext,\n });\n }\n\n /**\n * Convert a single node to an OTree\n */\n public convert(node: ts.Node | undefined): OTree {\n if (node === undefined) {\n return NO_SYNTAX;\n }\n\n // Basic transform of node\n const transformed = this.dispatch(node);\n transformed.setSpan(node.getStart(this.sourceFile), node.getEnd());\n if (!transformed.attachComment) {\n return transformed;\n }\n\n const withTrivia = this.attachLeadingTrivia(node, transformed);\n withTrivia.setSpan(node.getStart(this.sourceFile), node.getEnd());\n return withTrivia;\n }\n\n /**\n * Convert a set of nodes, filtering out hidden nodes\n */\n public convertAll(nodes: readonly ts.Node[]): OTree[] {\n return filterVisible(nodes).map(this.convert.bind(this));\n }\n\n public convertWithModifier(\n nodes: readonly ts.Node[],\n makeContext: (context: this, node: ts.Node, index: number) => AstRenderer<C>,\n ): OTree[] {\n const vis = assignVisibility(nodes);\n const result = new Array<OTree>();\n for (const [idx, { node, visible, maskingVoid }] of vis.entries()) {\n const renderedNode = visible ? node : maskingVoid;\n if (renderedNode) {\n const context = makeContext(this, renderedNode, idx);\n result.push(context.convert(renderedNode));\n }\n }\n return result;\n }\n\n /**\n * Convert a set of nodes, but update the context for the last one.\n *\n * Takes visibility into account.\n */\n public convertLastDifferently(nodes: readonly ts.Node[], lastContext: C): OTree[] {\n const lastConverter = this.updateContext(lastContext);\n\n const convert = this.convert.bind(this);\n const lastConvert = lastConverter.convert.bind(lastConverter);\n\n const ret: OTree[] = [];\n\n const vis = assignVisibility(nodes);\n for (let i = 0; i < vis.length; i++) {\n const whichConvert = i === vis.length - 1 ? lastConvert : convert;\n\n const node = vis[i].visible ? vis[i].node : vis[i].maskingVoid;\n if (node) {\n ret.push(whichConvert(node));\n }\n }\n\n return ret;\n }\n\n public getPosition(node: ts.Node): Span {\n return {\n start: node.getStart(this.sourceFile),\n end: node.getEnd(),\n };\n }\n\n public textOf(node: ts.Node): string {\n return node.getText(this.sourceFile);\n }\n\n public textAt(pos: number, end: number): string {\n return this.sourceFile.text.substring(pos, end);\n }\n\n /**\n * Infer type of expression by the argument it is assigned to\n *\n * If the type of the expression can include undefined (if the value is\n * optional), `undefined` will be removed from the union.\n *\n * (Will return undefined for object literals not unified with a declared type)\n *\n * @deprecated Use `inferredTypeOfExpression` instead\n */\n public inferredTypeOfExpression(node: ts.Expression) {\n return inferredTypeOfExpression(this.typeChecker, node);\n }\n\n /**\n * Type of expression from the text of the expression\n *\n * (Will return a map type for object literals)\n *\n * @deprecated Use `typeOfExpression` directly\n */\n public typeOfExpression(node: ts.Expression): ts.Type {\n return typeOfExpression(this.typeChecker, node);\n }\n\n public typeOfType(node: ts.TypeNode): ts.Type {\n return this.typeChecker.getTypeFromTypeNode(node);\n }\n\n public typeToString(type: ts.Type) {\n return this.typeChecker.typeToString(type);\n }\n\n public report(node: ts.Node, messageText: string, category: ts.DiagnosticCategory = ts.DiagnosticCategory.Error) {\n this.diagnostics.push({\n category,\n code: 0,\n source: 'rosetta',\n messageText,\n file: this.sourceFile,\n start: node.getStart(this.sourceFile),\n length: node.getWidth(this.sourceFile),\n });\n }\n\n public reportUnsupported(node: ts.Node, language: TargetLanguage | undefined): void {\n const nodeKind = ts.SyntaxKind[node.kind];\n // tslint:disable-next-line:max-line-length\n if (language) {\n this.report(\n node,\n `This TypeScript feature (${nodeKind}) is not supported in examples because we cannot translate it to ${language}. Please rewrite this example.`,\n );\n } else {\n this.report(\n node,\n `This TypeScript feature (${nodeKind}) is not supported in examples. Please rewrite this example.`,\n );\n }\n }\n\n /**\n * Whether there is non-whitespace on the same line before the given position\n */\n public codeOnLineBefore(pos: number) {\n const text = this.sourceFile.text;\n while (pos > 0) {\n const c = text[--pos];\n if (c === '\\n') {\n return false;\n }\n if (c !== ' ' && c !== '\\r' && c !== '\\t') {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return a newline if the given node is preceded by at least one newline\n *\n * Used to mirror newline use between matchin brackets (such as { ... } and [ ... ]).\n */\n public mirrorNewlineBefore(viz?: ts.Node, suffix = '', otherwise = ''): string {\n if (viz === undefined) {\n return suffix;\n }\n\n // Return a newline if the given node is preceded by newlines\n const leadingRanges = scanText(this.sourceFile.text, viz.getFullStart(), viz.getStart(this.sourceFile));\n const newlines = [];\n\n for (const range of leadingRanges) {\n if (range.type === 'other') {\n newlines.push(repeatNewlines(this.sourceFile.text.substring(range.pos, range.end)));\n }\n }\n\n return (newlines.join('').length > 0 ? '\\n' : otherwise) + suffix;\n }\n\n /**\n * Dispatch node to handler\n */\n private dispatch(tree: ts.Node): OTree {\n const visitor = this.handler;\n\n // Using a switch on tree.kind + forced down-casting, because this is significantly faster than\n // doing a cascade of `if` statements with the `ts.is<NodeType>` functions, since `tree.kind` is\n // effectively integers, and this switch statement is hence optimizable to a jump table. This is\n // a VERY significant enhancement to the debugging experience, too.\n switch (tree.kind) {\n case ts.SyntaxKind.EmptyStatement:\n // Additional semicolon where it doesn't belong.\n return NO_SYNTAX;\n case ts.SyntaxKind.SourceFile:\n return visitor.sourceFile(tree as ts.SourceFile, this);\n case ts.SyntaxKind.ImportEqualsDeclaration:\n return visitor.importStatement(analyzeImportEquals(tree as ts.ImportEqualsDeclaration, this), this);\n case ts.SyntaxKind.ImportDeclaration:\n return new OTree(\n [],\n analyzeImportDeclaration(tree as ts.ImportDeclaration, this, this.submoduleReferences).map((import_) =>\n visitor.importStatement(import_, this),\n ),\n { canBreakLine: true, separator: '\\n' },\n );\n case ts.SyntaxKind.StringLiteral:\n case ts.SyntaxKind.NoSubstitutionTemplateLiteral:\n return visitor.stringLiteral(tree as ts.StringLiteral | ts.NoSubstitutionTemplateLiteral, this);\n case ts.SyntaxKind.NumericLiteral:\n return visitor.numericLiteral(tree as ts.NumericLiteral, this);\n case ts.SyntaxKind.FunctionDeclaration:\n return visitor.functionDeclaration(tree as ts.FunctionDeclaration, this);\n case ts.SyntaxKind.Identifier:\n return visitor.identifier(tree as ts.Identifier, this);\n case ts.SyntaxKind.Block:\n return visitor.block(tree as ts.Block, this);\n case ts.SyntaxKind.Parameter:\n return visitor.parameterDeclaration(tree as ts.ParameterDeclaration, this);\n case ts.SyntaxKind.ReturnStatement:\n return visitor.returnStatement(tree as ts.ReturnStatement, this);\n case ts.SyntaxKind.BinaryExpression:\n return visitor.binaryExpression(tree as ts.BinaryExpression, this);\n case ts.SyntaxKind.IfStatement:\n return visitor.ifStatement(tree as ts.IfStatement, this);\n case ts.SyntaxKind.PropertyAccessExpression:\n const submoduleReference = this.submoduleReferences?.get(tree as ts.PropertyAccessExpression);\n return visitor.propertyAccessExpression(tree as ts.PropertyAccessExpression, this, submoduleReference);\n case ts.SyntaxKind.AwaitExpression:\n return visitor.awaitExpression(tree as ts.AwaitExpression, this);\n case ts.SyntaxKind.CallExpression:\n return visitor.callExpression(tree as ts.CallExpression, this);\n case ts.SyntaxKind.ExpressionStatement:\n return visitor.expressionStatement(tree as ts.ExpressionStatement, this);\n case ts.SyntaxKind.ObjectLiteralExpression:\n return visitor.objectLiteralExpression(tree as ts.ObjectLiteralExpression, this);\n case ts.SyntaxKind.NewExpression:\n return visitor.newExpression(tree as ts.NewExpression, this);\n case ts.SyntaxKind.PropertyAssignment:\n return visitor.propertyAssignment(tree as ts.PropertyAssignment, this);\n case ts.SyntaxKind.VariableStatement:\n return visitor.variableStatement(tree as ts.VariableStatement, this);\n case ts.SyntaxKind.VariableDeclarationList:\n return visitor.variableDeclarationList(tree as ts.VariableDeclarationList, this);\n case ts.SyntaxKind.VariableDeclaration:\n return visitor.variableDeclaration(tree as ts.VariableDeclaration, this);\n case ts.SyntaxKind.ArrayLiteralExpression:\n return visitor.arrayLiteralExpression(tree as ts.ArrayLiteralExpression, this);\n case ts.SyntaxKind.ShorthandPropertyAssignment:\n return visitor.shorthandPropertyAssignment(tree as ts.ShorthandPropertyAssignment, this);\n case ts.SyntaxKind.ForOfStatement:\n return visitor.forOfStatement(tree as ts.ForOfStatement, this);\n case ts.SyntaxKind.ClassDeclaration:\n return visitor.classDeclaration(tree as ts.ClassDeclaration, this);\n case ts.SyntaxKind.Constructor:\n return visitor.constructorDeclaration(tree as ts.ConstructorDeclaration, this);\n case ts.SyntaxKind.PropertyDeclaration:\n return visitor.propertyDeclaration(tree as ts.PropertyDeclaration, this);\n case ts.SyntaxKind.ComputedPropertyName:\n return visitor.computedPropertyName((tree as ts.ComputedPropertyName).expression, this);\n case ts.SyntaxKind.MethodDeclaration:\n return visitor.methodDeclaration(tree as ts.MethodDeclaration, this);\n case ts.SyntaxKind.InterfaceDeclaration:\n return visitor.interfaceDeclaration(tree as ts.InterfaceDeclaration, this);\n case ts.SyntaxKind.PropertySignature:\n return visitor.propertySignature(tree as ts.PropertySignature, this);\n case ts.SyntaxKind.MethodSignature:\n return visitor.methodSignature(tree as ts.MethodSignature, this);\n case ts.SyntaxKind.AsExpression:\n return visitor.asExpression(tree as ts.AsExpression, this);\n case ts.SyntaxKind.PrefixUnaryExpression:\n return visitor.prefixUnaryExpression(tree as ts.PrefixUnaryExpression, this);\n case ts.SyntaxKind.SpreadAssignment:\n if (this.textOf(tree) === '...') {\n return visitor.ellipsis(tree as ts.SpreadAssignment, this);\n }\n return visitor.spreadAssignment(tree as ts.SpreadAssignment, this);\n case ts.SyntaxKind.SpreadElement:\n if (this.textOf(tree) === '...') {\n return visitor.ellipsis(tree as ts.SpreadElement, this);\n }\n return visitor.spreadElement(tree as ts.SpreadElement, this);\n case ts.SyntaxKind.ElementAccessExpression:\n return visitor.elementAccessExpression(tree as ts.ElementAccessExpression, this);\n case ts.SyntaxKind.TemplateExpression:\n return visitor.templateExpression(tree as ts.TemplateExpression, this);\n case ts.SyntaxKind.NonNullExpression:\n return visitor.nonNullExpression(tree as ts.NonNullExpression, this);\n case ts.SyntaxKind.ParenthesizedExpression:\n return visitor.parenthesizedExpression(tree as ts.ParenthesizedExpression, this);\n case ts.SyntaxKind.VoidExpression:\n return visitor.maskingVoidExpression(tree as ts.VoidExpression, this);\n case ts.SyntaxKind.JSDocComment:\n return visitor.jsDoc(tree as ts.JSDoc, this);\n default:\n if (ts.isToken(tree)) {\n return visitor.token(tree, this);\n }\n this.reportUnsupported(tree, undefined);\n }\n\n if (this.options.bestEffort !== false) {\n // When doing best-effort conversion and we don't understand the node type, just return the complete text of it as-is\n return new OTree([this.textOf(tree)]);\n }\n // Otherwise, show a placeholder indicating we don't recognize the type\n const nodeKind = ts.SyntaxKind[tree.kind];\n return new UnknownSyntax(\n [`<${nodeKind} ${this.textOf(tree)}>`],\n ['\\n', ...nodeChildren(tree).map(this.convert.bind(this))],\n {\n indent: 2,\n },\n );\n }\n\n /**\n * Attach any leading whitespace and comments to the given output tree\n *\n * Regardless of whether it's declared to be able to accept such or not.\n */\n private attachLeadingTrivia(node: ts.Node, transformed: OTree): OTree {\n // Add comments and leading whitespace\n const leadingRanges = scanText(this.sourceFile.text, node.getFullStart(), node.getStart(this.sourceFile));\n\n const precede: OTree[] = [];\n for (const range of leadingRanges) {\n let trivia: OTree | undefined = undefined;\n switch (range.type) {\n case 'other':\n trivia = new OTree([repeatNewlines(this.sourceFile.text.substring(range.pos, range.end))], [], {\n renderOnce: `ws-${range.pos}`,\n });\n break;\n case 'linecomment':\n case 'blockcomment':\n trivia = this.handler.commentRange(\n commentSyntaxFromCommentRange(commentRangeFromTextRange(range), this),\n this,\n );\n break;\n\n case 'directive':\n break;\n }\n if (trivia != null) {\n // Set spans on comments to make sure their visibility is toggled correctly.\n trivia.setSpan(range.pos, range.end);\n precede.push(trivia);\n }\n }\n\n // FIXME: No trailing comments for now, they're too tricky\n\n if (precede.length > 0 && !transformed.isEmpty) {\n return new OTree([...precede, transformed], [], { canBreakLine: true });\n }\n return transformed;\n }\n}\n\n/**\n * Interface for AST handlers\n *\n * C is the type of hierarchical context the handler uses. Context\n * needs 2 operations: a constructor for a default context, and a\n * merge operation to combine 2 contexts to yield a new one.\n *\n * Otherwise, the handler should return an OTree for every type\n * of AST node.\n */\nexport interface AstHandler<C> {\n readonly language: TargetLanguage;\n\n readonly defaultContext: C;\n readonly indentChar?: ' ' | '\\t';\n mergeContext(old: C, update: Partial<C>): C;\n\n sourceFile(node: ts.SourceFile, context: AstRenderer<C>): OTree;\n commentRange(node: CommentSyntax, context: AstRenderer<C>): OTree;\n importStatement(node: ImportStatement, context: AstRenderer<C>): OTree;\n stringLiteral(node: ts.StringLiteral | ts.NoSubstitutionTemplateLiteral, children: AstRenderer<C>): OTree;\n numericLiteral(node: ts.NumericLiteral, children: AstRenderer<C>): OTree;\n functionDeclaration(node: ts.FunctionDeclaration, children: AstRenderer<C>): OTree;\n identifier(node: ts.Identifier, children: AstRenderer<C>): OTree;\n block(node: ts.Block, children: AstRenderer<C>): OTree;\n parameterDeclaration(node: ts.ParameterDeclaration, children: AstRenderer<C>): OTree;\n returnStatement(node: ts.ReturnStatement, context: AstRenderer<C>): OTree;\n binaryExpression(node: ts.BinaryExpression, context: AstRenderer<C>): OTree;\n ifStatement(node: ts.IfStatement, context: AstRenderer<C>): OTree;\n propertyAccessExpression(\n node: ts.PropertyAccessExpression,\n context: AstRenderer<C>,\n submoduleReference: SubmoduleReference | undefined,\n ): OTree;\n awaitExpression(node: ts.AwaitExpression, context: AstRenderer<C>): OTree;\n callExpression(node: ts.CallExpression, context: AstRenderer<C>): OTree;\n expressionStatement(node: ts.ExpressionStatement, context: AstRenderer<C>): OTree;\n token<A extends ts.SyntaxKind>(node: ts.Token<A>, context: AstRenderer<C>): OTree;\n objectLiteralExpression(node: ts.ObjectLiteralExpression, context: AstRenderer<C>): OTree;\n newExpression(node: ts.NewExpression, context: AstRenderer<C>): OTree;\n propertyAssignment(node: ts.PropertyAssignment, context: AstRenderer<C>): OTree;\n variableStatement(node: ts.VariableStatement, context: AstRenderer<C>): OTree;\n variableDeclarationList(node: ts.VariableDeclarationList, context: AstRenderer<C>): OTree;\n variableDeclaration(node: ts.VariableDeclaration, context: AstRenderer<C>): OTree;\n jsDoc(node: ts.JSDoc, context: AstRenderer<C>): OTree;\n arrayLiteralExpression(node: ts.ArrayLiteralExpression, context: AstRenderer<C>): OTree;\n shorthandPropertyAssignment(node: ts.ShorthandPropertyAssignment, context: AstRenderer<C>): OTree;\n forOfStatement(node: ts.ForOfStatement, context: AstRenderer<C>): OTree;\n classDeclaration(node: ts.ClassDeclaration, context: AstRenderer<C>): OTree;\n constructorDeclaration(node: ts.ConstructorDeclaration, context: AstRenderer<C>): OTree;\n propertyDeclaration(node: ts.PropertyDeclaration, context: AstRenderer<C>): OTree;\n computedPropertyName(node: ts.Expression, context: AstRenderer<C>): OTree;\n methodDeclaration(node: ts.MethodDeclaration, context: AstRenderer<C>): OTree;\n interfaceDeclaration(node: ts.InterfaceDeclaration, context: AstRenderer<C>): OTree;\n propertySignature(node: ts.PropertySignature, context: AstRenderer<C>): OTree;\n methodSignature(node: ts.MethodSignature, context: AstRenderer<C>): OTree;\n asExpression(node: ts.AsExpression, context: AstRenderer<C>): OTree;\n prefixUnaryExpression(node: ts.PrefixUnaryExpression, context: AstRenderer<C>): OTree;\n spreadElement(node: ts.SpreadElement, context: AstRenderer<C>): OTree;\n spreadAssignment(node: ts.SpreadAssignment, context: AstRenderer<C>): OTree;\n templateExpression(node: ts.TemplateExpression, context: AstRenderer<C>): OTree;\n nonNullExpression(node: ts.NonNullExpression, context: AstRenderer<C>): OTree;\n parenthesizedExpression(node: ts.ParenthesizedExpression, context: AstRenderer<C>): OTree;\n maskingVoidExpression(node: ts.VoidExpression, context: AstRenderer<C>): OTree;\n elementAccessExpression(node: ts.ElementAccessExpression, context: AstRenderer<C>): OTree;\n\n // Not a node, called when we recognize a spread element/assignment that is only\n // '...' and nothing else.\n ellipsis(node: ts.SpreadElement | ts.SpreadAssignment, context: AstRenderer<C>): OTree;\n}\n\nexport function nimpl<C>(node: ts.Node, context: AstRenderer<C>, options: { additionalInfo?: string } = {}) {\n const children = nodeChildren(node).map((c) => context.convert(c));\n\n let syntaxKind = ts.SyntaxKind[node.kind];\n if (syntaxKind === 'FirstPunctuation') {\n // These have the same identifier but this name is more descriptive\n syntaxKind = 'OpenBraceToken';\n }\n\n const parts = [`(${syntaxKind}`];\n if (options.additionalInfo) {\n parts.push(`{${options.additionalInfo}}`);\n }\n parts.push(context.textOf(node));\n\n return new UnknownSyntax([parts.join(' ')], children.length > 0 ? ['\\n', ...children] : [], {\n indent: 2,\n suffix: ')',\n separator: '\\n',\n canBreakLine: true,\n });\n}\n\nexport interface AstRendererOptions {\n /**\n * If enabled, don't translate the text of unknown nodes\n *\n * @default true\n */\n bestEffort?: boolean;\n}\n\ninterface ClassifiedNode {\n node: ts.Node;\n visible: boolean;\n maskingVoid?: ts.VoidExpression;\n}\n\nfunction filterVisible(nodes: readonly ts.Node[]): ts.Node[] {\n return assignVisibility(nodes)\n .map((c) => (c.visible ? c.node : c.maskingVoid))\n .filter(notUndefined);\n}\n\nfunction assignVisibility(nodes: readonly ts.Node[]): ClassifiedNode[] {\n const ret: ClassifiedNode[] = [];\n\n let visible = true;\n for (const node of nodes) {\n const maskingVoid = extractMaskingVoidExpression(node);\n if (visible && maskingVoid) {\n visible = false;\n }\n\n ret.push({ node, maskingVoid, visible });\n\n if (!visible) {\n const showing = extractShowingVoidExpression(node);\n if (showing) {\n visible = true;\n }\n }\n }\n\n return ret;\n}\n\nfunction notUndefined<A>(x: A | undefined): x is A {\n return x !== undefined;\n}\n\n/**\n * Our own representation of comments\n *\n * (So we can synthesize 'em\n */\nexport interface CommentSyntax {\n pos: number;\n text: string;\n hasTrailingNewLine?: boolean;\n kind: ts.CommentKind;\n\n /**\n * Whether it's at the end of a code line (so we can render a separating space)\n */\n isTrailing?: boolean;\n}\n\nfunction commentSyntaxFromCommentRange(rng: ts.CommentRange, renderer: AstRenderer<any>): CommentSyntax {\n return {\n hasTrailingNewLine: rng.hasTrailingNewLine,\n kind: rng.kind,\n pos: rng.pos,\n text: renderer.textAt(rng.pos, rng.end),\n isTrailing: renderer.codeOnLineBefore(rng.pos),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"renderer.js","sourceRoot":"","sources":["../src/renderer.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAGjC,qCAAiE;AAEjE,sDAOgC;AAChC,kDAAsG;AACtG,8CAAgF;AAEhF;;;;;;;GAOG;AACH,MAAa,WAAW;IAItB,YACmB,UAAyB,EAC1B,WAA2B,EAC1B,OAAsB,EACtB,UAA8B,EAAE,EACjC,sBAA6C,IAAI,GAAG,EAAE;QAJrD,eAAU,GAAV,UAAU,CAAe;QAC1B,gBAAW,GAAX,WAAW,CAAgB;QAC1B,YAAO,GAAP,OAAO,CAAe;QACtB,YAAO,GAAP,OAAO,CAAyB;QACjC,wBAAmB,GAAnB,mBAAmB,CAAmC;QARxD,gBAAW,GAAG,IAAI,KAAK,EAAiB,CAAC;QAUvD,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;IAC/C,CAAC;IAED;;OAEG;IACI,aAAa,CAAC,aAAyB;QAC5C,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,cAAc,EAAE,aAAa,CAAC,CAAC;QAEjF,yEAAyE;QACzE,+BAA+B;QAC/B,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE;YACxC,cAAc,EAAE,UAAU;SAC3B,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACI,OAAO,CAAC,IAAyB;QACtC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,kBAAS,CAAC;QACnB,C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AE,CAAC;QACzB,MAAM,WAAW,GAAG,IAAA,wCAA4B,EAAC,IAAI,CAAC,CAAC;QACvD,IAAI,OAAO,IAAI,WAAW,EAAE,CAAC;YAC3B,OAAO,GAAG,KAAK,CAAC;QAClB,CAAC;QAED,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,CAAC;QAEzC,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,MAAM,OAAO,GAAG,IAAA,wCAA4B,EAAC,IAAI,CAAC,CAAC;YACnD,IAAI,OAAO,EAAE,CAAC;gBACZ,OAAO,GAAG,IAAI,CAAC;YACjB,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,YAAY,CAAI,CAAgB;IACvC,OAAO,CAAC,KAAK,SAAS,CAAC;AACzB,CAAC;AAmBD,SAAS,6BAA6B,CAAC,GAAoB,EAAE,QAA0B;IACrF,OAAO;QACL,kBAAkB,EAAE,GAAG,CAAC,kBAAkB;QAC1C,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,GAAG,EAAE,GAAG,CAAC,GAAG;QACZ,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC;QACvC,UAAU,EAAE,QAAQ,CAAC,gBAAgB,CAAC,GAAG,CAAC,GAAG,CAAC;KAC/C,CAAC;AACJ,CAAC","sourcesContent":["import * as ts from 'typescript';\n\nimport { TargetLanguage } from './languages';\nimport { NO_SYNTAX, OTree, UnknownSyntax, Span } from './o-tree';\nimport { SubmoduleReference, SubmoduleReferenceMap } from './submodule-reference';\nimport {\n commentRangeFromTextRange,\n extractMaskingVoidExpression,\n extractShowingVoidExpression,\n nodeChildren,\n repeatNewlines,\n scanText,\n} from './typescript/ast-utils';\nimport { analyzeImportDeclaration, analyzeImportEquals, ImportStatement } from './typescript/imports';\nimport { typeOfExpression, inferredTypeOfExpression } from './typescript/types';\n\n/**\n * Render a TypeScript AST to some other representation (encoded in OTrees)\n *\n * Dispatch the actual conversion to a specific handler which will get the\n * appropriate method called for particular AST nodes. The handler may use\n * context to modify its own operations when traversing the tree hierarchy,\n * the type of which should be expressed via the C parameter.\n */\nexport class AstRenderer<C> {\n public readonly diagnostics = new Array<ts.Diagnostic>();\n public readonly currentContext: C;\n\n public constructor(\n private readonly sourceFile: ts.SourceFile,\n public readonly typeChecker: ts.TypeChecker,\n private readonly handler: AstHandler<C>,\n private readonly options: AstRendererOptions = {},\n public readonly submoduleReferences: SubmoduleReferenceMap = new Map(),\n ) {\n this.currentContext = handler.defaultContext;\n }\n\n /**\n * Merge the new context with the current context and create a new Converter from it\n */\n public updateContext(contextUpdate: Partial<C>): AstRenderer<C> {\n const newContext = this.handler.mergeContext(this.currentContext, contextUpdate);\n\n // Use prototypal inheritance to create a version of 'this' in which only\n // 'currentContext' is updated.\n return Object.assign(Object.create(this), {\n currentContext: newContext,\n });\n }\n\n /**\n * Convert a single node to an OTree\n */\n public convert(node: ts.Node | undefined): OTree {\n if (node === undefined) {\n return NO_SYNTAX;\n }\n\n // Basic transform of node\n const transformed = this.dispatch(node);\n transformed.setSpan(node.getStart(this.sourceFile), node.getEnd());\n if (!transformed.attachComment) {\n return transformed;\n }\n\n const withTrivia = this.attachLeadingTrivia(node, transformed);\n withTrivia.setSpan(node.getStart(this.sourceFile), node.getEnd());\n return withTrivia;\n }\n\n /**\n * Convert a set of nodes, filtering out hidden nodes\n */\n public convertAll(nodes: readonly ts.Node[]): OTree[] {\n return filterVisible(nodes).map(this.convert.bind(this));\n }\n\n public convertWithModifier(\n nodes: readonly ts.Node[],\n makeContext: (context: this, node: ts.Node, index: number) => AstRenderer<C>,\n ): OTree[] {\n const vis = assignVisibility(nodes);\n const result = new Array<OTree>();\n for (const [idx, { node, visible, maskingVoid }] of vis.entries()) {\n const renderedNode = visible ? node : maskingVoid;\n if (renderedNode) {\n const context = makeContext(this, renderedNode, idx);\n result.push(context.convert(renderedNode));\n }\n }\n return result;\n }\n\n /**\n * Convert a set of nodes, but update the context for the last one.\n *\n * Takes visibility into account.\n */\n public convertLastDifferently(nodes: readonly ts.Node[], lastContext: C): OTree[] {\n const lastConverter = this.updateContext(lastContext);\n\n const convert = this.convert.bind(this);\n const lastConvert = lastConverter.convert.bind(lastConverter);\n\n const ret: OTree[] = [];\n\n const vis = assignVisibility(nodes);\n for (let i = 0; i < vis.length; i++) {\n const whichConvert = i === vis.length - 1 ? lastConvert : convert;\n\n const node = vis[i].visible ? vis[i].node : vis[i].maskingVoid;\n if (node) {\n ret.push(whichConvert(node));\n }\n }\n\n return ret;\n }\n\n public getPosition(node: ts.Node): Span {\n return {\n start: node.getStart(this.sourceFile),\n end: node.getEnd(),\n };\n }\n\n public textOf(node: ts.Node): string {\n return node.getText(this.sourceFile);\n }\n\n public textAt(pos: number, end: number): string {\n return this.sourceFile.text.substring(pos, end);\n }\n\n /**\n * Infer type of expression by the argument it is assigned to\n *\n * If the type of the expression can include undefined (if the value is\n * optional), `undefined` will be removed from the union.\n *\n * (Will return undefined for object literals not unified with a declared type)\n *\n * @deprecated Use `inferredTypeOfExpression` instead\n */\n public inferredTypeOfExpression(node: ts.Expression) {\n return inferredTypeOfExpression(this.typeChecker, node);\n }\n\n /**\n * Type of expression from the text of the expression\n *\n * (Will return a map type for object literals)\n *\n * @deprecated Use `typeOfExpression` directly\n */\n public typeOfExpression(node: ts.Expression): ts.Type {\n return typeOfExpression(this.typeChecker, node);\n }\n\n public typeOfType(node: ts.TypeNode): ts.Type {\n return this.typeChecker.getTypeFromTypeNode(node);\n }\n\n public typeToString(type: ts.Type) {\n return this.typeChecker.typeToString(type);\n }\n\n public report(node: ts.Node, messageText: string, category: ts.DiagnosticCategory = ts.DiagnosticCategory.Error) {\n this.diagnostics.push({\n category,\n code: 0,\n source: 'rosetta',\n messageText,\n file: this.sourceFile,\n start: node.getStart(this.sourceFile),\n length: node.getWidth(this.sourceFile),\n });\n }\n\n public reportUnsupported(node: ts.Node, language: TargetLanguage | undefined): void {\n const nodeKind = ts.SyntaxKind[node.kind];\n // tslint:disable-next-line:max-line-length\n if (language) {\n this.report(\n node,\n `This TypeScript feature (${nodeKind}) is not supported in examples because we cannot translate it to ${language}. Please rewrite this example.`,\n );\n } else {\n this.report(\n node,\n `This TypeScript feature (${nodeKind}) is not supported in examples. Please rewrite this example.`,\n );\n }\n }\n\n /**\n * Whether there is non-whitespace on the same line before the given position\n */\n public codeOnLineBefore(pos: number) {\n const text = this.sourceFile.text;\n while (pos > 0) {\n const c = text[--pos];\n if (c === '\\n') {\n return false;\n }\n if (c !== ' ' && c !== '\\r' && c !== '\\t') {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return a newline if the given node is preceded by at least one newline\n *\n * Used to mirror newline use between matchin brackets (such as { ... } and [ ... ]).\n */\n public mirrorNewlineBefore(viz?: ts.Node, suffix = '', otherwise = ''): string {\n if (viz === undefined) {\n return suffix;\n }\n\n // Return a newline if the given node is preceded by newlines\n const leadingRanges = scanText(this.sourceFile.text, viz.getFullStart(), viz.getStart(this.sourceFile));\n const newlines = [];\n\n for (const range of leadingRanges) {\n if (range.type === 'other') {\n newlines.push(repeatNewlines(this.sourceFile.text.substring(range.pos, range.end)));\n }\n }\n\n return (newlines.join('').length > 0 ? '\\n' : otherwise) + suffix;\n }\n\n /**\n * Dispatch node to handler\n */\n private dispatch(tree: ts.Node): OTree {\n const visitor = this.handler;\n\n // Using a switch on tree.kind + forced down-casting, because this is significantly faster than\n // doing a cascade of `if` statements with the `ts.is<NodeType>` functions, since `tree.kind` is\n // effectively integers, and this switch statement is hence optimizable to a jump table. This is\n // a VERY significant enhancement to the debugging experience, too.\n switch (tree.kind) {\n case ts.SyntaxKind.EmptyStatement:\n // Additional semicolon where it doesn't belong.\n return NO_SYNTAX;\n case ts.SyntaxKind.SourceFile:\n return visitor.sourceFile(tree as ts.SourceFile, this);\n case ts.SyntaxKind.ImportEqualsDeclaration:\n return visitor.importStatement(analyzeImportEquals(tree as ts.ImportEqualsDeclaration, this), this);\n case ts.SyntaxKind.ImportDeclaration:\n return new OTree(\n [],\n analyzeImportDeclaration(tree as ts.ImportDeclaration, this, this.submoduleReferences).map((import_) =>\n visitor.importStatement(import_, this),\n ),\n { canBreakLine: true, separator: '\\n' },\n );\n case ts.SyntaxKind.StringLiteral:\n case ts.SyntaxKind.NoSubstitutionTemplateLiteral:\n return visitor.stringLiteral(tree as ts.StringLiteral | ts.NoSubstitutionTemplateLiteral, this);\n case ts.SyntaxKind.NumericLiteral:\n return visitor.numericLiteral(tree as ts.NumericLiteral, this);\n case ts.SyntaxKind.FunctionDeclaration:\n return visitor.functionDeclaration(tree as ts.FunctionDeclaration, this);\n case ts.SyntaxKind.Identifier:\n return visitor.identifier(tree as ts.Identifier, this);\n case ts.SyntaxKind.Block:\n return visitor.block(tree as ts.Block, this);\n case ts.SyntaxKind.Parameter:\n return visitor.parameterDeclaration(tree as ts.ParameterDeclaration, this);\n case ts.SyntaxKind.ReturnStatement:\n return visitor.returnStatement(tree as ts.ReturnStatement, this);\n case ts.SyntaxKind.BinaryExpression:\n return visitor.binaryExpression(tree as ts.BinaryExpression, this);\n case ts.SyntaxKind.IfStatement:\n return visitor.ifStatement(tree as ts.IfStatement, this);\n case ts.SyntaxKind.PropertyAccessExpression:\n const submoduleReference = this.submoduleReferences?.get(tree as ts.PropertyAccessExpression);\n return visitor.propertyAccessExpression(tree as ts.PropertyAccessExpression, this, submoduleReference);\n case ts.SyntaxKind.AwaitExpression:\n return visitor.awaitExpression(tree as ts.AwaitExpression, this);\n case ts.SyntaxKind.CallExpression:\n return visitor.callExpression(tree as ts.CallExpression, this);\n case ts.SyntaxKind.ExpressionStatement:\n return visitor.expressionStatement(tree as ts.ExpressionStatement, this);\n case ts.SyntaxKind.ObjectLiteralExpression:\n return visitor.objectLiteralExpression(tree as ts.ObjectLiteralExpression, this);\n case ts.SyntaxKind.NewExpression:\n return visitor.newExpression(tree as ts.NewExpression, this);\n case ts.SyntaxKind.PropertyAssignment:\n return visitor.propertyAssignment(tree as ts.PropertyAssignment, this);\n case ts.SyntaxKind.VariableStatement:\n return visitor.variableStatement(tree as ts.VariableStatement, this);\n case ts.SyntaxKind.VariableDeclarationList:\n return visitor.variableDeclarationList(tree as ts.VariableDeclarationList, this);\n case ts.SyntaxKind.VariableDeclaration:\n return visitor.variableDeclaration(tree as ts.VariableDeclaration, this);\n case ts.SyntaxKind.ArrayLiteralExpression:\n return visitor.arrayLiteralExpression(tree as ts.ArrayLiteralExpression, this);\n case ts.SyntaxKind.ShorthandPropertyAssignment:\n return visitor.shorthandPropertyAssignment(tree as ts.ShorthandPropertyAssignment, this);\n case ts.SyntaxKind.ForOfStatement:\n return visitor.forOfStatement(tree as ts.ForOfStatement, this);\n case ts.SyntaxKind.ClassDeclaration:\n return visitor.classDeclaration(tree as ts.ClassDeclaration, this);\n case ts.SyntaxKind.Constructor:\n return visitor.constructorDeclaration(tree as ts.ConstructorDeclaration, this);\n case ts.SyntaxKind.PropertyDeclaration:\n return visitor.propertyDeclaration(tree as ts.PropertyDeclaration, this);\n case ts.SyntaxKind.ComputedPropertyName:\n return visitor.computedPropertyName((tree as ts.ComputedPropertyName).expression, this);\n case ts.SyntaxKind.MethodDeclaration:\n return visitor.methodDeclaration(tree as ts.MethodDeclaration, this);\n case ts.SyntaxKind.InterfaceDeclaration:\n return visitor.interfaceDeclaration(tree as ts.InterfaceDeclaration, this);\n case ts.SyntaxKind.PropertySignature:\n return visitor.propertySignature(tree as ts.PropertySignature, this);\n case ts.SyntaxKind.MethodSignature:\n return visitor.methodSignature(tree as ts.MethodSignature, this);\n case ts.SyntaxKind.AsExpression:\n return visitor.asExpression(tree as ts.AsExpression, this);\n case ts.SyntaxKind.PrefixUnaryExpression:\n return visitor.prefixUnaryExpression(tree as ts.PrefixUnaryExpression, this);\n case ts.SyntaxKind.SpreadAssignment:\n if (this.textOf(tree) === '...') {\n return visitor.ellipsis(tree as ts.SpreadAssignment, this);\n }\n return visitor.spreadAssignment(tree as ts.SpreadAssignment, this);\n case ts.SyntaxKind.SpreadElement:\n if (this.textOf(tree) === '...') {\n return visitor.ellipsis(tree as ts.SpreadElement, this);\n }\n return visitor.spreadElement(tree as ts.SpreadElement, this);\n case ts.SyntaxKind.ElementAccessExpression:\n return visitor.elementAccessExpression(tree as ts.ElementAccessExpression, this);\n case ts.SyntaxKind.TemplateExpression:\n return visitor.templateExpression(tree as ts.TemplateExpression, this);\n case ts.SyntaxKind.NonNullExpression:\n return visitor.nonNullExpression(tree as ts.NonNullExpression, this);\n case ts.SyntaxKind.ParenthesizedExpression:\n return visitor.parenthesizedExpression(tree as ts.ParenthesizedExpression, this);\n case ts.SyntaxKind.VoidExpression:\n return visitor.maskingVoidExpression(tree as ts.VoidExpression, this);\n case ts.SyntaxKind.JSDocComment:\n return visitor.jsDoc(tree as ts.JSDoc, this);\n default:\n if (ts.isToken(tree)) {\n return visitor.token(tree, this);\n }\n this.reportUnsupported(tree, undefined);\n }\n\n if (this.options.bestEffort !== false) {\n // When doing best-effort conversion and we don't understand the node type, just return the complete text of it as-is\n return new OTree([this.textOf(tree)]);\n }\n // Otherwise, show a placeholder indicating we don't recognize the type\n const nodeKind = ts.SyntaxKind[tree.kind];\n return new UnknownSyntax(\n [`<${nodeKind} ${this.textOf(tree)}>`],\n ['\\n', ...nodeChildren(tree).map(this.convert.bind(this))],\n {\n indent: 2,\n },\n );\n }\n\n /**\n * Attach any leading whitespace and comments to the given output tree\n *\n * Regardless of whether it's declared to be able to accept such or not.\n */\n private attachLeadingTrivia(node: ts.Node, transformed: OTree): OTree {\n // Add comments and leading whitespace\n const leadingRanges = scanText(this.sourceFile.text, node.getFullStart(), node.getStart(this.sourceFile));\n\n const precede: OTree[] = [];\n for (const range of leadingRanges) {\n let trivia: OTree | undefined = undefined;\n switch (range.type) {\n case 'other':\n trivia = new OTree([repeatNewlines(this.sourceFile.text.substring(range.pos, range.end))], [], {\n renderOnce: `ws-${range.pos}`,\n });\n break;\n case 'linecomment':\n case 'blockcomment':\n trivia = this.handler.commentRange(\n commentSyntaxFromCommentRange(commentRangeFromTextRange(range), this),\n this,\n );\n break;\n\n case 'directive':\n break;\n }\n if (trivia != null) {\n // Set spans on comments to make sure their visibility is toggled correctly.\n trivia.setSpan(range.pos, range.end);\n precede.push(trivia);\n }\n }\n\n // FIXME: No trailing comments for now, they're too tricky\n\n if (precede.length > 0 && !transformed.isEmpty) {\n return new OTree([...precede, transformed], [], { canBreakLine: true });\n }\n return transformed;\n }\n}\n\n/**\n * Interface for AST handlers\n *\n * C is the type of hierarchical context the handler uses. Context\n * needs 2 operations: a constructor for a default context, and a\n * merge operation to combine 2 contexts to yield a new one.\n *\n * Otherwise, the handler should return an OTree for every type\n * of AST node.\n */\nexport interface AstHandler<C> {\n readonly language: TargetLanguage;\n\n readonly defaultContext: C;\n readonly indentChar?: ' ' | '\\t';\n mergeContext(old: C, update: Partial<C>): C;\n\n sourceFile(node: ts.SourceFile, context: AstRenderer<C>): OTree;\n commentRange(node: CommentSyntax, context: AstRenderer<C>): OTree;\n importStatement(node: ImportStatement, context: AstRenderer<C>): OTree;\n stringLiteral(node: ts.StringLiteral | ts.NoSubstitutionTemplateLiteral, children: AstRenderer<C>): OTree;\n numericLiteral(node: ts.NumericLiteral, children: AstRenderer<C>): OTree;\n functionDeclaration(node: ts.FunctionDeclaration, children: AstRenderer<C>): OTree;\n identifier(node: ts.Identifier, children: AstRenderer<C>): OTree;\n block(node: ts.Block, children: AstRenderer<C>): OTree;\n parameterDeclaration(node: ts.ParameterDeclaration, children: AstRenderer<C>): OTree;\n returnStatement(node: ts.ReturnStatement, context: AstRenderer<C>): OTree;\n binaryExpression(node: ts.BinaryExpression, context: AstRenderer<C>): OTree;\n ifStatement(node: ts.IfStatement, context: AstRenderer<C>): OTree;\n propertyAccessExpression(\n node: ts.PropertyAccessExpression,\n context: AstRenderer<C>,\n submoduleReference: SubmoduleReference | undefined,\n ): OTree;\n awaitExpression(node: ts.AwaitExpression, context: AstRenderer<C>): OTree;\n callExpression(node: ts.CallExpression, context: AstRenderer<C>): OTree;\n expressionStatement(node: ts.ExpressionStatement, context: AstRenderer<C>): OTree;\n token<A extends ts.SyntaxKind>(node: ts.Token<A>, context: AstRenderer<C>): OTree;\n objectLiteralExpression(node: ts.ObjectLiteralExpression, context: AstRenderer<C>): OTree;\n newExpression(node: ts.NewExpression, context: AstRenderer<C>): OTree;\n propertyAssignment(node: ts.PropertyAssignment, context: AstRenderer<C>): OTree;\n variableStatement(node: ts.VariableStatement, context: AstRenderer<C>): OTree;\n variableDeclarationList(node: ts.VariableDeclarationList, context: AstRenderer<C>): OTree;\n variableDeclaration(node: ts.VariableDeclaration, context: AstRenderer<C>): OTree;\n jsDoc(node: ts.JSDoc, context: AstRenderer<C>): OTree;\n arrayLiteralExpression(node: ts.ArrayLiteralExpression, context: AstRenderer<C>): OTree;\n shorthandPropertyAssignment(node: ts.ShorthandPropertyAssignment, context: AstRenderer<C>): OTree;\n forOfStatement(node: ts.ForOfStatement, context: AstRenderer<C>): OTree;\n classDeclaration(node: ts.ClassDeclaration, context: AstRenderer<C>): OTree;\n constructorDeclaration(node: ts.ConstructorDeclaration, context: AstRenderer<C>): OTree;\n propertyDeclaration(node: ts.PropertyDeclaration, context: AstRenderer<C>): OTree;\n computedPropertyName(node: ts.Expression, context: AstRenderer<C>): OTree;\n methodDeclaration(node: ts.MethodDeclaration, context: AstRenderer<C>): OTree;\n interfaceDeclaration(node: ts.InterfaceDeclaration, context: AstRenderer<C>): OTree;\n propertySignature(node: ts.PropertySignature, context: AstRenderer<C>): OTree;\n methodSignature(node: ts.MethodSignature, context: AstRenderer<C>): OTree;\n asExpression(node: ts.AsExpression, context: AstRenderer<C>): OTree;\n prefixUnaryExpression(node: ts.PrefixUnaryExpression, context: AstRenderer<C>): OTree;\n spreadElement(node: ts.SpreadElement, context: AstRenderer<C>): OTree;\n spreadAssignment(node: ts.SpreadAssignment, context: AstRenderer<C>): OTree;\n templateExpression(node: ts.TemplateExpression, context: AstRenderer<C>): OTree;\n nonNullExpression(node: ts.NonNullExpression, context: AstRenderer<C>): OTree;\n parenthesizedExpression(node: ts.ParenthesizedExpression, context: AstRenderer<C>): OTree;\n maskingVoidExpression(node: ts.VoidExpression, context: AstRenderer<C>): OTree;\n elementAccessExpression(node: ts.ElementAccessExpression, context: AstRenderer<C>): OTree;\n\n // Not a node, called when we recognize a spread element/assignment that is only\n // '...' and nothing else.\n ellipsis(node: ts.SpreadElement | ts.SpreadAssignment, context: AstRenderer<C>): OTree;\n}\n\nexport function nimpl<C>(node: ts.Node, context: AstRenderer<C>, options: { additionalInfo?: string } = {}) {\n const children = nodeChildren(node).map((c) => context.convert(c));\n\n let syntaxKind = ts.SyntaxKind[node.kind];\n if (syntaxKind === 'FirstPunctuation') {\n // These have the same identifier but this name is more descriptive\n syntaxKind = 'OpenBraceToken';\n }\n\n const parts = [`(${syntaxKind}`];\n if (options.additionalInfo) {\n parts.push(`{${options.additionalInfo}}`);\n }\n parts.push(context.textOf(node));\n\n return new UnknownSyntax([parts.join(' ')], children.length > 0 ? ['\\n', ...children] : [], {\n indent: 2,\n suffix: ')',\n separator: '\\n',\n canBreakLine: true,\n });\n}\n\nexport interface AstRendererOptions {\n /**\n * If enabled, don't translate the text of unknown nodes\n *\n * @default true\n */\n bestEffort?: boolean;\n}\n\ninterface ClassifiedNode {\n node: ts.Node;\n visible: boolean;\n maskingVoid?: ts.VoidExpression;\n}\n\nfunction filterVisible(nodes: readonly ts.Node[]): ts.Node[] {\n return assignVisibility(nodes)\n .map((c) => (c.visible ? c.node : c.maskingVoid))\n .filter(notUndefined);\n}\n\nfunction assignVisibility(nodes: readonly ts.Node[]): ClassifiedNode[] {\n const ret: ClassifiedNode[] = [];\n\n let visible = true;\n for (const node of nodes) {\n const maskingVoid = extractMaskingVoidExpression(node);\n if (visible && maskingVoid) {\n visible = false;\n }\n\n ret.push({ node, maskingVoid, visible });\n\n if (!visible) {\n const showing = extractShowingVoidExpression(node);\n if (showing) {\n visible = true;\n }\n }\n }\n\n return ret;\n}\n\nfunction notUndefined<A>(x: A | undefined): x is A {\n return x !== undefined;\n}\n\n/**\n * Our own representation of comments\n *\n * (So we can synthesize 'em\n */\nexport interface CommentSyntax {\n pos: number;\n text: string;\n hasTrailingNewLine?: boolean;\n kind: ts.CommentKind;\n\n /**\n * Whether it's at the end of a code line (so we can render a separating space)\n */\n isTrailing?: boolean;\n}\n\nfunction commentSyntaxFromCommentRange(rng: ts.CommentRange, renderer: AstRenderer<any>): CommentSyntax {\n return {\n hasTrailingNewLine: rng.hasTrailingNewLine,\n kind: rng.kind,\n pos: rng.pos,\n text: renderer.textAt(rng.pos, rng.end),\n isTrailing: renderer.codeOnLineBefore(rng.pos),\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rosetta-reader.js","sourceRoot":"","sources":["../src/rosetta-reader.ts"],"names":[],"mappings":";;;AAEA,kDAA+E;AAE/E,qCAAqC;AACrC,kDAAwD;AACxD,oEAAgE;AAChE,0FAAqF;AAErF,uCAMmB;AACnB,uCAA2C;AAC3C,+CAAgE;AAChE,2CAAyC;AACzC,iCAAoE;AAEpE,IAAY,kBAeX;AAfD,WAAY,kBAAkB;IAC5B;;OAEG;IACH,2CAAqB,CAAA;IAErB;;OAEG;IACH,6CAAuB,CAAA;IAEvB;;OAEG;IACH,mCAAa,CAAA;AACf,CAAC,EAfW,kBAAkB,kCAAlB,kBAAkB,QAe7B;AAsCD;;;;;;;;;;;GAWG;AACH,MAAa,mBAAmB;IAgB9B,YAAoC,UAA0B,EAAE;QAA5B,YAAO,GAAP,OAAO,CAAqB;QAfhE;;;;;WAKG;QACa,eAAU,GAAG,IAAI,wBAAc,EAAE,CAAC;QAEjC,kBAAa,GAAqB,EAAE,CAAC;QACrC,sBAAiB,GAAG,IAAI,GAAG,EAA6B,CAAC;QAOxE,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,C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C;IAED;;;OAGG;IACK,gBAAgB,CAAC,WAAoC,EAAE,gBAAyB;QACtF,IAAI,CAAC,gBAAgB,IAAI,WAAW,EAAE,UAAU,KAAK,KAAK,EAAE;YAC1D,OAAO,WAAW,CAAC;SACpB;QACD,MAAM,OAAO,GAAG,IAAA,mBAAY,EAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QACnD,MAAM,UAAU,GAAG,gFAAgF,CAAC;QACpG,OAAO;YACL,GAAG,WAAW;YACd,MAAM,EAAE,GAAG,OAAO,IAAI,UAAU,KAAK,WAAW,CAAC,MAAM,EAAE;SAC1D,CAAC;IACJ,CAAC;CACF;AA5OD,kDA4OC;AAED,SAAS,EAAE,CAAC,CAAc;IACxB,OAAO,CAAC,CAAC;AACX,CAAC;AAED;;;;GAIG;AACH,MAAa,OAAQ,SAAQ,mBAAmB;CAAG;AAAnD,0BAAmD","sourcesContent":["import * as spec from '@jsii/spec';\n\nimport { allTypeScriptSnippets, guessTabletLocation } from './jsii/assemblies';\nimport { TargetLanguage } from './languages';\nimport * as logging from './logging';\nimport { transformMarkdown } from './markdown/markdown';\nimport { MarkdownRenderer } from './markdown/markdown-renderer';\nimport { ReplaceTypeScriptTransform } from './markdown/replace-typescript-transform';\nimport { CodeBlock } from './markdown/types';\nimport {\n SnippetParameters,\n TypeScriptSnippet,\n updateParameters,\n ApiLocation,\n typeScriptSnippetFromSource,\n} from './snippet';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, Translation } from './tablets/tablets';\nimport { Translator } from './translate';\nimport { commentToken, pathExists, printDiagnostics } from './util';\n\nexport enum UnknownSnippetMode {\n /**\n * Return the snippet as given (untranslated)\n */\n VERBATIM = 'verbatim',\n\n /**\n * Live-translate the snippet as best as we can\n */\n TRANSLATE = 'translate',\n\n /**\n * Throw an error if this occurs\n */\n FAIL = 'fail',\n}\n\nexport interface RosettaOptions {\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.VERBATIM\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n\n /**\n * Target languages to use for live conversion\n *\n * @default All languages\n */\n readonly targetLanguages?: readonly TargetLanguage[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Whether this Rosetta should operate in \"loose\" mode, where missing literate\n * source files and missing fixtures are ignored instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Adds a disclaimer to start of snippet if it did not compile.\n *\n * @default false\n */\n readonly prefixDisclaimer?: boolean;\n}\n\n/**\n * Entry point class for consumers of Rosetta tablets (primarily: pacmak)\n *\n * Rosetta can work in one of two modes:\n *\n * 1. Live translation of snippets.\n * 2. Read translations from a pre-translated tablet (prepared using `jsii-rosetta extract` command).\n *\n * The second method affords more control over the precise circumstances of\n * sample compilation and is recommended, but the first method will do\n * when the second one is not necessary.\n */\nexport class RosettaTabletReader {\n /**\n * Newly translated samples\n *\n * In case live translation has been enabled, all samples that have been translated on-the-fly\n * are added to this tablet.\n */\n public readonly liveTablet = new LanguageTablet();\n\n private readonly loadedTablets: LanguageTablet[] = [];\n private readonly extractedSnippets = new Map<string, TypeScriptSnippet>();\n private readonly translator: Translator;\n private readonly loose: boolean;\n private readonly unknownSnippets: UnknownSnippetMode;\n private readonly _prefixDisclaimer: boolean;\n\n public constructor(private readonly options: RosettaOptions = {}) {\n this.loose = !!options.loose;\n this.unknownSnippets = options.unknownSnippets ?? UnknownSnippetMode.VERBATIM;\n this.translator = new Translator(options.includeCompilerDiagnostics ?? false);\n this._prefixDisclaimer = options.prefixDisclaimer ?? false;\n }\n\n /**\n * Diagnostics encountered while doing live translation\n */\n public get diagnostics() {\n return this.translator.diagnostics;\n }\n\n /**\n * Load a tablet as a source for translateable snippets\n *\n * Note: the snippets loaded from this tablet will NOT be validated for\n * their fingerprints or translator versions! If a matching snippet is found\n * in the tablet, it will always be returned, whether or not it is stale.\n */\n public async loadTabletFromFile(tabletFile: string) {\n const tablet = new LanguageTablet();\n await tablet.load(tabletFile);\n this.addTablet(tablet);\n }\n\n /**\n * Directly add a tablet to the list of tablets to load translations from\n */\n public addTablet(tablet: LanguageTablet) {\n this.loadedTablets.push(tablet);\n }\n\n /**\n * Add an assembly\n *\n * If a default tablet file is found in the assembly's directory, it will be\n * loaded (and assumed to contain a complete list of translated snippets for\n * this assembly already).\n *\n * Otherwise, if live conversion is enabled, the snippets in the assembly\n * become available for live translation later. This is necessary because we probably\n * need to fixturize snippets for successful compilation, and the information\n * pacmak sends our way later on is not going to be enough to do that.\n */\n public async addAssembly(assembly: spec.Assembly, assemblyDir: string) {\n const defaultTablet = guessTabletLocation(assemblyDir);\n if (await pathExists(defaultTablet)) {\n try {\n await this.loadTabletFromFile(defaultTablet);\n return;\n } catch (e: any) {\n logging.warn(`Error loading ${defaultTablet}: ${e.message}. Skipped.`);\n }\n }\n\n // Inventarize the snippets from this assembly, but only if there's a chance\n // we're going to need them.\n if (this.unknownSnippets === UnknownSnippetMode.TRANSLATE) {\n for (const tsnip of await allTypeScriptSnippets([{ assembly, directory: assemblyDir }], this.loose)) {\n this.extractedSnippets.set(snippetKey(tsnip), tsnip);\n }\n }\n }\n\n /**\n * Translate the given snippet for the given target language\n *\n * This will either:\n *\n * - Find an existing translation in a tablet and return that, if available.\n * - Otherwise, find a fixturized version of this snippet in an assembly that\n * was loaded beforehand, and translate it on-the-fly. Finding the fixture\n * will be based on the snippet key, which consists of a hash of the\n * visible source and the API location.\n * - Otherwise, translate the snippet as-is (without fixture information).\n *\n * This will do and store a full conversion of the given snippet, even if it only\n * returns one language. Subsequent retrievals for the same snippet in other\n * languages will reuse the translation from cache.\n *\n * If you are calling this for the side effect of adding translations to the live\n * tablet, you only need to do that for one language.\n */\n public translateSnippet(source: TypeScriptSnippet, targetLang: TargetLanguage): Translation | undefined {\n // Look for it in loaded tablets (or previous conversions)\n for (const tab of this.allTablets) {\n const ret = tab.lookup(source, targetLang);\n if (ret !== undefined) {\n return this.prefixDisclaimer(ret, this._prefixDisclaimer);\n }\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.VERBATIM) {\n return this.prefixDisclaimer(\n {\n language: targetLang,\n source: source.visibleSource,\n },\n this._prefixDisclaimer,\n );\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.FAIL) {\n const message = [\n 'The following snippet was not found in any of the loaded tablets:',\n source.visibleSource,\n `Location: ${JSON.stringify(source.location)}`,\n `Language: ${targetLang}`,\n ].join('\\n');\n throw new Error(message);\n }\n\n if (this.options.targetLanguages && !this.options.targetLanguages.includes(targetLang)) {\n throw new Error(\n `Rosetta configured for live conversion to ${this.options.targetLanguages.join(\n ', ',\n )}, but requested ${targetLang}`,\n );\n }\n\n // See if we can find a fixturized version of this snippet. If so, use that do the live\n // conversion.\n const extracted = this.extractedSnippets.get(snippetKey(source));\n if (extracted !== undefined) {\n const snippet = this.translator.translate(extracted, this.options.targetLanguages);\n this.liveTablet.addSnippet(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n // Try to live-convert it as-is.\n const snippet = this.translator.translate(source, this.options.targetLanguages);\n this.liveTablet.addSnippet(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n /**\n * Translate a snippet found in the \"@ example\" section of a jsii assembly\n *\n * Behaves exactly like `translateSnippet`, so see that method for documentation.\n */\n public translateExample(\n apiLocation: ApiLocation,\n example: string,\n targetLang: TargetLanguage,\n strict: boolean,\n compileDirectory = process.cwd(),\n ): Translation {\n const location = { api: apiLocation, field: { field: 'example' } } as const;\n\n const snippet = typeScriptSnippetFromSource(example, location, strict, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n });\n\n const translated = this.translateSnippet(snippet, targetLang);\n\n return translated ?? { language: 'typescript', source: example };\n }\n\n /**\n * Translate all TypeScript snippets found in a block of Markdown text\n *\n * For each snippet, behaves exactly like `translateSnippet`, so see that\n * method for documentation.\n */\n public translateSnippetsInMarkdown(\n apiLocation: ApiLocation,\n markdown: string,\n targetLang: TargetLanguage,\n strict: boolean,\n translationToCodeBlock: (x: Translation) => CodeBlock = id,\n compileDirectory = process.cwd(),\n ): string {\n return transformMarkdown(\n markdown,\n new MarkdownRenderer(),\n new ReplaceTypeScriptTransform(apiLocation, strict, (tsSnip) => {\n const translated = this.translateSnippet(\n updateParameters(tsSnip, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n }),\n targetLang,\n );\n if (!translated) {\n return undefined;\n }\n\n return translationToCodeBlock(translated);\n }),\n );\n }\n\n public printDiagnostics(stream: NodeJS.WritableStream, colors = true) {\n printDiagnostics(this.diagnostics, stream, colors);\n }\n\n public get hasErrors() {\n return this.diagnostics.some((d) => d.isError);\n }\n\n private get allTablets(): LanguageTablet[] {\n return [...this.loadedTablets, this.liveTablet];\n }\n\n /**\n * Adds a disclaimer to the front of the example if the prefixDisclaimer\n * flag is set and we know it does not compile.\n */\n private prefixDisclaimer(translation: Translation | undefined, prefixDisclaimer: boolean): Translation | undefined {\n if (!prefixDisclaimer || translation?.didCompile !== false) {\n return translation;\n }\n const comment = commentToken(translation.language);\n const disclaimer = 'Example automatically generated from non-compiling source. May contain errors.';\n return {\n ...translation,\n source: `${comment} ${disclaimer}\\n${translation.source}`,\n };\n }\n}\n\nfunction id(x: Translation) {\n return x;\n}\n\n/**\n * Backwards compatibility\n *\n * @deprecated use RosettaTabletReader instead\n */\nexport class Rosetta extends RosettaTabletReader {}\n"]}
|
|
1
|
+
{"version":3,"file":"rosetta-reader.js","sourceRoot":"","sources":["../src/rosetta-reader.ts"],"names":[],"mappings":";;;AAEA,kDAA+E;AAE/E,qCAAqC;AACrC,kDAAwD;AACxD,oEAAgE;AAChE,0FAAqF;AAErF,uCAMmB;AACnB,uCAA2C;AAC3C,+CAAgE;AAChE,2CAAyC;AACzC,iCAAoE;AAEpE,IAAY,kBAeX;AAfD,WAAY,kBAAkB;IAC5B;;OAEG;IACH,2CAAqB,CAAA;IAErB;;OAEG;IACH,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ACX,CAAC;YACF,IAAI,CAAC,UAAU,EAAE,CAAC;gBAChB,OAAO,SAAS,CAAC;YACnB,CAAC;YAED,OAAO,sBAAsB,CAAC,UAAU,CAAC,CAAC;QAC5C,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;IAEM,gBAAgB,CAAC,MAA6B,EAAE,MAAM,GAAG,IAAI;QAClE,IAAA,uBAAgB,EAAC,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACrD,CAAC;IAED,IAAW,SAAS;QAClB,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IACjD,CAAC;IAED,IAAY,UAAU;QACpB,OAAO,CAAC,GAAG,IAAI,CAAC,aAAa,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAClD,CAAC;IAED;;;OAGG;IACK,gBAAgB,CAAC,WAAoC,EAAE,gBAAyB;QACtF,IAAI,CAAC,gBAAgB,IAAI,WAAW,EAAE,UAAU,KAAK,KAAK,EAAE,CAAC;YAC3D,OAAO,WAAW,CAAC;QACrB,CAAC;QACD,MAAM,OAAO,GAAG,IAAA,mBAAY,EAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QACnD,MAAM,UAAU,GAAG,gFAAgF,CAAC;QACpG,OAAO;YACL,GAAG,WAAW;YACd,MAAM,EAAE,GAAG,OAAO,IAAI,UAAU,KAAK,WAAW,CAAC,MAAM,EAAE;SAC1D,CAAC;IACJ,CAAC;CACF;AA5OD,kDA4OC;AAED,SAAS,EAAE,CAAC,CAAc;IACxB,OAAO,CAAC,CAAC;AACX,CAAC;AAED;;;;GAIG;AACH,MAAa,OAAQ,SAAQ,mBAAmB;CAAG;AAAnD,0BAAmD","sourcesContent":["import * as spec from '@jsii/spec';\n\nimport { allTypeScriptSnippets, guessTabletLocation } from './jsii/assemblies';\nimport { TargetLanguage } from './languages';\nimport * as logging from './logging';\nimport { transformMarkdown } from './markdown/markdown';\nimport { MarkdownRenderer } from './markdown/markdown-renderer';\nimport { ReplaceTypeScriptTransform } from './markdown/replace-typescript-transform';\nimport { CodeBlock } from './markdown/types';\nimport {\n SnippetParameters,\n TypeScriptSnippet,\n updateParameters,\n ApiLocation,\n typeScriptSnippetFromSource,\n} from './snippet';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, Translation } from './tablets/tablets';\nimport { Translator } from './translate';\nimport { commentToken, pathExists, printDiagnostics } from './util';\n\nexport enum UnknownSnippetMode {\n /**\n * Return the snippet as given (untranslated)\n */\n VERBATIM = 'verbatim',\n\n /**\n * Live-translate the snippet as best as we can\n */\n TRANSLATE = 'translate',\n\n /**\n * Throw an error if this occurs\n */\n FAIL = 'fail',\n}\n\nexport interface RosettaOptions {\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.VERBATIM\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n\n /**\n * Target languages to use for live conversion\n *\n * @default All languages\n */\n readonly targetLanguages?: readonly TargetLanguage[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Whether this Rosetta should operate in \"loose\" mode, where missing literate\n * source files and missing fixtures are ignored instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Adds a disclaimer to start of snippet if it did not compile.\n *\n * @default false\n */\n readonly prefixDisclaimer?: boolean;\n}\n\n/**\n * Entry point class for consumers of Rosetta tablets (primarily: pacmak)\n *\n * Rosetta can work in one of two modes:\n *\n * 1. Live translation of snippets.\n * 2. Read translations from a pre-translated tablet (prepared using `jsii-rosetta extract` command).\n *\n * The second method affords more control over the precise circumstances of\n * sample compilation and is recommended, but the first method will do\n * when the second one is not necessary.\n */\nexport class RosettaTabletReader {\n /**\n * Newly translated samples\n *\n * In case live translation has been enabled, all samples that have been translated on-the-fly\n * are added to this tablet.\n */\n public readonly liveTablet = new LanguageTablet();\n\n private readonly loadedTablets: LanguageTablet[] = [];\n private readonly extractedSnippets = new Map<string, TypeScriptSnippet>();\n private readonly translator: Translator;\n private readonly loose: boolean;\n private readonly unknownSnippets: UnknownSnippetMode;\n private readonly _prefixDisclaimer: boolean;\n\n public constructor(private readonly options: RosettaOptions = {}) {\n this.loose = !!options.loose;\n this.unknownSnippets = options.unknownSnippets ?? UnknownSnippetMode.VERBATIM;\n this.translator = new Translator(options.includeCompilerDiagnostics ?? false);\n this._prefixDisclaimer = options.prefixDisclaimer ?? false;\n }\n\n /**\n * Diagnostics encountered while doing live translation\n */\n public get diagnostics() {\n return this.translator.diagnostics;\n }\n\n /**\n * Load a tablet as a source for translateable snippets\n *\n * Note: the snippets loaded from this tablet will NOT be validated for\n * their fingerprints or translator versions! If a matching snippet is found\n * in the tablet, it will always be returned, whether or not it is stale.\n */\n public async loadTabletFromFile(tabletFile: string) {\n const tablet = new LanguageTablet();\n await tablet.load(tabletFile);\n this.addTablet(tablet);\n }\n\n /**\n * Directly add a tablet to the list of tablets to load translations from\n */\n public addTablet(tablet: LanguageTablet) {\n this.loadedTablets.push(tablet);\n }\n\n /**\n * Add an assembly\n *\n * If a default tablet file is found in the assembly's directory, it will be\n * loaded (and assumed to contain a complete list of translated snippets for\n * this assembly already).\n *\n * Otherwise, if live conversion is enabled, the snippets in the assembly\n * become available for live translation later. This is necessary because we probably\n * need to fixturize snippets for successful compilation, and the information\n * pacmak sends our way later on is not going to be enough to do that.\n */\n public async addAssembly(assembly: spec.Assembly, assemblyDir: string) {\n const defaultTablet = guessTabletLocation(assemblyDir);\n if (await pathExists(defaultTablet)) {\n try {\n await this.loadTabletFromFile(defaultTablet);\n return;\n } catch (e: any) {\n logging.warn(`Error loading ${defaultTablet}: ${e.message}. Skipped.`);\n }\n }\n\n // Inventarize the snippets from this assembly, but only if there's a chance\n // we're going to need them.\n if (this.unknownSnippets === UnknownSnippetMode.TRANSLATE) {\n for (const tsnip of await allTypeScriptSnippets([{ assembly, directory: assemblyDir }], this.loose)) {\n this.extractedSnippets.set(snippetKey(tsnip), tsnip);\n }\n }\n }\n\n /**\n * Translate the given snippet for the given target language\n *\n * This will either:\n *\n * - Find an existing translation in a tablet and return that, if available.\n * - Otherwise, find a fixturized version of this snippet in an assembly that\n * was loaded beforehand, and translate it on-the-fly. Finding the fixture\n * will be based on the snippet key, which consists of a hash of the\n * visible source and the API location.\n * - Otherwise, translate the snippet as-is (without fixture information).\n *\n * This will do and store a full conversion of the given snippet, even if it only\n * returns one language. Subsequent retrievals for the same snippet in other\n * languages will reuse the translation from cache.\n *\n * If you are calling this for the side effect of adding translations to the live\n * tablet, you only need to do that for one language.\n */\n public translateSnippet(source: TypeScriptSnippet, targetLang: TargetLanguage): Translation | undefined {\n // Look for it in loaded tablets (or previous conversions)\n for (const tab of this.allTablets) {\n const ret = tab.lookup(source, targetLang);\n if (ret !== undefined) {\n return this.prefixDisclaimer(ret, this._prefixDisclaimer);\n }\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.VERBATIM) {\n return this.prefixDisclaimer(\n {\n language: targetLang,\n source: source.visibleSource,\n },\n this._prefixDisclaimer,\n );\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.FAIL) {\n const message = [\n 'The following snippet was not found in any of the loaded tablets:',\n source.visibleSource,\n `Location: ${JSON.stringify(source.location)}`,\n `Language: ${targetLang}`,\n ].join('\\n');\n throw new Error(message);\n }\n\n if (this.options.targetLanguages && !this.options.targetLanguages.includes(targetLang)) {\n throw new Error(\n `Rosetta configured for live conversion to ${this.options.targetLanguages.join(\n ', ',\n )}, but requested ${targetLang}`,\n );\n }\n\n // See if we can find a fixturized version of this snippet. If so, use that do the live\n // conversion.\n const extracted = this.extractedSnippets.get(snippetKey(source));\n if (extracted !== undefined) {\n const snippet = this.translator.translate(extracted, this.options.targetLanguages);\n this.liveTablet.addSnippet(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n // Try to live-convert it as-is.\n const snippet = this.translator.translate(source, this.options.targetLanguages);\n this.liveTablet.addSnippet(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n /**\n * Translate a snippet found in the \"@ example\" section of a jsii assembly\n *\n * Behaves exactly like `translateSnippet`, so see that method for documentation.\n */\n public translateExample(\n apiLocation: ApiLocation,\n example: string,\n targetLang: TargetLanguage,\n strict: boolean,\n compileDirectory = process.cwd(),\n ): Translation {\n const location = { api: apiLocation, field: { field: 'example' } } as const;\n\n const snippet = typeScriptSnippetFromSource(example, location, strict, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n });\n\n const translated = this.translateSnippet(snippet, targetLang);\n\n return translated ?? { language: 'typescript', source: example };\n }\n\n /**\n * Translate all TypeScript snippets found in a block of Markdown text\n *\n * For each snippet, behaves exactly like `translateSnippet`, so see that\n * method for documentation.\n */\n public translateSnippetsInMarkdown(\n apiLocation: ApiLocation,\n markdown: string,\n targetLang: TargetLanguage,\n strict: boolean,\n translationToCodeBlock: (x: Translation) => CodeBlock = id,\n compileDirectory = process.cwd(),\n ): string {\n return transformMarkdown(\n markdown,\n new MarkdownRenderer(),\n new ReplaceTypeScriptTransform(apiLocation, strict, (tsSnip) => {\n const translated = this.translateSnippet(\n updateParameters(tsSnip, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n }),\n targetLang,\n );\n if (!translated) {\n return undefined;\n }\n\n return translationToCodeBlock(translated);\n }),\n );\n }\n\n public printDiagnostics(stream: NodeJS.WritableStream, colors = true) {\n printDiagnostics(this.diagnostics, stream, colors);\n }\n\n public get hasErrors() {\n return this.diagnostics.some((d) => d.isError);\n }\n\n private get allTablets(): LanguageTablet[] {\n return [...this.loadedTablets, this.liveTablet];\n }\n\n /**\n * Adds a disclaimer to the front of the example if the prefixDisclaimer\n * flag is set and we know it does not compile.\n */\n private prefixDisclaimer(translation: Translation | undefined, prefixDisclaimer: boolean): Translation | undefined {\n if (!prefixDisclaimer || translation?.didCompile !== false) {\n return translation;\n }\n const comment = commentToken(translation.language);\n const disclaimer = 'Example automatically generated from non-compiling source. May contain errors.';\n return {\n ...translation,\n source: `${comment} ${disclaimer}\\n${translation.source}`,\n };\n }\n}\n\nfunction id(x: Translation) {\n return x;\n}\n\n/**\n * Backwards compatibility\n *\n * @deprecated use RosettaTabletReader instead\n */\nexport class Rosetta extends RosettaTabletReader {}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rosetta-translator.js","sourceRoot":"","sources":["../src/rosetta-translator.ts"],"names":[],"mappings":";;;AAAA,qCAAyC;AAGzC,0DAA0D;AAC1D,2CAA+C;AAC/C,qCAAqC;AACrC,uCAA8D;AAC9D,iEAKgC;AAChC,uCAA2C;AAC3C,+CAAsE;AACtE,mDAAmE;AAoCnE;;;;;GAKG;AACH,MAAa,iBAAiB;IAc5B,YAAmB,UAAoC,EAAE;QAbzD;;;;WAIG;QACa,WAAM,GAAG,IAAI,wBAAc,EAAE,CAAC;QAE9B,UAAK,GAAG,IAAI,wBAAc,EAAE,CAAC;QAO3C,IAAI,CAAC,aAAa,GAAG,IAAI,kCAAiB,CAAC,OAAO,EAAE,UAAU,IAAI,EAAE,CAAC,CAAC;QACtE,IAAI,CAAC,0BAA0B,GAAG,OAAO,CAAC,0BAA0B,IAAI,KAAK,CAAC;QAC9E,IAAI,CAAC,sBAAsB,GAAG,OAAO,CAAC,sBAAsB,IAAI,KAAK,CAAC;IACxE,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,SAAS,CAAC,QAAgB;QACrC,IAAI;YACF,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;SACjC;QAAC,OAAO,CAAM,EAAE;YACf,OAAO,CAAC,IAAI,CAAC,uBAAuB,QAAQ,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;SAC/D;IACH,CAAC;IAEM,KAAK,CAAC,UAAU,CAAC,QAAgB;QACtC,MAAM,GAAG,GAAG,MAAM,w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E;QACrE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAE,UAAU,EAAE,iBAAiB,EAAE,CAAC;KAC/G;IACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC7D,CAAC;AAcD,SAAS,SAAS,CAAC,OAA0B;IAC3C,OAAO,OAAO,CAAC,UAAU,EAAE,OAAO,KAAK,SAAS,CAAC;AACnD,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport * as spec from '@jsii/spec';\n\nimport { TypeFingerprinter } from './jsii/fingerprinting';\nimport { TARGET_LANGUAGES } from './languages';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, completeSource } from './snippet';\nimport {\n collectDependencies,\n validateAvailableDependencies,\n prepareDependencyDirectory,\n expandWithTransitiveDependencies,\n} from './snippet-dependencies';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, TranslatedSnippet } from './tablets/tablets';\nimport { translateAll, TranslateAllResult } from './translate_all';\n\nexport interface RosettaTranslatorOptions {\n /**\n * Assemblies to use for fingerprinting\n *\n * The set of assemblies here are used to invalidate the cache. Any types that are\n * used in snippets are looked up in this set of assemblies. If found, their type\n * information is fingerprinted and compared to the type information at the time\n * compilation of the cached sample. If different, this is considered to be a cache\n * miss.\n *\n * You must use the same set of assemblies when generating and reading the cache\n * file, otherwise the fingerprint is guaranteed to be different and the cache will\n * be useless (e.g. if you generate the cache WITH assembly information but\n * read it without, or vice versa).\n *\n * @default No assemblies.\n */\n readonly assemblies?: spec.Assembly[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n *\n * @default false\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Allow reading dirty translations from cache\n *\n * @default false\n */\n readonly allowDirtyTranslations?: boolean;\n}\n\n/**\n * Entry point for consumers that want to translate code on-the-fly\n *\n * If you want to generate and translate code on-the-fly, in ways that cannot\n * be achieved by the rosetta CLI, use this class.\n */\nexport class RosettaTranslator {\n /**\n * Tablet with fresh translations\n *\n * All new translations (not read from cache) are added to this tablet.\n */\n public readonly tablet = new LanguageTablet();\n\n public readonly cache = new LanguageTablet();\n\n private readonly fingerprinter: TypeFingerprinter;\n private readonly includeCompilerDiagnostics: boolean;\n private readonly allowDirtyTranslations: boolean;\n\n public constructor(options: RosettaTranslatorOptions = {}) {\n this.fingerprinter = new TypeFingerprinter(options?.assemblies ?? []);\n this.includeCompilerDiagnostics = options.includeCompilerDiagnostics ?? false;\n this.allowDirtyTranslations = options.allowDirtyTranslations ?? false;\n }\n\n /**\n * @deprecated use `addToCache` instead\n */\n public async loadCache(fileName: string) {\n try {\n await this.cache.load(fileName);\n } catch (e: any) {\n logging.warn(`Error reading cache ${fileName}: ${e.message}`);\n }\n }\n\n public async addToCache(filename: string) {\n const tab = await LanguageTablet.fromOptionalFile(filename);\n this.cache.addTablet(tab);\n }\n\n public addTabletsToCache(...tablets: LanguageTablet[]) {\n for (const tab of tablets) {\n this.cache.addTablet(tab);\n }\n }\n\n public hasCache() {\n return this.cache.count > 0;\n }\n\n /**\n * For all the given snippets, try to read translations from the cache\n *\n * Will remove the cached snippets from the input array.\n */\n public readFromCache(snippets: TypeScriptSnippet[], addToTablet = true, compiledOnly = false): ReadFromCacheResults {\n const translations = new Array<TranslatedSnippet>();\n const remaining = new Array<TypeScriptSnippet>();\n\n let infusedCount = 0;\n let dirtyCount = 0;\n let dirtySourceCount = 0;\n let dirtyTypesCount = 0;\n let dirtyTranslatorCount = 0;\n let dirtyDidntCompile = 0;\n\n for (const snippet of snippets) {\n const fromCache = tryReadFromCache(snippet, this.cache, this.fingerprinter, compiledOnly);\n switch (fromCache.type) {\n case 'hit':\n if (addToTablet) {\n this.tablet.addSnippet(fromCache.snippet);\n }\n translations.push(fromCache.snippet);\n\n infusedCount += fromCache.infused ? 1 : 0;\n break;\n\n case 'dirty':\n dirtyCount += 1;\n dirtySourceCount += fromCache.dirtySource ? 1 : 0;\n dirtyTranslatorCount += fromCache.dirtyTranslator ? 1 : 0;\n dirtyTypesCount += fromCache.dirtyTypes ? 1 : 0;\n dirtyDidntCompile += fromCache.dirtyDidntCompile ? 1 : 0;\n\n if (this.allowDirtyTranslations) {\n translations.push(fromCache.translation);\n } else {\n remaining.push(snippet);\n }\n break;\n\n case 'miss':\n remaining.push(snippet);\n break;\n }\n }\n\n return {\n translations,\n remaining,\n infusedCount,\n dirtyCount,\n dirtySourceCount,\n dirtyTranslatorCount,\n dirtyTypesCount,\n dirtyDidntCompile,\n };\n }\n\n public async translateAll(snippets: TypeScriptSnippet[], addToTablet?: boolean): Promise<TranslateAllResult>;\n public async translateAll(snippets: TypeScriptSnippet[], options?: TranslateAllOptions): Promise<TranslateAllResult>;\n public async translateAll(\n snippets: TypeScriptSnippet[],\n optionsOrAddToTablet?: boolean | TranslateAllOptions,\n ): Promise<TranslateAllResult> {\n const options =\n optionsOrAddToTablet && typeof optionsOrAddToTablet === 'object'\n ? optionsOrAddToTablet\n : { addToTablet: optionsOrAddToTablet };\n\n const exampleDependencies = collectDependencies(snippets);\n await expandWithTransitiveDependencies(exampleDependencies);\n\n let compilationDirectory;\n let cleanCompilationDir = false;\n if (options?.compilationDirectory) {\n // If the user provided a directory, we're going to trust-but-confirm.\n await validateAvailableDependencies(options.compilationDirectory, exampleDependencies);\n compilationDirectory = options.compilationDirectory;\n } else {\n compilationDirectory = await prepareDependencyDirectory(exampleDependencies);\n cleanCompilationDir = true;\n }\n\n const origDir = process.cwd();\n // Easiest way to get a fixed working directory (for sources) in is to chdir\n process.chdir(compilationDirectory);\n\n let result;\n try {\n result = await translateAll(snippets, this.includeCompilerDiagnostics);\n } finally {\n process.chdir(origDir);\n if (cleanCompilationDir) {\n if (options.cleanup ?? true) {\n await fs.rm(compilationDirectory, { force: true, recursive: true });\n } else {\n logging.info(`Leaving directory uncleaned: ${compilationDirectory}`);\n }\n }\n }\n\n const fingerprinted = result.translatedSnippets.map((snippet) =>\n snippet.withFingerprint(this.fingerprinter.fingerprintAll(snippet.fqnsReferenced())),\n );\n\n if (options?.addToTablet ?? true) {\n for (const translation of fingerprinted) {\n this.tablet.addSnippet(translation);\n }\n }\n\n return {\n translatedSnippets: fingerprinted,\n diagnostics: result.diagnostics,\n };\n }\n}\n\n/**\n * Try to find the translation for the given snippet in the given cache\n *\n * Rules for cacheability are:\n * - id is the same (== visible source didn't change)\n * - complete source is the same (== fixture didn't change)\n * - all types involved have the same fingerprint (== API surface didn't change)\n * - the versions of all translations match the versions on the available translators (== translator itself didn't change)\n *\n * For the versions check: we could have selectively picked some translations\n * from the cache while performing others. However, since the big work is in\n * parsing the TypeScript, and the rendering itself is peanutes (assumption), it\n * doesn't really make a lot of difference. So, for simplification's sake,\n * we'll regen all translations if there's at least one that's outdated.\n */\nfunction tryReadFromCache(\n sourceSnippet: TypeScriptSnippet,\n cache: LanguageTablet,\n fingerprinter: TypeFingerprinter,\n compiledOnly: boolean,\n): CacheHit {\n const fromCache = cache.tryGetSnippet(snippetKey(sourceSnippet));\n\n if (!fromCache) {\n return { type: 'miss' };\n }\n\n // infused snippets won't pass the full source check or the fingerprinter\n // but there is no reason to try to recompile it, so return cached snippet\n // if there exists one.\n if (isInfused(sourceSnippet)) {\n return { type: 'hit', snippet: fromCache, infused: true };\n }\n\n const dirtySource = completeSource(sourceSnippet) !== fromCache.snippet.fullSource;\n const dirtyTranslator = !Object.entries(TARGET_LANGUAGES).every(\n ([lang, translator]) => fromCache.snippet.translations?.[lang]?.version === translator.version,\n );\n const dirtyTypes = fingerprinter.fingerprintAll(fromCache.fqnsReferenced()) !== fromCache.snippet.fqnsFingerprint;\n const dirtyDidntCompile = compiledOnly && !fromCache.snippet.didCompile;\n\n if (dirtySource || dirtyTranslator || dirtyTypes || dirtyDidntCompile) {\n return { type: 'dirty', translation: fromCache, dirtySource, dirtyTranslator, dirtyTypes, dirtyDidntCompile };\n }\n return { type: 'hit', snippet: fromCache, infused: false };\n}\n\nexport type CacheHit =\n | { readonly type: 'miss' }\n | { readonly type: 'hit'; readonly snippet: TranslatedSnippet; readonly infused: boolean }\n | {\n readonly type: 'dirty';\n readonly translation: TranslatedSnippet;\n readonly dirtySource: boolean;\n readonly dirtyTranslator: boolean;\n readonly dirtyTypes: boolean;\n readonly dirtyDidntCompile: boolean;\n };\n\nfunction isInfused(snippet: TypeScriptSnippet) {\n return snippet.parameters?.infused !== undefined;\n}\n\nexport interface ReadFromCacheResults {\n /**\n * Successful translations\n */\n readonly translations: TranslatedSnippet[];\n\n /**\n * Successful but dirty hits\n */\n readonly remaining: TypeScriptSnippet[];\n\n /**\n * How many successfully hit translations were infused\n */\n readonly infusedCount: number;\n\n readonly dirtyCount: number;\n\n // Counts for dirtiness (a single snippet may be dirty for more than one reason)\n readonly dirtySourceCount: number;\n readonly dirtyTranslatorCount: number;\n readonly dirtyTypesCount: number;\n readonly dirtyDidntCompile: number;\n}\n\nexport interface TranslateAllOptions {\n /**\n * @default - Create a temporary directory with all necessary packages\n */\n readonly compilationDirectory?: string;\n\n /**\n * @default true\n */\n readonly addToTablet?: boolean;\n\n /**\n * @default true\n */\n readonly cleanup?: boolean;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"rosetta-translator.js","sourceRoot":"","sources":["../src/rosetta-translator.ts"],"names":[],"mappings":";;;AAAA,qCAAyC;AAGzC,0DAA0D;AAC1D,2CAA+C;AAC/C,qCAAqC;AACrC,uCAA8D;AAC9D,iEAKgC;AAChC,uCAA2C;AAC3C,+CAAsE;AACtE,mDAAmE;AAoCnE;;;;;GAKG;AACH,MAAa,iBAAiB;IAc5B,YAAmB,UAAoC,EAAE;QAbzD;;;;WAIG;QACa,WAAM,GAAG,IAAI,wBAAc,EAAE,CAAC;QAE9B,UAAK,GAAG,IAAI,wBAAc,EAAE,CAAC;QAO3C,IAAI,CAAC,aAAa,GAAG,IAAI,kCAAiB,CAAC,OAAO,EAAE,UAAU,IAAI,EAAE,CAAC,CAAC;QAC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C;QAC7B,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC5D,CAAC;IAED,MAAM,WAAW,GAAG,IAAA,wBAAc,EAAC,aAAa,CAAC,KAAK,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC;IACnF,MAAM,eAAe,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,4BAAgB,CAAC,CAAC,KAAK,CAC7D,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,IAAI,CAAC,EAAE,OAAO,KAAK,UAAU,CAAC,OAAO,CAC/F,CAAC;IACF,MAAM,UAAU,GAAG,aAAa,CAAC,cAAc,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC,KAAK,SAAS,CAAC,OAAO,CAAC,eAAe,CAAC;IAClH,MAAM,iBAAiB,GAAG,YAAY,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC;IAExE,IAAI,WAAW,IAAI,eAAe,IAAI,UAAU,IAAI,iBAAiB,EAAE,CAAC;QACtE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAE,UAAU,EAAE,iBAAiB,EAAE,CAAC;IAChH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC7D,CAAC;AAcD,SAAS,SAAS,CAAC,OAA0B;IAC3C,OAAO,OAAO,CAAC,UAAU,EAAE,OAAO,KAAK,SAAS,CAAC;AACnD,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport * as spec from '@jsii/spec';\n\nimport { TypeFingerprinter } from './jsii/fingerprinting';\nimport { TARGET_LANGUAGES } from './languages';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, completeSource } from './snippet';\nimport {\n collectDependencies,\n validateAvailableDependencies,\n prepareDependencyDirectory,\n expandWithTransitiveDependencies,\n} from './snippet-dependencies';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, TranslatedSnippet } from './tablets/tablets';\nimport { translateAll, TranslateAllResult } from './translate_all';\n\nexport interface RosettaTranslatorOptions {\n /**\n * Assemblies to use for fingerprinting\n *\n * The set of assemblies here are used to invalidate the cache. Any types that are\n * used in snippets are looked up in this set of assemblies. If found, their type\n * information is fingerprinted and compared to the type information at the time\n * compilation of the cached sample. If different, this is considered to be a cache\n * miss.\n *\n * You must use the same set of assemblies when generating and reading the cache\n * file, otherwise the fingerprint is guaranteed to be different and the cache will\n * be useless (e.g. if you generate the cache WITH assembly information but\n * read it without, or vice versa).\n *\n * @default No assemblies.\n */\n readonly assemblies?: spec.Assembly[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n *\n * @default false\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Allow reading dirty translations from cache\n *\n * @default false\n */\n readonly allowDirtyTranslations?: boolean;\n}\n\n/**\n * Entry point for consumers that want to translate code on-the-fly\n *\n * If you want to generate and translate code on-the-fly, in ways that cannot\n * be achieved by the rosetta CLI, use this class.\n */\nexport class RosettaTranslator {\n /**\n * Tablet with fresh translations\n *\n * All new translations (not read from cache) are added to this tablet.\n */\n public readonly tablet = new LanguageTablet();\n\n public readonly cache = new LanguageTablet();\n\n private readonly fingerprinter: TypeFingerprinter;\n private readonly includeCompilerDiagnostics: boolean;\n private readonly allowDirtyTranslations: boolean;\n\n public constructor(options: RosettaTranslatorOptions = {}) {\n this.fingerprinter = new TypeFingerprinter(options?.assemblies ?? []);\n this.includeCompilerDiagnostics = options.includeCompilerDiagnostics ?? false;\n this.allowDirtyTranslations = options.allowDirtyTranslations ?? false;\n }\n\n /**\n * @deprecated use `addToCache` instead\n */\n public async loadCache(fileName: string) {\n try {\n await this.cache.load(fileName);\n } catch (e: any) {\n logging.warn(`Error reading cache ${fileName}: ${e.message}`);\n }\n }\n\n public async addToCache(filename: string) {\n const tab = await LanguageTablet.fromOptionalFile(filename);\n this.cache.addTablet(tab);\n }\n\n public addTabletsToCache(...tablets: LanguageTablet[]) {\n for (const tab of tablets) {\n this.cache.addTablet(tab);\n }\n }\n\n public hasCache() {\n return this.cache.count > 0;\n }\n\n /**\n * For all the given snippets, try to read translations from the cache\n *\n * Will remove the cached snippets from the input array.\n */\n public readFromCache(snippets: TypeScriptSnippet[], addToTablet = true, compiledOnly = false): ReadFromCacheResults {\n const translations = new Array<TranslatedSnippet>();\n const remaining = new Array<TypeScriptSnippet>();\n\n let infusedCount = 0;\n let dirtyCount = 0;\n let dirtySourceCount = 0;\n let dirtyTypesCount = 0;\n let dirtyTranslatorCount = 0;\n let dirtyDidntCompile = 0;\n\n for (const snippet of snippets) {\n const fromCache = tryReadFromCache(snippet, this.cache, this.fingerprinter, compiledOnly);\n switch (fromCache.type) {\n case 'hit':\n if (addToTablet) {\n this.tablet.addSnippet(fromCache.snippet);\n }\n translations.push(fromCache.snippet);\n\n infusedCount += fromCache.infused ? 1 : 0;\n break;\n\n case 'dirty':\n dirtyCount += 1;\n dirtySourceCount += fromCache.dirtySource ? 1 : 0;\n dirtyTranslatorCount += fromCache.dirtyTranslator ? 1 : 0;\n dirtyTypesCount += fromCache.dirtyTypes ? 1 : 0;\n dirtyDidntCompile += fromCache.dirtyDidntCompile ? 1 : 0;\n\n if (this.allowDirtyTranslations) {\n translations.push(fromCache.translation);\n } else {\n remaining.push(snippet);\n }\n break;\n\n case 'miss':\n remaining.push(snippet);\n break;\n }\n }\n\n return {\n translations,\n remaining,\n infusedCount,\n dirtyCount,\n dirtySourceCount,\n dirtyTranslatorCount,\n dirtyTypesCount,\n dirtyDidntCompile,\n };\n }\n\n public async translateAll(snippets: TypeScriptSnippet[], addToTablet?: boolean): Promise<TranslateAllResult>;\n public async translateAll(snippets: TypeScriptSnippet[], options?: TranslateAllOptions): Promise<TranslateAllResult>;\n public async translateAll(\n snippets: TypeScriptSnippet[],\n optionsOrAddToTablet?: boolean | TranslateAllOptions,\n ): Promise<TranslateAllResult> {\n const options =\n optionsOrAddToTablet && typeof optionsOrAddToTablet === 'object'\n ? optionsOrAddToTablet\n : { addToTablet: optionsOrAddToTablet };\n\n const exampleDependencies = collectDependencies(snippets);\n await expandWithTransitiveDependencies(exampleDependencies);\n\n let compilationDirectory;\n let cleanCompilationDir = false;\n if (options?.compilationDirectory) {\n // If the user provided a directory, we're going to trust-but-confirm.\n await validateAvailableDependencies(options.compilationDirectory, exampleDependencies);\n compilationDirectory = options.compilationDirectory;\n } else {\n compilationDirectory = await prepareDependencyDirectory(exampleDependencies);\n cleanCompilationDir = true;\n }\n\n const origDir = process.cwd();\n // Easiest way to get a fixed working directory (for sources) in is to chdir\n process.chdir(compilationDirectory);\n\n let result;\n try {\n result = await translateAll(snippets, this.includeCompilerDiagnostics);\n } finally {\n process.chdir(origDir);\n if (cleanCompilationDir) {\n if (options.cleanup ?? true) {\n await fs.rm(compilationDirectory, { force: true, recursive: true });\n } else {\n logging.info(`Leaving directory uncleaned: ${compilationDirectory}`);\n }\n }\n }\n\n const fingerprinted = result.translatedSnippets.map((snippet) =>\n snippet.withFingerprint(this.fingerprinter.fingerprintAll(snippet.fqnsReferenced())),\n );\n\n if (options?.addToTablet ?? true) {\n for (const translation of fingerprinted) {\n this.tablet.addSnippet(translation);\n }\n }\n\n return {\n translatedSnippets: fingerprinted,\n diagnostics: result.diagnostics,\n };\n }\n}\n\n/**\n * Try to find the translation for the given snippet in the given cache\n *\n * Rules for cacheability are:\n * - id is the same (== visible source didn't change)\n * - complete source is the same (== fixture didn't change)\n * - all types involved have the same fingerprint (== API surface didn't change)\n * - the versions of all translations match the versions on the available translators (== translator itself didn't change)\n *\n * For the versions check: we could have selectively picked some translations\n * from the cache while performing others. However, since the big work is in\n * parsing the TypeScript, and the rendering itself is peanutes (assumption), it\n * doesn't really make a lot of difference. So, for simplification's sake,\n * we'll regen all translations if there's at least one that's outdated.\n */\nfunction tryReadFromCache(\n sourceSnippet: TypeScriptSnippet,\n cache: LanguageTablet,\n fingerprinter: TypeFingerprinter,\n compiledOnly: boolean,\n): CacheHit {\n const fromCache = cache.tryGetSnippet(snippetKey(sourceSnippet));\n\n if (!fromCache) {\n return { type: 'miss' };\n }\n\n // infused snippets won't pass the full source check or the fingerprinter\n // but there is no reason to try to recompile it, so return cached snippet\n // if there exists one.\n if (isInfused(sourceSnippet)) {\n return { type: 'hit', snippet: fromCache, infused: true };\n }\n\n const dirtySource = completeSource(sourceSnippet) !== fromCache.snippet.fullSource;\n const dirtyTranslator = !Object.entries(TARGET_LANGUAGES).every(\n ([lang, translator]) => fromCache.snippet.translations?.[lang]?.version === translator.version,\n );\n const dirtyTypes = fingerprinter.fingerprintAll(fromCache.fqnsReferenced()) !== fromCache.snippet.fqnsFingerprint;\n const dirtyDidntCompile = compiledOnly && !fromCache.snippet.didCompile;\n\n if (dirtySource || dirtyTranslator || dirtyTypes || dirtyDidntCompile) {\n return { type: 'dirty', translation: fromCache, dirtySource, dirtyTranslator, dirtyTypes, dirtyDidntCompile };\n }\n return { type: 'hit', snippet: fromCache, infused: false };\n}\n\nexport type CacheHit =\n | { readonly type: 'miss' }\n | { readonly type: 'hit'; readonly snippet: TranslatedSnippet; readonly infused: boolean }\n | {\n readonly type: 'dirty';\n readonly translation: TranslatedSnippet;\n readonly dirtySource: boolean;\n readonly dirtyTranslator: boolean;\n readonly dirtyTypes: boolean;\n readonly dirtyDidntCompile: boolean;\n };\n\nfunction isInfused(snippet: TypeScriptSnippet) {\n return snippet.parameters?.infused !== undefined;\n}\n\nexport interface ReadFromCacheResults {\n /**\n * Successful translations\n */\n readonly translations: TranslatedSnippet[];\n\n /**\n * Successful but dirty hits\n */\n readonly remaining: TypeScriptSnippet[];\n\n /**\n * How many successfully hit translations were infused\n */\n readonly infusedCount: number;\n\n readonly dirtyCount: number;\n\n // Counts for dirtiness (a single snippet may be dirty for more than one reason)\n readonly dirtySourceCount: number;\n readonly dirtyTranslatorCount: number;\n readonly dirtyTypesCount: number;\n readonly dirtyDidntCompile: number;\n}\n\nexport interface TranslateAllOptions {\n /**\n * @default - Create a temporary directory with all necessary packages\n */\n readonly compilationDirectory?: string;\n\n /**\n * @default true\n */\n readonly addToTablet?: boolean;\n\n /**\n * @default true\n */\n readonly cleanup?: boolean;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snippet-dependencies.js","sourceRoot":"","sources":["../src/snippet-dependencies.ts"],"names":[],"mappings":";;;AAAA,yCAAyC;AACzC,qCAAiD;AACjD,8BAA8B;AAC9B,8BAA8B;AAC9B,kCAAkC;AAElC,sCAAsC;AACtC,iCAAiC;AAEjC,6CAAgF;AAChF,qCAAqC;AAErC,iCAAwD;AACxD,iEAAiE;AACjE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAElD;;;;GAIG;AACH,SAAgB,mBAAmB,CAAC,QAA6B;IAC/D,MAAM,GAAG,GAA0C,EAAE,CAAC;IACtD,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;QAC9B,KAAK,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,uBAAuB,IAAI,EAAE,CAAC,EAAE;YAClF,GAAG,CAAC,IAAI,CAAC,GAAG,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;SACtD;KACF;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AARD,kDAQC;AAED;;;;;GAKG;AACI,KAAK,UAAU,gCAAgC,CAAC,IAA2C;IAChG,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IACpC,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAErD,IAAI,IAAI,GAAG,KAAK,CAAC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AAM,IAAI,IAAI,MAAM,CAAC,UAAU,EAAE,QAAQ,IAAI,EAAE,EAAE;YACpD,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;SACrC;KACF;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,UAAU,CAAC,CAAwB;IAC1C,OAAO,CAAC,CAAC,IAAI,KAAK,UAAU,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAI,EAAU,EAAE,EAAU;IAC1C,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE;QAClB,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;KACX;IACD,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;GAEG;AACH,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import * as cp from 'node:child_process';\nimport { promises as fsPromises } from 'node:fs';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { PackageJson } from '@jsii/spec';\nimport * as fastGlob from 'fast-glob';\nimport * as semver from 'semver';\n\nimport { findDependencyDirectory, findUp, isBuiltinModule } from './find-utils';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, CompilationDependency } from './snippet';\nimport { mkDict, formatList, pathExists } from './util';\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst { intersect } = require('semver-intersect');\n\n/**\n * Collect the dependencies of a bunch of snippets together in one declaration\n *\n * We assume here the dependencies will not conflict.\n */\nexport function collectDependencies(snippets: TypeScriptSnippet[]) {\n const ret: Record<string, CompilationDependency> = {};\n for (const snippet of snippets) {\n for (const [name, source] of Object.entries(snippet.compilationDependencies ?? {})) {\n ret[name] = resolveConflict(name, source, ret[name]);\n }\n }\n return ret;\n}\n\n/**\n * Add transitive dependencies of concrete dependencies to the array\n *\n * This is necessary to prevent multiple copies of transitive dependencies on disk, which\n * jsii-based packages might not deal with very well.\n */\nexport async function expandWithTransitiveDependencies(deps: Record<string, CompilationDependency>) {\n const pathsSeen = new Set<string>();\n const queue = Object.values(deps).filter(isConcrete);\n\n let next = queue.shift();\n while (next) {\n await addDependenciesOf(next.resolvedDirectory);\n next = queue.shift();\n }\n\n async function addDependenciesOf(dir: string) {\n if (pathsSeen.has(dir)) {\n return;\n }\n pathsSeen.add(dir);\n try {\n const pj: PackageJson = JSON.parse(\n await fsPromises.readFile(path.join(dir, 'package.json'), { encoding: 'utf-8' }),\n );\n for (const [name, dep] of Object.entries(await resolveDependenciesFromPackageJson(pj, dir))) {\n if (!deps[name]) {\n deps[name] = dep;\n queue.push(dep);\n }\n }\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return;\n }\n throw e;\n }\n }\n}\n\n/**\n * Find the corresponding package directories for all dependencies in a package.json\n */\nexport async function resolveDependenciesFromPackageJson(packageJson: PackageJson | undefined, directory: string) {\n return mkDict(\n await Promise.all(\n Object.keys({ ...packageJson?.dependencies, ...packageJson?.peerDependencies })\n .filter((name) => !isBuiltinModule(name))\n .filter(\n (name) =>\n !packageJson?.bundledDependencies?.includes(name) && !packageJson?.bundleDependencies?.includes(name),\n )\n .map(\n async (name) =>\n [\n name,\n {\n type: 'concrete',\n resolvedDirectory: await fsPromises.realpath(await findDependencyDirectory(name, directory)),\n },\n ] as const,\n ),\n ),\n );\n}\n\nfunction resolveConflict(\n name: string,\n a: CompilationDependency,\n b: CompilationDependency | undefined,\n): CompilationDependency {\n if (!b) {\n return a;\n }\n\n if (a.type === 'concrete' && b.type === 'concrete') {\n if (b.resolvedDirectory !== a.resolvedDirectory) {\n throw new Error(`Dependency conflict: ${name} can be either ${a.resolvedDirectory} or ${b.resolvedDirectory}`);\n }\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'symbolic') {\n // Intersect the ranges\n return {\n type: 'symbolic',\n versionRange: myVersionIntersect(a.versionRange, b.versionRange),\n };\n }\n\n if (a.type === 'concrete' && b.type === 'symbolic') {\n const concreteVersion: string = JSON.parse(\n fs.readFileSync(path.join(a.resolvedDirectory, 'package.json'), 'utf-8'),\n ).version;\n\n if (!semver.satisfies(concreteVersion, b.versionRange, { includePrerelease: true })) {\n throw new Error(\n `Dependency conflict: ${name} expected to match ${b.versionRange} but found ${concreteVersion} at ${a.resolvedDirectory}`,\n );\n }\n\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'concrete') {\n // Reverse roles so we fall into the previous case\n return resolveConflict(name, b, a);\n }\n\n throw new Error('Cases should have been exhaustive');\n}\n\n/**\n * Check that the directory we were given has all the necessary dependencies in it\n *\n * It's a warning if this is not true, not an error.\n */\nexport async function validateAvailableDependencies(directory: string, deps: Record<string, CompilationDependency>) {\n logging.info(`Validating dependencies at ${directory}`);\n const failures = await Promise.all(\n Object.entries(deps).flatMap(async ([name, _dep]) => {\n try {\n await findDependencyDirectory(name, directory);\n return [];\n } catch {\n return [name];\n }\n }),\n );\n\n if (failures.length > 0) {\n logging.warn(\n `${directory}: packages necessary to compile examples missing from supplied directory: ${failures.join(', ')}`,\n );\n }\n}\n\n/**\n * Intersect two semver ranges\n *\n * The package we are using for this doesn't support all syntaxes yet.\n * Do some work on top.\n */\nfunction myVersionIntersect(a: string, b: string): string {\n if (a === '*') {\n return b;\n }\n if (b === '*') {\n return a;\n }\n\n try {\n return intersect(a, b);\n } catch (e: any) {\n throw new Error(`semver-intersect does not support either '${a}' or '${b}': ${e.message}`);\n }\n}\n\n/**\n * Prepare a temporary directory with symlinks to all the dependencies we need.\n *\n * - Symlinks the concrete dependencies\n * - Tries to first find the symbolic dependencies in a potential monorepo that might be present\n * (try both `lerna` and `yarn` monorepos).\n * - Installs the remaining symbolic dependencies using 'npm'.\n */\nexport async function prepareDependencyDirectory(deps: Record<string, CompilationDependency>): Promise<string> {\n const concreteDirs = Object.values(deps)\n .filter(isConcrete)\n .map((x) => x.resolvedDirectory);\n const monorepoPackages = await scanMonoRepos(concreteDirs);\n\n const tmpDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'rosetta'));\n logging.info(`Preparing dependency closure at ${tmpDir} (-vv for more details)`);\n\n // Resolved symbolic packages against monorepo\n const resolvedDeps = mkDict(\n Object.entries(deps).map(([name, dep]) => [\n name,\n dep.type === 'concrete'\n ? dep\n : ((monorepoPackages[name]\n ? { type: 'concrete', resolvedDirectory: monorepoPackages[name] }\n : dep) as CompilationDependency),\n ]),\n );\n\n const dependencies: Record<string, string> = {};\n for (const [name, dep] of Object.entries(resolvedDeps)) {\n if (isConcrete(dep)) {\n logging.debug(`${name} -> ${dep.resolvedDirectory}`);\n dependencies[name] = `file:${dep.resolvedDirectory}`;\n } else {\n logging.debug(`${name} @ ${dep.versionRange}`);\n dependencies[name] = dep.versionRange;\n }\n }\n\n await fsPromises.writeFile(\n path.join(tmpDir, 'package.json'),\n JSON.stringify(\n {\n name: 'examples',\n version: '0.0.1',\n private: true,\n dependencies,\n },\n undefined,\n 2,\n ),\n {\n encoding: 'utf-8',\n },\n );\n\n // Run NPM install on this package.json. We need to include --force for packages\n // that have a symbolic version in the symlinked dev tree (like \"0.0.0\"), but have\n // actual version range dependencies from externally installed packages (like \"^2.0.0\").\n cp.execSync(`npm install --force --loglevel error`, { cwd: tmpDir, encoding: 'utf-8' });\n\n return tmpDir;\n}\n\n/**\n * Map package name to directory\n */\nasync function scanMonoRepos(startingDirs: readonly string[]): Promise<Record<string, string>> {\n const globs = new Set<string>();\n for (const dir of startingDirs) {\n // eslint-disable-next-line no-await-in-loop\n setExtend(globs, await findMonoRepoGlobs(dir));\n }\n\n if (globs.size === 0) {\n return {};\n }\n\n logging.debug(`Monorepo package sources: ${Array.from(globs).join(', ')}`);\n\n const packageDirectories = await fastGlob(Array.from(globs).map(windowsToUnix), { onlyDirectories: true });\n const results = mkDict(\n (\n await Promise.all(\n packageDirectories.map(async (directory) => {\n const pjLocation = path.join(directory, 'package.json');\n return (await pathExists(pjLocation))\n ? [[JSON.parse(await fsPromises.readFile(pjLocation, 'utf-8')).name as string, directory] as const]\n : [];\n }),\n )\n ).flat(),\n );\n\n logging.debug(`Found ${Object.keys(results).length} packages in monorepo: ${formatList(Object.keys(results))}`);\n return results;\n}\n\nasync function findMonoRepoGlobs(startingDir: string): Promise<Set<string>> {\n const ret = new Set<string>();\n\n // Lerna monorepo\n const lernaJsonDir = await findUp(startingDir, async (dir) => pathExists(path.join(dir, 'lerna.json')));\n if (lernaJsonDir) {\n const lernaJson = JSON.parse(await fsPromises.readFile(path.join(lernaJsonDir, 'lerna.json'), 'utf-8'));\n for (const glob of lernaJson?.packages ?? []) {\n ret.add(path.join(lernaJsonDir, glob));\n }\n }\n\n // Yarn monorepo\n const yarnWsDir = await findUp(\n startingDir,\n async (dir) =>\n (await pathExists(path.join(dir, 'package.json'))) &&\n JSON.parse(await fsPromises.readFile(path.join(dir, 'package.json'), 'utf-8'))?.workspaces !== undefined,\n );\n if (yarnWsDir) {\n const yarnWs = JSON.parse(await fsPromises.readFile(path.join(yarnWsDir, 'package.json'), 'utf-8'));\n for (const glob of yarnWs.workspaces?.packages ?? []) {\n ret.add(path.join(yarnWsDir, glob));\n }\n }\n\n return ret;\n}\n\nfunction isConcrete(x: CompilationDependency): x is Extract<CompilationDependency, { type: 'concrete' }> {\n return x.type === 'concrete';\n}\n\nfunction setExtend<A>(xs: Set<A>, ys: Set<A>) {\n for (const y of ys) {\n xs.add(y);\n }\n return xs;\n}\n\n/**\n * Necessary for fastGlob\n */\nfunction windowsToUnix(x: string) {\n return x.replace(/\\\\/g, '/');\n}\n"]}
|
|
1
|
+
{"version":3,"file":"snippet-dependencies.js","sourceRoot":"","sources":["../src/snippet-dependencies.ts"],"names":[],"mappings":";;;AAAA,yCAAyC;AACzC,qCAAiD;AACjD,8BAA8B;AAC9B,8BAA8B;AAC9B,kCAAkC;AAElC,sCAAsC;AACtC,iCAAiC;AAEjC,6CAAgF;AAChF,qCAAqC;AAErC,iCAAwD;AACxD,iEAAiE;A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AAE,IAAI,CAAC,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,UAAU,CAAC,CAAwB;IAC1C,OAAO,CAAC,CAAC,IAAI,KAAK,UAAU,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAI,EAAU,EAAE,EAAU;IAC1C,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;QACnB,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACZ,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;GAEG;AACH,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import * as cp from 'node:child_process';\nimport { promises as fsPromises } from 'node:fs';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { PackageJson } from '@jsii/spec';\nimport * as fastGlob from 'fast-glob';\nimport * as semver from 'semver';\n\nimport { findDependencyDirectory, findUp, isBuiltinModule } from './find-utils';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, CompilationDependency } from './snippet';\nimport { mkDict, formatList, pathExists } from './util';\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst { intersect } = require('semver-intersect');\n\n/**\n * Collect the dependencies of a bunch of snippets together in one declaration\n *\n * We assume here the dependencies will not conflict.\n */\nexport function collectDependencies(snippets: TypeScriptSnippet[]) {\n const ret: Record<string, CompilationDependency> = {};\n for (const snippet of snippets) {\n for (const [name, source] of Object.entries(snippet.compilationDependencies ?? {})) {\n ret[name] = resolveConflict(name, source, ret[name]);\n }\n }\n return ret;\n}\n\n/**\n * Add transitive dependencies of concrete dependencies to the array\n *\n * This is necessary to prevent multiple copies of transitive dependencies on disk, which\n * jsii-based packages might not deal with very well.\n */\nexport async function expandWithTransitiveDependencies(deps: Record<string, CompilationDependency>) {\n const pathsSeen = new Set<string>();\n const queue = Object.values(deps).filter(isConcrete);\n\n let next = queue.shift();\n while (next) {\n await addDependenciesOf(next.resolvedDirectory);\n next = queue.shift();\n }\n\n async function addDependenciesOf(dir: string) {\n if (pathsSeen.has(dir)) {\n return;\n }\n pathsSeen.add(dir);\n try {\n const pj: PackageJson = JSON.parse(\n await fsPromises.readFile(path.join(dir, 'package.json'), { encoding: 'utf-8' }),\n );\n for (const [name, dep] of Object.entries(await resolveDependenciesFromPackageJson(pj, dir))) {\n if (!deps[name]) {\n deps[name] = dep;\n queue.push(dep);\n }\n }\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return;\n }\n throw e;\n }\n }\n}\n\n/**\n * Find the corresponding package directories for all dependencies in a package.json\n */\nexport async function resolveDependenciesFromPackageJson(packageJson: PackageJson | undefined, directory: string) {\n return mkDict(\n await Promise.all(\n Object.keys({ ...packageJson?.dependencies, ...packageJson?.peerDependencies })\n .filter((name) => !isBuiltinModule(name))\n .filter(\n (name) =>\n !packageJson?.bundledDependencies?.includes(name) && !packageJson?.bundleDependencies?.includes(name),\n )\n .map(\n async (name) =>\n [\n name,\n {\n type: 'concrete',\n resolvedDirectory: await fsPromises.realpath(await findDependencyDirectory(name, directory)),\n },\n ] as const,\n ),\n ),\n );\n}\n\nfunction resolveConflict(\n name: string,\n a: CompilationDependency,\n b: CompilationDependency | undefined,\n): CompilationDependency {\n if (!b) {\n return a;\n }\n\n if (a.type === 'concrete' && b.type === 'concrete') {\n if (b.resolvedDirectory !== a.resolvedDirectory) {\n throw new Error(`Dependency conflict: ${name} can be either ${a.resolvedDirectory} or ${b.resolvedDirectory}`);\n }\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'symbolic') {\n // Intersect the ranges\n return {\n type: 'symbolic',\n versionRange: myVersionIntersect(a.versionRange, b.versionRange),\n };\n }\n\n if (a.type === 'concrete' && b.type === 'symbolic') {\n const concreteVersion: string = JSON.parse(\n fs.readFileSync(path.join(a.resolvedDirectory, 'package.json'), 'utf-8'),\n ).version;\n\n if (!semver.satisfies(concreteVersion, b.versionRange, { includePrerelease: true })) {\n throw new Error(\n `Dependency conflict: ${name} expected to match ${b.versionRange} but found ${concreteVersion} at ${a.resolvedDirectory}`,\n );\n }\n\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'concrete') {\n // Reverse roles so we fall into the previous case\n return resolveConflict(name, b, a);\n }\n\n throw new Error('Cases should have been exhaustive');\n}\n\n/**\n * Check that the directory we were given has all the necessary dependencies in it\n *\n * It's a warning if this is not true, not an error.\n */\nexport async function validateAvailableDependencies(directory: string, deps: Record<string, CompilationDependency>) {\n logging.info(`Validating dependencies at ${directory}`);\n const failures = await Promise.all(\n Object.entries(deps).flatMap(async ([name, _dep]) => {\n try {\n await findDependencyDirectory(name, directory);\n return [];\n } catch {\n return [name];\n }\n }),\n );\n\n if (failures.length > 0) {\n logging.warn(\n `${directory}: packages necessary to compile examples missing from supplied directory: ${failures.join(', ')}`,\n );\n }\n}\n\n/**\n * Intersect two semver ranges\n *\n * The package we are using for this doesn't support all syntaxes yet.\n * Do some work on top.\n */\nfunction myVersionIntersect(a: string, b: string): string {\n if (a === '*') {\n return b;\n }\n if (b === '*') {\n return a;\n }\n\n try {\n return intersect(a, b);\n } catch (e: any) {\n throw new Error(`semver-intersect does not support either '${a}' or '${b}': ${e.message}`);\n }\n}\n\n/**\n * Prepare a temporary directory with symlinks to all the dependencies we need.\n *\n * - Symlinks the concrete dependencies\n * - Tries to first find the symbolic dependencies in a potential monorepo that might be present\n * (try both `lerna` and `yarn` monorepos).\n * - Installs the remaining symbolic dependencies using 'npm'.\n */\nexport async function prepareDependencyDirectory(deps: Record<string, CompilationDependency>): Promise<string> {\n const concreteDirs = Object.values(deps)\n .filter(isConcrete)\n .map((x) => x.resolvedDirectory);\n const monorepoPackages = await scanMonoRepos(concreteDirs);\n\n const tmpDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'rosetta'));\n logging.info(`Preparing dependency closure at ${tmpDir} (-vv for more details)`);\n\n // Resolved symbolic packages against monorepo\n const resolvedDeps = mkDict(\n Object.entries(deps).map(([name, dep]) => [\n name,\n dep.type === 'concrete'\n ? dep\n : ((monorepoPackages[name]\n ? { type: 'concrete', resolvedDirectory: monorepoPackages[name] }\n : dep) as CompilationDependency),\n ]),\n );\n\n const dependencies: Record<string, string> = {};\n for (const [name, dep] of Object.entries(resolvedDeps)) {\n if (isConcrete(dep)) {\n logging.debug(`${name} -> ${dep.resolvedDirectory}`);\n dependencies[name] = `file:${dep.resolvedDirectory}`;\n } else {\n logging.debug(`${name} @ ${dep.versionRange}`);\n dependencies[name] = dep.versionRange;\n }\n }\n\n await fsPromises.writeFile(\n path.join(tmpDir, 'package.json'),\n JSON.stringify(\n {\n name: 'examples',\n version: '0.0.1',\n private: true,\n dependencies,\n },\n undefined,\n 2,\n ),\n {\n encoding: 'utf-8',\n },\n );\n\n // Run NPM install on this package.json. We need to include --force for packages\n // that have a symbolic version in the symlinked dev tree (like \"0.0.0\"), but have\n // actual version range dependencies from externally installed packages (like \"^2.0.0\").\n cp.execSync(`npm install --force --loglevel error`, { cwd: tmpDir, encoding: 'utf-8' });\n\n return tmpDir;\n}\n\n/**\n * Map package name to directory\n */\nasync function scanMonoRepos(startingDirs: readonly string[]): Promise<Record<string, string>> {\n const globs = new Set<string>();\n for (const dir of startingDirs) {\n // eslint-disable-next-line no-await-in-loop\n setExtend(globs, await findMonoRepoGlobs(dir));\n }\n\n if (globs.size === 0) {\n return {};\n }\n\n logging.debug(`Monorepo package sources: ${Array.from(globs).join(', ')}`);\n\n const packageDirectories = await fastGlob(Array.from(globs).map(windowsToUnix), { onlyDirectories: true });\n const results = mkDict(\n (\n await Promise.all(\n packageDirectories.map(async (directory) => {\n const pjLocation = path.join(directory, 'package.json');\n return (await pathExists(pjLocation))\n ? [[JSON.parse(await fsPromises.readFile(pjLocation, 'utf-8')).name as string, directory] as const]\n : [];\n }),\n )\n ).flat(),\n );\n\n logging.debug(`Found ${Object.keys(results).length} packages in monorepo: ${formatList(Object.keys(results))}`);\n return results;\n}\n\nasync function findMonoRepoGlobs(startingDir: string): Promise<Set<string>> {\n const ret = new Set<string>();\n\n // Lerna monorepo\n const lernaJsonDir = await findUp(startingDir, async (dir) => pathExists(path.join(dir, 'lerna.json')));\n if (lernaJsonDir) {\n const lernaJson = JSON.parse(await fsPromises.readFile(path.join(lernaJsonDir, 'lerna.json'), 'utf-8'));\n for (const glob of lernaJson?.packages ?? []) {\n ret.add(path.join(lernaJsonDir, glob));\n }\n }\n\n // Yarn monorepo\n const yarnWsDir = await findUp(\n startingDir,\n async (dir) =>\n (await pathExists(path.join(dir, 'package.json'))) &&\n JSON.parse(await fsPromises.readFile(path.join(dir, 'package.json'), 'utf-8'))?.workspaces !== undefined,\n );\n if (yarnWsDir) {\n const yarnWs = JSON.parse(await fsPromises.readFile(path.join(yarnWsDir, 'package.json'), 'utf-8'));\n for (const glob of yarnWs.workspaces?.packages ?? []) {\n ret.add(path.join(yarnWsDir, glob));\n }\n }\n\n return ret;\n}\n\nfunction isConcrete(x: CompilationDependency): x is Extract<CompilationDependency, { type: 'concrete' }> {\n return x.type === 'concrete';\n}\n\nfunction setExtend<A>(xs: Set<A>, ys: Set<A>) {\n for (const y of ys) {\n xs.add(y);\n }\n return xs;\n}\n\n/**\n * Necessary for fastGlob\n */\nfunction windowsToUnix(x: string) {\n return x.replace(/\\\\/g, '/');\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snippet-selectors.js","sourceRoot":"","sources":["../src/snippet-selectors.ts"],"names":[],"mappings":";;;AAIA,MAAM,YAAY;IAChB,YAAmC,OAA0B,EAAkB,KAAa;QAAzD,YAAO,GAAP,OAAO,CAAmB;QAAkB,UAAK,GAAL,KAAK,CAAQ;IAAG,CAAC;CACjG;AAED;;GAEG;AACH,SAAgB,OAAO,CAAC,QAA6B;IACnD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE;
|
|
1
|
+
{"version":3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CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAC1F,CAAC;AAED,SAAS,WAAW,CAAC,aAA6B;IAChD,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QACnC,OAAO,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,WAAW,CAAC,aAA6B;IAChD,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QACnC,OAAO,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { TranslatedSnippet } from './tablets/tablets';\n\nexport type SnippetSelector = (snippets: TranslatedSnippet[]) => TranslatedSnippet;\n\nclass SnippetScore {\n public constructor(public readonly snippet: TranslatedSnippet, public readonly score: number) {}\n}\n\n/**\n * Returns the longest available snippet.\n */\nexport function longest(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('longest: array cannot be empty');\n }\n const snippetScores: SnippetScore[] = [];\n for (const snippet of snippets) {\n snippetScores.push({ snippet: snippet, score: snippet.originalSource.source.length });\n }\n return getMaxScore(snippetScores).snippet;\n}\n\n/**\n * Returns the shortest available snippet.\n */\nexport function shortest(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('shortest: array cannot be empty');\n }\n const snippetScores: SnippetScore[] = [];\n for (const snippet of snippets) {\n snippetScores.push({ snippet: snippet, score: snippet.originalSource.source.length });\n }\n return getMinScore(snippetScores).snippet;\n}\n\n/**\n * Returns the snippet with the length closest to the mean length of the available snippets.\n */\nexport function meanLength(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('meanLength: array cannot be empty');\n }\n\n const meanLen = snippets.reduce((x, y) => x + y.originalSource.source.length, 0) / snippets.length;\n const snippetScores: SnippetScore[] = [];\n for (const snippet of snippets) {\n snippetScores.push({ snippet: snippet, score: Math.abs(snippet.originalSource.source.length - meanLen) });\n }\n return getMinScore(snippetScores).snippet;\n}\n\n/**\n * Finds and returns the mean sparse vector of available snippets for each type.\n */\nexport function mean(snippets: TranslatedSnippet[]): TranslatedSnippet {\n if (snippets.length === 0) {\n throw new Error('mean: array cannot be empty');\n }\n\n // Find mean counter.\n const counters: Array<Record<string, number>> = [];\n snippets.map((snippet) => {\n counters.push(snippet.snippet.syntaxKindCounter ?? {});\n });\n const meanCounter = findCenter(counters);\n // Find counter with closest euclidian distance.\n const snippetScores: SnippetScore[] = [];\n for (let i = 0; i < snippets.length; i++) {\n snippetScores.push({ snippet: snippets[i], score: euclideanDistance(meanCounter, counters[i]) });\n }\n return getMinScore(snippetScores).snippet;\n}\n\n/**\n * Given a list of Records, outputs a Record that averages all the items in each Record.\n */\nfunction findCenter(counters: Array<Record<string, number>>): Record<string, number> {\n const centerCounter: Record<string, number> = {};\n for (const counter of counters) {\n for (const [key, value] of Object.entries(counter)) {\n centerCounter[key] = value + (centerCounter[key] ?? 0);\n }\n }\n const total = counters.length;\n Object.entries(centerCounter).map(([key, value]) => {\n centerCounter[key] = value / total;\n });\n return centerCounter;\n}\n\n/**\n * Finds the euclidean distance between two sparse vectors.\n * !!! This function assumes that the center parameter is a superset of the counter parameter. !!!\n */\nfunction euclideanDistance(center: Record<string, number>, counter: Record<string, number>): number {\n const individualDistances: number[] = [];\n Object.entries(center).map(([key, value]) => {\n individualDistances.push(value - (counter[key] ?? 0));\n });\n return individualDistances.reduce((acc, curr) => acc + Math.sqrt(Math.pow(curr, 2)), 0);\n}\n\nfunction getMaxScore(snippetScores: SnippetScore[]): SnippetScore {\n return snippetScores.reduce((x, y) => {\n return x.score >= y.score ? x : y;\n });\n}\n\nfunction getMinScore(snippetScores: SnippetScore[]): SnippetScore {\n return snippetScores.reduce((x, y) => {\n return x.score <= y.score ? x : y;\n });\n}\n"]}
|
package/lib/snippet.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snippet.js","sourceRoot":"","sources":["../src/snippet.ts"],"names":[],"mappings":";;;AAAA,8DAAyE;AAuEzE;;;;;GAKG;AACU,QAAA,uBAAuB,GAAG,eAAe,CAAC;AAiBvD;;GAEG;AACH,SAAgB,cAAc,CAAC,QAAyB;IACtD,QAAQ,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE;QAC7B,KAAK,SAAS;YACZ,OAAO,GAAG,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC;QACtD,KAAK,UAAU;YACb,OAAO,GAAG,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;QACtE,KAAK,SAAS;YACZ,OAAO,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;KAC1C;AACH,CAAC;AATD,wCASC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,MAAmB;IACnD,QAAQ,MAAM,CAAC,GAAG,EAAE;QAClB,KAAK,MAAM;YACT,OAAO,MAAM,CAAC,QAAQ,CAAC;QACzB,KAAK,cAAc;YACjB,OAAO,GAAG,MAAM,CAAC,SAAS,SAAS,CAAC;QACtC,KAAK,MAAM;YACT,OAAO,MAAM,CAAC,GAAG,CAAC;QACpB,KAAK,aAAa;YAChB,OAAO,GAAG,MAAM,CAAC,GAAG,cAAc,CAAC;QACrC,KAAK,QAAQ;YACX,OAAO,GAAG,MAAM,CAAC,GAAG,IAAI,M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vB;;;;;;;;;;;OAWG;IACH,wCAAmB,CAAA;IAEnB;;;;;OAKG;IACH,sDAAiC,CAAA;IAEjC;;;;;OAKG;IACH,4DAAuC,CAAA;AACzC,CAAC,EAhDW,iBAAiB,iCAAjB,iBAAiB,QAgD5B","sourcesContent":["import { trimCompleteSourceToVisible } from './typescript/visible-spans';\n\n/**\n * A piece of TypeScript code found in an assembly, ready to be translated\n */\nexport interface TypeScriptSnippet {\n /**\n * The snippet code that ends up in the JSII assembly\n */\n readonly visibleSource: string;\n\n /**\n * Description of where the snippet was found\n */\n readonly location: SnippetLocation;\n\n /**\n * When enhanced with a fixture, the snippet's complete source code\n */\n readonly completeSource?: string;\n\n /**\n * Parameters for the conversion\n */\n readonly parameters?: Record<string, string>;\n\n /**\n * Whether this snippet must be processed as if `--strict` was always supplied.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * Dependencies necessary to compile this snippet\n *\n * Value is a regular { name -> semver } map like NPM's `dependencies`,\n * `devDependencies` etc.\n *\n * @default none\n */\n readonly compilationDependencies?: Record<string, CompilationDependency>;\n}\n\nexport type CompilationDependency =\n | { readonly type: 'concrete'; readonly resolvedDirectory: string }\n | { readonly type: 'symbolic'; readonly versionRange: string };\n\n/**\n * Description of a location where the snippet is found\n *\n * The location does not necessarily indicate an exact source file,\n * but it will generally refer to a location that can contain one or more\n * snippets.\n */\nexport interface SnippetLocation {\n /**\n * The jsii API with which this snippet is associated\n */\n readonly api: ApiLocation;\n\n /**\n * The API field in which the snippet is found, if any\n *\n * Absence of this field is appropriate for source files (or tests),\n * but for Markdown files 'field' should really be set to a Markdown\n * location.\n */\n readonly field?: FieldLocation;\n}\n\n/**\n * How to represent the initializer in a 'parameter' type.\n *\n * (Don't feel like making everyone's `case` statement worse by adding an\n * 'initializer-parameter' variant).\n */\nexport const INITIALIZER_METHOD_NAME = '<initializer>';\n\nexport type ApiLocation =\n | { readonly api: 'file'; readonly fileName: string }\n | { readonly api: 'moduleReadme'; readonly moduleFqn: string }\n | { readonly api: 'type'; readonly fqn: string }\n | { readonly api: 'initializer'; readonly fqn: string }\n | { readonly api: 'member'; readonly fqn: string; readonly memberName: string }\n | {\n readonly api: 'parameter';\n readonly fqn: string;\n readonly methodName: string | typeof INITIALIZER_METHOD_NAME;\n readonly parameterName: string;\n };\n\nexport type FieldLocation = { readonly field: 'markdown'; readonly line: number } | { readonly field: 'example' };\n\n/**\n * Render an API location to a human readable representation\n */\nexport function formatLocation(location: SnippetLocation): string {\n switch (location.field?.field) {\n case 'example':\n return `${renderApiLocation(location.api)}-example`;\n case 'markdown':\n return `${renderApiLocation(location.api)}-L${location.field.line}`;\n case undefined:\n return renderApiLocation(location.api);\n }\n}\n\n/**\n * Render an API location to an unique string\n *\n * This function is used in hashing examples for reuse, and so the formatting\n * here should not be changed lightly.\n */\nexport function renderApiLocation(apiLoc: ApiLocation): string {\n switch (apiLoc.api) {\n case 'file':\n return apiLoc.fileName;\n case 'moduleReadme':\n return `${apiLoc.moduleFqn}-README`;\n case 'type':\n return apiLoc.fqn;\n case 'initializer':\n return `${apiLoc.fqn}#initializer`;\n case 'member':\n return `${apiLoc.fqn}#${apiLoc.memberName}`;\n case 'parameter':\n return `${apiLoc.fqn}#${apiLoc.methodName}!#${apiLoc.parameterName}`;\n }\n}\n\n/**\n * Construct a TypeScript snippet from visible source\n *\n * Will parse parameters from a directive in the given source, but will not\n * interpret `/// !show` and `/// !hide` directives.\n *\n * `/// !show` and `/// !hide` directives WILL affect what gets displayed by\n * the translator, but they will NOT affect the snippet's cache key (i.e. the\n * cache key will be based on the full source given here).\n *\n * Use this if you are looking up a snippet in a tablet, which has been translated\n * previously using a fixture.\n */\nexport function typeScriptSnippetFromVisibleSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const visibleSource = source.trimRight();\n\n return {\n visibleSource,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\n/**\n * Construct a TypeScript snippet from literal source\n *\n * @deprecated Use `typeScriptSnippetFromVisibleSource`\n */\nexport function typeScriptSnippetFromSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n return typeScriptSnippetFromVisibleSource(typeScriptSource, location, strict, parameters);\n}\n\n/**\n * Construct a TypeScript snippet from complete source\n *\n * Will parse parameters from a directive in the given source, and will\n * interpret `/// !show` and `/// !hide` directives.\n *\n * The snippet's cache key will be based on the source that remains after\n * these directives are processed.\n *\n * Use this if you are building a snippet to be translated, and take care\n * to store the return object's `visibleSource` in the assembly (not the original\n * source you passed in).\n */\nexport function typeScriptSnippetFromCompleteSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const completeSrc = source.trimRight();\n\n const visibleSource = trimCompleteSourceToVisible(completeSrc);\n\n return {\n visibleSource,\n completeSource: visibleSource !== completeSrc ? completeSrc : undefined,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\nexport function updateParameters(snippet: TypeScriptSnippet, params: Record<string, string>): TypeScriptSnippet {\n return {\n ...snippet,\n parameters: Object.assign(Object.create(null), snippet.parameters ?? {}, params),\n };\n}\n\n/**\n * Get the complete (compilable) source of a snippet\n */\nexport function completeSource(snippet: TypeScriptSnippet) {\n return snippet.completeSource ?? snippet.visibleSource;\n}\n\n/**\n * Extract snippet parameters from the first line of the source if it's a compiler directive\n */\nfunction parametersFromSourceDirectives(source: string): [string, Record<string, string>] {\n const [firstLine, ...rest] = source.split('\\n');\n // Also extract parameters from an initial line starting with '/// ' (getting rid of that line).\n const m = /[/]{3}(.*)$/.exec(firstLine);\n if (m) {\n return [rest.join('\\n'), parseMetadataLine(m[1])];\n }\n\n return [source, {}];\n}\n\n/**\n * Parse a set of 'param param=value' directives into an object\n */\nexport function parseKeyValueList(parameters: string[]): Record<string, string> {\n const ret: Record<string, string> = {};\n for (const param of parameters) {\n const parts = param.split('=', 2);\n if (parts.length === 2) {\n ret[parts[0]] = parts[1];\n } else {\n ret[parts[0]] = '';\n }\n }\n return ret;\n}\n\nexport function parseMetadataLine(metadata: string): Record<string, string> {\n return parseKeyValueList(parseMetadata(metadata));\n\n function parseMetadata(md: string): string[] {\n return md\n .trim()\n .split(' ')\n .map((s) => s.trim())\n .filter((s) => s !== '');\n }\n}\n\nexport function renderMetadataline(metadata: Record<string, string> = {}): string | undefined {\n const line = Object.entries(metadata)\n .filter(([key, _]) => !key.startsWith('$'))\n .map(([key, value]) => (value !== '' ? `${key}=${value}` : key))\n .join(' ');\n\n return line ? line : undefined;\n}\n\n/**\n * Recognized snippet parameters\n */\nexport enum SnippetParameters {\n /**\n * Use fixture with the given name (author parameter)\n */\n FIXTURE = 'fixture',\n\n /**\n * Don't use a fixture (author parameter)\n */\n NO_FIXTURE = 'nofixture',\n\n /**\n * Snippet was extracted from this literate file (backwards compatibility)\n *\n * Parameter attached by 'jsii'; load the given file instead of any fixture,\n * process as usual.\n */\n LITERATE_SOURCE = 'lit',\n\n /**\n * This snippet has been infused\n *\n * This means it has been copied from a different location, and potentially\n * even from a different assembly. If so, we can't expect it to compile in\n * the future, and if doesn't, we ignore the errors.\n *\n * N.B: this shouldn't make a difference in normal operation, as the `infuse`\n * command will duplicate the translation to the target tablet. This only\n * matters if we remove the tablet and try to re-extract an assembly with\n * infused examples from somewher else.\n */\n INFUSED = 'infused',\n\n /**\n * What directory to resolve fixtures in for this snippet (system parameter)\n *\n * Attached during processing, should not be used by authors. Does NOT imply\n * anything about the directory where we pretend to compile this file.\n */\n $PROJECT_DIRECTORY = '$directory',\n\n /**\n * What directory to pretend the file is in (system parameter)\n *\n * Attached when compiling a literate file, as they compile in\n * the location where they are stored.\n */\n $COMPILATION_DIRECTORY = '$compilation',\n}\n"]}
|
|
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n/**\n * A piece of TypeScript code found in an assembly, ready to be translated\n */\nexport interface TypeScriptSnippet {\n /**\n * The snippet code that ends up in the JSII assembly\n */\n readonly visibleSource: string;\n\n /**\n * Description of where the snippet was found\n */\n readonly location: SnippetLocation;\n\n /**\n * When enhanced with a fixture, the snippet's complete source code\n */\n readonly completeSource?: string;\n\n /**\n * Parameters for the conversion\n */\n readonly parameters?: Record<string, string>;\n\n /**\n * Whether this snippet must be processed as if `--strict` was always supplied.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * Dependencies necessary to compile this snippet\n *\n * Value is a regular { name -> semver } map like NPM's `dependencies`,\n * `devDependencies` etc.\n *\n * @default none\n */\n readonly compilationDependencies?: Record<string, CompilationDependency>;\n}\n\nexport type CompilationDependency =\n | { readonly type: 'concrete'; readonly resolvedDirectory: string }\n | { readonly type: 'symbolic'; readonly versionRange: string };\n\n/**\n * Description of a location where the snippet is found\n *\n * The location does not necessarily indicate an exact source file,\n * but it will generally refer to a location that can contain one or more\n * snippets.\n */\nexport interface SnippetLocation {\n /**\n * The jsii API with which this snippet is associated\n */\n readonly api: ApiLocation;\n\n /**\n * The API field in which the snippet is found, if any\n *\n * Absence of this field is appropriate for source files (or tests),\n * but for Markdown files 'field' should really be set to a Markdown\n * location.\n */\n readonly field?: FieldLocation;\n}\n\n/**\n * How to represent the initializer in a 'parameter' type.\n *\n * (Don't feel like making everyone's `case` statement worse by adding an\n * 'initializer-parameter' variant).\n */\nexport const INITIALIZER_METHOD_NAME = '<initializer>';\n\nexport type ApiLocation =\n | { readonly api: 'file'; readonly fileName: string }\n | { readonly api: 'moduleReadme'; readonly moduleFqn: string }\n | { readonly api: 'type'; readonly fqn: string }\n | { readonly api: 'initializer'; readonly fqn: string }\n | { readonly api: 'member'; readonly fqn: string; readonly memberName: string }\n | {\n readonly api: 'parameter';\n readonly fqn: string;\n readonly methodName: string | typeof INITIALIZER_METHOD_NAME;\n readonly parameterName: string;\n };\n\nexport type FieldLocation = { readonly field: 'markdown'; readonly line: number } | { readonly field: 'example' };\n\n/**\n * Render an API location to a human readable representation\n */\nexport function formatLocation(location: SnippetLocation): string {\n switch (location.field?.field) {\n case 'example':\n return `${renderApiLocation(location.api)}-example`;\n case 'markdown':\n return `${renderApiLocation(location.api)}-L${location.field.line}`;\n case undefined:\n return renderApiLocation(location.api);\n }\n}\n\n/**\n * Render an API location to an unique string\n *\n * This function is used in hashing examples for reuse, and so the formatting\n * here should not be changed lightly.\n */\nexport function renderApiLocation(apiLoc: ApiLocation): string {\n switch (apiLoc.api) {\n case 'file':\n return apiLoc.fileName;\n case 'moduleReadme':\n return `${apiLoc.moduleFqn}-README`;\n case 'type':\n return apiLoc.fqn;\n case 'initializer':\n return `${apiLoc.fqn}#initializer`;\n case 'member':\n return `${apiLoc.fqn}#${apiLoc.memberName}`;\n case 'parameter':\n return `${apiLoc.fqn}#${apiLoc.methodName}!#${apiLoc.parameterName}`;\n }\n}\n\n/**\n * Construct a TypeScript snippet from visible source\n *\n * Will parse parameters from a directive in the given source, but will not\n * interpret `/// !show` and `/// !hide` directives.\n *\n * `/// !show` and `/// !hide` directives WILL affect what gets displayed by\n * the translator, but they will NOT affect the snippet's cache key (i.e. the\n * cache key will be based on the full source given here).\n *\n * Use this if you are looking up a snippet in a tablet, which has been translated\n * previously using a fixture.\n */\nexport function typeScriptSnippetFromVisibleSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const visibleSource = source.trimRight();\n\n return {\n visibleSource,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\n/**\n * Construct a TypeScript snippet from literal source\n *\n * @deprecated Use `typeScriptSnippetFromVisibleSource`\n */\nexport function typeScriptSnippetFromSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n return typeScriptSnippetFromVisibleSource(typeScriptSource, location, strict, parameters);\n}\n\n/**\n * Construct a TypeScript snippet from complete source\n *\n * Will parse parameters from a directive in the given source, and will\n * interpret `/// !show` and `/// !hide` directives.\n *\n * The snippet's cache key will be based on the source that remains after\n * these directives are processed.\n *\n * Use this if you are building a snippet to be translated, and take care\n * to store the return object's `visibleSource` in the assembly (not the original\n * source you passed in).\n */\nexport function typeScriptSnippetFromCompleteSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const completeSrc = source.trimRight();\n\n const visibleSource = trimCompleteSourceToVisible(completeSrc);\n\n return {\n visibleSource,\n completeSource: visibleSource !== completeSrc ? completeSrc : undefined,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\nexport function updateParameters(snippet: TypeScriptSnippet, params: Record<string, string>): TypeScriptSnippet {\n return {\n ...snippet,\n parameters: Object.assign(Object.create(null), snippet.parameters ?? {}, params),\n };\n}\n\n/**\n * Get the complete (compilable) source of a snippet\n */\nexport function completeSource(snippet: TypeScriptSnippet) {\n return snippet.completeSource ?? snippet.visibleSource;\n}\n\n/**\n * Extract snippet parameters from the first line of the source if it's a compiler directive\n */\nfunction parametersFromSourceDirectives(source: string): [string, Record<string, string>] {\n const [firstLine, ...rest] = source.split('\\n');\n // Also extract parameters from an initial line starting with '/// ' (getting rid of that line).\n const m = /[/]{3}(.*)$/.exec(firstLine);\n if (m) {\n return [rest.join('\\n'), parseMetadataLine(m[1])];\n }\n\n return [source, {}];\n}\n\n/**\n * Parse a set of 'param param=value' directives into an object\n */\nexport function parseKeyValueList(parameters: string[]): Record<string, string> {\n const ret: Record<string, string> = {};\n for (const param of parameters) {\n const parts = param.split('=', 2);\n if (parts.length === 2) {\n ret[parts[0]] = parts[1];\n } else {\n ret[parts[0]] = '';\n }\n }\n return ret;\n}\n\nexport function parseMetadataLine(metadata: string): Record<string, string> {\n return parseKeyValueList(parseMetadata(metadata));\n\n function parseMetadata(md: string): string[] {\n return md\n .trim()\n .split(' ')\n .map((s) => s.trim())\n .filter((s) => s !== '');\n }\n}\n\nexport function renderMetadataline(metadata: Record<string, string> = {}): string | undefined {\n const line = Object.entries(metadata)\n .filter(([key, _]) => !key.startsWith('$'))\n .map(([key, value]) => (value !== '' ? `${key}=${value}` : key))\n .join(' ');\n\n return line ? line : undefined;\n}\n\n/**\n * Recognized snippet parameters\n */\nexport enum SnippetParameters {\n /**\n * Use fixture with the given name (author parameter)\n */\n FIXTURE = 'fixture',\n\n /**\n * Don't use a fixture (author parameter)\n */\n NO_FIXTURE = 'nofixture',\n\n /**\n * Snippet was extracted from this literate file (backwards compatibility)\n *\n * Parameter attached by 'jsii'; load the given file instead of any fixture,\n * process as usual.\n */\n LITERATE_SOURCE = 'lit',\n\n /**\n * This snippet has been infused\n *\n * This means it has been copied from a different location, and potentially\n * even from a different assembly. If so, we can't expect it to compile in\n * the future, and if doesn't, we ignore the errors.\n *\n * N.B: this shouldn't make a difference in normal operation, as the `infuse`\n * command will duplicate the translation to the target tablet. This only\n * matters if we remove the tablet and try to re-extract an assembly with\n * infused examples from somewher else.\n */\n INFUSED = 'infused',\n\n /**\n * What directory to resolve fixtures in for this snippet (system parameter)\n *\n * Attached during processing, should not be used by authors. Does NOT imply\n * anything about the directory where we pretend to compile this file.\n */\n $PROJECT_DIRECTORY = '$directory',\n\n /**\n * What directory to pretend the file is in (system parameter)\n *\n * Attached when compiling a literate file, as they compile in\n * the location where they are stored.\n */\n $COMPILATION_DIRECTORY = '$compilation',\n}\n"]}
|