jsii 5.2.44 → 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/lib/case.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"case.js","sourceRoot":"","sources":["../src/case.ts"],"names":[],"mappings":";;;AAAA,6BAA6B;AAE7B,MAAM,SAAS,GACb,CAAC,IAA8B,EAA8B,EAAE,CAC/D,CAAC,IAAY,EAAE,EAAE,CACf,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAEf,QAAA,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,QAAA,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACpC,QAAA,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAChC,QAAA,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAE3C,MAAM,KAAK;IACF,MAAM,CAAC,KAAK,CAAC,IAAY,EAAE,IAA8B;QAC9D,qDAAqD;QACrD,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACpC,IAAI,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACtC,IAAI,KAAK,IAAI,IAAI,EAAE;YACjB,wBAAwB;YACxB,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;YAClC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;SAClC;QAED,0DAA0D;QAC1D,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC/B,IAAI,MAAM,IAAI,IAAI,EAAE;YAClB,OAAO,MAAM,CAAC;SACf;QAED,yBAAyB;QACzB,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;QAC1B,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACxB,OAAO,MAAM,CAAC;IAChB,CAAC;IAKD,gBAAuB,CAAC;;AAHxB,uFAAuF;AAC/D,YAAM,GAAG,IAAI,OAAO,EAAiC,CAAC;AAKhF,MAAM,QAAQ;IACL,MAAM,CAAC,GAAG,CAAC,IAAS;QACzB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,CAAC;QAC5C,IAAI,KAAK,IAAI,IAAI,EAAE;YACjB,OAAO,KAAK,CAAC;SACd;QACD,MAAM,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;QAC9B,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;QAC1C,OAAO,MAAM,CAAC;IAChB,CAAC;IAKD,gBAAuB,CAAC;;AAHxB,iGAAiG;AACzE,cAAK,GAAG,IAAI,GAAG,EAA0B,CAAC","sourcesContent":["import * as Case from 'case';\n\nconst withCache =\n (func: (text: string) => string): ((text: string) => string) =>\n (text: string) =>\n Cache.fetch(text, func);\n\nexport const camel = withCache(Case.camel);\nexport const constant = withCache(Case.constant);\nexport const pascal = withCache(Case.pascal);\nexport const snake = withCache(Case.snake);\n\nclass Cache {\n public static fetch(text: string, func: (text: string) => string): string {\n // Check whether we have a cache for this function...\n const cacheKey = CacheKey.for(func);\n let cache = this.CACHES.get(cacheKey);\n if (cache == null) {\n // If not, create one...\n cache = new Map<string, string>();\n this.CACHES.set(cacheKey, cache);\n }\n\n // Check if the current cache has a value for this text...\n const cached = cache.get(text);\n if (cached != null) {\n return cached;\n }\n\n // If not, compute one...\n const result = func(text);\n cache.set(text, result);\n return result;\n }\n\n // Cache is indexed on a weak CacheKey so the cache can be purged under memory pressure\n private static readonly CACHES = new WeakMap<CacheKey, Map<string, string>>();\n\n private constructor() {}\n}\n\nclass CacheKey {\n public static for(data: any) {\n const entry = this.STORE.get(data)?.deref();\n if (entry != null) {\n return entry;\n }\n const newKey = new CacheKey();\n this.STORE.set(data, new WeakRef(newKey));\n return newKey;\n }\n\n // Storing cache keys as weak references to allow garbage collection if there is memory pressure.\n private static readonly STORE = new Map<any, WeakRef<CacheKey>>();\n\n private constructor() {}\n}\n"]}
1
+ {"version":3,"file":"case.js","sourceRoot":"","sources":["../src/case.ts"],"names":[],"mappings":";;;AAAA,6BAA6B;AAE7B,MAAM,SAAS,GACb,CAAC,IAA8B,EAA8B,EAAE,CAC/D,CAAC,IAAY,EAAE,EAAE,CACf,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAEf,QAAA,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,QAAA,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACpC,QAAA,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAChC,QAAA,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAE3C,MAAM,KAAK;IACF,MAAM,CAAC,KAAK,CAAC,IAAY,EAAE,IAA8B;QAC9D,qDAAqD;QACrD,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACpC,IAAI,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QACtC,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;YAClB,wBAAwB;YACxB,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;YAClC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QACnC,CAAC;QAED,0DAA0D;QAC1D,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC/B,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;YACnB,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,yBAAyB;QACzB,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;QAC1B,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACxB,OAAO,MAAM,CAAC;IAChB,CAAC;IAKD,gBAAuB,CAAC;;AAHxB,uFAAuF;AAC/D,YAAM,GAAG,IAAI,OAAO,EAAiC,CAAC;AAKhF,MAAM,QAAQ;IACL,MAAM,CAAC,GAAG,CAAC,IAAS;QACzB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,CAAC;QAC5C,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;YAClB,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;QAC9B,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;QAC1C,OAAO,MAAM,CAAC;IAChB,CAAC;IAKD,gBAAuB,CAAC;;AAHxB,iGAAiG;AACzE,cAAK,GAAG,IAAI,GAAG,EAA0B,CAAC","sourcesContent":["import * as Case from 'case';\n\nconst withCache =\n (func: (text: string) => string): ((text: string) => string) =>\n (text: string) =>\n Cache.fetch(text, func);\n\nexport const camel = withCache(Case.camel);\nexport const constant = withCache(Case.constant);\nexport const pascal = withCache(Case.pascal);\nexport const snake = withCache(Case.snake);\n\nclass Cache {\n public static fetch(text: string, func: (text: string) => string): string {\n // Check whether we have a cache for this function...\n const cacheKey = CacheKey.for(func);\n let cache = this.CACHES.get(cacheKey);\n if (cache == null) {\n // If not, create one...\n cache = new Map<string, string>();\n this.CACHES.set(cacheKey, cache);\n }\n\n // Check if the current cache has a value for this text...\n const cached = cache.get(text);\n if (cached != null) {\n return cached;\n }\n\n // If not, compute one...\n const result = func(text);\n cache.set(text, result);\n return result;\n }\n\n // Cache is indexed on a weak CacheKey so the cache can be purged under memory pressure\n private static readonly CACHES = new WeakMap<CacheKey, Map<string, string>>();\n\n private constructor() {}\n}\n\nclass CacheKey {\n public static for(data: any) {\n const entry = this.STORE.get(data)?.deref();\n if (entry != null) {\n return entry;\n }\n const newKey = new CacheKey();\n this.STORE.set(data, new WeakRef(newKey));\n return newKey;\n }\n\n // Storing cache keys as weak references to allow garbage collection if there is memory pressure.\n private static readonly STORE = new Map<any, WeakRef<CacheKey>>();\n\n private constructor() {}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"find-utils.js","sourceRoot":"","sources":["../../src/common/find-utils.ts"],"names":[],"mappings":";;;AAAA,8BAA8B;AAC9B,kCAAkC;AAElC;;;;;;;GAOG;AACH,SAAgB,MAAM,CAAC,SAAiB,EAAE,IAA8B;IACtE,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC;IAE/B,IAAI,MAAM,EAAE;QACV,OAAO,SAAS,CAAC;KAClB;IAED,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACvC,IAAI,MAAM,KAAK,SAAS,EAAE;QACxB,OAAO,SAAS,CAAC;KAClB;IAED,OAAO,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAC9B,CAAC;AAbD,wBAaC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,WAAmB,EAAE,SAAiB;IACtE,OAAO,MAAM,CAAC,SAAS,EAAE,CAAC,GAAG,EAAE,EAAE;QAC/B,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QAC9C,OAAO,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,WAAW,CAAC;IACpG,CAAC,CAAC,CAAC;AACL,CAAC;AALD,8CAKC;AAED;;;;;GAKG;AACH,SAAgB,uBAAuB,CAAC,cAAsB,EAAE,WAAmB;IACjF,oFAAoF;IACpF,gDAAgD;IAChD,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,cAAc,EAAE;QACjD,KAAK,EAAE,CAAC,WAAW,CAAC;KACrB,CAAC,CAAC;IAEH,8EAA8E;IAC9E,6EAA6E;IAC7E,MAAM,cAAc,GAAG,iBAAiB,CAAC,cAAc,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;IAEnF,IAAI,CAAC,cAAc,EAAE;QACnB,MAAM,IAAI,KAAK,CAAC,8BAA8B,cAAc,WAAW,WAAW,GAAG,CAAC,CAAC;KACxF;IAED,OAAO,cAAc,CAAC;AACxB,CAAC;AAhBD,0DAgBC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * Find a directory up the tree from a starting directory matching a condition\n *\n * Will return `undefined` if no directory matches\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport function findUp(directory: string, pred: (dir: string) => boolean): string | undefined {\n const result = pred(directory);\n\n if (result) {\n return directory;\n }\n\n const parent = path.dirname(directory);\n if (parent === directory) {\n return undefined;\n }\n\n return findUp(parent, pred);\n}\n\n/**\n * Find the package.json for a given package upwards from the given directory\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport function findPackageJsonUp(packageName: string, directory: string) {\n return findUp(directory, (dir) => {\n const pjFile = path.join(dir, 'package.json');\n return fs.existsSync(pjFile) && JSON.parse(fs.readFileSync(pjFile, 'utf-8')).name === packageName;\n });\n}\n\n/**\n * Find the directory that contains a given dependency, identified by its 'package.json', from a starting search directory\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport function findDependencyDirectory(dependencyName: string, searchStart: string) {\n // Explicitly do not use 'require(\"dep/package.json\")' because that will fail if the\n // package does not export that particular file.\n const entryPoint = require.resolve(dependencyName, {\n paths: [searchStart],\n });\n\n // Search up from the given directory, looking for a package.json that matches\n // the dependency name (so we don't accidentally find stray 'package.jsons').\n const depPkgJsonPath = findPackageJsonUp(dependencyName, path.dirname(entryPoint));\n\n if (!depPkgJsonPath) {\n throw new Error(`Could not find dependency '${dependencyName}' from '${searchStart}'`);\n }\n\n return depPkgJsonPath;\n}\n"]}
1
+ {"version":3,"file":"find-utils.js","sourceRoot":"","sources":["../../src/common/find-utils.ts"],"names":[],"mappings":";;;AAAA,8BAA8B;AAC9B,kCAAkC;AAElC;;;;;;;GAOG;AACH,SAAgB,MAAM,CAAC,SAAiB,EAAE,IAA8B;IACtE,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC;IAE/B,IAAI,MAAM,EAAE,CAAC;QACX,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACvC,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACzB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAC9B,CAAC;AAbD,wBAaC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,WAAmB,EAAE,SAAiB;IACtE,OAAO,MAAM,CAAC,SAAS,EAAE,CAAC,GAAG,EAAE,EAAE;QAC/B,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QAC9C,OAAO,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,WAAW,CAAC;IACpG,CAAC,CAAC,CAAC;AACL,CAAC;AALD,8CAKC;AAED;;;;;GAKG;AACH,SAAgB,uBAAuB,CAAC,cAAsB,EAAE,WAAmB;IACjF,oFAAoF;IACpF,gDAAgD;IAChD,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,cAAc,EAAE;QACjD,KAAK,EAAE,CAAC,WAAW,CAAC;KACrB,CAAC,CAAC;IAEH,8EAA8E;IAC9E,6EAA6E;IAC7E,MAAM,cAAc,GAAG,iBAAiB,CAAC,cAAc,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;IAEnF,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CAAC,8BAA8B,cAAc,WAAW,WAAW,GAAG,CAAC,CAAC;IACzF,CAAC;IAED,OAAO,cAAc,CAAC;AACxB,CAAC;AAhBD,0DAgBC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * Find a directory up the tree from a starting directory matching a condition\n *\n * Will return `undefined` if no directory matches\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport function findUp(directory: string, pred: (dir: string) => boolean): string | undefined {\n const result = pred(directory);\n\n if (result) {\n return directory;\n }\n\n const parent = path.dirname(directory);\n if (parent === directory) {\n return undefined;\n }\n\n return findUp(parent, pred);\n}\n\n/**\n * Find the package.json for a given package upwards from the given directory\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport function findPackageJsonUp(packageName: string, directory: string) {\n return findUp(directory, (dir) => {\n const pjFile = path.join(dir, 'package.json');\n return fs.existsSync(pjFile) && JSON.parse(fs.readFileSync(pjFile, 'utf-8')).name === packageName;\n });\n}\n\n/**\n * Find the directory that contains a given dependency, identified by its 'package.json', from a starting search directory\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport function findDependencyDirectory(dependencyName: string, searchStart: string) {\n // Explicitly do not use 'require(\"dep/package.json\")' because that will fail if the\n // package does not export that particular file.\n const entryPoint = require.resolve(dependencyName, {\n paths: [searchStart],\n });\n\n // Search up from the given directory, looking for a package.json that matches\n // the dependency name (so we don't accidentally find stray 'package.jsons').\n const depPkgJsonPath = findPackageJsonUp(dependencyName, path.dirname(entryPoint));\n\n if (!depPkgJsonPath) {\n throw new Error(`Could not find dependency '${dependencyName}' from '${searchStart}'`);\n }\n\n return depPkgJsonPath;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"symbol-id.js","sourceRoot":"","sources":["../../src/common/symbol-id.ts"],"names":[],"mappings":";;;AAAA,8BAA8B;AAC9B,kCAAkC;AAElC,iCAAiC;AAEjC,6CAAsC;AAgBtC;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,SAAgB,gBAAgB,CAC9B,WAA2B,EAC3B,GAAc,EACd,UAA2B,EAAE;IAE7B,0DAA0D;IAC1D,sCAAsC;IACtC,OAAO,CAAC,GAAG,CAAC,KAAK,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;QAC/C,GAAG,GAAG,WAAW,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC;KACzC;IAED,MAAM,QAAQ;IACZ,sCAAsC;IACtC,CAAC,GAAG,CAAC,KAAK;QACR,sCAAsC;QACtC,CAAC,EAAE,CAAC,WAAW,CAAC,MAAM;YACpB,sCAAsC;YACtC,EAAE,CAAC,WAAW,CAAC,QAAQ;YACvB,EAAE,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;QAC/B,CAAC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jsii/spec';\nimport * as ts from 'typescript';\n\nimport { findUp } from './find-utils';\n\n/**\n * Additional options that may be provided to the symbolIdentifier.\n */\ninterface SymbolIdOptions {\n /**\n * The assembly that the symbol is found in.\n * This is used to provide the correct root directory\n * as specified in the assembly metadata. In turn,\n * the root directory is used to ensure that the\n * symbolId comes from source code and not compiled code.\n */\n readonly assembly?: Assembly;\n}\n\n/**\n * Return a symbol identifier for the given symbol\n *\n * The symbol identifier identifies a TypeScript symbol in a source file inside\n * a package. We can use this to map between jsii entries in the manifest, and\n * entities in the TypeScript source code.\n *\n * Going via symbol id is the only way to identify symbols in submodules. Otherwise,\n * all the TypeScript compiler sees is:\n *\n * ```\n * /my/package/lib/source/directory/dist.js <containing> MyClass\n * ```\n *\n * And there's no way to figure out what submodule name\n * `lib/source/directory/dist` is exported as.\n *\n * The format of a symbol id is:\n *\n * ```\n * relative/source/file:Name.space.Class[#member]\n * ```\n *\n * We used to build this identifier ourselves. Turns out there was a built-in\n * way to get pretty much the same, by calling `typeChecker.getFullyQualifiedName()`.\n * Whoops ^_^ (this historical accident is why the format is similar to but\n * different from what the TS checker returns).\n */\nexport function symbolIdentifier(\n typeChecker: ts.TypeChecker,\n sym: ts.Symbol,\n options: SymbolIdOptions = {},\n): string | undefined {\n // If this symbol happens to be an alias, resolve it first\n // eslint-disable-next-line no-bitwise\n while ((sym.flags & ts.SymbolFlags.Alias) !== 0) {\n sym = typeChecker.getAliasedSymbol(sym);\n }\n\n const isMember =\n // eslint-disable-next-line no-bitwise\n (sym.flags &\n // eslint-disable-next-line no-bitwise\n (ts.SymbolFlags.Method |\n // eslint-disable-next-line no-bitwise\n ts.SymbolFlags.Property |\n ts.SymbolFlags.EnumMember)) !==\n 0;\n\n const tsName = typeChecker.getFullyQualifiedName(sym);\n\n // TypeScript fqn looks like \"/path/to/file\"[.name.in.file]\n const groups = /^\"([^\"]+)\"(?:\\.(.*))?$/.exec(tsName);\n if (!groups) {\n return undefined;\n }\n\n const [, fileName, inFileName] = groups; // inFileName may be absent\n\n const relFile = Helper.for(typeChecker).assemblyRelativeSourceFile(fileName, options?.assembly);\n if (!relFile) {\n return undefined;\n }\n\n // If this is a member symbol, replace the final '.' with a '#'\n const typeSymbol = isMember ? (inFileName ?? '').replace(/\\.([^.]+)$/, '#$1') : inFileName ?? '';\n\n return `${relFile}:${typeSymbol}`;\n}\n\nclass Helper {\n public static for(typeChecker: ts.TypeChecker) {\n const cached = this.INSTANCES.get(typeChecker);\n if (cached != null) {\n return cached;\n }\n const helper = new Helper();\n this.INSTANCES.set(typeChecker, helper);\n return helper;\n }\n\n private static readonly INSTANCES = new WeakMap<ts.TypeChecker, Helper>();\n\n private readonly packageInfo = new Map<string, PackageInfo | undefined>();\n\n private constructor() {}\n\n public assemblyRelativeSourceFile(sourceFileName: string, asm?: Assembly) {\n const packageInfo = this.findPackageInfo(path.dirname(sourceFileName));\n if (!packageInfo) {\n return undefined;\n }\n\n let sourcePath = removePrefix(packageInfo.outdir ?? '', path.relative(packageInfo.packageJsonDir, sourceFileName));\n\n // Modify the namespace if we send in the assembly.\n if (asm) {\n const tscRootDir = packageInfo.tscRootDir ?? asm.metadata?.tscRootDir;\n const tscOutDir = packageInfo.tscOutDir;\n sourcePath = normalizePath(sourcePath, tscRootDir, tscOutDir);\n }\n\n return sourcePath.replace(/(\\.d)?\\.ts$/, '');\n\n function removePrefix(prefix: string, filePath: string) {\n const prefixParts = prefix.split(/[/\\\\]/g);\n const pathParts = filePath.split(/[/\\\\]/g);\n let i = 0;\n while (prefixParts[i] === pathParts[i]) {\n i++;\n }\n return pathParts.slice(i).join('/');\n }\n }\n\n private findPackageInfo(from: string): PackageInfo | undefined {\n if (this.packageInfo.has(from)) {\n return this.packageInfo.get(from);\n }\n\n const packageJsonDir = findUp(from, (dir) => fs.existsSync(path.join(dir, 'package.json')));\n\n if (!packageJsonDir) {\n this.packageInfo.set(from, undefined);\n return undefined;\n }\n\n if (this.packageInfo.has(packageJsonDir)) {\n return this.packageInfo.get(packageJsonDir);\n }\n\n const { jsii } = JSON.parse(fs.readFileSync(path.join(packageJsonDir, 'package.json'), 'utf-8'));\n\n const result = {\n packageJsonDir,\n outdir: jsii?.outdir,\n tscRootDir: jsii?.tsc?.rootDir,\n tscOutDir: jsii?.tsc?.outDir,\n };\n this.packageInfo.set(from, result);\n this.packageInfo.set(packageJsonDir, result);\n return result;\n }\n}\n\ninterface PackageInfo {\n readonly packageJsonDir: string;\n readonly outdir: string | undefined;\n readonly tscRootDir: string | undefined;\n readonly tscOutDir: string | undefined;\n}\n\n/**\n * Ensures that the sourcePath is pointing to the source code\n * and not compiled code. This can happen if the root directory\n * and/or out directory is set for the project. We check to see\n * if the out directory is present in the sourcePath, and if so,\n * we replace it with the root directory.\n */\nexport function normalizePath(sourcePath: string, rootDir?: string, outDir?: string): string {\n if (rootDir === undefined || outDir === undefined) {\n return sourcePath;\n }\n\n outDir = removeEndSlash(path.normalize(outDir));\n const outDirLength = outDir.split(path.sep).length;\n rootDir = removeEndSlash(path.normalize(rootDir));\n\n let paths = path.normalize(sourcePath).split(path.sep);\n const pathDir = paths.slice(0, outDirLength).join(path.sep);\n\n if (outDir === pathDir || outDir === '.') {\n // outDir === '.' is a special case where we do not want\n // to remove any paths from the list.\n if (outDir !== '.') {\n paths = paths.slice(outDirLength);\n }\n sourcePath = rootDir === '.' ? paths.join('/') : `${rootDir}/${paths.join('/')}`;\n }\n return unixize(sourcePath);\n\n function removeEndSlash(filePath: string) {\n return filePath.endsWith(path.sep) ? filePath.slice(0, filePath.length - 1) : filePath;\n }\n}\n\n/**\n * Turn backslashes in a path into forward slashes\n */\nfunction unixize(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n"]}
1
+ {"version":3,"file":"symbol-id.js","sourceRoot":"","sources":["../../src/common/symbol-id.ts"],"names":[],"mappings":";;;AAAA,8BAA8B;AAC9B,kCAAkC;AAElC,iCAAiC;AAEjC,6CAAsC;AAgBtC;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;A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G,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;IACnF,CAAC;IACD,OAAO,OAAO,CAAC,UAAU,CAAC,CAAC;IAE3B,SAAS,cAAc,CAAC,QAAgB;QACtC,OAAO,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;IACzF,CAAC;AACH,CAAC;AAzBD,sCAyBC;AAED;;GAEG;AACH,SAAS,OAAO,CAAC,CAAS;IACxB,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { Assembly } from '@jsii/spec';\nimport * as ts from 'typescript';\n\nimport { findUp } from './find-utils';\n\n/**\n * Additional options that may be provided to the symbolIdentifier.\n */\ninterface SymbolIdOptions {\n /**\n * The assembly that the symbol is found in.\n * This is used to provide the correct root directory\n * as specified in the assembly metadata. In turn,\n * the root directory is used to ensure that the\n * symbolId comes from source code and not compiled code.\n */\n readonly assembly?: Assembly;\n}\n\n/**\n * Return a symbol identifier for the given symbol\n *\n * The symbol identifier identifies a TypeScript symbol in a source file inside\n * a package. We can use this to map between jsii entries in the manifest, and\n * entities in the TypeScript source code.\n *\n * Going via symbol id is the only way to identify symbols in submodules. Otherwise,\n * all the TypeScript compiler sees is:\n *\n * ```\n * /my/package/lib/source/directory/dist.js <containing> MyClass\n * ```\n *\n * And there's no way to figure out what submodule name\n * `lib/source/directory/dist` is exported as.\n *\n * The format of a symbol id is:\n *\n * ```\n * relative/source/file:Name.space.Class[#member]\n * ```\n *\n * We used to build this identifier ourselves. Turns out there was a built-in\n * way to get pretty much the same, by calling `typeChecker.getFullyQualifiedName()`.\n * Whoops ^_^ (this historical accident is why the format is similar to but\n * different from what the TS checker returns).\n */\nexport function symbolIdentifier(\n typeChecker: ts.TypeChecker,\n sym: ts.Symbol,\n options: SymbolIdOptions = {},\n): string | undefined {\n // If this symbol happens to be an alias, resolve it first\n // eslint-disable-next-line no-bitwise\n while ((sym.flags & ts.SymbolFlags.Alias) !== 0) {\n sym = typeChecker.getAliasedSymbol(sym);\n }\n\n const isMember =\n // eslint-disable-next-line no-bitwise\n (sym.flags &\n // eslint-disable-next-line no-bitwise\n (ts.SymbolFlags.Method |\n // eslint-disable-next-line no-bitwise\n ts.SymbolFlags.Property |\n ts.SymbolFlags.EnumMember)) !==\n 0;\n\n const tsName = typeChecker.getFullyQualifiedName(sym);\n\n // TypeScript fqn looks like \"/path/to/file\"[.name.in.file]\n const groups = /^\"([^\"]+)\"(?:\\.(.*))?$/.exec(tsName);\n if (!groups) {\n return undefined;\n }\n\n const [, fileName, inFileName] = groups; // inFileName may be absent\n\n const relFile = Helper.for(typeChecker).assemblyRelativeSourceFile(fileName, options?.assembly);\n if (!relFile) {\n return undefined;\n }\n\n // If this is a member symbol, replace the final '.' with a '#'\n const typeSymbol = isMember ? (inFileName ?? '').replace(/\\.([^.]+)$/, '#$1') : inFileName ?? '';\n\n return `${relFile}:${typeSymbol}`;\n}\n\nclass Helper {\n public static for(typeChecker: ts.TypeChecker) {\n const cached = this.INSTANCES.get(typeChecker);\n if (cached != null) {\n return cached;\n }\n const helper = new Helper();\n this.INSTANCES.set(typeChecker, helper);\n return helper;\n }\n\n private static readonly INSTANCES = new WeakMap<ts.TypeChecker, Helper>();\n\n private readonly packageInfo = new Map<string, PackageInfo | undefined>();\n\n private constructor() {}\n\n public assemblyRelativeSourceFile(sourceFileName: string, asm?: Assembly) {\n const packageInfo = this.findPackageInfo(path.dirname(sourceFileName));\n if (!packageInfo) {\n return undefined;\n }\n\n let sourcePath = removePrefix(packageInfo.outdir ?? '', path.relative(packageInfo.packageJsonDir, sourceFileName));\n\n // Modify the namespace if we send in the assembly.\n if (asm) {\n const tscRootDir = packageInfo.tscRootDir ?? asm.metadata?.tscRootDir;\n const tscOutDir = packageInfo.tscOutDir;\n sourcePath = normalizePath(sourcePath, tscRootDir, tscOutDir);\n }\n\n return sourcePath.replace(/(\\.d)?\\.ts$/, '');\n\n function removePrefix(prefix: string, filePath: string) {\n const prefixParts = prefix.split(/[/\\\\]/g);\n const pathParts = filePath.split(/[/\\\\]/g);\n let i = 0;\n while (prefixParts[i] === pathParts[i]) {\n i++;\n }\n return pathParts.slice(i).join('/');\n }\n }\n\n private findPackageInfo(from: string): PackageInfo | undefined {\n if (this.packageInfo.has(from)) {\n return this.packageInfo.get(from);\n }\n\n const packageJsonDir = findUp(from, (dir) => fs.existsSync(path.join(dir, 'package.json')));\n\n if (!packageJsonDir) {\n this.packageInfo.set(from, undefined);\n return undefined;\n }\n\n if (this.packageInfo.has(packageJsonDir)) {\n return this.packageInfo.get(packageJsonDir);\n }\n\n const { jsii } = JSON.parse(fs.readFileSync(path.join(packageJsonDir, 'package.json'), 'utf-8'));\n\n const result = {\n packageJsonDir,\n outdir: jsii?.outdir,\n tscRootDir: jsii?.tsc?.rootDir,\n tscOutDir: jsii?.tsc?.outDir,\n };\n this.packageInfo.set(from, result);\n this.packageInfo.set(packageJsonDir, result);\n return result;\n }\n}\n\ninterface PackageInfo {\n readonly packageJsonDir: string;\n readonly outdir: string | undefined;\n readonly tscRootDir: string | undefined;\n readonly tscOutDir: string | undefined;\n}\n\n/**\n * Ensures that the sourcePath is pointing to the source code\n * and not compiled code. This can happen if the root directory\n * and/or out directory is set for the project. We check to see\n * if the out directory is present in the sourcePath, and if so,\n * we replace it with the root directory.\n */\nexport function normalizePath(sourcePath: string, rootDir?: string, outDir?: string): string {\n if (rootDir === undefined || outDir === undefined) {\n return sourcePath;\n }\n\n outDir = removeEndSlash(path.normalize(outDir));\n const outDirLength = outDir.split(path.sep).length;\n rootDir = removeEndSlash(path.normalize(rootDir));\n\n let paths = path.normalize(sourcePath).split(path.sep);\n const pathDir = paths.slice(0, outDirLength).join(path.sep);\n\n if (outDir === pathDir || outDir === '.') {\n // outDir === '.' is a special case where we do not want\n // to remove any paths from the list.\n if (outDir !== '.') {\n paths = paths.slice(outDirLength);\n }\n sourcePath = rootDir === '.' ? paths.join('/') : `${rootDir}/${paths.join('/')}`;\n }\n return unixize(sourcePath);\n\n function removeEndSlash(filePath: string) {\n return filePath.endsWith(path.sep) ? filePath.slice(0, filePath.length - 1) : filePath;\n }\n}\n\n/**\n * Turn backslashes in a path into forward slashes\n */\nfunction unixize(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"compiler.js","sourceRoot":"","sources":["../src/compiler.ts"],"names":[],"mappings":";;;AAAA,8BAA8B;AAC9B,kCAAkC;AAClC,+BAA+B;AAC/B,iCAAiC;AACjC,iCAAiC;AAEjC,2CAAwC;AACxC,+BAA+B;AAC/B,oDAA8D;AAC9D,mDAA4E;AAE5E,uDAAmD;AAEnD,4EAA2E;AAC3E,iCAAiC;AAEjC,MAAM,qBAAqB,GAAuB;IAChD,YAAY,EAAE,IAAI;IAClB,WAAW,EAAE,IAAI;IACjB,sBAAsB,EAAE,IAAI;IAC5B,WAAW,EAAE,IAAI;IACjB,GAAG,EAAE,CAAC,iBAAiB,CAAC;IACxB,MAAM,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ;IAC9B,aAAa,EAAE,IAAI;IACnB,0BAA0B,EAAE,IAAI;IAChC,aAAa,EAAE,IAAI;IACnB,iBAAiB,EAAE,IAAI;IACvB,cAAc,EAAE,IAAI;IACpB,cAAc,EAAE,IAAI;IACpB,kBAAkB,EAAE,IAAI;IACxB,iBAAiB,EAAE,IAAI;IACvB,YAAY,EAAE,IAAI;IAClB,MAAM,EAAE,IAAI;IACZ,gBAAgB,EAAE,IAAI;IACtB,4BA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EAAE,EAAE,CAAC;IAC3C,IAAI,CAAC,GAAG,EAAE;QACR,MAAM,IAAI,KAAK,CACb,wEAAwE,qBAAqB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAC/G,CAAC;KACH;IACD,OAAO,qBAAqB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;AACvE,CAAC;AAED,SAAS,+BAA+B,CAAC,IAAqB;IAC5D,uBAAuB;IACvB,sHAAsH;IACtH,OAAO;QACL,UAAU,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;QACrC,aAAa,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK;YACvD,IAAI,IAAI,CAAC,aAAa,KAAK,SAAS,EAAE;gBACpC,MAAM,IAAI,KAAK,CAAC,2FAA2F,CAAC,CAAC;aAC9G;YACD,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;QACzE,CAAC;QACD,QAAQ,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QACjC,yBAAyB,EAAE,IAAI,CAAC,yBAAyB,EAAE;QAC3D,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,KAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;KACtD,CAAC;AACJ,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as chalk from 'chalk';\nimport * as log4js from 'log4js';\nimport * as ts from 'typescript';\n\nimport { Assembler } from './assembler';\nimport * as Case from './case';\nimport { findDependencyDirectory } from './common/find-utils';\nimport { emitDownleveledDeclarations, TYPES_COMPAT } from './downlevel-dts';\nimport { Emitter } from './emitter';\nimport { JsiiDiagnostic } from './jsii-diagnostic';\nimport { ProjectInfo } from './project-info';\nimport { WARNINGSCODE_FILE_NAME } from './transforms/deprecation-warnings';\nimport * as utils from './utils';\n\nconst BASE_COMPILER_OPTIONS: ts.CompilerOptions = {\n alwaysStrict: true,\n declaration: true,\n experimentalDecorators: true,\n incremental: true,\n lib: ['lib.es2020.d.ts'],\n module: ts.ModuleKind.CommonJS,\n noEmitOnError: true,\n noFallthroughCasesInSwitch: true,\n noImplicitAny: true,\n noImplicitReturns: true,\n noImplicitThis: true,\n noUnusedLocals: true,\n noUnusedParameters: true,\n resolveJsonModule: true,\n skipLibCheck: true,\n strict: true,\n strictNullChecks: true,\n strictPropertyInitialization: true,\n stripInternal: false,\n target: ts.ScriptTarget.ES2020,\n};\n\nconst LOG = log4js.getLogger('jsii/compiler');\nexport const DIAGNOSTICS = 'diagnostics';\nexport const JSII_DIAGNOSTICS_CODE = 9999;\n\nexport interface CompilerOptions {\n /** The information about the project to be built */\n projectInfo: ProjectInfo;\n /** Whether the compiler should watch for changes or just compile once */\n watch?: boolean;\n /** Whether to detect and generate TypeScript project references */\n projectReferences?: boolean;\n /** Whether to fail when a warning is emitted */\n failOnWarnings?: boolean;\n /** Whether to strip deprecated members from emitted artifacts */\n stripDeprecated?: boolean;\n /** The path to an allowlist of FQNs to strip if stripDeprecated is set */\n stripDeprecatedAllowListFile?: string;\n /** Whether to add warnings for deprecated elements */\n addDeprecationWarnings?: boolean;\n /**\n * The name of the tsconfig file to generate\n * @default \"tsconfig.json\"\n */\n generateTypeScriptConfig?: string;\n /**\n * Whether to compress the assembly\n * @default false\n */\n compressAssembly?: boolean;\n}\n\nexport interface TypescriptConfig {\n compilerOptions: ts.CompilerOptions;\n include?: string[];\n exclude?: string[];\n references?: ts.ProjectReference[];\n}\n\nexport class Compiler implements Emitter {\n private readonly system: ts.System;\n private readonly compilerHost: ts.CompilerHost;\n private typescriptConfig?: TypescriptConfig;\n private rootFiles: string[] = [];\n private readonly configPath: string;\n private readonly projectReferences: boolean;\n\n public constructor(private readonly options: CompilerOptions) {\n const rootDir = this.options.projectInfo.projectRoot;\n this.system = {\n ...ts.sys,\n getCurrentDirectory: () => rootDir,\n createDirectory: (pth) => ts.sys.createDirectory(path.resolve(rootDir, pth)),\n deleteFile: ts.sys.deleteFile && ((pth) => ts.sys.deleteFile!(path.join(rootDir, pth))),\n fileExists: (pth) => ts.sys.fileExists(path.resolve(rootDir, pth)),\n getFileSize: ts.sys.getFileSize && ((pth) => ts.sys.getFileSize!(path.resolve(rootDir, pth))),\n readFile: (pth, encoding) => ts.sys.readFile(path.resolve(rootDir, pth), encoding),\n watchFile:\n ts.sys.watchFile &&\n ((pth, callback, pollingInterval, watchOptions) =>\n ts.sys.watchFile!(path.resolve(rootDir, pth), callback, pollingInterval, watchOptions)),\n writeFile: (pth, data, writeByteOrderMark) =>\n ts.sys.writeFile(path.resolve(rootDir, pth), data, writeByteOrderMark),\n };\n this.compilerHost = ts.createIncrementalCompilerHost(BASE_COMPILER_OPTIONS, this.system);\n\n const configFileName = options.generateTypeScriptConfig ?? 'tsconfig.json';\n\n this.configPath = path.join(this.options.projectInfo.projectRoot, configFileName);\n\n this.projectReferences =\n options.projectReferences !== undefined\n ? options.projectReferences\n : options.projectInfo.projectReferences !== undefined\n ? options.projectInfo.projectReferences\n : false;\n }\n\n /**\n * Compiles the configured program.\n *\n * @param files can be specified to override the standard source code location logic. Useful for example when testing \"negatives\".\n */\n public emit(...files: string[]): ts.EmitResult {\n this._prepareForBuild(...files);\n return this._buildOnce();\n }\n\n /**\n * Watches for file-system changes and dynamically recompiles the project as needed. In non-blocking mode, this\n * returns the TypeScript watch handle for the application to use.\n *\n * @internal\n */\n public async watch(opts: NonBlockingWatchOptions): Promise<ts.Watch<ts.BuilderProgram>>;\n /**\n * Watches for file-system changes and dynamically recompiles the project as needed. In blocking mode, this results\n * in a never-resolving promise.\n */\n public async watch(): Promise<never>;\n public async watch(opts?: NonBlockingWatchOptions): Promise<ts.Watch<ts.BuilderProgram> | never> {\n this._prepareForBuild();\n\n const pi = this.options.projectInfo;\n const projectRoot = pi.projectRoot;\n const host = ts.createWatchCompilerHost(\n this.configPath,\n {\n ...pi.tsc,\n ...BASE_COMPILER_OPTIONS,\n noEmitOnError: false,\n },\n this.system,\n ts.createEmitAndSemanticDiagnosticsBuilderProgram,\n opts?.reportDiagnostics,\n opts?.reportWatchStatus,\n );\n if (!host.getDefaultLibLocation) {\n throw new Error('No default library location was found on the TypeScript compiler host!');\n }\n const orig = host.afterProgramCreate;\n // This is a callback cascade, so it's \"okay\" to return an unhandled promise there. This may\n // cause an unhandled promise rejection warning, but that's not a big deal.\n //\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n host.afterProgramCreate = (builderProgram) => {\n const emitResult = this._consumeProgram(builderProgram.getProgram(), host.getDefaultLibLocation!());\n\n for (const diag of emitResult.diagnostics.filter((d) => d.code === JSII_DIAGNOSTICS_CODE)) {\n utils.logDiagnostic(diag, projectRoot);\n }\n\n if (orig) {\n orig.call(host, builderProgram);\n }\n if (opts?.compilationComplete) {\n opts.compilationComplete(emitResult);\n }\n };\n const watch = ts.createWatchProgram(host);\n\n if (opts?.nonBlocking) {\n // In non-blocking mode, returns the handle to the TypeScript watch interface.\n return watch;\n }\n // In blocking mode, returns a never-resolving promise.\n return new Promise<never>(() => null);\n }\n\n /**\n * Prepares the project for build, by creating the necessary configuration\n * file(s), and assigning the relevant root file(s).\n *\n * @param files the files that were specified as input in the CLI invocation.\n */\n private _prepareForBuild(...files: string[]) {\n this.buildTypeScriptConfig();\n this.writeTypeScriptConfig();\n this.rootFiles = this.determineSources(files);\n }\n\n /**\n * Do a single build\n */\n private _buildOnce(): ts.EmitResult {\n if (!this.compilerHost.getDefaultLibLocation) {\n throw new Error('No default library location was found on the TypeScript compiler host!');\n }\n\n const tsconf = this.typescriptConfig!;\n const pi = this.options.projectInfo;\n\n const prog = ts.createIncrementalProgram({\n rootNames: this.rootFiles.concat(_pathOfLibraries(this.compilerHost)),\n options: {\n ...pi.tsc,\n ...(tsconf?.compilerOptions ?? BASE_COMPILER_OPTIONS),\n },\n // Make the references absolute for the compiler\n projectReferences: tsconf.references?.map((ref) => ({\n path: path.resolve(path.dirname(this.configPath), ref.path),\n })),\n host: this.compilerHost,\n });\n\n return this._consumeProgram(prog.getProgram(), this.compilerHost.getDefaultLibLocation());\n }\n\n private _consumeProgram(program: ts.Program, stdlib: string): ts.EmitResult {\n const diagnostics = [...ts.getPreEmitDiagnostics(program)];\n let hasErrors = false;\n\n if (!hasErrors && this.diagsHaveAbortableErrors(diagnostics)) {\n hasErrors = true;\n LOG.error('Compilation errors prevented the JSII assembly from being created');\n }\n\n // Do the \"Assembler\" part first because we need some of the analysis done in there\n // to post-process the AST\n const assembler = new Assembler(this.options.projectInfo, this.system, program, stdlib, {\n stripDeprecated: this.options.stripDeprecated,\n stripDeprecatedAllowListFile: this.options.stripDeprecatedAllowListFile,\n addDeprecationWarnings: this.options.addDeprecationWarnings,\n compressAssembly: this.options.compressAssembly,\n });\n\n try {\n const assmEmit = assembler.emit();\n if (!hasErrors && (assmEmit.emitSkipped || this.diagsHaveAbortableErrors(assmEmit.diagnostics))) {\n hasErrors = true;\n LOG.error('Type model errors prevented the JSII assembly from being created');\n }\n\n diagnostics.push(...assmEmit.diagnostics);\n } catch (e: any) {\n diagnostics.push(JsiiDiagnostic.JSII_9997_UNKNOWN_ERROR.createDetached(e));\n hasErrors = true;\n }\n\n // Do the emit, but add in transformers which are going to replace real\n // comments with synthetic ones.\n const emit = program.emit(\n undefined, // targetSourceFile\n undefined, // writeFile\n undefined, // cancellationToken\n undefined, // emitOnlyDtsFiles\n assembler.customTransformers,\n );\n diagnostics.push(...emit.diagnostics);\n\n if (!hasErrors && (emit.emitSkipped || this.diagsHaveAbortableErrors(emit.diagnostics))) {\n hasErrors = true;\n LOG.error('Compilation errors prevented the JSII assembly from being created');\n }\n\n if (!hasErrors) {\n emitDownleveledDeclarations(this.options.projectInfo);\n }\n\n // Some extra validation on the config.\n // Make sure that { \"./.warnings.jsii.js\": \"./.warnings.jsii.js\" } is in the set of\n // exports, if they are specified.\n if (this.options.addDeprecationWarnings && this.options.projectInfo.exports !== undefined) {\n const expected = `./${WARNINGSCODE_FILE_NAME}`;\n const warningsExport = Object.entries(this.options.projectInfo.exports).filter(\n ([k, v]) => k === expected && v === expected,\n );\n\n if (warningsExport.length === 0) {\n hasErrors = true;\n diagnostics.push(JsiiDiagnostic.JSII_0007_MISSING_WARNINGS_EXPORT.createDetached());\n }\n }\n\n return {\n emitSkipped: hasErrors,\n diagnostics: ts.sortAndDeduplicateDiagnostics(diagnostics),\n emittedFiles: emit.emittedFiles,\n };\n }\n\n /**\n * Build the TypeScript config object\n *\n * This is the object that will be written to disk.\n */\n private buildTypeScriptConfig() {\n let references: string[] | undefined;\n if (this.projectReferences) {\n references = this.findProjectReferences();\n }\n\n const pi = this.options.projectInfo;\n\n this.typescriptConfig = {\n compilerOptions: {\n ...pi.tsc,\n ...BASE_COMPILER_OPTIONS,\n // Enable composite mode if project references are enabled\n composite: this.projectReferences,\n // When incremental, configure a tsbuildinfo file\n tsBuildInfoFile: path.join(pi.tsc?.outDir ?? '.', 'tsconfig.tsbuildinfo'),\n },\n include: [pi.tsc?.rootDir != null ? path.join(pi.tsc.rootDir, '**', '*.ts') : path.join('**', '*.ts')],\n exclude: [\n 'node_modules',\n pi.tsc?.outDir != null ? path.resolve(pi.tsc.outDir, TYPES_COMPAT) : TYPES_COMPAT,\n ...(pi.excludeTypescript ?? []),\n ...(pi.tsc?.outDir != null &&\n (pi.tsc?.rootDir == null || path.resolve(pi.tsc.outDir).startsWith(path.resolve(pi.tsc.rootDir) + path.sep))\n ? [path.join(pi.tsc.outDir, '**', '*.ts')]\n : []),\n ],\n // Change the references a little. We write 'originalpath' to the\n // file under the 'path' key, which is the same as what the\n // TypeScript compiler does. Make it relative so that the files are\n // movable. Not strictly required but looks better.\n references: references?.map((p) => ({ path: p })),\n };\n }\n\n /**\n * Creates a `tsconfig.json` file to improve the IDE experience.\n *\n * @return the fully qualified path to the `tsconfig.json` file\n */\n private writeTypeScriptConfig(): void {\n const commentKey = '_generated_by_jsii_';\n const commentValue = 'Generated by jsii - safe to delete, and ideally should be in .gitignore';\n\n (this.typescriptConfig as any)[commentKey] = commentValue;\n\n if (fs.existsSync(this.configPath)) {\n const currentConfig = JSON.parse(fs.readFileSync(this.configPath, 'utf-8'));\n if (!(commentKey in currentConfig)) {\n throw new Error(\n `A '${this.configPath}' file that was not generated by jsii is in ${this.options.projectInfo.projectRoot}. Aborting instead of overwriting.`,\n );\n }\n }\n\n const outputConfig = {\n ...this.typescriptConfig,\n compilerOptions: {\n ...this.typescriptConfig?.compilerOptions,\n lib: this.typescriptConfig?.compilerOptions?.lib?.map((lib) =>\n // Drop the \"lib.\" prefix and \".d.ts\" suffix before writing up the tsconfig.json file\n lib.slice(4, lib.length - 5),\n ),\n // Re-write the module, targets & jsx to be the JSON format instead of Programmatic API\n module: (this.typescriptConfig?.compilerOptions?.module &&\n ts.ModuleKind[this.typescriptConfig.compilerOptions.module]) as any,\n newLine: newLineForTsconfigJson(this.typescriptConfig?.compilerOptions.newLine),\n target: (this.typescriptConfig?.compilerOptions?.target &&\n ts.ScriptTarget[this.typescriptConfig.compilerOptions.target]) as any,\n jsx: (this.typescriptConfig?.compilerOptions?.jsx &&\n Case.snake(ts.JsxEmit[this.typescriptConfig.compilerOptions.jsx])) as any,\n },\n };\n\n LOG.debug(`Creating or updating ${chalk.blue(this.configPath)}`);\n fs.writeFileSync(this.configPath, JSON.stringify(outputConfig, null, 2), 'utf8');\n\n /**\n * This is annoying - the values expected in the tsconfig.json file are not\n * the same as the enum constant names, or their values. So we need this\n * function to map the \"compiler API version\" to the \"tsconfig.json version\"\n *\n * @param newLine the compiler form of the new line configuration\n *\n * @return the requivalent value to put in tsconfig.json\n */\n function newLineForTsconfigJson(newLine: ts.NewLineKind | undefined) {\n switch (newLine) {\n case ts.NewLineKind.CarriageReturnLineFeed:\n return 'crlf';\n case ts.NewLineKind.LineFeed:\n return 'lf';\n default:\n return undefined;\n }\n }\n }\n\n /**\n * Find all dependencies that look like TypeScript projects.\n *\n * Enumerate all dependencies, if they have a tsconfig.json file with\n * \"composite: true\" we consider them project references.\n *\n * (Note: TypeScript seems to only correctly find transitive project references\n * if there's an \"index\" tsconfig.json of all projects somewhere up the directory\n * tree)\n */\n private findProjectReferences(): string[] {\n const pkg = this.options.projectInfo.packageJson;\n\n const ret = new Array<string>();\n\n const dependencyNames = new Set<string>();\n for (const dependencyMap of [pkg.dependencies, pkg.devDependencies, pkg.peerDependencies]) {\n if (dependencyMap === undefined) {\n continue;\n }\n for (const name of Object.keys(dependencyMap)) {\n dependencyNames.add(name);\n }\n }\n\n for (const tsconfigFile of Array.from(dependencyNames).map((depName) => this.findMonorepoPeerTsconfig(depName))) {\n if (!tsconfigFile) {\n continue;\n }\n\n const { config: tsconfig } = ts.readConfigFile(tsconfigFile, this.system.readFile);\n\n // Add references to any TypeScript package we find that is 'composite' enabled.\n // Make it relative.\n if (tsconfig.compilerOptions?.composite) {\n ret.push(path.relative(this.options.projectInfo.projectRoot, path.dirname(tsconfigFile)));\n } else {\n // Not a composite package--if this package is in a node_modules directory, that is most\n // likely correct, otherwise it is most likely an error (heuristic here, I don't know how to\n // properly check this).\n if (tsconfigFile.includes('node_modules')) {\n LOG.warn('%s: not a composite TypeScript package, but it probably should be', path.dirname(tsconfigFile));\n }\n }\n }\n\n return ret;\n }\n\n /**\n * Find source files using the same mechanism that the TypeScript compiler itself uses.\n *\n * Respects includes/excludes/etc.\n *\n * This makes it so that running 'typescript' and running 'jsii' has the same behavior.\n */\n private determineSources(files: string[]): string[] {\n const ret = new Array<string>();\n\n if (files.length > 0) {\n ret.push(...files);\n } else {\n const parseConfigHost = parseConfigHostFromCompilerHost(this.compilerHost);\n const parsed = ts.parseJsonConfigFileContent(\n this.typescriptConfig,\n parseConfigHost,\n this.options.projectInfo.projectRoot,\n );\n ret.push(...parsed.fileNames);\n }\n\n return ret;\n }\n\n /**\n * Resolve the given dependency name from the current package, and find the associated tsconfig.json location\n *\n * Because we have the following potential directory layout:\n *\n * package/node_modules/some_dependency\n * package/tsconfig.json\n *\n * We resolve symlinks and only find a \"TypeScript\" dependency if doesn't have 'node_modules' in\n * the path after resolving symlinks (i.e., if it's a peer package in the same monorepo).\n *\n * Returns undefined if no such tsconfig could be found.\n */\n private findMonorepoPeerTsconfig(depName: string): string | undefined {\n // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-var-requires\n const { builtinModules } = require('node:module');\n if ((builtinModules ?? []).includes(depName)) {\n // Can happen for modules like 'punycode' which are declared as dependency for polyfill purposes\n return undefined;\n }\n\n try {\n const depDir = findDependencyDirectory(depName, this.options.projectInfo.projectRoot);\n\n const dep = path.join(depDir, 'tsconfig.json');\n if (!fs.existsSync(dep)) {\n return undefined;\n }\n\n // Resolve symlinks, to check if this is a monorepo peer\n const dependencyRealPath = fs.realpathSync(dep);\n if (dependencyRealPath.split(path.sep).includes('node_modules')) {\n return undefined;\n }\n\n return dependencyRealPath;\n } catch (e: any) {\n // @types modules cannot be required, for example\n if (['MODULE_NOT_FOUND', 'ERR_PACKAGE_PATH_NOT_EXPORTED'].includes(e.code)) {\n return undefined;\n }\n throw e;\n }\n }\n\n private diagsHaveAbortableErrors(diags: readonly ts.Diagnostic[]) {\n return diags.some(\n (d) =>\n d.category === ts.DiagnosticCategory.Error ||\n (this.options.failOnWarnings && d.category === ts.DiagnosticCategory.Warning),\n );\n }\n}\n\n/**\n * Options for Watch in non-blocking mode.\n *\n * @internal\n */\nexport interface NonBlockingWatchOptions {\n /**\n * Signals non-blocking execution\n */\n readonly nonBlocking: true;\n\n /**\n * Configures the diagnostics reporter\n */\n readonly reportDiagnostics: ts.DiagnosticReporter;\n\n /**\n * Configures the watch status reporter\n */\n readonly reportWatchStatus: ts.WatchStatusReporter;\n\n /**\n * This hook gets invoked when a compilation cycle (complete with Assembler execution) completes.\n */\n readonly compilationComplete: (emitResult: ts.EmitResult) => void;\n}\n\nfunction _pathOfLibraries(host: ts.CompilerHost | ts.WatchCompilerHost<any>): string[] {\n if (!BASE_COMPILER_OPTIONS.lib || BASE_COMPILER_OPTIONS.lib.length === 0) {\n return [];\n }\n const lib = host.getDefaultLibLocation?.();\n if (!lib) {\n throw new Error(\n `Compiler host doesn't have a default library directory available for ${BASE_COMPILER_OPTIONS.lib.join(', ')}`,\n );\n }\n return BASE_COMPILER_OPTIONS.lib.map((name) => path.join(lib, name));\n}\n\nfunction parseConfigHostFromCompilerHost(host: ts.CompilerHost): ts.ParseConfigHost {\n // Copied from upstream\n // https://github.com/Microsoft/TypeScript/blob/9e05abcfd3f8bb3d6775144ede807daceab2e321/src/compiler/program.ts#L3105\n return {\n fileExists: (f) => host.fileExists(f),\n readDirectory(root, extensions, excludes, includes, depth) {\n if (host.readDirectory === undefined) {\n throw new Error(\"'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'\");\n }\n return host.readDirectory(root, extensions, excludes, includes, depth);\n },\n readFile: (f) => host.readFile(f),\n useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),\n trace: host.trace ? (s) => host.trace!(s) : undefined,\n };\n}\n"]}
1
+ {"version":3,"file":"compiler.js","sourceRoot":"","sources":["../src/compiler.ts"],"names":[],"mappings":";;;AAAA,8BAA8B;AAC9B,kCAAkC;AAClC,+BAA+B;AAC/B,iCAAiC;AACjC,iCAAiC;AAEjC,2CAAwC;AACxC,+BAA+B;AAC/B,oDAA8D;AAC9D,mDAA4E;AAE5E,uDAAmD;AAEnD,4EAA2E;AAC3E,iCAAiC;AAEjC,MAAM,qBAAqB,GAAuB;IAChD,YAAY,EAAE,IAAI;IAClB,WAAW,EAAE,IAAI;IACjB,sBAAsB,EAAE,IAAI;IAC5B,WAAW,EAAE,IAAI;IACjB,GAAG,EAAE,CA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AC,UAAU,CAAC,CAAC,CAAC;QACrC,aAAa,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK;YACvD,IAAI,IAAI,CAAC,aAAa,KAAK,SAAS,EAAE,CAAC;gBACrC,MAAM,IAAI,KAAK,CAAC,2FAA2F,CAAC,CAAC;YAC/G,CAAC;YACD,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;QACzE,CAAC;QACD,QAAQ,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QACjC,yBAAyB,EAAE,IAAI,CAAC,yBAAyB,EAAE;QAC3D,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,KAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;KACtD,CAAC;AACJ,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as chalk from 'chalk';\nimport * as log4js from 'log4js';\nimport * as ts from 'typescript';\n\nimport { Assembler } from './assembler';\nimport * as Case from './case';\nimport { findDependencyDirectory } from './common/find-utils';\nimport { emitDownleveledDeclarations, TYPES_COMPAT } from './downlevel-dts';\nimport { Emitter } from './emitter';\nimport { JsiiDiagnostic } from './jsii-diagnostic';\nimport { ProjectInfo } from './project-info';\nimport { WARNINGSCODE_FILE_NAME } from './transforms/deprecation-warnings';\nimport * as utils from './utils';\n\nconst BASE_COMPILER_OPTIONS: ts.CompilerOptions = {\n alwaysStrict: true,\n declaration: true,\n experimentalDecorators: true,\n incremental: true,\n lib: ['lib.es2020.d.ts'],\n module: ts.ModuleKind.CommonJS,\n noEmitOnError: true,\n noFallthroughCasesInSwitch: true,\n noImplicitAny: true,\n noImplicitReturns: true,\n noImplicitThis: true,\n noUnusedLocals: true,\n noUnusedParameters: true,\n resolveJsonModule: true,\n skipLibCheck: true,\n strict: true,\n strictNullChecks: true,\n strictPropertyInitialization: true,\n stripInternal: false,\n target: ts.ScriptTarget.ES2020,\n};\n\nconst LOG = log4js.getLogger('jsii/compiler');\nexport const DIAGNOSTICS = 'diagnostics';\nexport const JSII_DIAGNOSTICS_CODE = 9999;\n\nexport interface CompilerOptions {\n /** The information about the project to be built */\n projectInfo: ProjectInfo;\n /** Whether the compiler should watch for changes or just compile once */\n watch?: boolean;\n /** Whether to detect and generate TypeScript project references */\n projectReferences?: boolean;\n /** Whether to fail when a warning is emitted */\n failOnWarnings?: boolean;\n /** Whether to strip deprecated members from emitted artifacts */\n stripDeprecated?: boolean;\n /** The path to an allowlist of FQNs to strip if stripDeprecated is set */\n stripDeprecatedAllowListFile?: string;\n /** Whether to add warnings for deprecated elements */\n addDeprecationWarnings?: boolean;\n /**\n * The name of the tsconfig file to generate\n * @default \"tsconfig.json\"\n */\n generateTypeScriptConfig?: string;\n /**\n * Whether to compress the assembly\n * @default false\n */\n compressAssembly?: boolean;\n}\n\nexport interface TypescriptConfig {\n compilerOptions: ts.CompilerOptions;\n include?: string[];\n exclude?: string[];\n references?: ts.ProjectReference[];\n}\n\nexport class Compiler implements Emitter {\n private readonly system: ts.System;\n private readonly compilerHost: ts.CompilerHost;\n private typescriptConfig?: TypescriptConfig;\n private rootFiles: string[] = [];\n private readonly configPath: string;\n private readonly projectReferences: boolean;\n\n public constructor(private readonly options: CompilerOptions) {\n const rootDir = this.options.projectInfo.projectRoot;\n this.system = {\n ...ts.sys,\n getCurrentDirectory: () => rootDir,\n createDirectory: (pth) => ts.sys.createDirectory(path.resolve(rootDir, pth)),\n deleteFile: ts.sys.deleteFile && ((pth) => ts.sys.deleteFile!(path.join(rootDir, pth))),\n fileExists: (pth) => ts.sys.fileExists(path.resolve(rootDir, pth)),\n getFileSize: ts.sys.getFileSize && ((pth) => ts.sys.getFileSize!(path.resolve(rootDir, pth))),\n readFile: (pth, encoding) => ts.sys.readFile(path.resolve(rootDir, pth), encoding),\n watchFile:\n ts.sys.watchFile &&\n ((pth, callback, pollingInterval, watchOptions) =>\n ts.sys.watchFile!(path.resolve(rootDir, pth), callback, pollingInterval, watchOptions)),\n writeFile: (pth, data, writeByteOrderMark) =>\n ts.sys.writeFile(path.resolve(rootDir, pth), data, writeByteOrderMark),\n };\n this.compilerHost = ts.createIncrementalCompilerHost(BASE_COMPILER_OPTIONS, this.system);\n\n const configFileName = options.generateTypeScriptConfig ?? 'tsconfig.json';\n\n this.configPath = path.join(this.options.projectInfo.projectRoot, configFileName);\n\n this.projectReferences =\n options.projectReferences !== undefined\n ? options.projectReferences\n : options.projectInfo.projectReferences !== undefined\n ? options.projectInfo.projectReferences\n : false;\n }\n\n /**\n * Compiles the configured program.\n *\n * @param files can be specified to override the standard source code location logic. Useful for example when testing \"negatives\".\n */\n public emit(...files: string[]): ts.EmitResult {\n this._prepareForBuild(...files);\n return this._buildOnce();\n }\n\n /**\n * Watches for file-system changes and dynamically recompiles the project as needed. In non-blocking mode, this\n * returns the TypeScript watch handle for the application to use.\n *\n * @internal\n */\n public async watch(opts: NonBlockingWatchOptions): Promise<ts.Watch<ts.BuilderProgram>>;\n /**\n * Watches for file-system changes and dynamically recompiles the project as needed. In blocking mode, this results\n * in a never-resolving promise.\n */\n public async watch(): Promise<never>;\n public async watch(opts?: NonBlockingWatchOptions): Promise<ts.Watch<ts.BuilderProgram> | never> {\n this._prepareForBuild();\n\n const pi = this.options.projectInfo;\n const projectRoot = pi.projectRoot;\n const host = ts.createWatchCompilerHost(\n this.configPath,\n {\n ...pi.tsc,\n ...BASE_COMPILER_OPTIONS,\n noEmitOnError: false,\n },\n this.system,\n ts.createEmitAndSemanticDiagnosticsBuilderProgram,\n opts?.reportDiagnostics,\n opts?.reportWatchStatus,\n );\n if (!host.getDefaultLibLocation) {\n throw new Error('No default library location was found on the TypeScript compiler host!');\n }\n const orig = host.afterProgramCreate;\n // This is a callback cascade, so it's \"okay\" to return an unhandled promise there. This may\n // cause an unhandled promise rejection warning, but that's not a big deal.\n //\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n host.afterProgramCreate = (builderProgram) => {\n const emitResult = this._consumeProgram(builderProgram.getProgram(), host.getDefaultLibLocation!());\n\n for (const diag of emitResult.diagnostics.filter((d) => d.code === JSII_DIAGNOSTICS_CODE)) {\n utils.logDiagnostic(diag, projectRoot);\n }\n\n if (orig) {\n orig.call(host, builderProgram);\n }\n if (opts?.compilationComplete) {\n opts.compilationComplete(emitResult);\n }\n };\n const watch = ts.createWatchProgram(host);\n\n if (opts?.nonBlocking) {\n // In non-blocking mode, returns the handle to the TypeScript watch interface.\n return watch;\n }\n // In blocking mode, returns a never-resolving promise.\n return new Promise<never>(() => null);\n }\n\n /**\n * Prepares the project for build, by creating the necessary configuration\n * file(s), and assigning the relevant root file(s).\n *\n * @param files the files that were specified as input in the CLI invocation.\n */\n private _prepareForBuild(...files: string[]) {\n this.buildTypeScriptConfig();\n this.writeTypeScriptConfig();\n this.rootFiles = this.determineSources(files);\n }\n\n /**\n * Do a single build\n */\n private _buildOnce(): ts.EmitResult {\n if (!this.compilerHost.getDefaultLibLocation) {\n throw new Error('No default library location was found on the TypeScript compiler host!');\n }\n\n const tsconf = this.typescriptConfig!;\n const pi = this.options.projectInfo;\n\n const prog = ts.createIncrementalProgram({\n rootNames: this.rootFiles.concat(_pathOfLibraries(this.compilerHost)),\n options: {\n ...pi.tsc,\n ...(tsconf?.compilerOptions ?? BASE_COMPILER_OPTIONS),\n },\n // Make the references absolute for the compiler\n projectReferences: tsconf.references?.map((ref) => ({\n path: path.resolve(path.dirname(this.configPath), ref.path),\n })),\n host: this.compilerHost,\n });\n\n return this._consumeProgram(prog.getProgram(), this.compilerHost.getDefaultLibLocation());\n }\n\n private _consumeProgram(program: ts.Program, stdlib: string): ts.EmitResult {\n const diagnostics = [...ts.getPreEmitDiagnostics(program)];\n let hasErrors = false;\n\n if (!hasErrors && this.diagsHaveAbortableErrors(diagnostics)) {\n hasErrors = true;\n LOG.error('Compilation errors prevented the JSII assembly from being created');\n }\n\n // Do the \"Assembler\" part first because we need some of the analysis done in there\n // to post-process the AST\n const assembler = new Assembler(this.options.projectInfo, this.system, program, stdlib, {\n stripDeprecated: this.options.stripDeprecated,\n stripDeprecatedAllowListFile: this.options.stripDeprecatedAllowListFile,\n addDeprecationWarnings: this.options.addDeprecationWarnings,\n compressAssembly: this.options.compressAssembly,\n });\n\n try {\n const assmEmit = assembler.emit();\n if (!hasErrors && (assmEmit.emitSkipped || this.diagsHaveAbortableErrors(assmEmit.diagnostics))) {\n hasErrors = true;\n LOG.error('Type model errors prevented the JSII assembly from being created');\n }\n\n diagnostics.push(...assmEmit.diagnostics);\n } catch (e: any) {\n diagnostics.push(JsiiDiagnostic.JSII_9997_UNKNOWN_ERROR.createDetached(e));\n hasErrors = true;\n }\n\n // Do the emit, but add in transformers which are going to replace real\n // comments with synthetic ones.\n const emit = program.emit(\n undefined, // targetSourceFile\n undefined, // writeFile\n undefined, // cancellationToken\n undefined, // emitOnlyDtsFiles\n assembler.customTransformers,\n );\n diagnostics.push(...emit.diagnostics);\n\n if (!hasErrors && (emit.emitSkipped || this.diagsHaveAbortableErrors(emit.diagnostics))) {\n hasErrors = true;\n LOG.error('Compilation errors prevented the JSII assembly from being created');\n }\n\n if (!hasErrors) {\n emitDownleveledDeclarations(this.options.projectInfo);\n }\n\n // Some extra validation on the config.\n // Make sure that { \"./.warnings.jsii.js\": \"./.warnings.jsii.js\" } is in the set of\n // exports, if they are specified.\n if (this.options.addDeprecationWarnings && this.options.projectInfo.exports !== undefined) {\n const expected = `./${WARNINGSCODE_FILE_NAME}`;\n const warningsExport = Object.entries(this.options.projectInfo.exports).filter(\n ([k, v]) => k === expected && v === expected,\n );\n\n if (warningsExport.length === 0) {\n hasErrors = true;\n diagnostics.push(JsiiDiagnostic.JSII_0007_MISSING_WARNINGS_EXPORT.createDetached());\n }\n }\n\n return {\n emitSkipped: hasErrors,\n diagnostics: ts.sortAndDeduplicateDiagnostics(diagnostics),\n emittedFiles: emit.emittedFiles,\n };\n }\n\n /**\n * Build the TypeScript config object\n *\n * This is the object that will be written to disk.\n */\n private buildTypeScriptConfig() {\n let references: string[] | undefined;\n if (this.projectReferences) {\n references = this.findProjectReferences();\n }\n\n const pi = this.options.projectInfo;\n\n this.typescriptConfig = {\n compilerOptions: {\n ...pi.tsc,\n ...BASE_COMPILER_OPTIONS,\n // Enable composite mode if project references are enabled\n composite: this.projectReferences,\n // When incremental, configure a tsbuildinfo file\n tsBuildInfoFile: path.join(pi.tsc?.outDir ?? '.', 'tsconfig.tsbuildinfo'),\n },\n include: [pi.tsc?.rootDir != null ? path.join(pi.tsc.rootDir, '**', '*.ts') : path.join('**', '*.ts')],\n exclude: [\n 'node_modules',\n pi.tsc?.outDir != null ? path.resolve(pi.tsc.outDir, TYPES_COMPAT) : TYPES_COMPAT,\n ...(pi.excludeTypescript ?? []),\n ...(pi.tsc?.outDir != null &&\n (pi.tsc?.rootDir == null || path.resolve(pi.tsc.outDir).startsWith(path.resolve(pi.tsc.rootDir) + path.sep))\n ? [path.join(pi.tsc.outDir, '**', '*.ts')]\n : []),\n ],\n // Change the references a little. We write 'originalpath' to the\n // file under the 'path' key, which is the same as what the\n // TypeScript compiler does. Make it relative so that the files are\n // movable. Not strictly required but looks better.\n references: references?.map((p) => ({ path: p })),\n };\n }\n\n /**\n * Creates a `tsconfig.json` file to improve the IDE experience.\n *\n * @return the fully qualified path to the `tsconfig.json` file\n */\n private writeTypeScriptConfig(): void {\n const commentKey = '_generated_by_jsii_';\n const commentValue = 'Generated by jsii - safe to delete, and ideally should be in .gitignore';\n\n (this.typescriptConfig as any)[commentKey] = commentValue;\n\n if (fs.existsSync(this.configPath)) {\n const currentConfig = JSON.parse(fs.readFileSync(this.configPath, 'utf-8'));\n if (!(commentKey in currentConfig)) {\n throw new Error(\n `A '${this.configPath}' file that was not generated by jsii is in ${this.options.projectInfo.projectRoot}. Aborting instead of overwriting.`,\n );\n }\n }\n\n const outputConfig = {\n ...this.typescriptConfig,\n compilerOptions: {\n ...this.typescriptConfig?.compilerOptions,\n lib: this.typescriptConfig?.compilerOptions?.lib?.map((lib) =>\n // Drop the \"lib.\" prefix and \".d.ts\" suffix before writing up the tsconfig.json file\n lib.slice(4, lib.length - 5),\n ),\n // Re-write the module, targets & jsx to be the JSON format instead of Programmatic API\n module: (this.typescriptConfig?.compilerOptions?.module &&\n ts.ModuleKind[this.typescriptConfig.compilerOptions.module]) as any,\n newLine: newLineForTsconfigJson(this.typescriptConfig?.compilerOptions.newLine),\n target: (this.typescriptConfig?.compilerOptions?.target &&\n ts.ScriptTarget[this.typescriptConfig.compilerOptions.target]) as any,\n jsx: (this.typescriptConfig?.compilerOptions?.jsx &&\n Case.snake(ts.JsxEmit[this.typescriptConfig.compilerOptions.jsx])) as any,\n },\n };\n\n LOG.debug(`Creating or updating ${chalk.blue(this.configPath)}`);\n fs.writeFileSync(this.configPath, JSON.stringify(outputConfig, null, 2), 'utf8');\n\n /**\n * This is annoying - the values expected in the tsconfig.json file are not\n * the same as the enum constant names, or their values. So we need this\n * function to map the \"compiler API version\" to the \"tsconfig.json version\"\n *\n * @param newLine the compiler form of the new line configuration\n *\n * @return the requivalent value to put in tsconfig.json\n */\n function newLineForTsconfigJson(newLine: ts.NewLineKind | undefined) {\n switch (newLine) {\n case ts.NewLineKind.CarriageReturnLineFeed:\n return 'crlf';\n case ts.NewLineKind.LineFeed:\n return 'lf';\n default:\n return undefined;\n }\n }\n }\n\n /**\n * Find all dependencies that look like TypeScript projects.\n *\n * Enumerate all dependencies, if they have a tsconfig.json file with\n * \"composite: true\" we consider them project references.\n *\n * (Note: TypeScript seems to only correctly find transitive project references\n * if there's an \"index\" tsconfig.json of all projects somewhere up the directory\n * tree)\n */\n private findProjectReferences(): string[] {\n const pkg = this.options.projectInfo.packageJson;\n\n const ret = new Array<string>();\n\n const dependencyNames = new Set<string>();\n for (const dependencyMap of [pkg.dependencies, pkg.devDependencies, pkg.peerDependencies]) {\n if (dependencyMap === undefined) {\n continue;\n }\n for (const name of Object.keys(dependencyMap)) {\n dependencyNames.add(name);\n }\n }\n\n for (const tsconfigFile of Array.from(dependencyNames).map((depName) => this.findMonorepoPeerTsconfig(depName))) {\n if (!tsconfigFile) {\n continue;\n }\n\n const { config: tsconfig } = ts.readConfigFile(tsconfigFile, this.system.readFile);\n\n // Add references to any TypeScript package we find that is 'composite' enabled.\n // Make it relative.\n if (tsconfig.compilerOptions?.composite) {\n ret.push(path.relative(this.options.projectInfo.projectRoot, path.dirname(tsconfigFile)));\n } else {\n // Not a composite package--if this package is in a node_modules directory, that is most\n // likely correct, otherwise it is most likely an error (heuristic here, I don't know how to\n // properly check this).\n if (tsconfigFile.includes('node_modules')) {\n LOG.warn('%s: not a composite TypeScript package, but it probably should be', path.dirname(tsconfigFile));\n }\n }\n }\n\n return ret;\n }\n\n /**\n * Find source files using the same mechanism that the TypeScript compiler itself uses.\n *\n * Respects includes/excludes/etc.\n *\n * This makes it so that running 'typescript' and running 'jsii' has the same behavior.\n */\n private determineSources(files: string[]): string[] {\n const ret = new Array<string>();\n\n if (files.length > 0) {\n ret.push(...files);\n } else {\n const parseConfigHost = parseConfigHostFromCompilerHost(this.compilerHost);\n const parsed = ts.parseJsonConfigFileContent(\n this.typescriptConfig,\n parseConfigHost,\n this.options.projectInfo.projectRoot,\n );\n ret.push(...parsed.fileNames);\n }\n\n return ret;\n }\n\n /**\n * Resolve the given dependency name from the current package, and find the associated tsconfig.json location\n *\n * Because we have the following potential directory layout:\n *\n * package/node_modules/some_dependency\n * package/tsconfig.json\n *\n * We resolve symlinks and only find a \"TypeScript\" dependency if doesn't have 'node_modules' in\n * the path after resolving symlinks (i.e., if it's a peer package in the same monorepo).\n *\n * Returns undefined if no such tsconfig could be found.\n */\n private findMonorepoPeerTsconfig(depName: string): string | undefined {\n // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-var-requires\n const { builtinModules } = require('node:module');\n if ((builtinModules ?? []).includes(depName)) {\n // Can happen for modules like 'punycode' which are declared as dependency for polyfill purposes\n return undefined;\n }\n\n try {\n const depDir = findDependencyDirectory(depName, this.options.projectInfo.projectRoot);\n\n const dep = path.join(depDir, 'tsconfig.json');\n if (!fs.existsSync(dep)) {\n return undefined;\n }\n\n // Resolve symlinks, to check if this is a monorepo peer\n const dependencyRealPath = fs.realpathSync(dep);\n if (dependencyRealPath.split(path.sep).includes('node_modules')) {\n return undefined;\n }\n\n return dependencyRealPath;\n } catch (e: any) {\n // @types modules cannot be required, for example\n if (['MODULE_NOT_FOUND', 'ERR_PACKAGE_PATH_NOT_EXPORTED'].includes(e.code)) {\n return undefined;\n }\n throw e;\n }\n }\n\n private diagsHaveAbortableErrors(diags: readonly ts.Diagnostic[]) {\n return diags.some(\n (d) =>\n d.category === ts.DiagnosticCategory.Error ||\n (this.options.failOnWarnings && d.category === ts.DiagnosticCategory.Warning),\n );\n }\n}\n\n/**\n * Options for Watch in non-blocking mode.\n *\n * @internal\n */\nexport interface NonBlockingWatchOptions {\n /**\n * Signals non-blocking execution\n */\n readonly nonBlocking: true;\n\n /**\n * Configures the diagnostics reporter\n */\n readonly reportDiagnostics: ts.DiagnosticReporter;\n\n /**\n * Configures the watch status reporter\n */\n readonly reportWatchStatus: ts.WatchStatusReporter;\n\n /**\n * This hook gets invoked when a compilation cycle (complete with Assembler execution) completes.\n */\n readonly compilationComplete: (emitResult: ts.EmitResult) => void;\n}\n\nfunction _pathOfLibraries(host: ts.CompilerHost | ts.WatchCompilerHost<any>): string[] {\n if (!BASE_COMPILER_OPTIONS.lib || BASE_COMPILER_OPTIONS.lib.length === 0) {\n return [];\n }\n const lib = host.getDefaultLibLocation?.();\n if (!lib) {\n throw new Error(\n `Compiler host doesn't have a default library directory available for ${BASE_COMPILER_OPTIONS.lib.join(', ')}`,\n );\n }\n return BASE_COMPILER_OPTIONS.lib.map((name) => path.join(lib, name));\n}\n\nfunction parseConfigHostFromCompilerHost(host: ts.CompilerHost): ts.ParseConfigHost {\n // Copied from upstream\n // https://github.com/Microsoft/TypeScript/blob/9e05abcfd3f8bb3d6775144ede807daceab2e321/src/compiler/program.ts#L3105\n return {\n fileExists: (f) => host.fileExists(f),\n readDirectory(root, extensions, excludes, includes, depth) {\n if (host.readDirectory === undefined) {\n throw new Error(\"'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'\");\n }\n return host.readDirectory(root, extensions, excludes, includes, depth);\n },\n readFile: (f) => host.readFile(f),\n useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),\n trace: host.trace ? (s) => host.trace!(s) : undefined,\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"directives.js","sourceRoot":"","sources":["../src/directives.ts"],"names":[],"mappings":";;;;;;;;;AAAA,iCAAiC;AACjC,uDAAmD;AAEnD;;GAEG;AACH,MAAa,UAAU;IACrB;;;;;;OAMG;IACI,MAAM,CAAC,EAAE,CAAC,IAAa,EAAE,YAA4C;QAC1E,MAAM,KAAK,GAAG,uBAAA,EAAU,6BAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC1C,IAAI,KAAK,IAAI,IAAI,EAAE;YACjB,OAAO,KAAK,CAAC;SACd;QAED,MAAM,UAAU,GAAG,IAAI,EAAU,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;QACtD,uBAAA,EAAU,6BAAO,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;QACxC,OAAO,UAAU,CAAC;IACpB,CAAC;IAWD,YAAoB,IAAa,EAAE,YAA4C;QAC7E,KAAK,MAAM,GAAG,IAAI,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE;YACvC,QAAQ,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE;gBACxB,KAAK,UAAU;oBACb,IAAI,CAAC,UAAU,KAAf,IAAI,CAAC,UAAU,GAAK,GAAG,EAAC;oBACxB,MAAM;gBACR,KAAK,MAAM;oBACT,MAAM,QAA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IACzF,OAAO,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,SAAS,EAAa,EAAE;QAClD,IAAI,IAAY,CAAC;QACjB,QAAQ,SAAS,CAAC,IAAI,EAAE;YACtB,KAAK,EAAE,CAAC,UAAU,CAAC,SAAS;gBAC1B,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC;gBACtB,MAAM;YACR,KAAK,EAAE,CAAC,UAAU,CAAC,SAAS,CAAC;YAC7B,KAAK,EAAE,CAAC,UAAU,CAAC,aAAa,CAAC;YACjC,KAAK,EAAE,CAAC,UAAU,CAAC,cAAc;gBAC/B,IAAI,GAAG,SAAS,CAAC,IAAI;oBACnB,CAAC,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC,KAAK,SAAS,CAAC,IAAI,EAAE;oBAChF,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC;gBACnB,MAAM;SACT;QACD,IAAI,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;QACnB,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC3C,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import * as ts from 'typescript';\nimport { JsiiDiagnostic } from './jsii-diagnostic';\n\n/**\n * TSDoc-style directives that can be attached to a symbol.\n */\nexport class Directives {\n /**\n * Obtains the `Directives` for a given TypeScript AST node.\n *\n * @param node the node for which directives are requested.\n * @param onDiagnostic a callback invoked whenever a diagnostic message is\n * emitted when parsing directives.\n */\n public static of(node: ts.Node, onDiagnostic: (diag: JsiiDiagnostic) => void): Directives {\n const found = Directives.#CACHE.get(node);\n if (found != null) {\n return found;\n }\n\n const directives = new Directives(node, onDiagnostic);\n Directives.#CACHE.set(node, directives);\n return directives;\n }\n\n static readonly #CACHE = new WeakMap<ts.Node, Directives>();\n\n /** Whether the node has the `@internal` JSDoc tag. */\n public readonly tsInternal?: ts.JSDocTag;\n /** Whether the node has the `@jsii ignore` directive set. */\n public readonly ignore?: ts.JSDocComment | ts.JSDocTag;\n /** Whether the node has the `@jsii struct` directive set. */\n public readonly struct?: ts.JSDocComment | ts.JSDocTag;\n\n private constructor(node: ts.Node, onDiagnostic: (diag: JsiiDiagnostic) => void) {\n for (const tag of ts.getJSDocTags(node)) {\n switch (tag.tagName.text) {\n case 'internal':\n this.tsInternal ??= tag;\n break;\n case 'jsii':\n const comments = getComments(tag);\n if (comments.length === 0) {\n onDiagnostic(JsiiDiagnostic.JSII_2000_MISSING_DIRECTIVE_ARGUMENT.create(tag));\n continue;\n }\n for (const { text, jsdocNode } of comments) {\n switch (text) {\n case 'ignore':\n this.ignore ??= jsdocNode;\n break;\n default:\n onDiagnostic(JsiiDiagnostic.JSII_2999_UNKNOWN_DIRECTIVE.create(jsdocNode, text));\n break;\n }\n }\n break;\n default: // Ignore\n }\n }\n }\n}\n\nfunction getComments(tag: ts.JSDocTag): Comment[] {\n if (tag.comment == null) {\n return [];\n }\n\n if (typeof tag.comment === 'string') {\n const text = tag.comment.trim();\n return text\n ? text.split(/[\\n,]/).flatMap((line) => {\n line = line.trim();\n return line ? [{ text: line, jsdocNode: tag }] : [];\n })\n : [];\n }\n\n // Possible per the type signature in the compiler, however not sure in which conditions.\n return tag.comment.flatMap((jsdocNode): Comment[] => {\n let text: string;\n switch (jsdocNode.kind) {\n case ts.SyntaxKind.JSDocText:\n text = jsdocNode.text;\n break;\n case ts.SyntaxKind.JSDocLink:\n case ts.SyntaxKind.JSDocLinkCode:\n case ts.SyntaxKind.JSDocLinkPlain:\n text = jsdocNode.name\n ? `${jsdocNode.name.getText(jsdocNode.name.getSourceFile())}: ${jsdocNode.text}`\n : jsdocNode.text;\n break;\n }\n text = text.trim();\n return text ? [{ text, jsdocNode }] : [];\n });\n}\n\ninterface Comment {\n readonly text: string;\n readonly jsdocNode: ts.JSDocComment | ts.JSDocTag;\n}\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UAAU,CAAC,aAAa,CAAC;YACjC,KAAK,EAAE,CAAC,UAAU,CAAC,cAAc;gBAC/B,IAAI,GAAG,SAAS,CAAC,IAAI;oBACnB,CAAC,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC,KAAK,SAAS,CAAC,IAAI,EAAE;oBAChF,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC;gBACnB,MAAM;QACV,CAAC;QACD,IAAI,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;QACnB,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC3C,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import * as ts from 'typescript';\nimport { JsiiDiagnostic } from './jsii-diagnostic';\n\n/**\n * TSDoc-style directives that can be attached to a symbol.\n */\nexport class Directives {\n /**\n * Obtains the `Directives` for a given TypeScript AST node.\n *\n * @param node the node for which directives are requested.\n * @param onDiagnostic a callback invoked whenever a diagnostic message is\n * emitted when parsing directives.\n */\n public static of(node: ts.Node, onDiagnostic: (diag: JsiiDiagnostic) => void): Directives {\n const found = Directives.#CACHE.get(node);\n if (found != null) {\n return found;\n }\n\n const directives = new Directives(node, onDiagnostic);\n Directives.#CACHE.set(node, directives);\n return directives;\n }\n\n static readonly #CACHE = new WeakMap<ts.Node, Directives>();\n\n /** Whether the node has the `@internal` JSDoc tag. */\n public readonly tsInternal?: ts.JSDocTag;\n /** Whether the node has the `@jsii ignore` directive set. */\n public readonly ignore?: ts.JSDocComment | ts.JSDocTag;\n /** Whether the node has the `@jsii struct` directive set. */\n public readonly struct?: ts.JSDocComment | ts.JSDocTag;\n\n private constructor(node: ts.Node, onDiagnostic: (diag: JsiiDiagnostic) => void) {\n for (const tag of ts.getJSDocTags(node)) {\n switch (tag.tagName.text) {\n case 'internal':\n this.tsInternal ??= tag;\n break;\n case 'jsii':\n const comments = getComments(tag);\n if (comments.length === 0) {\n onDiagnostic(JsiiDiagnostic.JSII_2000_MISSING_DIRECTIVE_ARGUMENT.create(tag));\n continue;\n }\n for (const { text, jsdocNode } of comments) {\n switch (text) {\n case 'ignore':\n this.ignore ??= jsdocNode;\n break;\n default:\n onDiagnostic(JsiiDiagnostic.JSII_2999_UNKNOWN_DIRECTIVE.create(jsdocNode, text));\n break;\n }\n }\n break;\n default: // Ignore\n }\n }\n }\n}\n\nfunction getComments(tag: ts.JSDocTag): Comment[] {\n if (tag.comment == null) {\n return [];\n }\n\n if (typeof tag.comment === 'string') {\n const text = tag.comment.trim();\n return text\n ? text.split(/[\\n,]/).flatMap((line) => {\n line = line.trim();\n return line ? [{ text: line, jsdocNode: tag }] : [];\n })\n : [];\n }\n\n // Possible per the type signature in the compiler, however not sure in which conditions.\n return tag.comment.flatMap((jsdocNode): Comment[] => {\n let text: string;\n switch (jsdocNode.kind) {\n case ts.SyntaxKind.JSDocText:\n text = jsdocNode.text;\n break;\n case ts.SyntaxKind.JSDocLink:\n case ts.SyntaxKind.JSDocLinkCode:\n case ts.SyntaxKind.JSDocLinkPlain:\n text = jsdocNode.name\n ? `${jsdocNode.name.getText(jsdocNode.name.getSourceFile())}: ${jsdocNode.text}`\n : jsdocNode.text;\n break;\n }\n text = text.trim();\n return text ? [{ text, jsdocNode }] : [];\n });\n}\n\ninterface Comment {\n readonly text: string;\n readonly jsdocNode: ts.JSDocComment | ts.JSDocTag;\n}\n"]}
package/lib/docs.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"docs.js","sourceRoot":"","sources":["../src/docs.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,mCAAmC;AACnC,iCAAiC;AAEjC;;GAEG;AACH,IAAK,MAiBJ;AAjBD,WAAK,MAAM;IACT,yBAAe,CAAA;IACf,6BAAmB,CAAA;IACnB,wCAA8B,CAAA;IAC9B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AC,EAAE;gBAClE,2DAA2D;gBAC3D,MAAA,GAAG,CAAC,CAAC,CAAC,EAAC,IAAI,QAAJ,IAAI,GAAK,EAAE,EAAC;gBACnB,GAAG,CAAC,CAAC,CAAC,CAAC,IAAK,CAAC,IAAI,CAAC;oBAChB,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE;oBAC7C,IAAI,EAAE,EAAE;iBACT,CAAC,CAAC;gBACH,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;aACtB;SACF;QACD,CAAC,EAAE,CAAC;KACL;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Doc Comment parsing\n *\n * I tried using TSDoc here.\n *\n * Pro:\n * - Future standard.\n * - Does validating parsing and complains on failure.\n * - Has a more flexible interpretation of the @example tag (starts in text mode).\n *\n * Con:\n * - Different tags from JSDoc (@defaultValue instead of @default, \"@param name\n * description\" instead \"@param name description\".\n * - @example tag has a different interpretation than VSCode and JSDoc\n * (VSCode/JSDoc starts in code mode), which is confusing for syntax\n * highlighting in the editor.\n * - Allows no unknown tags.\n * - Wants to be in charge of parsing TypeScript, integrating into other build is\n * possible but harder.\n * - Parse to a DOM with no easy way to roundtrip back to equivalent MarkDown.\n *\n * Especially the last point: while parsing to and storing the parsed docs DOM\n * in the jsii assembly is superior in the long term (for example for\n * converting to different output formats, JavaDoc, C# docs, refdocs which all\n * accept slightly different syntaxes), right now we can get 80% of the bang\n * for 10% of the buck by just reading, storing and reproducing MarkDown, which\n * is Readable Enough(tm).\n *\n * If we ever want to attempt TSDoc again, this would be a good place to look at:\n *\n * https://github.com/Microsoft/tsdoc/blob/master/api-demo/src/advancedDemo.ts\n */\nimport * as spec from '@jsii/spec';\nimport * as ts from 'typescript';\n\n/**\n * Tags that we recognize\n */\nenum DocTag {\n PARAM = 'param',\n DEFAULT = 'default',\n DEFAULT_VALUE = 'defaultValue',\n DEPRECATED = 'deprecated',\n RETURNS = 'returns',\n RETURN = 'return',\n STABLE = 'stable',\n EXPERIMENTAL = 'experimental',\n SEE = 'see',\n SUBCLASSABLE = 'subclassable',\n EXAMPLE = 'example',\n STABILITY = 'stability',\n STRUCT = 'struct',\n\n // Not forwarded, this is compiler-internal.\n JSII = 'jsii',\n}\n\nconst RECOGNIZED_TAGS: ReadonlySet<String> = new Set(Object.values(DocTag));\n\n/**\n * Parse all doc comments that apply to a symbol into JSIIDocs format\n */\nexport function parseSymbolDocumentation(sym: ts.Symbol, typeChecker: ts.TypeChecker): DocsParsingResult {\n const comment = ts.displayPartsToString(sym.getDocumentationComment(typeChecker)).trim();\n const tags = reabsorbExampleTags(sym.getJsDocTags());\n\n // Right here we'll just guess that the first declaration site is the most important one.\n return parseDocParts(comment, tags);\n}\n\n/**\n * Return the list of parameter names that are referenced in the docstring for this symbol\n */\nexport function getReferencedDocParams(sym: ts.Symbol): string[] {\n const ret = new Array<string>();\n for (const tag of sym.getJsDocTags()) {\n if (tag.name === DocTag.PARAM) {\n const parts = ts.displayPartsToString(tag.text).split(' ');\n ret.push(parts[0]);\n }\n }\n return ret;\n}\n\nfunction parseDocParts(comments: string | undefined, tags: ts.JSDocTagInfo[]): DocsParsingResult {\n const diagnostics = new Array<string>();\n const docs: spec.Docs = {};\n const hints: TypeSystemHints = {};\n\n [docs.summary, docs.remarks] = splitSummary(comments);\n\n const tagNames = new Map<string, string | undefined>();\n for (const tag of tags) {\n // 'param' gets parsed as a tag and as a comment for a method\n // 'jsii' is internal-only and shouldn't surface in the API doc\n if (tag.name !== DocTag.PARAM && tag.name !== DocTag.JSII) {\n tagNames.set(tag.name, tag.text && ts.displayPartsToString(tag.text));\n }\n }\n\n function eatTag(...names: string[]): string | undefined {\n for (const name of names) {\n if (tagNames.has(name)) {\n const ret = tagNames.get(name);\n tagNames.delete(name);\n return ret ?? '';\n }\n }\n return undefined;\n }\n\n if (eatTag(DocTag.STRUCT) != null) {\n hints.struct = true;\n }\n\n docs.default = eatTag(DocTag.DEFAULT, DocTag.DEFAULT_VALUE);\n docs.deprecated = eatTag(DocTag.DEPRECATED);\n docs.example = eatTag(DocTag.EXAMPLE);\n docs.returns = eatTag(DocTag.RETURNS, DocTag.RETURN);\n docs.see = eatTag(DocTag.SEE);\n docs.subclassable = eatTag(DocTag.SUBCLASSABLE) !== undefined ? true : undefined;\n\n docs.stability = parseStability(eatTag(DocTag.STABILITY), diagnostics);\n // @experimental is a shorthand for '@stability experimental', same for '@stable'\n const experimental = eatTag(DocTag.EXPERIMENTAL) !== undefined;\n const stable = eatTag(DocTag.STABLE) !== undefined;\n // Can't combine them\n if (countBools(docs.stability !== undefined, experimental, stable) > 1) {\n diagnostics.push('Use only one of @stability, @experimental or @stable');\n }\n if (experimental) {\n docs.stability = spec.Stability.Experimental;\n }\n if (stable) {\n docs.stability = spec.Stability.Stable;\n }\n\n // Can combine '@stability deprecated' with '@deprecated <reason>'\n if (docs.deprecated !== undefined) {\n if (docs.stability !== undefined && docs.stability !== spec.Stability.Deprecated) {\n diagnostics.push(\"@deprecated tag requires '@stability deprecated' or no @stability at all.\");\n }\n docs.stability = spec.Stability.Deprecated;\n }\n\n if (docs.example?.includes('```')) {\n // This is currently what the JSDoc standard expects, and VSCode highlights it in\n // this way as well. TSDoc disagrees and says that examples start in text mode\n // which I tend to agree with, but that hasn't become a widely used standard yet.\n //\n // So we conform to existing reality.\n diagnostics.push('@example must be code only, no code block fences allowed.');\n }\n\n if (docs.deprecated?.trim() === '') {\n diagnostics.push('@deprecated tag needs a reason and/or suggested alternatives.');\n }\n\n if (tagNames.size > 0) {\n docs.custom = {};\n for (const [key, value] of tagNames.entries()) {\n docs.custom[key] = value ?? 'true'; // Key must have a value or it will be stripped from the assembly\n }\n }\n\n return { docs, diagnostics, hints };\n}\n\nexport interface DocsParsingResult {\n docs: spec.Docs;\n hints: TypeSystemHints;\n diagnostics?: string[];\n}\n\nexport interface TypeSystemHints {\n /**\n * Only present on interfaces. This indicates that interface must be handled as a struct/data type\n * even through it's name starts with a capital letter `I`.\n */\n struct?: boolean;\n}\n\n/**\n * Split the doc comment into summary and remarks\n *\n * Normally, we'd expect people to split into a summary line and detail lines using paragraph\n * markers. However, a LOT of people do not do this, and just paste a giant comment block into\n * the docstring. If we detect that situation, we will try and extract the first sentence (using\n * a period) as the summary.\n */\nexport function splitSummary(docBlock: string | undefined): [string | undefined, string | undefined] {\n if (!docBlock) {\n return [undefined, undefined];\n }\n const summary = summaryLine(docBlock);\n const remarks = uberTrim(docBlock.slice(summary.length));\n return [endWithPeriod(noNewlines(summary.trim())), remarks];\n}\n\n/**\n * Replace newlines with spaces for use in tables\n */\nfunction noNewlines(s: string) {\n return s.replace(/\\n/g, ' ');\n}\n\nfunction endWithPeriod(s: string) {\n return ENDS_WITH_PUNCTUATION_REGEX.test(s) ? s : `${s}.`;\n}\n\n/**\n * Trims a string and turns it into `undefined` if the result would have been an\n * empty string.\n */\nfunction uberTrim(str: string): string | undefined {\n str = str.trim();\n return str === '' ? undefined : str;\n}\n\nconst SUMMARY_MAX_WORDS = 20;\n\n/**\n * Find the summary line for a doc comment\n *\n * In principle we'll take the first paragraph, but if there are no paragraphs\n * (because people don't put in paragraph breaks) or the first paragraph is too\n * long, we'll take the first sentence (terminated by a punctuation).\n */\nfunction summaryLine(str: string) {\n const paras = str.split('\\n\\n');\n if (paras.length > 1 && paras[0].split(' ').length < SUMMARY_MAX_WORDS) {\n return paras[0];\n }\n\n const m = FIRST_SENTENCE_REGEX.exec(str);\n if (m) {\n return m[1];\n }\n\n return paras[0];\n}\n\nconst PUNCTUATION = ['!', '?', '.', ';'].map((s) => `\\\\${s}`).join('');\nconst ENDS_WITH_PUNCTUATION_REGEX = new RegExp(`[${PUNCTUATION}]$`);\nconst FIRST_SENTENCE_REGEX = new RegExp(`^([^${PUNCTUATION}]+[${PUNCTUATION}][ \\n\\r])`); // Needs a whitespace after the punctuation.\n\nfunction intBool(x: boolean): number {\n return x ? 1 : 0;\n}\n\nfunction countBools(...x: boolean[]) {\n return x.map(intBool).reduce((a, b) => a + b, 0);\n}\n\nfunction parseStability(s: string | undefined, diagnostics: string[]): spec.Stability | undefined {\n if (s === undefined) {\n return undefined;\n }\n\n switch (s) {\n case 'stable':\n return spec.Stability.Stable;\n case 'experimental':\n return spec.Stability.Experimental;\n case 'external':\n return spec.Stability.External;\n case 'deprecated':\n return spec.Stability.Deprecated;\n }\n diagnostics.push(`Unrecognized @stability: '${s}'`);\n return undefined;\n}\n\n/**\n * Unrecognized tags that follow an '@ example' tag will be absorbed back into the example value\n *\n * The TypeScript parser by itself is naive and will start parsing a new tag there.\n *\n * We do this until we encounter a supported @ keyword.\n */\nfunction reabsorbExampleTags(tags: ts.JSDocTagInfo[]): ts.JSDocTagInfo[] {\n const ret = [...tags];\n\n let i = 0;\n while (i < ret.length) {\n if (ret[i].name === 'example') {\n while (i + 1 < ret.length && !RECOGNIZED_TAGS.has(ret[i + 1].name)) {\n // Incorrectly classified as @tag, absorb back into example\n ret[i].text ??= [];\n ret[i].text!.push({\n text: `@${ret[i + 1].name}${ret[i + 1].text}`,\n kind: '',\n });\n ret.splice(i + 1, 1);\n }\n }\n i++;\n }\n\n return ret;\n}\n"]}
1
+ {"version":3,"file":"docs.js","sourceRoot":"","sources":["../src/docs.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,mCAAmC;AACnC,iCAAiC;AAEjC;;GAEG;AACH,IAAK,MAiBJ;AAjBD,WAAK,MAAM;IACT,yBAAe,CAAA;IACf,6BAAmB,CAAA;IACnB,wCAA8B,CAAA;IAC9B,mCAAyB,CAAA;IACzB,6BAAmB,CAAA;IACnB,2BAAiB,CAAA;IACjB,2BAAiB,CAAA;IACjB,uCAA6B,CAAA;IAC7B,qBAAW,CAAA;IACX,uCAA6B,CAAA;IAC7B,6BAAmB,CAAA;IACnB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CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;gBACnE,2DAA2D;gBAC3D,MAAA,GAAG,CAAC,CAAC,CAAC,EAAC,IAAI,QAAJ,IAAI,GAAK,EAAE,EAAC;gBACnB,GAAG,CAAC,CAAC,CAAC,CAAC,IAAK,CAAC,IAAI,CAAC;oBAChB,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE;oBAC7C,IAAI,EAAE,EAAE;iBACT,CAAC,CAAC;gBACH,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;YACvB,CAAC;QACH,CAAC;QACD,CAAC,EAAE,CAAC;IACN,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Doc Comment parsing\n *\n * I tried using TSDoc here.\n *\n * Pro:\n * - Future standard.\n * - Does validating parsing and complains on failure.\n * - Has a more flexible interpretation of the @example tag (starts in text mode).\n *\n * Con:\n * - Different tags from JSDoc (@defaultValue instead of @default, \"@param name\n * description\" instead \"@param name description\".\n * - @example tag has a different interpretation than VSCode and JSDoc\n * (VSCode/JSDoc starts in code mode), which is confusing for syntax\n * highlighting in the editor.\n * - Allows no unknown tags.\n * - Wants to be in charge of parsing TypeScript, integrating into other build is\n * possible but harder.\n * - Parse to a DOM with no easy way to roundtrip back to equivalent MarkDown.\n *\n * Especially the last point: while parsing to and storing the parsed docs DOM\n * in the jsii assembly is superior in the long term (for example for\n * converting to different output formats, JavaDoc, C# docs, refdocs which all\n * accept slightly different syntaxes), right now we can get 80% of the bang\n * for 10% of the buck by just reading, storing and reproducing MarkDown, which\n * is Readable Enough(tm).\n *\n * If we ever want to attempt TSDoc again, this would be a good place to look at:\n *\n * https://github.com/Microsoft/tsdoc/blob/master/api-demo/src/advancedDemo.ts\n */\nimport * as spec from '@jsii/spec';\nimport * as ts from 'typescript';\n\n/**\n * Tags that we recognize\n */\nenum DocTag {\n PARAM = 'param',\n DEFAULT = 'default',\n DEFAULT_VALUE = 'defaultValue',\n DEPRECATED = 'deprecated',\n RETURNS = 'returns',\n RETURN = 'return',\n STABLE = 'stable',\n EXPERIMENTAL = 'experimental',\n SEE = 'see',\n SUBCLASSABLE = 'subclassable',\n EXAMPLE = 'example',\n STABILITY = 'stability',\n STRUCT = 'struct',\n\n // Not forwarded, this is compiler-internal.\n JSII = 'jsii',\n}\n\nconst RECOGNIZED_TAGS: ReadonlySet<String> = new Set(Object.values(DocTag));\n\n/**\n * Parse all doc comments that apply to a symbol into JSIIDocs format\n */\nexport function parseSymbolDocumentation(sym: ts.Symbol, typeChecker: ts.TypeChecker): DocsParsingResult {\n const comment = ts.displayPartsToString(sym.getDocumentationComment(typeChecker)).trim();\n const tags = reabsorbExampleTags(sym.getJsDocTags());\n\n // Right here we'll just guess that the first declaration site is the most important one.\n return parseDocParts(comment, tags);\n}\n\n/**\n * Return the list of parameter names that are referenced in the docstring for this symbol\n */\nexport function getReferencedDocParams(sym: ts.Symbol): string[] {\n const ret = new Array<string>();\n for (const tag of sym.getJsDocTags()) {\n if (tag.name === DocTag.PARAM) {\n const parts = ts.displayPartsToString(tag.text).split(' ');\n ret.push(parts[0]);\n }\n }\n return ret;\n}\n\nfunction parseDocParts(comments: string | undefined, tags: ts.JSDocTagInfo[]): DocsParsingResult {\n const diagnostics = new Array<string>();\n const docs: spec.Docs = {};\n const hints: TypeSystemHints = {};\n\n [docs.summary, docs.remarks] = splitSummary(comments);\n\n const tagNames = new Map<string, string | undefined>();\n for (const tag of tags) {\n // 'param' gets parsed as a tag and as a comment for a method\n // 'jsii' is internal-only and shouldn't surface in the API doc\n if (tag.name !== DocTag.PARAM && tag.name !== DocTag.JSII) {\n tagNames.set(tag.name, tag.text && ts.displayPartsToString(tag.text));\n }\n }\n\n function eatTag(...names: string[]): string | undefined {\n for (const name of names) {\n if (tagNames.has(name)) {\n const ret = tagNames.get(name);\n tagNames.delete(name);\n return ret ?? '';\n }\n }\n return undefined;\n }\n\n if (eatTag(DocTag.STRUCT) != null) {\n hints.struct = true;\n }\n\n docs.default = eatTag(DocTag.DEFAULT, DocTag.DEFAULT_VALUE);\n docs.deprecated = eatTag(DocTag.DEPRECATED);\n docs.example = eatTag(DocTag.EXAMPLE);\n docs.returns = eatTag(DocTag.RETURNS, DocTag.RETURN);\n docs.see = eatTag(DocTag.SEE);\n docs.subclassable = eatTag(DocTag.SUBCLASSABLE) !== undefined ? true : undefined;\n\n docs.stability = parseStability(eatTag(DocTag.STABILITY), diagnostics);\n // @experimental is a shorthand for '@stability experimental', same for '@stable'\n const experimental = eatTag(DocTag.EXPERIMENTAL) !== undefined;\n const stable = eatTag(DocTag.STABLE) !== undefined;\n // Can't combine them\n if (countBools(docs.stability !== undefined, experimental, stable) > 1) {\n diagnostics.push('Use only one of @stability, @experimental or @stable');\n }\n if (experimental) {\n docs.stability = spec.Stability.Experimental;\n }\n if (stable) {\n docs.stability = spec.Stability.Stable;\n }\n\n // Can combine '@stability deprecated' with '@deprecated <reason>'\n if (docs.deprecated !== undefined) {\n if (docs.stability !== undefined && docs.stability !== spec.Stability.Deprecated) {\n diagnostics.push(\"@deprecated tag requires '@stability deprecated' or no @stability at all.\");\n }\n docs.stability = spec.Stability.Deprecated;\n }\n\n if (docs.example?.includes('```')) {\n // This is currently what the JSDoc standard expects, and VSCode highlights it in\n // this way as well. TSDoc disagrees and says that examples start in text mode\n // which I tend to agree with, but that hasn't become a widely used standard yet.\n //\n // So we conform to existing reality.\n diagnostics.push('@example must be code only, no code block fences allowed.');\n }\n\n if (docs.deprecated?.trim() === '') {\n diagnostics.push('@deprecated tag needs a reason and/or suggested alternatives.');\n }\n\n if (tagNames.size > 0) {\n docs.custom = {};\n for (const [key, value] of tagNames.entries()) {\n docs.custom[key] = value ?? 'true'; // Key must have a value or it will be stripped from the assembly\n }\n }\n\n return { docs, diagnostics, hints };\n}\n\nexport interface DocsParsingResult {\n docs: spec.Docs;\n hints: TypeSystemHints;\n diagnostics?: string[];\n}\n\nexport interface TypeSystemHints {\n /**\n * Only present on interfaces. This indicates that interface must be handled as a struct/data type\n * even through it's name starts with a capital letter `I`.\n */\n struct?: boolean;\n}\n\n/**\n * Split the doc comment into summary and remarks\n *\n * Normally, we'd expect people to split into a summary line and detail lines using paragraph\n * markers. However, a LOT of people do not do this, and just paste a giant comment block into\n * the docstring. If we detect that situation, we will try and extract the first sentence (using\n * a period) as the summary.\n */\nexport function splitSummary(docBlock: string | undefined): [string | undefined, string | undefined] {\n if (!docBlock) {\n return [undefined, undefined];\n }\n const summary = summaryLine(docBlock);\n const remarks = uberTrim(docBlock.slice(summary.length));\n return [endWithPeriod(noNewlines(summary.trim())), remarks];\n}\n\n/**\n * Replace newlines with spaces for use in tables\n */\nfunction noNewlines(s: string) {\n return s.replace(/\\n/g, ' ');\n}\n\nfunction endWithPeriod(s: string) {\n return ENDS_WITH_PUNCTUATION_REGEX.test(s) ? s : `${s}.`;\n}\n\n/**\n * Trims a string and turns it into `undefined` if the result would have been an\n * empty string.\n */\nfunction uberTrim(str: string): string | undefined {\n str = str.trim();\n return str === '' ? undefined : str;\n}\n\nconst SUMMARY_MAX_WORDS = 20;\n\n/**\n * Find the summary line for a doc comment\n *\n * In principle we'll take the first paragraph, but if there are no paragraphs\n * (because people don't put in paragraph breaks) or the first paragraph is too\n * long, we'll take the first sentence (terminated by a punctuation).\n */\nfunction summaryLine(str: string) {\n const paras = str.split('\\n\\n');\n if (paras.length > 1 && paras[0].split(' ').length < SUMMARY_MAX_WORDS) {\n return paras[0];\n }\n\n const m = FIRST_SENTENCE_REGEX.exec(str);\n if (m) {\n return m[1];\n }\n\n return paras[0];\n}\n\nconst PUNCTUATION = ['!', '?', '.', ';'].map((s) => `\\\\${s}`).join('');\nconst ENDS_WITH_PUNCTUATION_REGEX = new RegExp(`[${PUNCTUATION}]$`);\nconst FIRST_SENTENCE_REGEX = new RegExp(`^([^${PUNCTUATION}]+[${PUNCTUATION}][ \\n\\r])`); // Needs a whitespace after the punctuation.\n\nfunction intBool(x: boolean): number {\n return x ? 1 : 0;\n}\n\nfunction countBools(...x: boolean[]) {\n return x.map(intBool).reduce((a, b) => a + b, 0);\n}\n\nfunction parseStability(s: string | undefined, diagnostics: string[]): spec.Stability | undefined {\n if (s === undefined) {\n return undefined;\n }\n\n switch (s) {\n case 'stable':\n return spec.Stability.Stable;\n case 'experimental':\n return spec.Stability.Experimental;\n case 'external':\n return spec.Stability.External;\n case 'deprecated':\n return spec.Stability.Deprecated;\n }\n diagnostics.push(`Unrecognized @stability: '${s}'`);\n return undefined;\n}\n\n/**\n * Unrecognized tags that follow an '@ example' tag will be absorbed back into the example value\n *\n * The TypeScript parser by itself is naive and will start parsing a new tag there.\n *\n * We do this until we encounter a supported @ keyword.\n */\nfunction reabsorbExampleTags(tags: ts.JSDocTagInfo[]): ts.JSDocTagInfo[] {\n const ret = [...tags];\n\n let i = 0;\n while (i < ret.length) {\n if (ret[i].name === 'example') {\n while (i + 1 < ret.length && !RECOGNIZED_TAGS.has(ret[i + 1].name)) {\n // Incorrectly classified as @tag, absorb back into example\n ret[i].text ??= [];\n ret[i].text!.push({\n text: `@${ret[i + 1].name}${ret[i + 1].text}`,\n kind: '',\n });\n ret.splice(i + 1, 1);\n }\n }\n i++;\n }\n\n return ret;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"downlevel-dts.js","sourceRoot":"","sources":["../src/downlevel-dts.ts"],"names":[],"mappings":";;;AAAA,qCAUiB;AACjB,qCAAiC;AACjC,yCAA8D;AAC9D,iDAAkD;AAClD,iCAAiC;AACjC,mCAAgC;AAChC,iCAAiC;AAIpB,QAAA,YAAY,GAAG,eAAe,CAAC;AAE5C,MAAM,GAAG,GAAG,MAAM,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;AA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AAG,CAAC,CAAC,CAAC;SACjE;QAED,OAAO,UAAU,CAAC;IACpB,CAAC,CAAC;IAEF,IAAI,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;IACnC,KAAK,GAAG,qBAAqB,CAAC,KAAK,CAAC,CAAC;IAErC,OAAO,IAAI,KAAK,KAAK,CAAC;AACxB,CAAC;AAED;;;;;;GAMG;AACH,QAAQ,CAAC,CAAC,aAAa,CAAC,GAAW,EAAE,OAAe,GAAG;IACrD,KAAK,MAAM,IAAI,IAAI,IAAA,qBAAW,EAAC,GAAG,CAAC,EAAE;QACnC,MAAM,QAAQ,GAAG,IAAA,gBAAI,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACjC,IAAI,IAAA,kBAAQ,EAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,EAAE;YACpC,uCAAuC;YACvC,KAAK,CAAC,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;SACtC;aAAM,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;YAC/C,0CAA0C;YAC1C,MAAM,IAAA,oBAAQ,EAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;SAChC;KACF;AACH,CAAC","sourcesContent":["import {\n copyFileSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { basename, dirname, join, relative } from 'node:path';\nimport { main as downlevel } from 'downlevel-dts';\nimport * as log4js from 'log4js';\nimport { SemVer } from 'semver';\nimport * as ts from 'typescript';\nimport type { PackageJson, ProjectInfo } from './project-info';\nimport type { Mutable } from './utils';\n\nexport const TYPES_COMPAT = '.types-compat';\n\nconst LOG = log4js.getLogger('jsii/compiler');\n\nconst TS_VERSION = new SemVer(`${ts.versionMajorMinor}.0`);\n\n/**\n * Declares what versions of the TypeScript language will be supported by the\n * declarations files (and `typesVersions` entries) produced by this compiler\n * release.\n *\n * This should contain only `major.minor` specifiers, similar to the value of\n * the `ts.versionMajorMinor` property, and must be sorted in ascending version\n * order, as this dictates the order of entries in the `typesVersions` redirects\n * which has a direct impact on resolution (first match wins), and we don't want\n * to have to perform a sort pass on this list.\n */\nconst DOWNLEVEL_BREAKPOINTS: readonly SemVer[] = ['3.9'].map((ver) => new SemVer(`${ver}.0`));\n\n/**\n * Produces down-leveled declaration files to ensure compatibility with previous\n * compiler releases (macthing TypeScript's `major.minor` versioning scheme).\n * This is necessary in order to ensure a package change compiler release lines\n * does not force all it's consumers to do the same (and vice-versa).\n *\n * @returns the `typesVersions` object that should be recorded in `package.json`\n */\nexport function emitDownleveledDeclarations({ packageJson, projectRoot, tsc }: ProjectInfo) {\n const compatRoot = join(projectRoot, ...(tsc?.outDir != null ? [tsc?.outDir] : []), TYPES_COMPAT);\n rmSync(compatRoot, { force: true, recursive: true });\n\n const rewrites = new Set<`${number}.${number}`>();\n\n for (const breakpoint of DOWNLEVEL_BREAKPOINTS) {\n if (TS_VERSION.compare(breakpoint) <= 0) {\n // This TypeScript release is older or same as the breakpoint, so no need\n // for down-leveling here.\n continue;\n }\n\n const rewriteSet = new Map<string, string>();\n let needed = false;\n\n // We'll emit down-leveled declarations in a temporary directory...\n const workdir = mkdtempSync(join(tmpdir(), `downlevel-dts-${breakpoint}-${basename(projectRoot)}-`));\n try {\n downlevel(projectRoot, workdir, breakpoint.version);\n const projectOutDir = tsc?.outDir != null ? join(projectRoot, tsc.outDir) : projectRoot;\n const workOutDir = tsc?.outDir != null ? join(workdir, tsc.outDir) : workdir;\n for (const dts of walkDirectory(workOutDir)) {\n const original = readFileSync(join(projectOutDir, dts), 'utf-8');\n const downleveledPath = join(workOutDir, dts);\n const downleveled = readFileSync(downleveledPath, 'utf-8');\n needed ||= !semanticallyEqualDeclarations(original, downleveled);\n rewriteSet.set(dts, downleveledPath);\n }\n\n // If none of the declarations files changed during the down-level, then\n // we don't need to actually write it out & cause a redirect. This would\n // be wasteful. Most codebases won't incur any rewrite at all, since the\n // declarations files only reference \"visible\" members, and `jsii`\n // actually does not allow most of the unsupported syntaxes to be used\n // anyway.\n if (needed) {\n rewrites.add(`${breakpoint.major}.${breakpoint.minor}`);\n\n const versionSuffix = `ts${breakpoint.major}.${breakpoint.minor}`;\n const compatDir = join(compatRoot, versionSuffix);\n if (!existsSync(compatDir)) {\n mkdirSync(compatDir, { recursive: true });\n try {\n // Write an empty .npmignore file so that npm pack doesn't use the .gitignore file...\n writeFileSync(join(compatRoot, '.npmignore'), '\\n', 'utf-8');\n // Make sure all of this is gitignored, out of courtesy...\n writeFileSync(join(compatRoot, '.gitignore'), '*\\n', 'utf-8');\n } catch {\n // Ignore any error here... This is inconsequential.\n }\n }\n\n for (const [dts, downleveledPath] of rewriteSet) {\n const rewritten = join(compatDir, dts);\n // Make sure the parent directory exists (dts might be nested)\n mkdirSync(dirname(rewritten), { recursive: true });\n // Write the re-written declarations file there...\n copyFileSync(downleveledPath, rewritten);\n }\n }\n } finally {\n // Clean up after outselves...\n rmSync(workdir, { force: true, recursive: true });\n }\n }\n\n let typesVersions: Mutable<PackageJson['typesVersions']>;\n\n for (const version of rewrites) {\n // Register the type redirect in the typesVersions configuration\n typesVersions ??= {};\n const from = [...(tsc?.outDir != null ? [tsc?.outDir] : []), '*'].join('/');\n const to = [...(tsc?.outDir != null ? [tsc?.outDir] : []), TYPES_COMPAT, `ts${version}`, '*'].join('/');\n // We put 2 candidate redirects (first match wins), so that it works for nested imports, too (see: https://github.com/microsoft/TypeScript/issues/43133)\n typesVersions[`<=${version}`] = { [from]: [to, `${to}/index.d.ts`] };\n }\n\n // Compare JSON stringifications, as the order of keys is important here...\n if (JSON.stringify(packageJson.typesVersions) === JSON.stringify(typesVersions)) {\n // The existing configuration matches the new one. We're done here.\n return;\n }\n\n LOG.info('The required `typesVersions` configuration has changed. Updating \"package.json\" accordingly...');\n\n // Prepare the new contents of `PackageJson`.\n const newPackageJson = Object.entries(packageJson).reduce((obj, [key, value]) => {\n // NB: \"as any\" below are required becuase we must ignore `readonly` attributes from the source.\n if (key === 'typesVersions') {\n if (typesVersions != null) {\n obj[key] = typesVersions as any;\n }\n } else {\n obj[key] = value as any;\n // If there isn't currently a `typesVersions` entry, but there is a `types` entry,\n // we'll insert `typesVersions` right after `types`.\n if (key === 'types' && typesVersions != null && !('typesVersions' in packageJson)) {\n obj.typesVersions = typesVersions as any;\n }\n }\n return obj;\n }, {} as Mutable<PackageJson>);\n // If there was neither `types` nor `typesVersions` in the original `package.json`, we'll\n // add `typesVersions` at the end of it.\n if (!('typesVersions' in newPackageJson)) {\n newPackageJson.typesVersions = typesVersions as any;\n }\n\n const packageJsonFile = join(projectRoot, 'package.json');\n\n // We try \"hard\" to preserve the existing indent in the `package.json` file when updating it.\n const [, indent] = readFileSync(packageJsonFile, 'utf-8').match(/^(\\s*)\"/m) ?? [null, 2];\n\n writeFileSync(packageJsonFile, `${JSON.stringify(newPackageJson, undefined, indent)}\\n`, 'utf-8');\n}\n\n/**\n * Compares the contents of two declaration files semantically.\n *\n * @param left the first string.\n * @param right the second string.\n *\n * @returns `true` if `left` and `right` contain the same declarations.\n */\nfunction semanticallyEqualDeclarations(left: string, right: string): boolean {\n // We normalize declarations largely by parsing & re-printing them.\n const normalizeDeclarations = (code: string): string => {\n const sourceFile = ts.createSourceFile('index.d.ts', code, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);\n const printer = ts.createPrinter({\n newLine: ts.NewLineKind.LineFeed,\n noEmitHelpers: true,\n omitTrailingSemicolon: false,\n removeComments: true,\n });\n let normalized = printer.printFile(sourceFile);\n\n // TypeScript may emit duplicated reference declarations... which are absent from Downlevel-DTS' output...\n // https://github.com/microsoft/TypeScript/issues/48143\n const REFERENCES_TYPES_NODE = '/// <reference types=\"node\" />';\n while (normalized.startsWith(`${REFERENCES_TYPES_NODE}\\n${REFERENCES_TYPES_NODE}`)) {\n normalized = normalized.slice(REFERENCES_TYPES_NODE.length + 1);\n }\n\n return normalized;\n };\n\n left = normalizeDeclarations(left);\n right = normalizeDeclarations(right);\n\n return left === right;\n}\n\n/**\n * Recursively traverse the provided directory and yield the relative (to the\n * specified `root`) paths of all the `.d.ts` files found there.\n *\n * @param dir the directory to be walked.\n * @param root the root to which paths should be relative.\n */\nfunction* walkDirectory(dir: string, root: string = dir): Generator<string, void, void> {\n for (const file of readdirSync(dir)) {\n const filePath = join(dir, file);\n if (statSync(filePath).isDirectory()) {\n // This is a directory, recurse down...\n yield* walkDirectory(filePath, root);\n } else if (file.toLowerCase().endsWith('.d.ts')) {\n // This is a declaration file, yield it...\n yield relative(root, filePath);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"downlevel-dts.js","sourceRoot":"","sources":["../src/downlevel-dts.ts"],"names":[],"mappings":";;;AAAA,qCAUiB;AACjB,qCAAiC;AACjC,yCAA8D;AAC9D,iDAAkD;AAClD,iCAAiC;AACjC,mCAAgC;AAChC,iCAAiC;AAIpB,QAAA,YAAY,GAAG,eAAe,CAAC;AAE5C,MAAM,GAAG,GAAG,MAAM,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;AAE9C,MAAM,UAAU,GAAG,IAAI,eAAM,CAAC,GAAG,EAAE,CAAC,iBAAiB,IAAI,CAAC,CAAC;AAE3D;;;;;;;;;;GAUG;AACH,MAAM,qBAAqB,GAAsB,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,eAAM,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC;AAE9F;;;;;;;GAOG;AACH,SAAgB,2BAA2B,CAAC,EAAE,WAAW,EAAE,WAAW,EAAE,GAAG,EAAe;IACxF,MAAM,UAAU,GAAG,IAAA,gBAAI,EAAC,WAAW,EAAE,GAAG,CAAC,GAAG,EAAE,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,oBA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AI,IAAI,IAAA,qBAAW,EAAC,GAAG,CAAC,EAAE,CAAC;QACpC,MAAM,QAAQ,GAAG,IAAA,gBAAI,EAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACjC,IAAI,IAAA,kBAAQ,EAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC;YACrC,uCAAuC;YACvC,KAAK,CAAC,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QACvC,CAAC;aAAM,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;YAChD,0CAA0C;YAC1C,MAAM,IAAA,oBAAQ,EAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import {\n copyFileSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { basename, dirname, join, relative } from 'node:path';\nimport { main as downlevel } from 'downlevel-dts';\nimport * as log4js from 'log4js';\nimport { SemVer } from 'semver';\nimport * as ts from 'typescript';\nimport type { PackageJson, ProjectInfo } from './project-info';\nimport type { Mutable } from './utils';\n\nexport const TYPES_COMPAT = '.types-compat';\n\nconst LOG = log4js.getLogger('jsii/compiler');\n\nconst TS_VERSION = new SemVer(`${ts.versionMajorMinor}.0`);\n\n/**\n * Declares what versions of the TypeScript language will be supported by the\n * declarations files (and `typesVersions` entries) produced by this compiler\n * release.\n *\n * This should contain only `major.minor` specifiers, similar to the value of\n * the `ts.versionMajorMinor` property, and must be sorted in ascending version\n * order, as this dictates the order of entries in the `typesVersions` redirects\n * which has a direct impact on resolution (first match wins), and we don't want\n * to have to perform a sort pass on this list.\n */\nconst DOWNLEVEL_BREAKPOINTS: readonly SemVer[] = ['3.9'].map((ver) => new SemVer(`${ver}.0`));\n\n/**\n * Produces down-leveled declaration files to ensure compatibility with previous\n * compiler releases (macthing TypeScript's `major.minor` versioning scheme).\n * This is necessary in order to ensure a package change compiler release lines\n * does not force all it's consumers to do the same (and vice-versa).\n *\n * @returns the `typesVersions` object that should be recorded in `package.json`\n */\nexport function emitDownleveledDeclarations({ packageJson, projectRoot, tsc }: ProjectInfo) {\n const compatRoot = join(projectRoot, ...(tsc?.outDir != null ? [tsc?.outDir] : []), TYPES_COMPAT);\n rmSync(compatRoot, { force: true, recursive: true });\n\n const rewrites = new Set<`${number}.${number}`>();\n\n for (const breakpoint of DOWNLEVEL_BREAKPOINTS) {\n if (TS_VERSION.compare(breakpoint) <= 0) {\n // This TypeScript release is older or same as the breakpoint, so no need\n // for down-leveling here.\n continue;\n }\n\n const rewriteSet = new Map<string, string>();\n let needed = false;\n\n // We'll emit down-leveled declarations in a temporary directory...\n const workdir = mkdtempSync(join(tmpdir(), `downlevel-dts-${breakpoint}-${basename(projectRoot)}-`));\n try {\n downlevel(projectRoot, workdir, breakpoint.version);\n const projectOutDir = tsc?.outDir != null ? join(projectRoot, tsc.outDir) : projectRoot;\n const workOutDir = tsc?.outDir != null ? join(workdir, tsc.outDir) : workdir;\n for (const dts of walkDirectory(workOutDir)) {\n const original = readFileSync(join(projectOutDir, dts), 'utf-8');\n const downleveledPath = join(workOutDir, dts);\n const downleveled = readFileSync(downleveledPath, 'utf-8');\n needed ||= !semanticallyEqualDeclarations(original, downleveled);\n rewriteSet.set(dts, downleveledPath);\n }\n\n // If none of the declarations files changed during the down-level, then\n // we don't need to actually write it out & cause a redirect. This would\n // be wasteful. Most codebases won't incur any rewrite at all, since the\n // declarations files only reference \"visible\" members, and `jsii`\n // actually does not allow most of the unsupported syntaxes to be used\n // anyway.\n if (needed) {\n rewrites.add(`${breakpoint.major}.${breakpoint.minor}`);\n\n const versionSuffix = `ts${breakpoint.major}.${breakpoint.minor}`;\n const compatDir = join(compatRoot, versionSuffix);\n if (!existsSync(compatDir)) {\n mkdirSync(compatDir, { recursive: true });\n try {\n // Write an empty .npmignore file so that npm pack doesn't use the .gitignore file...\n writeFileSync(join(compatRoot, '.npmignore'), '\\n', 'utf-8');\n // Make sure all of this is gitignored, out of courtesy...\n writeFileSync(join(compatRoot, '.gitignore'), '*\\n', 'utf-8');\n } catch {\n // Ignore any error here... This is inconsequential.\n }\n }\n\n for (const [dts, downleveledPath] of rewriteSet) {\n const rewritten = join(compatDir, dts);\n // Make sure the parent directory exists (dts might be nested)\n mkdirSync(dirname(rewritten), { recursive: true });\n // Write the re-written declarations file there...\n copyFileSync(downleveledPath, rewritten);\n }\n }\n } finally {\n // Clean up after outselves...\n rmSync(workdir, { force: true, recursive: true });\n }\n }\n\n let typesVersions: Mutable<PackageJson['typesVersions']>;\n\n for (const version of rewrites) {\n // Register the type redirect in the typesVersions configuration\n typesVersions ??= {};\n const from = [...(tsc?.outDir != null ? [tsc?.outDir] : []), '*'].join('/');\n const to = [...(tsc?.outDir != null ? [tsc?.outDir] : []), TYPES_COMPAT, `ts${version}`, '*'].join('/');\n // We put 2 candidate redirects (first match wins), so that it works for nested imports, too (see: https://github.com/microsoft/TypeScript/issues/43133)\n typesVersions[`<=${version}`] = { [from]: [to, `${to}/index.d.ts`] };\n }\n\n // Compare JSON stringifications, as the order of keys is important here...\n if (JSON.stringify(packageJson.typesVersions) === JSON.stringify(typesVersions)) {\n // The existing configuration matches the new one. We're done here.\n return;\n }\n\n LOG.info('The required `typesVersions` configuration has changed. Updating \"package.json\" accordingly...');\n\n // Prepare the new contents of `PackageJson`.\n const newPackageJson = Object.entries(packageJson).reduce((obj, [key, value]) => {\n // NB: \"as any\" below are required becuase we must ignore `readonly` attributes from the source.\n if (key === 'typesVersions') {\n if (typesVersions != null) {\n obj[key] = typesVersions as any;\n }\n } else {\n obj[key] = value as any;\n // If there isn't currently a `typesVersions` entry, but there is a `types` entry,\n // we'll insert `typesVersions` right after `types`.\n if (key === 'types' && typesVersions != null && !('typesVersions' in packageJson)) {\n obj.typesVersions = typesVersions as any;\n }\n }\n return obj;\n }, {} as Mutable<PackageJson>);\n // If there was neither `types` nor `typesVersions` in the original `package.json`, we'll\n // add `typesVersions` at the end of it.\n if (!('typesVersions' in newPackageJson)) {\n newPackageJson.typesVersions = typesVersions as any;\n }\n\n const packageJsonFile = join(projectRoot, 'package.json');\n\n // We try \"hard\" to preserve the existing indent in the `package.json` file when updating it.\n const [, indent] = readFileSync(packageJsonFile, 'utf-8').match(/^(\\s*)\"/m) ?? [null, 2];\n\n writeFileSync(packageJsonFile, `${JSON.stringify(newPackageJson, undefined, indent)}\\n`, 'utf-8');\n}\n\n/**\n * Compares the contents of two declaration files semantically.\n *\n * @param left the first string.\n * @param right the second string.\n *\n * @returns `true` if `left` and `right` contain the same declarations.\n */\nfunction semanticallyEqualDeclarations(left: string, right: string): boolean {\n // We normalize declarations largely by parsing & re-printing them.\n const normalizeDeclarations = (code: string): string => {\n const sourceFile = ts.createSourceFile('index.d.ts', code, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);\n const printer = ts.createPrinter({\n newLine: ts.NewLineKind.LineFeed,\n noEmitHelpers: true,\n omitTrailingSemicolon: false,\n removeComments: true,\n });\n let normalized = printer.printFile(sourceFile);\n\n // TypeScript may emit duplicated reference declarations... which are absent from Downlevel-DTS' output...\n // https://github.com/microsoft/TypeScript/issues/48143\n const REFERENCES_TYPES_NODE = '/// <reference types=\"node\" />';\n while (normalized.startsWith(`${REFERENCES_TYPES_NODE}\\n${REFERENCES_TYPES_NODE}`)) {\n normalized = normalized.slice(REFERENCES_TYPES_NODE.length + 1);\n }\n\n return normalized;\n };\n\n left = normalizeDeclarations(left);\n right = normalizeDeclarations(right);\n\n return left === right;\n}\n\n/**\n * Recursively traverse the provided directory and yield the relative (to the\n * specified `root`) paths of all the `.d.ts` files found there.\n *\n * @param dir the directory to be walked.\n * @param root the root to which paths should be relative.\n */\nfunction* walkDirectory(dir: string, root: string = dir): Generator<string, void, void> {\n for (const file of readdirSync(dir)) {\n const filePath = join(dir, file);\n if (statSync(filePath).isDirectory()) {\n // This is a directory, recurse down...\n yield* walkDirectory(filePath, root);\n } else if (file.toLowerCase().endsWith('.d.ts')) {\n // This is a declaration file, yield it...\n yield relative(root, filePath);\n }\n }\n}\n"]}
package/lib/helpers.js CHANGED
@@ -135,7 +135,7 @@ function makeProjectInfo(types, cb) {
135
135
  const packageJson = {
136
136
  types,
137
137
  main: types.replace(/(?:\.d)?\.ts(x?)/, '.js$1'),
138
- name: 'testpkg',
138
+ name: 'testpkg', // That's what package.json would tell if we look up...
139
139
  version: '0.0.1',
140
140
  license: 'Apache-2.0',
141
141
  author: { name: 'John Doe' },
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,8BAA8B;AAC9B,8BAA8B;AAC9B,kCAAkC;AAClC,qCAA8E;AAE9E,2CAAgD;AAEhD,yCAAuD;AACvD,iDAA8D;AAC9D,mCAA2C;AAU3C;;;;;;;;;GASG;AACH,SAAgB,sBAAsB,CACpC,MAAoC,EACpC,OAA+D;IAE/D,OAAO,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC;AACtD,CAAC;AALD,wDAKC;AAwBD;;;;;;;;;GASG;AACH,SAAgB,kBAAkB,CAChC,MAA+D,EAC/D,OAA+D,EAC/D,eAAgE;IAEhE,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;QAC9B,MAAM,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;KACjC;IAED,MAAM,cAAc,GAClB,eAAe,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAElH,oFAAoF;IACpF,+EAA+E;IAC/E,OAAO,cAAc,CAAC,GAAG,EAAE;QACzB,KAAK,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC,IAAI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B,CAAC,CAAC;YACH,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,YAAY,CAAC,CAAC;SAC7D;IACH,CAAC;IAEM,aAAa,CAAC,IAAY;QAC/B,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;YAC7B,MAAM,IAAI,KAAK,CAAC,4BAA4B,IAAI,sBAAsB,CAAC,CAAC;SACzE;QACD,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,cAAc,EAAE,IAAI,CAAC,CAAC;IAC7D,CAAC;IAEM,OAAO;QACZ,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAClE,CAAC;CACF;AA3ED,sCA2EC","sourcesContent":["/**\n * Helper routines for use with the jsii compiler\n *\n * These are mostly used for testing, but all projects that need to exercise\n * the JSII compiler to test something need to share this code, so might as\n * well put it in one reusable place.\n */\n\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { PackageJson, loadAssemblyFromPath, writeAssembly } from '@jsii/spec';\nimport * as spec from '@jsii/spec';\nimport { DiagnosticCategory } from 'typescript';\n\nimport { Compiler, CompilerOptions } from './compiler';\nimport { loadProjectInfo, ProjectInfo } from './project-info';\nimport { formatDiagnostic } from './utils';\n\n/**\n * A set of source files for `sourceToAssemblyHelper`, at least containing 'index.ts'\n */\nexport type MultipleSourceFiles = {\n 'index.ts': string;\n [name: string]: string;\n};\n\n/**\n * Compile a piece of source and return the JSII assembly for it\n *\n * Only usable for trivial cases and tests.\n *\n * @param source can either be a single `string` (the content of `index.ts`), or\n * a map of fileName to content, which *must* include `index.ts`.\n * @param options accepts a callback for historical reasons but really expects to\n * take an options object.\n */\nexport function sourceToAssemblyHelper(\n source: string | MultipleSourceFiles,\n options?: TestCompilationOptions | ((obj: PackageJson) => void),\n): spec.Assembly {\n return compileJsiiForTest(source, options).assembly;\n}\n\nexport interface HelperCompilationResult {\n /**\n * The generated assembly\n */\n readonly assembly: spec.Assembly;\n\n /**\n * Generated .js/.d.ts file(s)\n */\n readonly files: Record<string, string>;\n\n /**\n * The packageInfo used\n */\n readonly packageJson: PackageJson;\n\n /**\n * Whether to compress the assembly file\n */\n readonly compressAssembly: boolean;\n}\n\n/**\n * Compile a piece of source and return the assembly and compiled sources for it\n *\n * Only usable for trivial cases and tests.\n *\n * @param source can either be a single `string` (the content of `index.ts`), or\n * a map of fileName to content, which *must* include `index.ts`.\n * @param options accepts a callback for historical reasons but really expects to\n * take an options object.\n */\nexport function compileJsiiForTest(\n source: string | { 'index.ts': string; [name: string]: string },\n options?: TestCompilationOptions | ((obj: PackageJson) => void),\n compilerOptions?: Omit<CompilerOptions, 'projectInfo' | 'watch'>,\n): HelperCompilationResult {\n if (typeof source === 'string') {\n source = { 'index.ts': source };\n }\n\n const inSomeLocation =\n isOptionsObject(options) && options.compilationDirectory ? inOtherDir(options.compilationDirectory) : inTempDir;\n\n // Easiest way to get the source into the compiler is to write it to disk somewhere.\n // I guess we could make an in-memory compiler host but that seems like work...\n return inSomeLocation(() => {\n for (const [fileName, content] of Object.entries(source)) {\n fs.mkdirSync(path.dirname(fileName), { recursive: true });\n fs.writeFileSync(fileName, content, { encoding: 'utf-8' });\n }\n const { projectInfo, packageJson } = makeProjectInfo(\n 'index.ts',\n typeof options === 'function'\n ? options\n : (pi) => {\n Object.assign(pi, options?.packageJson ?? options?.projectInfo ?? {});\n },\n );\n const compiler = new Compiler({\n projectInfo,\n ...compilerOptions,\n });\n const emitResult = compiler.emit();\n\n const errors = emitResult.diagnostics.filter((d) => d.category === DiagnosticCategory.Error);\n for (const error of errors) {\n console.error(formatDiagnostic(error, projectInfo.projectRoot));\n // logDiagnostic() doesn't work out of the box, so console.error() it is.\n }\n if (errors.length > 0 || emitResult.emitSkipped) {\n throw new Error('There were compiler errors');\n }\n const assembly = loadAssemblyFromPath(process.cwd(), false);\n const files: Record<string, string> = {};\n\n for (const filename of Object.keys(source)) {\n let jsFile = filename.replace(/\\.ts$/, '.js');\n let dtsFile = filename.replace(/\\.ts$/, '.d.ts');\n if (projectInfo.tsc?.outDir && filename !== 'README.md') {\n jsFile = path.join(projectInfo.tsc.outDir, jsFile);\n dtsFile = path.join(projectInfo.tsc.outDir, dtsFile);\n }\n\n // eslint-disable-next-line no-await-in-loop\n files[jsFile] = fs.readFileSync(jsFile, { encoding: 'utf-8' });\n // eslint-disable-next-line no-await-in-loop\n files[dtsFile] = fs.readFileSync(dtsFile, { encoding: 'utf-8' });\n\n const warningsFileName = '.warnings.jsii.js';\n if (fs.existsSync(warningsFileName)) {\n // eslint-disable-next-line no-await-in-loop\n files[warningsFileName] = fs.readFileSync(warningsFileName, {\n encoding: 'utf-8',\n });\n }\n }\n\n return {\n assembly,\n files,\n packageJson,\n compressAssembly: isOptionsObject(options) && options.compressAssembly ? true : false,\n } as HelperCompilationResult;\n });\n}\n\nfunction inTempDir<T>(block: () => T): T {\n const origDir = process.cwd();\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsii'));\n process.chdir(tmpDir);\n const ret = block();\n process.chdir(origDir);\n fs.rmSync(tmpDir, { force: true, recursive: true });\n return ret;\n}\n\nfunction inOtherDir(dir: string) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint\n return <T extends unknown>(block: () => T): T => {\n const origDir = process.cwd();\n process.chdir(dir);\n try {\n return block();\n } finally {\n process.chdir(origDir);\n }\n };\n}\n\n/**\n * Obtain project info so we can call the compiler\n *\n * Creating this directly in-memory leads to slightly different behavior from calling\n * jsii from the command-line, and I don't want to figure out right now.\n *\n * Most consistent behavior seems to be to write a package.json to disk and\n * then calling the same functions as the CLI would.\n */\nfunction makeProjectInfo(\n types: string,\n cb?: (obj: PackageJson) => void,\n): { projectInfo: ProjectInfo; packageJson: PackageJson } {\n const packageJson: PackageJson = {\n types,\n main: types.replace(/(?:\\.d)?\\.ts(x?)/, '.js$1'),\n name: 'testpkg', // That's what package.json would tell if we look up...\n version: '0.0.1',\n license: 'Apache-2.0',\n author: { name: 'John Doe' },\n repository: { type: 'git', url: 'https://github.com/aws/jsii.git' },\n jsii: {},\n };\n\n if (cb) {\n cb(packageJson);\n }\n\n fs.writeFileSync(\n 'package.json',\n JSON.stringify(packageJson, (_: string, v: any) => v, 2),\n 'utf-8',\n );\n\n const { projectInfo } = loadProjectInfo(path.resolve(process.cwd(), '.'));\n return { projectInfo, packageJson };\n}\n\nexport interface TestCompilationOptions {\n /**\n * The directory in which we write and compile the files\n */\n readonly compilationDirectory?: string;\n\n /**\n * Parts of projectInfo to override (package name etc)\n *\n * @deprecated Prefer using `packageJson` instead.\n */\n readonly projectInfo?: Partial<PackageJson>;\n\n /**\n * Parts of projectInfo to override (package name etc)\n *\n * @default - Use some default values\n */\n readonly packageJson?: Partial<PackageJson>;\n\n /**\n * Whether to compress the assembly file.\n *\n * @default false\n */\n readonly compressAssembly?: boolean;\n}\n\nfunction isOptionsObject(\n x: TestCompilationOptions | ((obj: PackageJson) => void) | undefined,\n): x is TestCompilationOptions {\n return x ? typeof x === 'object' : false;\n}\n\n/**\n * An NPM-ready workspace where we can install test-compile dependencies and compile new assemblies\n */\nexport class TestWorkspace {\n /**\n * Create a new workspace.\n *\n * Creates a temporary directory, don't forget to call cleanUp\n */\n public static create(): TestWorkspace {\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsii-testworkspace'));\n fs.mkdirSync(tmpDir, { recursive: true });\n return new TestWorkspace(tmpDir);\n }\n\n /**\n * Execute a block with a temporary workspace\n */\n public static withWorkspace<A>(block: (ws: TestWorkspace) => A): A {\n const ws = TestWorkspace.create();\n try {\n return block(ws);\n } finally {\n ws.cleanup();\n }\n }\n\n private readonly installed = new Set<string>();\n\n private constructor(public readonly rootDirectory: string) {}\n\n /**\n * Add a test-compiled jsii assembly as a dependency\n */\n public addDependency(dependencyAssembly: HelperCompilationResult) {\n if (this.installed.has(dependencyAssembly.assembly.name)) {\n throw new Error(\n `A dependency with name '${dependencyAssembly.assembly.name}' was already installed. Give one a different name.`,\n );\n }\n this.installed.add(dependencyAssembly.assembly.name);\n\n // The following is silly, however: the helper has compiled the given source to\n // an assembly, and output files, and then removed their traces from disk.\n // We need those files back on disk, so write them back out again.\n //\n // We will drop them in 'node_modules/<name>' so they can be imported\n // as if they were installed.\n const modDir = path.join(this.rootDirectory, 'node_modules', dependencyAssembly.assembly.name);\n fs.mkdirSync(modDir, { recursive: true });\n\n writeAssembly(modDir, dependencyAssembly.assembly, {\n compress: dependencyAssembly.compressAssembly,\n });\n fs.writeFileSync(\n path.join(modDir, 'package.json'),\n JSON.stringify(dependencyAssembly.packageJson, null, 2),\n 'utf-8',\n );\n\n for (const [fileName, fileContents] of Object.entries(dependencyAssembly.files)) {\n fs.mkdirSync(path.dirname(path.join(modDir, fileName)), {\n recursive: true,\n });\n fs.writeFileSync(path.join(modDir, fileName), fileContents);\n }\n }\n\n public dependencyDir(name: string) {\n if (!this.installed.has(name)) {\n throw new Error(`No dependency with name '${name}' has been installed`);\n }\n return path.join(this.rootDirectory, 'node_modules', name);\n }\n\n public cleanup() {\n fs.rmSync(this.rootDirectory, { force: true, recursive: true });\n }\n}\n\n// Alias for backwards compatibility\nexport type PackageInfo = PackageJson;\n"]}
1
+ {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,8BAA8B;AAC9B,8BAA8B;AAC9B,kCAAkC;AAClC,qCAA8E;AAE9E,2CAAgD;AAEhD,yCAAuD;AACvD,iDAA8D;AAC9D,mCAA2C;AAU3C;;;;;;;;;GASG;AACH,SAAgB,sBAAsB,CACpC,MAAoC,EACpC,OAA+D;IAE/D,OAAO,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC;AACtD,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;CACF;AA3ED,sCA2EC","sourcesContent":["/**\n * Helper routines for use with the jsii compiler\n *\n * These are mostly used for testing, but all projects that need to exercise\n * the JSII compiler to test something need to share this code, so might as\n * well put it in one reusable place.\n */\n\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { PackageJson, loadAssemblyFromPath, writeAssembly } from '@jsii/spec';\nimport * as spec from '@jsii/spec';\nimport { DiagnosticCategory } from 'typescript';\n\nimport { Compiler, CompilerOptions } from './compiler';\nimport { loadProjectInfo, ProjectInfo } from './project-info';\nimport { formatDiagnostic } from './utils';\n\n/**\n * A set of source files for `sourceToAssemblyHelper`, at least containing 'index.ts'\n */\nexport type MultipleSourceFiles = {\n 'index.ts': string;\n [name: string]: string;\n};\n\n/**\n * Compile a piece of source and return the JSII assembly for it\n *\n * Only usable for trivial cases and tests.\n *\n * @param source can either be a single `string` (the content of `index.ts`), or\n * a map of fileName to content, which *must* include `index.ts`.\n * @param options accepts a callback for historical reasons but really expects to\n * take an options object.\n */\nexport function sourceToAssemblyHelper(\n source: string | MultipleSourceFiles,\n options?: TestCompilationOptions | ((obj: PackageJson) => void),\n): spec.Assembly {\n return compileJsiiForTest(source, options).assembly;\n}\n\nexport interface HelperCompilationResult {\n /**\n * The generated assembly\n */\n readonly assembly: spec.Assembly;\n\n /**\n * Generated .js/.d.ts file(s)\n */\n readonly files: Record<string, string>;\n\n /**\n * The packageInfo used\n */\n readonly packageJson: PackageJson;\n\n /**\n * Whether to compress the assembly file\n */\n readonly compressAssembly: boolean;\n}\n\n/**\n * Compile a piece of source and return the assembly and compiled sources for it\n *\n * Only usable for trivial cases and tests.\n *\n * @param source can either be a single `string` (the content of `index.ts`), or\n * a map of fileName to content, which *must* include `index.ts`.\n * @param options accepts a callback for historical reasons but really expects to\n * take an options object.\n */\nexport function compileJsiiForTest(\n source: string | { 'index.ts': string; [name: string]: string },\n options?: TestCompilationOptions | ((obj: PackageJson) => void),\n compilerOptions?: Omit<CompilerOptions, 'projectInfo' | 'watch'>,\n): HelperCompilationResult {\n if (typeof source === 'string') {\n source = { 'index.ts': source };\n }\n\n const inSomeLocation =\n isOptionsObject(options) && options.compilationDirectory ? inOtherDir(options.compilationDirectory) : inTempDir;\n\n // Easiest way to get the source into the compiler is to write it to disk somewhere.\n // I guess we could make an in-memory compiler host but that seems like work...\n return inSomeLocation(() => {\n for (const [fileName, content] of Object.entries(source)) {\n fs.mkdirSync(path.dirname(fileName), { recursive: true });\n fs.writeFileSync(fileName, content, { encoding: 'utf-8' });\n }\n const { projectInfo, packageJson } = makeProjectInfo(\n 'index.ts',\n typeof options === 'function'\n ? options\n : (pi) => {\n Object.assign(pi, options?.packageJson ?? options?.projectInfo ?? {});\n },\n );\n const compiler = new Compiler({\n projectInfo,\n ...compilerOptions,\n });\n const emitResult = compiler.emit();\n\n const errors = emitResult.diagnostics.filter((d) => d.category === DiagnosticCategory.Error);\n for (const error of errors) {\n console.error(formatDiagnostic(error, projectInfo.projectRoot));\n // logDiagnostic() doesn't work out of the box, so console.error() it is.\n }\n if (errors.length > 0 || emitResult.emitSkipped) {\n throw new Error('There were compiler errors');\n }\n const assembly = loadAssemblyFromPath(process.cwd(), false);\n const files: Record<string, string> = {};\n\n for (const filename of Object.keys(source)) {\n let jsFile = filename.replace(/\\.ts$/, '.js');\n let dtsFile = filename.replace(/\\.ts$/, '.d.ts');\n if (projectInfo.tsc?.outDir && filename !== 'README.md') {\n jsFile = path.join(projectInfo.tsc.outDir, jsFile);\n dtsFile = path.join(projectInfo.tsc.outDir, dtsFile);\n }\n\n // eslint-disable-next-line no-await-in-loop\n files[jsFile] = fs.readFileSync(jsFile, { encoding: 'utf-8' });\n // eslint-disable-next-line no-await-in-loop\n files[dtsFile] = fs.readFileSync(dtsFile, { encoding: 'utf-8' });\n\n const warningsFileName = '.warnings.jsii.js';\n if (fs.existsSync(warningsFileName)) {\n // eslint-disable-next-line no-await-in-loop\n files[warningsFileName] = fs.readFileSync(warningsFileName, {\n encoding: 'utf-8',\n });\n }\n }\n\n return {\n assembly,\n files,\n packageJson,\n compressAssembly: isOptionsObject(options) && options.compressAssembly ? true : false,\n } as HelperCompilationResult;\n });\n}\n\nfunction inTempDir<T>(block: () => T): T {\n const origDir = process.cwd();\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsii'));\n process.chdir(tmpDir);\n const ret = block();\n process.chdir(origDir);\n fs.rmSync(tmpDir, { force: true, recursive: true });\n return ret;\n}\n\nfunction inOtherDir(dir: string) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint\n return <T extends unknown>(block: () => T): T => {\n const origDir = process.cwd();\n process.chdir(dir);\n try {\n return block();\n } finally {\n process.chdir(origDir);\n }\n };\n}\n\n/**\n * Obtain project info so we can call the compiler\n *\n * Creating this directly in-memory leads to slightly different behavior from calling\n * jsii from the command-line, and I don't want to figure out right now.\n *\n * Most consistent behavior seems to be to write a package.json to disk and\n * then calling the same functions as the CLI would.\n */\nfunction makeProjectInfo(\n types: string,\n cb?: (obj: PackageJson) => void,\n): { projectInfo: ProjectInfo; packageJson: PackageJson } {\n const packageJson: PackageJson = {\n types,\n main: types.replace(/(?:\\.d)?\\.ts(x?)/, '.js$1'),\n name: 'testpkg', // That's what package.json would tell if we look up...\n version: '0.0.1',\n license: 'Apache-2.0',\n author: { name: 'John Doe' },\n repository: { type: 'git', url: 'https://github.com/aws/jsii.git' },\n jsii: {},\n };\n\n if (cb) {\n cb(packageJson);\n }\n\n fs.writeFileSync(\n 'package.json',\n JSON.stringify(packageJson, (_: string, v: any) => v, 2),\n 'utf-8',\n );\n\n const { projectInfo } = loadProjectInfo(path.resolve(process.cwd(), '.'));\n return { projectInfo, packageJson };\n}\n\nexport interface TestCompilationOptions {\n /**\n * The directory in which we write and compile the files\n */\n readonly compilationDirectory?: string;\n\n /**\n * Parts of projectInfo to override (package name etc)\n *\n * @deprecated Prefer using `packageJson` instead.\n */\n readonly projectInfo?: Partial<PackageJson>;\n\n /**\n * Parts of projectInfo to override (package name etc)\n *\n * @default - Use some default values\n */\n readonly packageJson?: Partial<PackageJson>;\n\n /**\n * Whether to compress the assembly file.\n *\n * @default false\n */\n readonly compressAssembly?: boolean;\n}\n\nfunction isOptionsObject(\n x: TestCompilationOptions | ((obj: PackageJson) => void) | undefined,\n): x is TestCompilationOptions {\n return x ? typeof x === 'object' : false;\n}\n\n/**\n * An NPM-ready workspace where we can install test-compile dependencies and compile new assemblies\n */\nexport class TestWorkspace {\n /**\n * Create a new workspace.\n *\n * Creates a temporary directory, don't forget to call cleanUp\n */\n public static create(): TestWorkspace {\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsii-testworkspace'));\n fs.mkdirSync(tmpDir, { recursive: true });\n return new TestWorkspace(tmpDir);\n }\n\n /**\n * Execute a block with a temporary workspace\n */\n public static withWorkspace<A>(block: (ws: TestWorkspace) => A): A {\n const ws = TestWorkspace.create();\n try {\n return block(ws);\n } finally {\n ws.cleanup();\n }\n }\n\n private readonly installed = new Set<string>();\n\n private constructor(public readonly rootDirectory: string) {}\n\n /**\n * Add a test-compiled jsii assembly as a dependency\n */\n public addDependency(dependencyAssembly: HelperCompilationResult) {\n if (this.installed.has(dependencyAssembly.assembly.name)) {\n throw new Error(\n `A dependency with name '${dependencyAssembly.assembly.name}' was already installed. Give one a different name.`,\n );\n }\n this.installed.add(dependencyAssembly.assembly.name);\n\n // The following is silly, however: the helper has compiled the given source to\n // an assembly, and output files, and then removed their traces from disk.\n // We need those files back on disk, so write them back out again.\n //\n // We will drop them in 'node_modules/<name>' so they can be imported\n // as if they were installed.\n const modDir = path.join(this.rootDirectory, 'node_modules', dependencyAssembly.assembly.name);\n fs.mkdirSync(modDir, { recursive: true });\n\n writeAssembly(modDir, dependencyAssembly.assembly, {\n compress: dependencyAssembly.compressAssembly,\n });\n fs.writeFileSync(\n path.join(modDir, 'package.json'),\n JSON.stringify(dependencyAssembly.packageJson, null, 2),\n 'utf-8',\n );\n\n for (const [fileName, fileContents] of Object.entries(dependencyAssembly.files)) {\n fs.mkdirSync(path.dirname(path.join(modDir, fileName)), {\n recursive: true,\n });\n fs.writeFileSync(path.join(modDir, fileName), fileContents);\n }\n }\n\n public dependencyDir(name: string) {\n if (!this.installed.has(name)) {\n throw new Error(`No dependency with name '${name}' has been installed`);\n }\n return path.join(this.rootDirectory, 'node_modules', name);\n }\n\n public cleanup() {\n fs.rmSync(this.rootDirectory, { force: true, recursive: true });\n }\n}\n\n// Alias for backwards compatibility\nexport type PackageInfo = PackageJson;\n"]}