@platforma-sdk/tengo-builder 1.17.3 → 1.17.5

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/compiler/util.ts","../src/compiler/package.ts","../src/compiler/template.ts","../src/compiler/artifactset.ts","../src/compiler/compileroptions.ts","../src/compiler/compiler.ts","../src/compiler/source.ts","../src/compiler/main.ts","../src/shared/basecmd.ts","../src/commands/build.ts","../src/shared/dump.ts","../src/shared/proc.ts","../src/commands/check.ts","../src/commands/test.ts","../src/commands/dump/all.ts","../src/commands/dump/assets.ts","../src/commands/dump/libs.ts","../src/commands/dump/software.ts","../src/commands/dump/templates.ts","../src/commands/dump/tests.ts","../src/index.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as winston from 'winston';\n\nexport function assertNever(x: never): never {\n throw new Error('Unexpected object: ' + x);\n}\n\nexport function createLogger(level: string = 'debug'): winston.Logger {\n return winston.createLogger({\n level: level,\n format: winston.format.printf(({ level, message }) => {\n return `${level.padStart(6, ' ')}: ${message}`;\n }),\n transports: [\n new winston.transports.Console({\n stderrLevels: ['error', 'warn', 'info', 'debug'],\n handleExceptions: true\n })\n ]\n });\n}\n\nexport function findNodeModules(): string {\n let currentDir = process.cwd();\n\n while (currentDir) {\n const possibleNodeModulesPath = path.join(currentDir, 'node_modules');\n\n if (fs.existsSync(possibleNodeModulesPath)) return possibleNodeModulesPath;\n\n const parentDir = path.resolve(currentDir, '..');\n if (parentDir === currentDir) break; // reached the root directory\n\n currentDir = parentDir;\n }\n\n throw new Error('Unable to find node_modules directory.');\n}\n\nexport type PathType = 'absent' | 'file' | 'dir' | 'link' | 'unknown';\n\nexport function pathType(path: string): PathType {\n try {\n const s = fs.statSync(path);\n if (s.isDirectory()) return 'dir';\n if (s.isFile()) return 'file';\n if (s.isSymbolicLink()) return 'link';\n return 'unknown';\n } catch (err: any) {\n if (err.code == 'ENOENT') return 'absent';\n else throw err;\n }\n}\n\nexport function isUUID(uuid: string): boolean {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return uuidRegex.test(uuid.toLowerCase());\n}\n","/*\n Package \"@milaboratory/current-tengo-package\".\n\n Structure:\n\n src/\n local-template.pl.tengo <- this one will be compiled and put into ./dist/tengo/tpl/local-template.pl.pkg\n local-library.tengo <- this one will be normalized and put into ./dist/tengo/lib/local-library.tengo\n main.tpl.tengo <- this one will be compiled into ./dist/tengo/tpl/main.pl.pkg and published by external tool\n\n Code of \"main.tpl.tengo\":\n\n plapi := import(\"plapi\")\n\n plapi.getTemplateId(\"@milaboratory/some-tengo-template\") // -> getTemplateId(\"@milaboratory/some-tengo-template:main\")\n import(\"@milaboratory/some-tengo-library\") // -> import(\"@milaboratory/some-tengo-library:main\")\n\n */\n\nexport type CompileMode = 'dist';\n\nexport type CompilerOption = {\n /** Option name, like 'hash_override' */\n name: string; // we can't use strict literals typing here as we will break compatibility of the code through the lifetime of the compiler.\n\n /** Arguments of the option. Everything that follows option name */\n args: string[];\n};\n\nexport type ArtifactType = 'library' | 'template' | 'test' | 'software' | 'asset';\n\n/** Artifact Name including package version */\nexport interface FullArtifactName {\n /** Dependency type */\n type: ArtifactType;\n\n /** Fully qualified package */\n pkg: string;\n\n /** Id of the artifact inside the package */\n id: string;\n\n /** Package version */\n version: string;\n}\n\nexport type FullArtifactNameWithoutType = Omit<FullArtifactName, 'type'>;\n\nexport type TypedArtifactName = Pick<FullArtifactName, 'type' | 'pkg' | 'id'>;\n\nexport type PackageName = Pick<FullArtifactName, 'pkg' | 'version'>;\n\nexport type ArtifactName = Pick<FullArtifactName, 'pkg' | 'id'>;\n\nexport function artifactKey(name: TypedArtifactName): string {\n return `${name.type}||${name.pkg}||${name.id}`;\n}\n\nexport function fullNameToString(name: FullArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}:${name.version}`;\n}\n\n/** used for exceptions */\nexport function typedArtifactNameToString(name: TypedArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}`;\n}\n\nexport function typedArtifactNamesEquals(\n name1: TypedArtifactName,\n name2: TypedArtifactName\n): boolean {\n return name1.type == name2.type && name1.pkg == name2.pkg && name1.id == name2.id;\n}\n\n/** used to format artefact name while generating output files */\nexport function artifactNameToString(name: ArtifactName): string {\n return `${name.pkg}:${name.id}`;\n}\n\n/** used to format artefact name and version while generating output files */\nexport function formatArtefactNameAndVersion(name: FullArtifactName): {\n name: string;\n version: string;\n} {\n return { name: artifactNameToString(name), version: name.version };\n}\n\n/** used to format artefact name and version while generating output files */\nexport function parseArtefactNameAndVersion(nameAndVersion: {\n name: string;\n version: string;\n}): FullArtifactNameWithoutType {\n const match = nameAndVersion.name.match(/^(?<pkg>[^:]*):(?<id>[^:]*)$/);\n if (!match) throw new Error(`malformed artifact name: ${nameAndVersion.name}`);\n return { pkg: match.groups!['pkg'], id: match.groups!['id'], version: nameAndVersion.version };\n}\n\nexport function fullNameWithoutTypeToString(name: FullArtifactNameWithoutType): string {\n return `${name.pkg}:${name.id}:${name.version}`;\n}\n\nexport function fullNameWithoutType(name: FullArtifactName): FullArtifactNameWithoutType {\n return { pkg: name.pkg, id: name.id, version: name.version };\n}\n","import { gunzipSync, gzipSync } from 'node:zlib';\nimport canonicalize from 'canonicalize';\nimport {\n CompileMode,\n FullArtifactName,\n FullArtifactNameWithoutType,\n fullNameWithoutTypeToString,\n parseArtefactNameAndVersion\n} from './package';\n\nexport interface TemplateLibData {\n /** i.e. @milaboratory/some-package:lib1 */\n name: string;\n /** i.e. 1.2.3 */\n version: string;\n /** full source code */\n src: string,\n}\n\nexport interface TemplateSoftwareData {\n /** i.e. @milaboratory/mixcr:main */\n name: string;\n /** i.e. 4.2.3 */\n version: string;\n /** full contents of software dependency description */\n src: string,\n}\n\nexport interface TemplateAssetData {\n /** i.e. @milaboratory/mixcr:main */\n name: string;\n /** i.e. 4.2.3 */\n version: string;\n /** full contents of asset dependency description */\n src: string,\n}\n\nexport interface TemplateData {\n /** Discriminator for future use */\n type: 'pl.tengo-template.v2';\n\n /** i.e. @milaboratory/some-package:template */\n name: string;\n /** i.e. 1.2.3 */\n version: string;\n\n /**\n * Custom hash token of the template for deduplication purposes. Can be set with 'hash_override' compiler option.\n * Dangerous! Remember: great power comes with great responsibility.\n */\n hashOverride?: string;\n\n /** i.e. @milaboratory/some-package:some-lib -> normalized library source code */\n libs: Record<string, TemplateLibData>;\n /** i.e. @milaboratory/some-package:some-lib -> to nested template data */\n templates: Record<string, TemplateData>;\n /** i.e. @milaboratory/mixcr:main -> software metadata */\n software: Record<string, TemplateSoftwareData>;\n /** i.e. @milaboratory/genome:human -> asset metadata */\n assets: Record<string, TemplateAssetData>;\n /** Template source code */\n src: string;\n}\n\nconst decoder = new TextDecoder();\nconst encoder = new TextEncoder();\n\nexport class Template {\n public readonly data: TemplateData;\n public readonly content: Uint8Array;\n\n constructor(\n public readonly compileMode: CompileMode,\n public readonly fullName: FullArtifactName,\n body: {\n data?: TemplateData,\n content?: Uint8Array\n }\n ) {\n let { data, content } = body;\n if (data === undefined && content === undefined)\n throw new Error('Neither data nor content is provided for template constructor');\n if (data !== undefined && content !== undefined)\n throw new Error('Both data and content are provided for template constructor');\n\n if (data === undefined) {\n data = JSON.parse(decoder.decode(gunzipSync(content!))) as TemplateData;\n if (data.type !== 'pl.tengo-template.v2')\n throw new Error('malformed template');\n }\n\n if (content === undefined)\n content = gzipSync(encoder.encode(canonicalize(data!)));\n\n const nameFromData: FullArtifactNameWithoutType = parseArtefactNameAndVersion(data);\n\n if (nameFromData.pkg !== fullName.pkg || nameFromData.id !== fullName.id || nameFromData.version !== fullName.version)\n throw new Error(`Compiled template name don't match it's package and file names: ${fullNameWithoutTypeToString(nameFromData)} != ${fullNameWithoutTypeToString(fullName)}`);\n\n this.data = data;\n this.content = content;\n }\n\n toJSON() {\n return { compileMode: this.compileMode, fullName: this.fullName, data: this.data }\n }\n}\n","import { CompileMode, TypedArtifactName, artifactKey } from './package';\nimport { assertNever } from './util';\n\nexport class ArtifactMap<T> {\n private readonly map = new Map<string, T>();\n\n constructor(private readonly nameExtractor: (obj: T) => TypedArtifactName) {\n }\n\n add(obj: T, replace: boolean = true): T | undefined {\n const key = artifactKey(this.nameExtractor(obj));\n const ret = this.map.get(key);\n if (ret && !replace)\n return ret;\n this.map.set(key, obj);\n return ret;\n }\n\n get(name: TypedArtifactName): T | undefined {\n return this.map.get(artifactKey(name));\n }\n\n get array(): T[] {\n const ret: T[] = [];\n this.map.forEach(obj => ret.push(obj));\n return ret;\n }\n\n forEach(callback: (value: T, key: TypedArtifactName) => void) {\n this.map.forEach(v => callback(v, this.nameExtractor(v)));\n }\n}\n\nexport function createArtifactNameSet(): ArtifactMap<TypedArtifactName> {\n return new ArtifactMap<TypedArtifactName>(obj => obj);\n}\n\nexport class ArtifactStore<T> {\n private readonly dev: ArtifactMap<T>\n private readonly dist: ArtifactMap<T>\n\n constructor(private readonly nameExtractor: (obj: T) => TypedArtifactName) {\n this.dev = new ArtifactMap<T>(nameExtractor)\n this.dist = new ArtifactMap<T>(nameExtractor)\n }\n\n add(mode: CompileMode, obj: T, replace: boolean = true): T | undefined {\n switch (mode) {\n case 'dist':\n return this.dist.add(obj, replace)\n\n default:\n assertNever(mode)\n }\n }\n\n get(mode: CompileMode, name: TypedArtifactName): T | undefined {\n switch (mode) {\n case 'dist':\n return this.dist.get(name);\n\n default:\n assertNever(mode)\n }\n }\n\n array(mode: CompileMode): T[] {\n const ret: T[] = [];\n this.forEach(mode, obj => ret.push(obj));\n return ret;\n }\n\n forEach(mode: CompileMode, callback: (value: T, key: TypedArtifactName) => void) {\n this.dist.forEach( (obj, k) => callback(this.get(mode, k) ?? obj, k) )\n }\n}\n","import { CompilerOption } from './package';\nimport { TemplateData, TemplateLibData } from './template';\nimport * as util from './util';\n\nexport function applyTemplateCompilerOptions(opts: CompilerOption[], tpl: TemplateData) {\n for (const opt of opts) {\n switch (opt.name) {\n case 'hash_override': {\n tpl.hashOverride = hashOverride(opt.args);\n break;\n }\n }\n }\n}\n\nexport function applyLibraryCompilerOptions(opts: CompilerOption[], lib: TemplateLibData) {\n for (const opt of opts) {\n switch (opt.name) {\n case 'hash_override': {\n throw new Error(\n `hash_override compiler option can be used ONLY on template level. Even in templates it is already dangerous enough` +\n ` to potentially break everything in Platforma Backend. In libraries with the transitive dependencies`+\n ` resolution and flattening of libraries list on template level, it becomes so unpredictibally disasterous, that`+\n ` we are doomed to never find the ends of a knot if anything goes wrong.`\n );\n }\n }\n }\n}\n\nexport function hashOverride(args: string[]): string {\n if (args.length != 1) {\n throw new Error(\n 'hash_override compiler option expects exactly one argument: hash_override <some string>. Note, you can use only UUID as a value.'\n );\n }\n\n const override = args[0].toLowerCase();\n\n if (!util.isUUID(override)) {\n throw new Error(\n 'hash_override must contain valid UUID as an override. As hash_override affects deduplication,' +\n \" it becomes completely not possible to distinguish several different templates from each other on backend's side.\" +\n ' This means, if you set hash_override to a simple value (say, letter \"a\") on two completely different templates,' +\n \" they will be marked as interchangeable on backend's side with unpredictable consequences.\" +\n ' UUID looks like a safe enough tradeoff between the feature usage simplicity and duplication safety'\n );\n }\n\n return override;\n}\n","import { ArtifactSource } from './source';\nimport { Template, TemplateData } from './template';\nimport {\n TypedArtifactName,\n fullNameToString,\n typedArtifactNameToString,\n artifactNameToString,\n formatArtefactNameAndVersion, typedArtifactNamesEquals, FullArtifactName,\n CompileMode\n} from './package';\nimport { ArtifactStore } from './artifactset';\nimport { assertNever } from './util';\nimport { applyLibraryCompilerOptions, applyTemplateCompilerOptions } from './compileroptions';\n\nexport interface TemplatesAndLibs {\n templates: Template[],\n libs: ArtifactSource[],\n software: ArtifactSource[]\n assets: ArtifactSource[]\n}\n\nexport class TengoTemplateCompiler {\n constructor(\n private readonly compileMode: CompileMode\n ) { }\n\n private readonly libs = new ArtifactStore<ArtifactSource>(src => src.fullName);\n private readonly software = new ArtifactStore<ArtifactSource>(src => src.fullName);\n private readonly assets = new ArtifactStore<ArtifactSource>(src => src.fullName);\n private readonly templates = new ArtifactStore<Template>(tpl => tpl.fullName);\n\n private populateTemplateDataFromDependencies(fullName: FullArtifactName,\n data: TemplateData,\n deps: TypedArtifactName[],\n trace: string[]) {\n for (const dep of deps) {\n switch (dep.type) {\n case 'library': {\n const lib = this.getLibOrError(dep);\n\n const recursionStart = trace.indexOf(artifactNameToString(dep))\n if (recursionStart >= 0) {\n let errorMessage = `library import recursion detected: ${trace.slice(recursionStart).join(\" -> \")} -> ${artifactNameToString(dep)}`\n throw new Error(errorMessage)\n }\n\n const tplLib = {\n ...formatArtefactNameAndVersion(lib.fullName),\n src: lib.src\n }\n\n applyLibraryCompilerOptions(lib.compilerOptions, tplLib)\n data.libs[artifactNameToString(dep)] = tplLib;\n\n // populate with transient library dependencies\n this.populateTemplateDataFromDependencies(fullName, data, lib.dependencies, [...trace, artifactNameToString(dep)]);\n\n break;\n }\n case 'software':\n const software = this.getSoftwareOrError(dep);\n data.software[artifactNameToString(dep)] = {\n ...formatArtefactNameAndVersion(software.fullName),\n src: software.src\n }\n\n break;\n case 'asset':\n const asset = this.getAssetOrError(dep);\n // Yes, we temporarily put assets into 'software' section of template, so controller can\n // handle it the right way without updates\n data.software[artifactNameToString(dep)] = {\n ...formatArtefactNameAndVersion(asset.fullName),\n src: asset.src\n }\n\n break;\n case 'template':\n if (typedArtifactNamesEquals(fullName, dep))\n // skipping self reference\n continue;\n\n const tpl = this.getTemplateOrError(dep);\n data.templates[artifactNameToString(dep)] = tpl.data;\n break;\n case 'test':\n throw new Error(\n `dependencies tree error: tests should never be part of template: ${typedArtifactNameToString(dep)} is dependency of ${artifactNameToString(fullName)}`,\n )\n default:\n assertNever(dep.type);\n }\n }\n }\n\n /** This method assumes that all dependencies are already added to the compiler's context */\n private compileAndAddTemplate(tplSrc: ArtifactSource): Template {\n if (tplSrc.fullName.type !== 'template')\n throw new Error('unexpected source type');\n\n // creating template with unpopulated dependencies\n const tplData: TemplateData = {\n type: 'pl.tengo-template.v2',\n ...formatArtefactNameAndVersion(tplSrc.fullName),\n templates: {},\n libs: {},\n software: {},\n assets: {},\n src: tplSrc.src\n };\n\n applyTemplateCompilerOptions(tplSrc.compilerOptions, tplData);\n\n // collecting dependencies in output format\n this.populateTemplateDataFromDependencies(tplSrc.fullName, tplData, tplSrc.dependencies, []);\n\n const tpl = new Template(tplSrc.compileMode, tplSrc.fullName, { data: tplData });\n this.addTemplate(tpl);\n return tpl;\n }\n\n addLib(lib: ArtifactSource) {\n const libFromMap = this.libs.add(lib.compileMode, lib, false)\n if (libFromMap)\n throw new Error(\n `compiler already contain such library: adding = ${fullNameToString(lib.fullName)}, contains = ${fullNameToString(libFromMap.fullName)}`\n );\n }\n\n allLibs(): ArtifactSource[] {\n return this.libs.array(this.compileMode)\n }\n\n getLib(name: TypedArtifactName): ArtifactSource | undefined {\n if (name.type !== 'library')\n throw new Error(`illegal artifact type: got ${name.type} instead of 'library`);\n return this.libs.get(this.compileMode, name);\n }\n\n getLibOrError(name: TypedArtifactName): ArtifactSource {\n const lib = this.getLib(name);\n if (!lib)\n throw new Error(`library not found: ${artifactNameToString(name)}`);\n return lib;\n }\n\n addSoftware(software: ArtifactSource) {\n const swFromMap = this.software.add(software.compileMode, software, false)\n if (swFromMap)\n throw new Error(\n `compiler already contain info for software: adding = ${fullNameToString(software.fullName)}, contains = ${fullNameToString(swFromMap.fullName)}`\n );\n }\n\n allSoftware(): ArtifactSource[] {\n return this.software.array(this.compileMode)\n }\n\n getSoftware(name: TypedArtifactName): ArtifactSource | undefined {\n if (name.type !== 'software')\n throw new Error(`illegal artifact type: got ${name.type} instead of 'software`);\n\n return this.software.get(this.compileMode, name);\n }\n\n getSoftwareOrError(name: TypedArtifactName): ArtifactSource {\n const software = this.getSoftware(name);\n if (!software)\n throw new Error(`software info not found: ${artifactNameToString(name)}`);\n return software;\n }\n\n addAsset(asset: ArtifactSource) {\n const assetFromMap = this.assets.add(asset.compileMode, asset, false)\n if (assetFromMap)\n throw new Error(\n `compiler already contain info for asset: adding = ${fullNameToString(asset.fullName)}, contains = ${fullNameToString(assetFromMap.fullName)}`\n );\n }\n\n allAssets(): ArtifactSource[] {\n return this.assets.array(this.compileMode)\n }\n\n getAsset(name: TypedArtifactName): ArtifactSource | undefined {\n if (name.type !== 'asset')\n throw new Error(`illegal artifact type: got ${name.type} instead of 'asset`);\n\n return this.assets.get(this.compileMode, name);\n }\n\n getAssetOrError(name: TypedArtifactName): ArtifactSource {\n const asset = this.getAsset(name);\n if (!asset)\n throw new Error(`asset info not found: ${artifactNameToString(name)}`);\n return asset;\n }\n\n addTemplate(tpl: Template) {\n const tplFromMap = this.templates.add(tpl.compileMode, tpl, false);\n if (tplFromMap)\n throw new Error(\n `compiler already contain such template: adding = ${fullNameToString(tpl.fullName)}, contains = ${fullNameToString(tplFromMap.fullName)}`\n );\n }\n\n allTemplates(): Template[] {\n return this.templates.array(this.compileMode)\n }\n\n getTemplate(name: TypedArtifactName): Template | undefined {\n if (name.type !== 'template')\n throw new Error(`illegal artifact type: got ${name.type} instead of 'template`);\n return this.templates.get(this.compileMode, name);\n }\n\n getTemplateOrError(name: TypedArtifactName): Template {\n const tpl = this.getTemplate(name);\n if (!tpl)\n throw new Error(`template not found: ${artifactNameToString(name)}`);\n return tpl;\n }\n\n getArtefact(name: TypedArtifactName): ArtifactSource | Template | undefined {\n switch (name.type) {\n case 'template':\n return this.getTemplate(name);\n case 'library':\n return this.getLib(name);\n case 'software':\n return this.getSoftware(name);\n case 'asset':\n return this.getAsset(name);\n case 'test':\n // Tests are ignored by the complier. They should never be compiled into templates or libs and\n // should never be a dependency.\n return undefined;\n default:\n assertNever(name.type);\n }\n }\n\n checkLibs() {\n this.libs.forEach(this.compileMode, lib => {\n for (const dep of lib.dependencies) {\n if (dep.type === 'test')\n throw new Error(`test should never be dependency of production code: ${typedArtifactNameToString(dep)} test is dependency of ${fullNameToString(lib.fullName)}`);\n\n if (!this.getArtefact(dep))\n throw new Error(`unresolved dependency ${typedArtifactNameToString(dep)} for ${fullNameToString(lib.fullName)}`);\n }\n });\n }\n\n compileAndAdd(sources: ArtifactSource[]): TemplatesAndLibs {\n const ret: TemplatesAndLibs = { templates: [], libs: [], software: [], assets: [] };\n let current: ArtifactSource[] = [];\n\n for (const src of sources) {\n if (src.fullName.type === 'library') {\n // add libraries 'as-is' to be able to resolve them as dependencies\n this.addLib(src);\n ret.libs.push(src);\n } else if (src.fullName.type === 'software') {\n // add software 'as-is' to be able to resolve them as dependencies\n this.addSoftware(src);\n ret.software.push(src);\n } else if (src.fullName.type === 'asset') {\n // add assets 'as-is' to be able to resolve them as dependencies\n this.addAsset(src);\n ret.assets.push(src);\n } else {\n current.push(src)\n }\n }\n\n while (current.length > 0) {\n const unprocessed: { src: ArtifactSource, err: Error }[] = [];\n\n for (const src of current) {\n //\n // If one of the dependencies can't be resolved with current compiler context,\n // we put aside the source until next iteration, in hope that the dependency\n // will be satisfied then.\n //\n // This is equivalent to topological sorting of input sources.\n //\n const unsatisfied = src.dependencies.filter(dep =>\n !this.getArtefact(dep) &&\n // allow self reference for templates\n !(src.fullName.type === 'template' && typedArtifactNamesEquals(src.fullName, dep))\n )\n if (unsatisfied.length > 0) {\n let errorMessage = `Unsatisfied dependencies in ${fullNameToString(src.fullName)}:\\n`\n for (const dep of unsatisfied) {\n errorMessage += ` - ${typedArtifactNameToString(dep)}\\n`;\n }\n unprocessed.push({ src, err: Error(errorMessage) })\n\n continue;\n }\n\n // type specific processing\n switch (src.fullName.type) {\n case 'library':\n // libraries are added as is\n this.addLib(src);\n ret.libs.push(src);\n break;\n case 'software':\n // software dependencies are added as is\n this.addSoftware(src);\n ret.software.push(src);\n break;\n case 'asset':\n // software dependencies are added as is\n this.addAsset(src);\n ret.assets.push(src);\n break;\n case 'template':\n // templates are compiled and then added\n try {\n const tpl = this.compileAndAddTemplate(src);\n ret.templates.push(tpl);\n } catch (err: any) {\n let errorMessage = `Unsatisfied dependencies in ${fullNameToString(src.fullName)}:\\n`\n errorMessage += ` - ${err.message}\\n`;\n\n unprocessed.push({ src, err: Error(errorMessage) }) // one or more dependencies are not resolvable yet\n }\n break;\n case 'test':\n // Ignore tests: they never should be part of compiled code or be a dependency.\n break;\n default:\n assertNever(src.fullName.type);\n }\n }\n\n // checking that we successfully added at least one source,\n // if not all the source files in unprocessed array have unmet dependencies\n if (current.length === unprocessed.length) {\n let errorMessage = '';\n\n for (const u of unprocessed) {\n errorMessage += `\\n${u.err.message}`\n }\n throw new Error(errorMessage);\n }\n\n current = unprocessed.map(({ src: ArtifactSource }) => ArtifactSource);\n }\n\n return ret;\n }\n}\n","import { readFileSync } from 'node:fs';\nimport winston from 'winston';\nimport {\n TypedArtifactName,\n FullArtifactName,\n ArtifactType,\n CompileMode,\n CompilerOption\n} from './package';\nimport { ArtifactMap, createArtifactNameSet } from './artifactset';\n\n// matches any valid name in tengo. Don't forget to use '\\b' when needed to limit the boundaries!\nconst namePattern = '[_a-zA-Z][_a-zA-Z0-9]*';\n\nconst functionCallRE = (moduleName: string, fnName: string) => {\n return new RegExp(\n `\\\\b${moduleName}\\\\.(?<fnCall>(?<fnName>` +\n fnName +\n `)\\\\s*\\\\(\\\\s*\"(?<templateName>[^\"]+)\"\\\\s*\\\\))`\n );\n};\n\nconst newGetTemplateIdRE = (moduleName: string) => {\n return functionCallRE(moduleName, 'getTemplateId');\n};\nconst newGetSoftwareInfoRE = (moduleName: string) => {\n return functionCallRE(moduleName, 'getSoftwareInfo');\n};\n\nconst newImportTemplateRE = (moduleName: string) => {\n return functionCallRE(moduleName, 'importTemplate');\n};\nconst newImportSoftwareRE = (moduleName: string) => {\n return functionCallRE(moduleName, 'importSoftware');\n};\nconst newImportAssetRE = (moduleName: string) => {\n return functionCallRE(moduleName, 'importAsset');\n};\n\nconst emptyLineRE = /^\\s*$/;\nconst compilerOptionRE = /^\\/\\/tengo:[\\w]/;\nconst wrongCompilerOptionRE = /^\\s*\\/\\/\\s*tengo:\\s*./;\nconst singlelineCommentRE = /^\\s*(\\/\\/)|(\\/\\*.*\\*\\/)/;\nconst multilineCommentStartRE = /^\\s*\\/\\*/;\nconst multilineCommentEndRE = /\\*\\//;\nconst importRE = /\\s*:=\\s*import\\s*\\(\\s*\"(?<moduleName>[^\"]+)\"\\s*\\)/;\nconst importNameRE = new RegExp(\n `\\\\b(?<importName>${namePattern}(\\\\.${namePattern})*)${importRE.source}`\n);\nconst dependencyRE = /(?<pkgName>[^\"]+)?:(?<depID>[^\"]+)/; // use it to parse <moduleName> from importPattern or <templateName> акщь getTemplateID\n\n/**\n * Parse compiler option string representation\n * Compiler option line is a comment starting with '//tengo:', say\n * //tengo:hash_override tralala\n *\n * The common compiler option syntax is:\n * //tengo:<option name> [<option arg1> [<option arg 2> [...]]]\n */\nconst parseComplierOption = (opt: string): CompilerOption => {\n const parts = opt.split(' ');\n const namePart = parts[0].split(':');\n if (namePart.length != 2) {\n throw new Error(\n \"compiler option format is wrong: expect to have option name after 'tengo:' prefix, like 'tengo:MyOption'\"\n );\n }\n const optName = namePart[1];\n\n return {\n name: optName,\n args: parts.slice(1)\n };\n};\n\nexport class ArtifactSource {\n constructor(\n /** The mode this artifact was built (dev or dist) */\n public readonly compileMode: CompileMode,\n /** Full artifact id, including package version */\n public readonly fullName: FullArtifactName,\n /** Normalized source code */\n public readonly src: string,\n /** Path to source file where artifact came from */\n public readonly srcName: string,\n /** List of dependencies */\n public readonly dependencies: TypedArtifactName[],\n /** Additional compiler options detected in source code */\n public readonly compilerOptions: CompilerOption[]\n ) {}\n}\n\nexport function parseSourceFile(\n logger: winston.Logger,\n mode: CompileMode,\n srcFile: string,\n fullSourceName: FullArtifactName,\n normalize: boolean\n): ArtifactSource {\n const src = readFileSync(srcFile).toString();\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(mode, fullSourceName, normalized, srcFile, deps.array, opts);\n}\n\nexport function parseSource(\n logger: winston.Logger,\n mode: CompileMode,\n src: string,\n fullSourceName: FullArtifactName,\n normalize: boolean\n): ArtifactSource {\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(mode, fullSourceName, normalized, '', deps.array, opts);\n}\n\nfunction parseSourceData(\n logger: winston.Logger,\n src: string,\n fullSourceName: FullArtifactName,\n globalizeImports: boolean\n): {\n normalized: string;\n deps: ArtifactMap<TypedArtifactName>;\n opts: CompilerOption[];\n} {\n const dependencySet = createArtifactNameSet();\n const optionList: CompilerOption[] = [];\n\n // iterating over lines\n const lines = src.split('\\n');\n\n // processedLines keep all the original lines from <src>.\n // If <globalizeImport>==true, the parser modifies 'import' and 'getTemplateId' lines\n // with Platforma Tengo lib and template usages, resolving local names (\":<item>\") to\n // global (\"@milaboratory/pkg:<item>\")\n const processedLines: string[] = [];\n let parserContext: sourceParserContext = {\n isInCommentBlock: false,\n canDetectOptions: true,\n tplDepREs: new Map<string, [ArtifactType, RegExp][]>(),\n lineNo: 0\n };\n\n for (const line of lines) {\n parserContext.lineNo++;\n\n try {\n const result = parseSingleSourceLine(\n logger,\n line,\n parserContext,\n fullSourceName.pkg,\n globalizeImports\n );\n processedLines.push(result.line);\n parserContext = result.context;\n\n if (result.artifact) {\n dependencySet.add(result.artifact);\n }\n if (result.option) {\n optionList.push(result.option);\n }\n } catch (error: any) {\n throw new Error(`[line ${parserContext.lineNo}]: ${error.message}\\n\\t${line}`);\n }\n }\n\n return {\n normalized: processedLines.join('\\n'),\n deps: dependencySet,\n opts: optionList\n };\n}\n\ninterface sourceParserContext {\n isInCommentBlock: boolean;\n canDetectOptions: boolean;\n tplDepREs: Map<string, [ArtifactType, RegExp][]>;\n lineNo: number;\n}\n\nfunction parseSingleSourceLine(\n logger: winston.Logger,\n line: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean\n): {\n line: string;\n context: sourceParserContext;\n artifact: TypedArtifactName | undefined;\n option: CompilerOption | undefined;\n} {\n if (context.isInCommentBlock) {\n if (multilineCommentEndRE.exec(line)) {\n context.isInCommentBlock = false;\n }\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (compilerOptionRE.exec(line)) {\n if (!context.canDetectOptions) {\n logger.error(\n `[line ${context.lineNo}]: compiler option '//tengo:' was detected, but it cannot be applied as compiler options can be set only at the file header, before any code line'`\n );\n throw new Error(\"tengo compiler options ('//tengo:' comments) can be set only in file header\");\n }\n return { line, context, artifact: undefined, option: parseComplierOption(line) };\n }\n\n if (wrongCompilerOptionRE.exec(line) && context.canDetectOptions) {\n logger.warn(\n `[line ${context.lineNo}]: text simillar to compiler option ('//tengo:...') was detected, but it has wrong format. Leave it as is, if you did not mean to use a line as compiler option. Or format it to '//tengo:<option>' otherwise (no spaces between '//' and 'tengo', no spaces between ':' and option name)`\n );\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (singlelineCommentRE.exec(line)) {\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (multilineCommentStartRE.exec(line)) {\n context.isInCommentBlock = true;\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (emptyLineRE.exec(line)) {\n return { line, context, artifact: undefined, option: undefined };\n }\n\n context.canDetectOptions = false;\n\n const importInstruction = importRE.exec(line);\n\n if (importInstruction) {\n const iInfo = parseImport(line);\n\n if (iInfo.module === 'plapi') {\n if (!context.tplDepREs.has(iInfo.module)) {\n context.tplDepREs.set(iInfo.module, [\n ['template', newGetTemplateIdRE(iInfo.alias)],\n ['software', newGetSoftwareInfoRE(iInfo.alias)]\n ]);\n }\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (\n iInfo.module === '@milaboratory/tengo-sdk:ll' ||\n iInfo.module === '@platforma-sdk/workflow-tengo:ll' ||\n ((localPackageName === '@milaboratory/tengo-sdk' ||\n localPackageName === '@platforma-sdk/workflow-tengo') &&\n iInfo.module === ':ll')\n ) {\n if (!context.tplDepREs.has(iInfo.module)) {\n context.tplDepREs.set(iInfo.module, [\n ['template', newImportTemplateRE(iInfo.alias)],\n ['software', newImportSoftwareRE(iInfo.alias)]\n ]);\n }\n }\n\n if (\n iInfo.module === '@milaboratory/tengo-sdk:assets' ||\n iInfo.module === '@platforma-sdk/workflow-tengo:assets' ||\n ((localPackageName === '@milaboratory/tengo-sdk' ||\n localPackageName === '@platforma-sdk/workflow-tengo') &&\n iInfo.module === ':assets')\n ) {\n if (!context.tplDepREs.has(iInfo.module)) {\n context.tplDepREs.set(iInfo.module, [\n ['template', newImportTemplateRE(iInfo.alias)],\n ['software', newImportSoftwareRE(iInfo.alias)],\n ['asset', newImportAssetRE(iInfo.alias)]\n ]);\n }\n }\n\n const artifact = parseArtifactName(iInfo.module, 'library', localPackageName);\n if (!artifact) {\n // not a Platforma Tengo library import\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (globalizeImports) {\n line = line.replace(importInstruction[0], ` := import(\"${artifact.pkg}:${artifact.id}\")`);\n }\n\n return { line, context, artifact, option: undefined };\n }\n\n if (context.tplDepREs.size > 0) {\n for (const [key, artifactRE] of context.tplDepREs) {\n for (const [artifactType, re] of artifactRE) {\n const match = re.exec(line);\n if (!match || !match.groups) {\n continue;\n }\n\n const { fnCall, templateName, fnName } = match.groups;\n\n if (!fnCall || !templateName || !fnName) {\n throw Error(`failed to parse template import statement`);\n }\n\n const artifact = parseArtifactName(templateName, artifactType, localPackageName);\n if (!artifact) {\n throw Error(`failed to parse artifact name in ${fnName} import statement`);\n }\n\n if (globalizeImports) {\n line = line.replace(fnCall, `${fnName}(\"${artifact.pkg}:${artifact.id}\")`);\n }\n\n return { line, context, artifact, option: undefined };\n }\n }\n }\n\n return { line, context, artifact: undefined, option: undefined };\n}\n\ninterface ImportInfo {\n module: string; // the module name without wrapping quotes: import(\"<module>\")\n alias: string; // the name of variable that keeps imported module: <alias> := import(\"<module>\")\n}\n\nfunction parseImport(line: string): ImportInfo {\n const match = importNameRE.exec(line);\n\n if (!match || !match.groups) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n const { importName, moduleName } = match.groups;\n if (!importName || !moduleName) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n return {\n module: moduleName,\n alias: importName\n };\n}\n\nfunction parseArtifactName(\n moduleName: string,\n aType: ArtifactType,\n localPackageName: string\n): TypedArtifactName | undefined {\n const depInfo = dependencyRE.exec(moduleName);\n if (!depInfo) {\n return;\n }\n\n if (!depInfo.groups) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`\n );\n }\n\n const { pkgName, depID } = depInfo.groups;\n if (!depID) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`\n );\n }\n\n return { type: aType, pkg: pkgName ?? localPackageName, id: depID };\n}\n\nfunction parseTemplateUse(match: RegExpExecArray, localPackageName: string): TypedArtifactName {\n const { templateName } = match.groups!;\n\n if (!templateName) {\n throw Error(`failed to parse 'getTemplateId' statement`);\n }\n\n const depInfo = dependencyRE.exec(templateName);\n if (!depInfo || !depInfo.groups) {\n throw Error(\n `failed to parse dependency name inside 'getTemplateId' statement. The dependency name should have format '<package>:<templateName>'`\n );\n }\n\n const { pkgName, depID } = depInfo.groups;\n if (!pkgName || !depID) {\n throw Error(\n `failed to parse dependency name inside 'getTemplateId' statement. The dependency name should have format '<package>:<templateName>'`\n );\n }\n\n return { type: 'template', pkg: pkgName ?? localPackageName, id: depID };\n}\n","#!/usr/bin/env node\n\nimport * as path from 'node:path';\nimport * as fs from 'node:fs';\nimport { findNodeModules, pathType } from './util';\nimport { TemplatesAndLibs, TengoTemplateCompiler } from './compiler';\nimport {\n artifactNameToString,\n CompileMode,\n FullArtifactName,\n fullNameToString,\n typedArtifactNameToString\n} from './package';\nimport { ArtifactSource, parseSourceFile } from './source';\nimport { Template } from './template';\nimport winston from 'winston';\n\ninterface PackageJson {\n name: string;\n version: string;\n type: string;\n}\n\nconst compiledTplSuffix = '.plj.gz';\nconst compiledLibSuffix = '.lib.tengo';\nconst compiledSoftwareSuffix = '.sw.json';\nconst compiledAssetSuffix = '.as.json';\n\n// We need to keep track of dependencies for correct tgo-test CLI utility configuraiton.\n// It is much simpler to do this here, than duplicate all tle logic regarding dependencies\n// in go code.\nconst srcTestSuffix = '.test.tengo';\n\nconst srcTplSuffix = '.tpl.tengo';\nconst srcLibSuffix = '.lib.tengo';\nconst srcSoftwareSuffix = '.sw.json';\nconst srcAssetSuffix = '.as.json';\nconst compilableSuffixes = [srcLibSuffix, srcTplSuffix, srcSoftwareSuffix, srcAssetSuffix];\n\nexport function getPackageInfo(): PackageJson {\n const packageInfo: PackageJson = JSON.parse(fs.readFileSync('package.json').toString());\n return packageInfo;\n}\n\nfunction resolveLibsDst(mode: CompileMode, root: string) {\n return path.resolve(root, mode, 'tengo', 'lib');\n}\n\nfunction resolveTemplatesDst(mode: CompileMode, root: string) {\n return path.resolve(root, mode, 'tengo', 'tpl');\n}\n\nfunction resolveSoftwareDst(mode: CompileMode, root: string) {\n return path.resolve(root, mode, 'tengo', 'software');\n}\n\nfunction resolveAssetsDst(mode: CompileMode, root: string) {\n return path.resolve(root, mode, 'tengo', 'asset');\n}\n\nfunction loadDependencies(\n logger: winston.Logger,\n compiler: TengoTemplateCompiler,\n packageInfo: PackageJson,\n searchIn: string,\n isLink: boolean = false\n): void {\n const packageJsonPath = path.resolve(searchIn, 'package.json');\n\n if (pathType(packageJsonPath) !== 'file') {\n // We're not in package root. Recursively iterate over all folders looking for packages.\n\n for (const f of fs.readdirSync(searchIn)) {\n const isLink = pathType(path.join(searchIn, f)) === 'link';\n const file = path.resolve(searchIn, f);\n const type = pathType(file);\n if (type === 'dir') {\n loadDependencies(logger, compiler, packageInfo, file, isLink);\n }\n }\n\n return;\n }\n\n // we are in package folder\n const libDistFolder = resolveLibsDst('dist', searchIn);\n const tplDistFolder = resolveTemplatesDst('dist', searchIn);\n const softwareDistFolder = resolveSoftwareDst('dist', searchIn);\n const assetDistFolder = resolveAssetsDst('dist', searchIn);\n\n const libDistExists = pathType(libDistFolder) === 'dir';\n const tplDistExists = pathType(tplDistFolder) === 'dir';\n const softwareDistExists = pathType(softwareDistFolder) === 'dir';\n const assetDistExists = pathType(assetDistFolder) === 'dir';\n\n if (!libDistExists && !tplDistExists && !softwareDistExists && !assetDistExists)\n // if neither of tengo-specific folders detected, skipping package\n return;\n\n // we are in tengo dependency folder\n const packageJson: PackageJson = JSON.parse(fs.readFileSync(packageJsonPath).toString());\n\n // in a workspace we will find ourselves in node_modules, ignoring\n if (packageJson.name === packageInfo.name) return;\n\n if (pathType(path.resolve(searchIn, 'node_modules')) === 'dir' && isLink)\n throw new Error(\n `nested node_modules is a sign of library dependencies version incompatibility in ${searchIn}`\n );\n\n if (libDistExists) {\n loadLibsFromDir(logger, packageJson, 'dist', libDistFolder, compiler);\n }\n\n if (tplDistExists) {\n loadTemplatesFromDir(logger, packageJson, 'dist', tplDistFolder, compiler);\n }\n\n if (softwareDistExists) {\n loadSoftwareFromDir(logger, packageJson, 'dist', softwareDistFolder, compiler);\n }\n\n if (assetDistExists) {\n loadAssetsFromDir(logger, packageJson, 'dist', assetDistFolder, compiler);\n }\n}\n\nfunction loadLibsFromDir(\n logger: winston.Logger,\n packageJson: PackageJson,\n mode: CompileMode,\n folder: string,\n compiler: TengoTemplateCompiler\n) {\n for (const f of fs.readdirSync(folder)) {\n const file = path.resolve(folder, f);\n if (!f.endsWith(compiledLibSuffix)) throw new Error(`unexpected file in 'lib' folder: ${file}`);\n const fullName: FullArtifactName = {\n type: 'library',\n pkg: packageJson.name,\n id: f.slice(0, f.length - compiledLibSuffix.length),\n version: packageJson.version\n };\n const src = parseSourceFile(logger, mode, file, fullName, true);\n compiler.addLib(src);\n logger.debug(`Adding dependency ${fullNameToString(fullName)} from ${file}`);\n if (src.dependencies.length > 0) {\n logger.debug('Dependencies:');\n for (const dep of src.dependencies) logger.debug(` - ${typedArtifactNameToString(dep)}`);\n }\n }\n}\n\nfunction loadTemplatesFromDir(\n logger: winston.Logger,\n packageJson: PackageJson,\n mode: CompileMode,\n folder: string,\n compiler: TengoTemplateCompiler\n) {\n // adding templates\n for (const f of fs.readdirSync(folder)) {\n const file = path.resolve(folder, f);\n if (!f.endsWith(compiledTplSuffix)) throw new Error(`unexpected file in 'tpl' folder: ${file}`);\n const fullName: FullArtifactName = {\n type: 'template',\n pkg: packageJson.name,\n id: f.slice(0, f.length - compiledTplSuffix.length),\n version: packageJson.version\n };\n const tpl = new Template(mode, fullName, { content: fs.readFileSync(file) });\n compiler.addTemplate(tpl);\n logger.debug(`Adding dependency ${fullNameToString(fullName)} from ${file}`);\n }\n}\n\nfunction loadSoftwareFromDir(\n logger: winston.Logger,\n packageJson: PackageJson,\n mode: CompileMode,\n folder: string,\n compiler: TengoTemplateCompiler\n) {\n for (const f of fs.readdirSync(folder)) {\n const file = path.resolve(folder, f);\n if (!f.endsWith(compiledSoftwareSuffix))\n throw new Error(`unexpected file in 'software' folder: ${file}`);\n const fullName: FullArtifactName = {\n type: 'software',\n pkg: packageJson.name,\n id: f.slice(0, f.length - compiledSoftwareSuffix.length),\n version: packageJson.version\n };\n\n const software = new ArtifactSource(mode, fullName, fs.readFileSync(file).toString(), file, [], []);\n\n logger.debug(`Adding dependency ${fullNameToString(fullName)} from ${file}`);\n compiler.addSoftware(software);\n }\n}\n\nfunction loadAssetsFromDir(\n logger: winston.Logger,\n packageJson: PackageJson,\n mode: CompileMode,\n folder: string,\n compiler: TengoTemplateCompiler\n) {\n for (const f of fs.readdirSync(folder)) {\n const file = path.resolve(folder, f);\n if (!f.endsWith(compiledAssetSuffix))\n throw new Error(`unexpected file in 'asset' folder: ${file}`);\n const fullName: FullArtifactName = {\n type: 'asset',\n pkg: packageJson.name,\n id: f.slice(0, f.length - compiledAssetSuffix.length),\n version: packageJson.version\n };\n\n const asset = new ArtifactSource(mode, fullName, fs.readFileSync(file).toString(), file, [], []);\n\n logger.debug(`Adding dependency ${fullNameToString(fullName)} from ${file}`);\n compiler.addAsset(asset);\n }\n}\n\nexport function parseSources(\n logger: winston.Logger,\n packageInfo: PackageJson,\n mode: CompileMode,\n root: string,\n subdir: string\n): ArtifactSource[] {\n const sources: ArtifactSource[] = [];\n\n for (const f of fs.readdirSync(path.join(root, subdir))) {\n const inRootPath = path.join(subdir, f); // path to item inside given <root>\n const fullPath = path.join(root, inRootPath); // full path to item from CWD (or abs path, if <root> is abs path)\n\n if (pathType(fullPath) === 'dir') {\n const nested = parseSources(logger, packageInfo, mode, root, inRootPath);\n sources.push(...nested);\n continue;\n }\n\n const artifactName =\n f === 'index.lib.tengo' ? `${path.dirname(inRootPath)}.lib.tengo` : inRootPath;\n\n const fullName = fullNameFromFileName(packageInfo, artifactName.replaceAll(path.sep, '.'));\n if (!fullName) {\n continue; // skip unknown file types\n }\n\n // if (subdir != '') {\n // // prettier-ignore\n // throw new Error(`Templates and libraries should reside only inside '${root}' dir.\n // You are free to have any file and dirs structure inside '${root}' keeping other files where you want,\n // but regarding ${compilableSuffixes.join(', ')}, the flat file structure is mandatory.`);\n // }\n\n const file = path.resolve(root, inRootPath);\n logger.debug(`Parsing ${fullNameToString(fullName)} from ${file}`);\n const newSrc = parseSourceFile(logger, mode, file, fullName, true);\n if (newSrc.dependencies.length > 0) {\n logger.debug('Detected dependencies:');\n for (const dep of newSrc.dependencies) logger.debug(` - ${typedArtifactNameToString(dep)}`);\n }\n\n sources.push(newSrc);\n }\n\n return sources;\n}\n\nexport function newCompiler(\n logger: winston.Logger,\n packageInfo: PackageJson,\n mode: CompileMode\n): TengoTemplateCompiler {\n const compiler = new TengoTemplateCompiler(mode);\n\n // collect all data (templates, libs and software) from dependency tree\n loadDependencies(logger, compiler, packageInfo, findNodeModules());\n\n return compiler;\n}\n\nfunction fullNameFromFileName(\n packageJson: PackageJson,\n artifactName: string\n): FullArtifactName | null {\n const pkgAndVersion = { pkg: packageJson.name, version: packageJson.version };\n if (artifactName.endsWith(srcLibSuffix)) {\n return {\n ...pkgAndVersion,\n id: artifactName.substring(0, artifactName.length - srcLibSuffix.length),\n type: 'library'\n };\n }\n\n if (artifactName.endsWith(srcTplSuffix)) {\n return {\n ...pkgAndVersion,\n id: artifactName.substring(0, artifactName.length - srcTplSuffix.length),\n type: 'template'\n };\n }\n\n if (artifactName.endsWith(srcSoftwareSuffix)) {\n return {\n ...pkgAndVersion,\n id: artifactName.substring(0, artifactName.length - srcSoftwareSuffix.length),\n type: 'software'\n };\n }\n\n if (artifactName.endsWith(srcAssetSuffix)) {\n return {\n ...pkgAndVersion,\n id: artifactName.substring(0, artifactName.length - srcAssetSuffix.length),\n type: 'asset'\n };\n }\n\n if (artifactName.endsWith(srcTestSuffix)) {\n return {\n ...pkgAndVersion,\n id: artifactName.substring(0, artifactName.length - srcTestSuffix.length),\n type: 'test'\n };\n }\n\n return null;\n}\n\nexport function compile(logger: winston.Logger, mode: CompileMode): TemplatesAndLibs {\n const packageInfo = getPackageInfo();\n const compiler = newCompiler(logger, packageInfo, mode);\n const sources = parseSources(logger, packageInfo, mode, 'src', '');\n\n // checking that we have something to do\n if (sources.length === 0) {\n const lookFor: string[] = [];\n for (const suffix of compilableSuffixes) {\n lookFor.push(`*${suffix}`);\n }\n\n logger.error(`Nothing to compile. Looked for ${lookFor.join(', ')}`);\n process.exit(1);\n }\n\n // compilation\n logger.info(`Compiling '${mode}'...`);\n const compiled = compiler.compileAndAdd(sources);\n logger.debug(`Done.`);\n\n return compiled;\n}\n\nexport function savePacks(logger: winston.Logger, compiled: TemplatesAndLibs, mode: CompileMode) {\n // writing libs\n if (compiled.libs.length > 0) {\n const libOutput = resolveLibsDst(mode, '.');\n fs.mkdirSync(libOutput, { recursive: true });\n for (const lib of compiled.libs) {\n const file = path.resolve(libOutput, lib.fullName.id + compiledLibSuffix);\n logger.info(` - writing ${file}`);\n fs.writeFileSync(file, lib.src);\n }\n }\n\n // writing templates\n if (compiled.templates.length > 0) {\n const tplOutput = resolveTemplatesDst(mode, '.');\n fs.mkdirSync(tplOutput, { recursive: true });\n for (const tpl of compiled.templates) {\n const file = path.resolve(tplOutput, tpl.fullName.id + compiledTplSuffix);\n logger.info(` - writing ${file}`);\n fs.writeFileSync(file, tpl.content);\n }\n }\n\n // writing software\n if (compiled.software.length > 0) {\n const swOutput = resolveSoftwareDst(mode, '.');\n fs.mkdirSync(swOutput, { recursive: true });\n for (const sw of compiled.software) {\n const file = path.resolve(swOutput, sw.fullName.id + compiledSoftwareSuffix);\n logger.info(` - writing ${file}`);\n fs.writeFileSync(file, sw.src);\n }\n }\n\n // writing assets\n if (compiled.assets.length > 0) {\n const swOutput = resolveAssetsDst(mode, '.');\n fs.mkdirSync(swOutput, { recursive: true });\n for (const sw of compiled.software) {\n const file = path.resolve(swOutput, sw.fullName.id + compiledAssetSuffix);\n logger.info(` - writing ${file}`);\n fs.writeFileSync(file, sw.src);\n }\n }\n}\n","import { Flags } from '@oclif/core'\n\nexport const GlobalFlags = {\n \"log-level\": Flags.string({\n description: \"logging level\",\n default: \"info\",\n options: [\"error\", \"warn\", \"info\", \"debug\"],\n })\n}\n\nexport const CtagsFlags = {\n \"generate-tags\": Flags.boolean({\n description: \"generate tags, default false\",\n default: false,\n }),\n\n \"tags-file\": Flags.file({\n description: \"where to put \\\".tags\\\" file, it should be a root of VS Code project\",\n default: \"../../.tags\" // usually a user opens a directory with all blocks\n }),\n\n \"tags-additional-args\": Flags.string({\n description: \"additional flags for universal-ctags command: e.g. -e for emacs\",\n default: [],\n multiple: true,\n delimiter: ',',\n })\n}\n","import { SpawnSyncReturns, spawnSync } from 'child_process';\nimport { Command } from '@oclif/core';\nimport { compile, savePacks, getPackageInfo } from '../compiler/main';\nimport { createLogger } from '../compiler/util';\nimport { CtagsFlags, GlobalFlags } from '../shared/basecmd';\nimport * as fs from 'node:fs';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as winston from 'winston';\n\nexport default class Build extends Command {\n static override description = 'build tengo sources into single distributable pack file';\n\n static override examples = ['<%= config.bin %> <%= command.id %>'];\n\n static override flags = {\n ...GlobalFlags,\n ...CtagsFlags\n };\n\n public async run(): Promise<void> {\n const { flags } = await this.parse(Build);\n const logger = createLogger(flags['log-level']);\n\n const packageInfo = getPackageInfo();\n const compiledDist = compile(logger, 'dist');\n savePacks(logger, compiledDist, 'dist');\n logger.info('');\n\n // Building TS bindings for templates\n let dts = `declare type TemplateFromFile = { readonly type: \"from-file\"; readonly path: string; };\\n`;\n dts += `declare type TplName = ${compiledDist.templates\n .map((tpl) => '\"' + tpl.fullName.id + '\"')\n .join(' | ')};\\n`;\n dts += `declare const Templates: Record<TplName, TemplateFromFile>;\\n`;\n dts += `export { Templates };\\n`;\n let cjs = `module.exports = { Templates: {\\n`;\n let mjs = `import { resolve } from 'node:path';\\nexport const Templates = {\\n`;\n const recordsCjs = compiledDist.templates\n .map(\n (tpl) =>\n ` '${tpl.fullName.id}': { type: 'from-file', path: require.resolve('./tengo/tpl/${tpl.fullName.id}.plj.gz') }`\n )\n .join(',\\n');\n const recordsMjs = compiledDist.templates\n .map(\n (tpl) =>\n ` '${tpl.fullName.id}': { type: 'from-file', path: resolve(import.meta.dirname, './tengo/tpl/${tpl.fullName.id}.plj.gz') }`\n )\n .join(',\\n');\n cjs += recordsCjs;\n mjs += recordsMjs;\n cjs += `\\n}};\\n`;\n mjs += `\\n};\\n`;\n\n await fsp.writeFile('dist/index.d.ts', dts);\n if (packageInfo.type === 'module') {\n await fsp.writeFile('dist/index.cjs', cjs);\n await fsp.writeFile('dist/index.js', mjs);\n } else {\n await fsp.writeFile('dist/index.js', cjs);\n await fsp.writeFile('dist/index.mjs', mjs);\n }\n\n mergeTagsEnvs(flags);\n if (flags['generate-tags']) checkAndGenerateCtags(logger, flags);\n\n logger.info('Template Pack build done.');\n }\n}\n\nfunction mergeTagsEnvs(flags: {\n 'generate-tags': boolean;\n 'tags-file': string;\n 'tags-additional-args': string[] | string;\n}) {\n if (process.env.GENERATE_TAGS != undefined) {\n flags['generate-tags'] = process.env.GENERATE_TAGS == 'true';\n }\n\n if (process.env.TAGS_FILE != undefined) {\n flags['tags-file'] = process.env.TAGS_FILE;\n }\n\n if (process.env.TAGS_ADDITIONAL_ARGS != undefined) {\n flags['tags-additional-args'] = process.env.TAGS_ADDITIONAL_ARGS.split(',');\n }\n}\n\nfunction checkAndGenerateCtags(\n logger: winston.Logger,\n flags: {\n 'tags-file': string;\n 'tags-additional-args': string[];\n }\n) {\n const fileName = path.resolve(flags['tags-file']);\n const rootDir = path.dirname(fileName);\n const additionalArgs = flags['tags-additional-args'];\n\n // all tengo files in dirs and subdirs\n const tengoFiles = getTengoFiles(rootDir);\n\n logger.info(\n `Generating tags for tengo autocompletion from \"${rootDir}\" \\\nin \"${fileName}\", additional arguments: \"${additionalArgs}\".\nFound ${tengoFiles.length} tengo files...`\n );\n\n // see https://docs.ctags.io/en/lates// t/man/ctags-optlib.7.html#perl-pod\n const result = spawnSync(\n 'ctags',\n [\n '-f',\n fileName,\n ...additionalArgs,\n '--langdef=tengo',\n '--map-tengo=+.tengo',\n '--kinddef-tengo=f,function,function',\n '--regex-tengo=/^\\\\s*(.*)(:| :=| =) ?func.*/\\\\1/f/',\n '--kinddef-tengo=c,constant,constant',\n '--regex-tengo=/^\\\\s*(.*) := (\"|\\\\{).*/\\\\1/c/',\n '-R',\n ...tengoFiles\n ],\n {\n env: process.env,\n stdio: 'inherit',\n cwd: rootDir\n }\n );\n\n if (result.error?.message.includes('ENOENT')) {\n console.log(`\npl-tengo can create tags for tengo autocompletion,\nbut the program should be installed\nwith \"brew install universal-ctags\" on OSX\nor \"sudo apt install universal-ctags\" on Ubuntu.\n\nFor vscode, you should also install ctags extension:\nhttps://marketplace.visualstudio.com/items?itemName=jaydenlin.ctags-support`);\n\n return;\n }\n\n checkRunError(result, 'failed to generate ctags');\n\n logger.info('Generation of tags is done.');\n}\n\nfunction getTengoFiles(dir: string): string[] {\n const files = fs.readdirSync(dir, { withFileTypes: true, recursive: true });\n const tengoFiles: string[] = [];\n\n files.forEach((file) => {\n if (!file.isDirectory() && file.name.endsWith('.tengo')) {\n // Note that VS Code extension likes only relatives paths to the root of the opened dir.\n const relativePath = path.join(file.parentPath, file.name).replace(dir, '.');\n tengoFiles.push(relativePath);\n }\n });\n\n return tengoFiles;\n}\n\nfunction checkRunError(result: SpawnSyncReturns<Buffer>, message?: string) {\n if (result.error) {\n console.log(result.error);\n }\n\n const msg = message ?? 'failed to run command';\n\n if (result.status !== 0) {\n console.log(`WARN: ${msg} the build will continue as-is`);\n }\n}\n","import winston from 'winston';\nimport { getPackageInfo, newCompiler, parseSources } from '../compiler/main';\nimport { ArtifactType, typedArtifactNameToString } from '../compiler/package';\n\nexport function dumpAll(\n logger: winston.Logger,\n stream: NodeJS.WritableStream\n): void {\n const packageInfo = getPackageInfo();\n\n const sources = parseSources(logger, packageInfo, 'dist', 'src', '');\n\n const compiler = newCompiler(logger, packageInfo, 'dist');\n\n // group output by type:\n // - all libs\n // - all templates\n // - all software\n // - all assets\n // - all tests\n\n // Libs\n\n for (const lib of compiler.allLibs()) {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(lib.fullName)}`\n );\n stream.write(JSON.stringify(lib) + '\\n');\n }\n\n for (const src of sources) {\n if (src.fullName.type === 'library') {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(src.fullName)}`\n );\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n\n // Templates\n\n for (const tpl of compiler.allTemplates()) {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(tpl.fullName)}`\n );\n stream.write(JSON.stringify(tpl) + '\\n');\n }\n\n for (const src of sources) {\n if (src.fullName.type === 'template') {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(src.fullName)} ${\n src.srcName\n }`\n );\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n\n // Software\n\n for (const sw of compiler.allSoftware()) {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(sw.fullName)}`\n );\n stream.write(JSON.stringify(sw) + '\\n');\n }\n\n for (const src of sources) {\n if (src.fullName.type === 'software') {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(src.fullName)}`\n );\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n\n // Assets\n\n for (const asset of compiler.allAssets()) {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(asset.fullName)}`\n );\n stream.write(JSON.stringify(asset) + '\\n');\n }\n\n for (const src of sources) {\n if (src.fullName.type === 'asset') {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(src.fullName)}`\n );\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n\n // Tests\n\n for (const src of sources) {\n if (src.fullName.type === 'test') {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(src.fullName)} ${\n src.srcName\n }`\n );\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n}\n\nexport function dumpLibs(\n logger: winston.Logger,\n dumpDeps: boolean,\n stream: NodeJS.WritableStream\n): void {\n const packageInfo = getPackageInfo();\n\n const sources = parseSources(logger, packageInfo, 'dist', 'src', '');\n\n if (!dumpDeps) {\n for (const src of sources) {\n if (src.fullName.type === 'library') {\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n\n return;\n }\n\n const compiler = newCompiler(logger, packageInfo, 'dist');\n for (const src of sources) {\n if (src.fullName.type === 'library') {\n compiler.addLib(src);\n }\n }\n\n for (const lib of compiler.allLibs()) {\n stream.write(JSON.stringify(lib) + '\\n');\n }\n}\n\nfunction dumpArtifacts(\n logger: winston.Logger,\n stream: NodeJS.WritableStream,\n aType: ArtifactType,\n): void {\n const packageInfo = getPackageInfo();\n\n const sources = parseSources(logger, packageInfo, 'dist', 'src', '');\n\n for (const src of sources) {\n if (src.fullName.type === aType) {\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n}\n\nexport function dumpTemplates(\n logger: winston.Logger,\n stream: NodeJS.WritableStream\n): void {\n dumpArtifacts(logger, stream, 'template')\n}\n\nexport function dumpSoftware(\n logger: winston.Logger,\n stream: NodeJS.WritableStream\n): void {\n dumpArtifacts(logger, stream, 'software')\n}\n\nexport function dumpAssets(\n logger: winston.Logger,\n stream: NodeJS.WritableStream\n): void {\n dumpArtifacts(logger, stream, 'asset')\n}\n\nexport function dumpTests(\n logger: winston.Logger,\n stream: NodeJS.WritableStream\n): void {\n dumpArtifacts(logger, stream, 'test')\n}\n","import { spawn, ChildProcess, ChildProcessByStdio } from 'child_process';\nimport { Writable } from 'stream';\n\nexport function spawnEmbed(\n cmd: string,\n ...args: string[]\n): ChildProcessByStdio<Writable, null, null> {\n const p = spawn(cmd, args, { stdio: ['pipe', 'inherit', 'inherit'] });\n\n p.stdin.on('error', (err: any) => {\n if (err.code === 'EPIPE') {\n // ignore EPIPE error as it stands for broken command run.\n // The command will write normal problem description by itself.\n }\n });\n\n return p;\n}\n\nexport function waitFor(p: ChildProcess): Promise<number> {\n return new Promise((resolve, reject) => {\n p.on('close', (code: number) => {\n resolve(code);\n });\n p.on('error', (err) => {\n reject(err);\n });\n });\n}\n","import { Command } from '@oclif/core';\nimport { createLogger } from '../compiler/util';\nimport { dumpAll } from '../shared/dump';\nimport { GlobalFlags } from '../shared/basecmd';\nimport { spawnEmbed, waitFor } from '../shared/proc';\nimport { TengoTesterBinaryPath } from '@milaboratories/tengo-tester';\n\nexport default class Check extends Command {\n static override description = 'check tengo sources for language processor an';\n\n // static override args = {\n // \"log-level\": Args.string({description: 'logging level'}),\n // }\n\n static strict = false;\n\n static override flags = { ...GlobalFlags };\n\n static override examples = ['<%= config.bin %> <%= command.id %>'];\n\n public async run(): Promise<void> {\n const { flags, argv } = await this.parse(Check);\n const logger = createLogger(flags['log-level']);\n\n const testerArgs: string[] = argv.length == 0 ? ['./src'] : (argv as string[]);\n\n // prettier-ignore\n const tester = spawnEmbed(\n TengoTesterBinaryPath,\n 'check', '--log-level', flags['log-level'],\n '--artifacts', '-',\n ...testerArgs\n )\n\n try {\n dumpAll(logger, tester.stdin);\n } catch (err: unknown) {\n logger.error(err);\n } finally {\n tester.stdin.end();\n const code = await waitFor(tester);\n process.exit(code);\n }\n }\n}\n","import { Command } from '@oclif/core';\nimport { createLogger } from '../compiler/util';\nimport { dumpAll } from '../shared/dump';\nimport { GlobalFlags } from '../shared/basecmd';\nimport { spawnEmbed, waitFor } from '../shared/proc';\nimport { TengoTesterBinaryPath } from '@milaboratories/tengo-tester';\n\nexport default class Test extends Command {\n static override description = 'run tengo unit tests (.test.tengo)';\n\n static strict = false;\n\n static override flags = { ...GlobalFlags };\n\n static override examples = ['<%= config.bin %> <%= command.id %>'];\n\n public async run(): Promise<void> {\n const { flags } = await this.parse(Test);\n const logger = createLogger(flags['log-level']);\n\n const testerArgs: string[] = this.argv.length == 0 ? ['./src'] : this.argv;\n\n // prettier-ignore\n const tester = spawnEmbed(\n TengoTesterBinaryPath,\n 'run', '--log-level', flags['log-level'],\n '--artifacts', '-',\n ...testerArgs,\n )\n\n try {\n dumpAll(logger, tester.stdin);\n } catch (err: unknown) {\n logger.error(err);\n } finally {\n tester.stdin.end();\n const code = await waitFor(tester);\n process.exit(code);\n }\n }\n}\n","import { Command } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpAll } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpAll extends Command {\n static override description = 'parse sources in current package and dump all found artifacts to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n public async run(): Promise<void> {\n const logger = createLogger()\n dumpAll(logger, stdout)\n }\n}\n","import { Command } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpAssets } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpAssets extends Command {\n static override description = 'parse sources in current package and dump all found tests to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n public async run(): Promise<void> {\n const logger = createLogger()\n dumpAssets(logger, stdout)\n }\n}\n","import { Command, Flags } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpLibs } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpLibs extends Command {\n static override description = 'parse sources in current package and dump all found templates to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n static override flags = {\n deps: Flags.boolean({name: 'deps', description: 'add also all libraries found in node_modules'}),\n }\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(DumpLibs)\n\n const logger = createLogger()\n dumpLibs(logger, flags.deps, stdout)\n }\n}\n\n","import { Command } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpSoftware } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpSoftware extends Command {\n static override description = 'parse sources in current package and dump all found tests to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n public async run(): Promise<void> {\n const logger = createLogger()\n dumpSoftware(logger, stdout)\n }\n}\n","import { Command } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpTemplates } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpTemplates extends Command {\n static override description = 'parse sources in current package and dump all found templates to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n public async run(): Promise<void> {\n const logger = createLogger()\n dumpTemplates(logger, stdout)\n }\n}\n\n","import { Command } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpTests } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpTests extends Command {\n static override description = 'parse sources in current package and dump all found tests to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n public async run(): Promise<void> {\n const logger = createLogger()\n dumpTests(logger, stdout)\n }\n}\n","// DO NOT EDIT. This file was generated by oclif-index utility.\n\nimport Cmd0 from './commands/build';\nimport Cmd1 from './commands/check';\nimport Cmd2 from './commands/test';\nimport Cmd3 from './commands/dump/all';\nimport Cmd4 from './commands/dump/assets';\nimport Cmd5 from './commands/dump/libs';\nimport Cmd6 from './commands/dump/software';\nimport Cmd7 from './commands/dump/templates';\nimport Cmd8 from './commands/dump/tests';\n\n// prettier-ignore\nexport const COMMANDS = {\n 'build': Cmd0,\n 'check': Cmd1,\n 'test': Cmd2,\n 'dump:all': Cmd3,\n 'dump:assets': Cmd4,\n 'dump:libs': Cmd5,\n 'dump:software': Cmd6,\n 'dump:templates': Cmd7,\n 'dump:tests': Cmd8\n};\n"],"names":["assertNever","x","createLogger","level","winston","message","findNodeModules","currentDir","possibleNodeModulesPath","path","fs","parentDir","pathType","s","err","isUUID","uuid","artifactKey","name","fullNameToString","typedArtifactNameToString","typedArtifactNamesEquals","name1","name2","artifactNameToString","formatArtefactNameAndVersion","parseArtefactNameAndVersion","nameAndVersion","match","fullNameWithoutTypeToString","decoder","encoder","Template","compileMode","fullName","body","__publicField","data","content","gunzipSync","gzipSync","canonicalize","nameFromData","ArtifactMap","nameExtractor","obj","replace","key","ret","callback","v","createArtifactNameSet","ArtifactStore","mode","k","applyTemplateCompilerOptions","opts","tpl","opt","hashOverride","applyLibraryCompilerOptions","lib","args","override","util.isUUID","TengoTemplateCompiler","src","deps","trace","dep","recursionStart","errorMessage","tplLib","software","asset","tplSrc","tplData","libFromMap","swFromMap","assetFromMap","tplFromMap","sources","current","unprocessed","unsatisfied","u","ArtifactSource","namePattern","functionCallRE","moduleName","fnName","newGetTemplateIdRE","newGetSoftwareInfoRE","newImportTemplateRE","newImportSoftwareRE","newImportAssetRE","emptyLineRE","compilerOptionRE","wrongCompilerOptionRE","singlelineCommentRE","multilineCommentStartRE","multilineCommentEndRE","importRE","importNameRE","dependencyRE","parseComplierOption","parts","namePart","srcName","dependencies","compilerOptions","parseSourceFile","logger","srcFile","fullSourceName","normalize","readFileSync","normalized","parseSourceData","globalizeImports","dependencySet","optionList","lines","processedLines","parserContext","line","result","parseSingleSourceLine","error","context","localPackageName","importInstruction","iInfo","parseImport","artifact","parseArtifactName","artifactRE","artifactType","re","fnCall","templateName","importName","aType","depInfo","pkgName","depID","compiledTplSuffix","compiledLibSuffix","compiledSoftwareSuffix","compiledAssetSuffix","srcTestSuffix","srcTplSuffix","srcLibSuffix","srcSoftwareSuffix","srcAssetSuffix","compilableSuffixes","getPackageInfo","resolveLibsDst","root","resolveTemplatesDst","resolveSoftwareDst","resolveAssetsDst","loadDependencies","compiler","packageInfo","searchIn","isLink","packageJsonPath","f","file","libDistFolder","tplDistFolder","softwareDistFolder","assetDistFolder","libDistExists","tplDistExists","softwareDistExists","assetDistExists","packageJson","loadLibsFromDir","loadTemplatesFromDir","loadSoftwareFromDir","loadAssetsFromDir","folder","parseSources","subdir","inRootPath","fullPath","nested","artifactName","fullNameFromFileName","newSrc","newCompiler","pkgAndVersion","compile","lookFor","suffix","compiled","savePacks","libOutput","tplOutput","swOutput","sw","GlobalFlags","Flags","CtagsFlags","_Build","Command","flags","compiledDist","dts","cjs","mjs","recordsCjs","recordsMjs","fsp","mergeTagsEnvs","checkAndGenerateCtags","Build","fileName","rootDir","additionalArgs","tengoFiles","getTengoFiles","spawnSync","_a","checkRunError","dir","files","relativePath","msg","dumpAll","stream","dumpLibs","dumpDeps","dumpArtifacts","dumpTemplates","dumpSoftware","dumpAssets","dumpTests","spawnEmbed","cmd","p","spawn","waitFor","resolve","reject","code","_Check","argv","testerArgs","tester","TengoTesterBinaryPath","Check","_Test","Test","DumpAll","stdout","DumpAssets","_DumpLibs","DumpLibs","DumpSoftware","DumpTemplates","DumpTests","COMMANDS","Cmd0","Cmd1","Cmd2","Cmd3","Cmd4","Cmd5","Cmd6","Cmd7","Cmd8"],"mappings":"s0BAIO,SAASA,EAAYC,EAAiB,CACrC,MAAA,IAAI,MAAM,sBAAwBA,CAAC,CAC3C,CAEgB,SAAAC,EAAaC,EAAgB,QAAyB,CACpE,OAAOC,EAAQ,aAAa,CAC1B,MAAAD,EACA,OAAQC,EAAQ,OAAO,OAAO,CAAC,CAAE,MAAAD,EAAO,QAAAE,KAC/B,GAAGF,EAAM,SAAS,EAAG,GAAG,CAAC,KAAKE,CAAO,EAC7C,EACD,WAAY,CACV,IAAID,EA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MAASC,EACT,KAAQC,EACR,WAAYC,EACZ,cAAeC,EACf,YAAaC,EACb,gBAAiBC,GACjB,iBAAkBC,GAClB,aAAcC,EAChB"}
1
+ {"version":3,"file":"index.js","sources":["../src/compiler/util.ts","../src/compiler/package.ts","../src/compiler/template.ts","../src/compiler/artifactset.ts","../src/compiler/compileroptions.ts","../src/compiler/compiler.ts","../src/compiler/source.ts","../src/compiler/main.ts","../src/shared/basecmd.ts","../src/commands/build.ts","../src/shared/dump.ts","../src/shared/proc.ts","../src/commands/check.ts","../src/commands/test.ts","../src/commands/dump/all.ts","../src/commands/dump/assets.ts","../src/commands/dump/libs.ts","../src/commands/dump/software.ts","../src/commands/dump/templates.ts","../src/commands/dump/tests.ts","../src/index.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as winston from 'winston';\n\nexport function assertNever(x: never): never {\n throw new Error('Unexpected object: ' + x);\n}\n\nexport function createLogger(level: string = 'debug'): winston.Logger {\n return winston.createLogger({\n level: level,\n format: winston.format.printf(({ level, message }) => {\n return `${level.padStart(6, ' ')}: ${message}`;\n }),\n transports: [\n new winston.transports.Console({\n stderrLevels: ['error', 'warn', 'info', 'debug'],\n handleExceptions: true\n })\n ]\n });\n}\n\nexport function findNodeModules(): string {\n let currentDir = process.cwd();\n\n while (currentDir) {\n const possibleNodeModulesPath = path.join(currentDir, 'node_modules');\n\n if (fs.existsSync(possibleNodeModulesPath)) return possibleNodeModulesPath;\n\n const parentDir = path.resolve(currentDir, '..');\n if (parentDir === currentDir) break; // reached the root directory\n\n currentDir = parentDir;\n }\n\n throw new Error('Unable to find node_modules directory.');\n}\n\nexport type PathType = 'absent' | 'file' | 'dir' | 'link' | 'unknown';\n\nexport function pathType(path: string): PathType {\n try {\n const s = fs.statSync(path);\n if (s.isDirectory()) return 'dir';\n if (s.isFile()) return 'file';\n if (s.isSymbolicLink()) return 'link';\n return 'unknown';\n } catch (err: any) {\n if (err.code == 'ENOENT') return 'absent';\n else throw err;\n }\n}\n\nexport function isUUID(uuid: string): boolean {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return uuidRegex.test(uuid.toLowerCase());\n}\n","/*\n Package \"@milaboratory/current-tengo-package\".\n\n Structure:\n\n src/\n local-template.pl.tengo <- this one will be compiled and put into ./dist/tengo/tpl/local-template.pl.pkg\n local-library.tengo <- this one will be normalized and put into ./dist/tengo/lib/local-library.tengo\n main.tpl.tengo <- this one will be compiled into ./dist/tengo/tpl/main.pl.pkg and published by external tool\n\n Code of \"main.tpl.tengo\":\n\n plapi := import(\"plapi\")\n\n plapi.getTemplateId(\"@milaboratory/some-tengo-template\") // -> getTemplateId(\"@milaboratory/some-tengo-template:main\")\n import(\"@milaboratory/some-tengo-library\") // -> import(\"@milaboratory/some-tengo-library:main\")\n\n */\n\nexport type CompileMode = 'dist';\n\nexport type CompilerOption = {\n /** Option name, like 'hash_override' */\n name: string; // we can't use strict literals typing here as we will break compatibility of the code through the lifetime of the compiler.\n\n /** Arguments of the option. Everything that follows option name */\n args: string[];\n};\n\nexport type ArtifactType = 'library' | 'template' | 'test' | 'software' | 'asset';\n\n/** Artifact Name including package version */\nexport interface FullArtifactName {\n /** Dependency type */\n type: ArtifactType;\n\n /** Fully qualified package */\n pkg: string;\n\n /** Id of the artifact inside the package */\n id: string;\n\n /** Package version */\n version: string;\n}\n\nexport type FullArtifactNameWithoutType = Omit<FullArtifactName, 'type'>;\n\nexport type TypedArtifactName = Pick<FullArtifactName, 'type' | 'pkg' | 'id'>;\n\nexport type PackageName = Pick<FullArtifactName, 'pkg' | 'version'>;\n\nexport type ArtifactName = Pick<FullArtifactName, 'pkg' | 'id'>;\n\nexport function artifactKey(name: TypedArtifactName): string {\n return `${name.type}||${name.pkg}||${name.id}`;\n}\n\nexport function fullNameToString(name: FullArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}:${name.version}`;\n}\n\n/** used for exceptions */\nexport function typedArtifactNameToString(name: TypedArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}`;\n}\n\nexport function typedArtifactNamesEquals(\n name1: TypedArtifactName,\n name2: TypedArtifactName\n): boolean {\n return name1.type == name2.type && name1.pkg == name2.pkg && name1.id == name2.id;\n}\n\n/** used to format artefact name while generating output files */\nexport function artifactNameToString(name: ArtifactName): string {\n return `${name.pkg}:${name.id}`;\n}\n\n/** used to format artefact name and version while generating output files */\nexport function formatArtefactNameAndVersion(name: FullArtifactName): {\n name: string;\n version: string;\n} {\n return { name: artifactNameToString(name), version: name.version };\n}\n\n/** used to format artefact name and version while generating output files */\nexport function parseArtefactNameAndVersion(nameAndVersion: {\n name: string;\n version: string;\n}): FullArtifactNameWithoutType {\n const match = nameAndVersion.name.match(/^(?<pkg>[^:]*):(?<id>[^:]*)$/);\n if (!match) throw new Error(`malformed artifact name: ${nameAndVersion.name}`);\n return { pkg: match.groups!['pkg'], id: match.groups!['id'], version: nameAndVersion.version };\n}\n\nexport function fullNameWithoutTypeToString(name: FullArtifactNameWithoutType): string {\n return `${name.pkg}:${name.id}:${name.version}`;\n}\n\nexport function fullNameWithoutType(name: FullArtifactName): FullArtifactNameWithoutType {\n return { pkg: name.pkg, id: name.id, version: name.version };\n}\n","import type {\n CompileMode,\n FullArtifactName,\n FullArtifactNameWithoutType,\n} from './package';\nimport {\n fullNameWithoutTypeToString,\n parseArtefactNameAndVersion,\n} from './package';\nimport type { TemplateData } from '@milaboratories/pl-model-backend';\nimport {\n parseTemplate,\n serializeTemplate,\n} from '@milaboratories/pl-model-backend';\n\nexport class Template {\n public readonly data: TemplateData;\n public readonly content: Uint8Array;\n\n constructor(\n public readonly compileMode: CompileMode,\n public readonly fullName: FullArtifactName,\n body: {\n data?: TemplateData;\n content?: Uint8Array;\n },\n ) {\n let { data, content } = body;\n if (data === undefined && content === undefined)\n throw new Error('Neither data nor content is provided for template constructor');\n if (data !== undefined && content !== undefined)\n throw new Error('Both data and content are provided for template constructor');\n\n if (data === undefined) data = parseTemplate(content!);\n if (content === undefined) content = serializeTemplate(data);\n\n const nameFromData: FullArtifactNameWithoutType = parseArtefactNameAndVersion(data);\n\n if (\n nameFromData.pkg !== fullName.pkg\n || nameFromData.id !== fullName.id\n || nameFromData.version !== fullName.version\n )\n throw new Error(\n `Compiled template name don't match it's package and file names: ${fullNameWithoutTypeToString(nameFromData)} != ${fullNameWithoutTypeToString(fullName)}`,\n );\n\n this.data = data;\n this.content = content;\n }\n\n toJSON() {\n return { compileMode: this.compileMode, fullName: this.fullName, data: this.data };\n }\n}\n","import { CompileMode, TypedArtifactName, artifactKey } from './package';\nimport { assertNever } from './util';\n\nexport class ArtifactMap<T> {\n private readonly map = new Map<string, T>();\n\n constructor(private readonly nameExtractor: (obj: T) => TypedArtifactName) {\n }\n\n add(obj: T, replace: boolean = true): T | undefined {\n const key = artifactKey(this.nameExtractor(obj));\n const ret = this.map.get(key);\n if (ret && !replace)\n return ret;\n this.map.set(key, obj);\n return ret;\n }\n\n get(name: TypedArtifactName): T | undefined {\n return this.map.get(artifactKey(name));\n }\n\n get array(): T[] {\n const ret: T[] = [];\n this.map.forEach(obj => ret.push(obj));\n return ret;\n }\n\n forEach(callback: (value: T, key: TypedArtifactName) => void) {\n this.map.forEach(v => callback(v, this.nameExtractor(v)));\n }\n}\n\nexport function createArtifactNameSet(): ArtifactMap<TypedArtifactName> {\n return new ArtifactMap<TypedArtifactName>(obj => obj);\n}\n\nexport class ArtifactStore<T> {\n private readonly dev: ArtifactMap<T>\n private readonly dist: ArtifactMap<T>\n\n constructor(private readonly nameExtractor: (obj: T) => TypedArtifactName) {\n this.dev = new ArtifactMap<T>(nameExtractor)\n this.dist = new ArtifactMap<T>(nameExtractor)\n }\n\n add(mode: CompileMode, obj: T, replace: boolean = true): T | undefined {\n switch (mode) {\n case 'dist':\n return this.dist.add(obj, replace)\n\n default:\n assertNever(mode)\n }\n }\n\n get(mode: CompileMode, name: TypedArtifactName): T | undefined {\n switch (mode) {\n case 'dist':\n return this.dist.get(name);\n\n default:\n assertNever(mode)\n }\n }\n\n array(mode: CompileMode): T[] {\n const ret: T[] = [];\n this.forEach(mode, obj => ret.push(obj));\n return ret;\n }\n\n forEach(mode: CompileMode, callback: (value: T, key: TypedArtifactName) => void) {\n this.dist.forEach( (obj, k) => callback(this.get(mode, k) ?? obj, k) )\n }\n}\n","import { TemplateData, TemplateLibData } from '@milaboratories/pl-model-backend';\nimport { CompilerOption } from './package';\nimport * as util from './util';\n\nexport function applyTemplateCompilerOptions(opts: CompilerOption[], tpl: TemplateData) {\n for (const opt of opts) {\n switch (opt.name) {\n case 'hash_override': {\n tpl.hashOverride = hashOverride(opt.args);\n break;\n }\n }\n }\n}\n\nexport function applyLibraryCompilerOptions(opts: CompilerOption[], lib: TemplateLibData) {\n for (const opt of opts) {\n switch (opt.name) {\n case 'hash_override': {\n throw new Error(\n `hash_override compiler option can be used ONLY on template level. Even in templates it is already dangerous enough` +\n ` to potentially break everything in Platforma Backend. In libraries with the transitive dependencies`+\n ` resolution and flattening of libraries list on template level, it becomes so unpredictibally disasterous, that`+\n ` we are doomed to never find the ends of a knot if anything goes wrong.`\n );\n }\n }\n }\n}\n\nexport function hashOverride(args: string[]): string {\n if (args.length != 1) {\n throw new Error(\n 'hash_override compiler option expects exactly one argument: hash_override <some string>. Note, you can use only UUID as a value.'\n );\n }\n\n const override = args[0].toLowerCase();\n\n if (!util.isUUID(override)) {\n throw new Error(\n 'hash_override must contain valid UUID as an override. As hash_override affects deduplication,' +\n \" it becomes completely not possible to distinguish several different templates from each other on backend's side.\" +\n ' This means, if you set hash_override to a simple value (say, letter \"a\") on two completely different templates,' +\n \" they will be marked as interchangeable on backend's side with unpredictable consequences.\" +\n ' UUID looks like a safe enough tradeoff between the feature usage simplicity and duplication safety'\n );\n }\n\n return override;\n}\n","import { ArtifactSource } from './source';\nimport { Template } from './template';\nimport {\n TypedArtifactName,\n fullNameToString,\n typedArtifactNameToString,\n artifactNameToString,\n formatArtefactNameAndVersion, typedArtifactNamesEquals, FullArtifactName,\n CompileMode\n} from './package';\nimport { ArtifactStore } from './artifactset';\nimport { assertNever } from './util';\nimport { applyLibraryCompilerOptions, applyTemplateCompilerOptions } from './compileroptions';\nimport { TemplateData } from '@milaboratories/pl-model-backend';\n\nexport interface TemplatesAndLibs {\n templates: Template[],\n libs: ArtifactSource[],\n software: ArtifactSource[]\n assets: ArtifactSource[]\n}\n\nexport class TengoTemplateCompiler {\n constructor(\n private readonly compileMode: CompileMode\n ) { }\n\n private readonly libs = new ArtifactStore<ArtifactSource>(src => src.fullName);\n private readonly software = new ArtifactStore<ArtifactSource>(src => src.fullName);\n private readonly assets = new ArtifactStore<ArtifactSource>(src => src.fullName);\n private readonly templates = new ArtifactStore<Template>(tpl => tpl.fullName);\n\n private populateTemplateDataFromDependencies(fullName: FullArtifactName,\n data: TemplateData,\n deps: TypedArtifactName[],\n trace: string[]) {\n for (const dep of deps) {\n switch (dep.type) {\n case 'library': {\n const lib = this.getLibOrError(dep);\n\n const recursionStart = trace.indexOf(artifactNameToString(dep))\n if (recursionStart >= 0) {\n let errorMessage = `library import recursion detected: ${trace.slice(recursionStart).join(\" -> \")} -> ${artifactNameToString(dep)}`\n throw new Error(errorMessage)\n }\n\n const tplLib = {\n ...formatArtefactNameAndVersion(lib.fullName),\n src: lib.src\n }\n\n applyLibraryCompilerOptions(lib.compilerOptions, tplLib)\n data.libs[artifactNameToString(dep)] = tplLib;\n\n // populate with transient library dependencies\n this.populateTemplateDataFromDependencies(fullName, data, lib.dependencies, [...trace, artifactNameToString(dep)]);\n\n break;\n }\n case 'software':\n const software = this.getSoftwareOrError(dep);\n data.software[artifactNameToString(dep)] = {\n ...formatArtefactNameAndVersion(software.fullName),\n src: software.src\n }\n\n break;\n case 'asset':\n const asset = this.getAssetOrError(dep);\n // Yes, we temporarily put assets into 'software' section of template, so controller can\n // handle it the right way without updates\n data.software[artifactNameToString(dep)] = {\n ...formatArtefactNameAndVersion(asset.fullName),\n src: asset.src\n }\n\n break;\n case 'template':\n if (typedArtifactNamesEquals(fullName, dep))\n // skipping self reference\n continue;\n\n const tpl = this.getTemplateOrError(dep);\n data.templates[artifactNameToString(dep)] = tpl.data;\n break;\n case 'test':\n throw new Error(\n `dependencies tree error: tests should never be part of template: ${typedArtifactNameToString(dep)} is dependency of ${artifactNameToString(fullName)}`,\n )\n default:\n assertNever(dep.type);\n }\n }\n }\n\n /** This method assumes that all dependencies are already added to the compiler's context */\n private compileAndAddTemplate(tplSrc: ArtifactSource): Template {\n if (tplSrc.fullName.type !== 'template')\n throw new Error('unexpected source type');\n\n // creating template with unpopulated dependencies\n const tplData: TemplateData = {\n type: 'pl.tengo-template.v2',\n ...formatArtefactNameAndVersion(tplSrc.fullName),\n templates: {},\n libs: {},\n software: {},\n assets: {},\n src: tplSrc.src\n };\n\n applyTemplateCompilerOptions(tplSrc.compilerOptions, tplData);\n\n // collecting dependencies in output format\n this.populateTemplateDataFromDependencies(tplSrc.fullName, tplData, tplSrc.dependencies, []);\n\n const tpl = new Template(tplSrc.compileMode, tplSrc.fullName, { data: tplData });\n this.addTemplate(tpl);\n return tpl;\n }\n\n addLib(lib: ArtifactSource) {\n const libFromMap = this.libs.add(lib.compileMode, lib, false)\n if (libFromMap)\n throw new Error(\n `compiler already contain such library: adding = ${fullNameToString(lib.fullName)}, contains = ${fullNameToString(libFromMap.fullName)}`\n );\n }\n\n allLibs(): ArtifactSource[] {\n return this.libs.array(this.compileMode)\n }\n\n getLib(name: TypedArtifactName): ArtifactSource | undefined {\n if (name.type !== 'library')\n throw new Error(`illegal artifact type: got ${name.type} instead of 'library`);\n return this.libs.get(this.compileMode, name);\n }\n\n getLibOrError(name: TypedArtifactName): ArtifactSource {\n const lib = this.getLib(name);\n if (!lib)\n throw new Error(`library not found: ${artifactNameToString(name)}`);\n return lib;\n }\n\n addSoftware(software: ArtifactSource) {\n const swFromMap = this.software.add(software.compileMode, software, false)\n if (swFromMap)\n throw new Error(\n `compiler already contain info for software: adding = ${fullNameToString(software.fullName)}, contains = ${fullNameToString(swFromMap.fullName)}`\n );\n }\n\n allSoftware(): ArtifactSource[] {\n return this.software.array(this.compileMode)\n }\n\n getSoftware(name: TypedArtifactName): ArtifactSource | undefined {\n if (name.type !== 'software')\n throw new Error(`illegal artifact type: got ${name.type} instead of 'software`);\n\n return this.software.get(this.compileMode, name);\n }\n\n getSoftwareOrError(name: TypedArtifactName): ArtifactSource {\n const software = this.getSoftware(name);\n if (!software)\n throw new Error(`software info not found: ${artifactNameToString(name)}`);\n return software;\n }\n\n addAsset(asset: ArtifactSource) {\n const assetFromMap = this.assets.add(asset.compileMode, asset, false)\n if (assetFromMap)\n throw new Error(\n `compiler already contain info for asset: adding = ${fullNameToString(asset.fullName)}, contains = ${fullNameToString(assetFromMap.fullName)}`\n );\n }\n\n allAssets(): ArtifactSource[] {\n return this.assets.array(this.compileMode)\n }\n\n getAsset(name: TypedArtifactName): ArtifactSource | undefined {\n if (name.type !== 'asset')\n throw new Error(`illegal artifact type: got ${name.type} instead of 'asset`);\n\n return this.assets.get(this.compileMode, name);\n }\n\n getAssetOrError(name: TypedArtifactName): ArtifactSource {\n const asset = this.getAsset(name);\n if (!asset)\n throw new Error(`asset info not found: ${artifactNameToString(name)}`);\n return asset;\n }\n\n addTemplate(tpl: Template) {\n const tplFromMap = this.templates.add(tpl.compileMode, tpl, false);\n if (tplFromMap)\n throw new Error(\n `compiler already contain such template: adding = ${fullNameToString(tpl.fullName)}, contains = ${fullNameToString(tplFromMap.fullName)}`\n );\n }\n\n allTemplates(): Template[] {\n return this.templates.array(this.compileMode)\n }\n\n getTemplate(name: TypedArtifactName): Template | undefined {\n if (name.type !== 'template')\n throw new Error(`illegal artifact type: got ${name.type} instead of 'template`);\n return this.templates.get(this.compileMode, name);\n }\n\n getTemplateOrError(name: TypedArtifactName): Template {\n const tpl = this.getTemplate(name);\n if (!tpl)\n throw new Error(`template not found: ${artifactNameToString(name)}`);\n return tpl;\n }\n\n getArtefact(name: TypedArtifactName): ArtifactSource | Template | undefined {\n switch (name.type) {\n case 'template':\n return this.getTemplate(name);\n case 'library':\n return this.getLib(name);\n case 'software':\n return this.getSoftware(name);\n case 'asset':\n return this.getAsset(name);\n case 'test':\n // Tests are ignored by the complier. They should never be compiled into templates or libs and\n // should never be a dependency.\n return undefined;\n default:\n assertNever(name.type);\n }\n }\n\n checkLibs() {\n this.libs.forEach(this.compileMode, lib => {\n for (const dep of lib.dependencies) {\n if (dep.type === 'test')\n throw new Error(`test should never be dependency of production code: ${typedArtifactNameToString(dep)} test is dependency of ${fullNameToString(lib.fullName)}`);\n\n if (!this.getArtefact(dep))\n throw new Error(`unresolved dependency ${typedArtifactNameToString(dep)} for ${fullNameToString(lib.fullName)}`);\n }\n });\n }\n\n compileAndAdd(sources: ArtifactSource[]): TemplatesAndLibs {\n const ret: TemplatesAndLibs = { templates: [], libs: [], software: [], assets: [] };\n let current: ArtifactSource[] = [];\n\n for (const src of sources) {\n if (src.fullName.type === 'library') {\n // add libraries 'as-is' to be able to resolve them as dependencies\n this.addLib(src);\n ret.libs.push(src);\n } else if (src.fullName.type === 'software') {\n // add software 'as-is' to be able to resolve them as dependencies\n this.addSoftware(src);\n ret.software.push(src);\n } else if (src.fullName.type === 'asset') {\n // add assets 'as-is' to be able to resolve them as dependencies\n this.addAsset(src);\n ret.assets.push(src);\n } else {\n current.push(src)\n }\n }\n\n while (current.length > 0) {\n const unprocessed: { src: ArtifactSource, err: Error }[] = [];\n\n for (const src of current) {\n //\n // If one of the dependencies can't be resolved with current compiler context,\n // we put aside the source until next iteration, in hope that the dependency\n // will be satisfied then.\n //\n // This is equivalent to topological sorting of input sources.\n //\n const unsatisfied = src.dependencies.filter(dep =>\n !this.getArtefact(dep) &&\n // allow self reference for templates\n !(src.fullName.type === 'template' && typedArtifactNamesEquals(src.fullName, dep))\n )\n if (unsatisfied.length > 0) {\n let errorMessage = `Unsatisfied dependencies in ${fullNameToString(src.fullName)}:\\n`\n for (const dep of unsatisfied) {\n errorMessage += ` - ${typedArtifactNameToString(dep)}\\n`;\n }\n unprocessed.push({ src, err: Error(errorMessage) })\n\n continue;\n }\n\n // type specific processing\n switch (src.fullName.type) {\n case 'library':\n // libraries are added as is\n this.addLib(src);\n ret.libs.push(src);\n break;\n case 'software':\n // software dependencies are added as is\n this.addSoftware(src);\n ret.software.push(src);\n break;\n case 'asset':\n // software dependencies are added as is\n this.addAsset(src);\n ret.assets.push(src);\n break;\n case 'template':\n // templates are compiled and then added\n try {\n const tpl = this.compileAndAddTemplate(src);\n ret.templates.push(tpl);\n } catch (err: any) {\n let errorMessage = `Unsatisfied dependencies in ${fullNameToString(src.fullName)}:\\n`\n errorMessage += ` - ${err.message}\\n`;\n\n unprocessed.push({ src, err: Error(errorMessage) }) // one or more dependencies are not resolvable yet\n }\n break;\n case 'test':\n // Ignore tests: they never should be part of compiled code or be a dependency.\n break;\n default:\n assertNever(src.fullName.type);\n }\n }\n\n // checking that we successfully added at least one source,\n // if not all the source files in unprocessed array have unmet dependencies\n if (current.length === unprocessed.length) {\n let errorMessage = '';\n\n for (const u of unprocessed) {\n errorMessage += `\\n${u.err.message}`\n }\n throw new Error(errorMessage);\n }\n\n current = unprocessed.map(({ src: ArtifactSource }) => ArtifactSource);\n }\n\n return ret;\n }\n}\n","import { readFileSync } from 'node:fs';\nimport winston from 'winston';\nimport {\n TypedArtifactName,\n FullArtifactName,\n ArtifactType,\n CompileMode,\n CompilerOption\n} from './package';\nimport { ArtifactMap, createArtifactNameSet } from './artifactset';\n\n// matches any valid name in tengo. Don't forget to use '\\b' when needed to limit the boundaries!\nconst namePattern = '[_a-zA-Z][_a-zA-Z0-9]*';\n\nconst functionCallRE = (moduleName: string, fnName: string) => {\n return new RegExp(\n `\\\\b${moduleName}\\\\.(?<fnCall>(?<fnName>` +\n fnName +\n `)\\\\s*\\\\(\\\\s*\"(?<templateName>[^\"]+)\"\\\\s*\\\\))`\n );\n};\n\nconst newGetTemplateIdRE = (moduleName: string) => {\n return functionCallRE(moduleName, 'getTemplateId');\n};\nconst newGetSoftwareInfoRE = (moduleName: string) => {\n return functionCallRE(moduleName, 'getSoftwareInfo');\n};\n\nconst newImportTemplateRE = (moduleName: string) => {\n return functionCallRE(moduleName, 'importTemplate');\n};\nconst newImportSoftwareRE = (moduleName: string) => {\n return functionCallRE(moduleName, 'importSoftware');\n};\nconst newImportAssetRE = (moduleName: string) => {\n return functionCallRE(moduleName, 'importAsset');\n};\n\nconst emptyLineRE = /^\\s*$/;\nconst compilerOptionRE = /^\\/\\/tengo:[\\w]/;\nconst wrongCompilerOptionRE = /^\\s*\\/\\/\\s*tengo:\\s*./;\nconst singlelineCommentRE = /^\\s*(\\/\\/)|(\\/\\*.*\\*\\/)/;\nconst multilineCommentStartRE = /^\\s*\\/\\*/;\nconst multilineCommentEndRE = /\\*\\//;\nconst importRE = /\\s*:=\\s*import\\s*\\(\\s*\"(?<moduleName>[^\"]+)\"\\s*\\)/;\nconst importNameRE = new RegExp(\n `\\\\b(?<importName>${namePattern}(\\\\.${namePattern})*)${importRE.source}`\n);\nconst dependencyRE = /(?<pkgName>[^\"]+)?:(?<depID>[^\"]+)/; // use it to parse <moduleName> from importPattern or <templateName> акщь getTemplateID\n\n/**\n * Parse compiler option string representation\n * Compiler option line is a comment starting with '//tengo:', say\n * //tengo:hash_override tralala\n *\n * The common compiler option syntax is:\n * //tengo:<option name> [<option arg1> [<option arg 2> [...]]]\n */\nconst parseComplierOption = (opt: string): CompilerOption => {\n const parts = opt.split(' ');\n const namePart = parts[0].split(':');\n if (namePart.length != 2) {\n throw new Error(\n \"compiler option format is wrong: expect to have option name after 'tengo:' prefix, like 'tengo:MyOption'\"\n );\n }\n const optName = namePart[1];\n\n return {\n name: optName,\n args: parts.slice(1)\n };\n};\n\nexport class ArtifactSource {\n constructor(\n /** The mode this artifact was built (dev or dist) */\n public readonly compileMode: CompileMode,\n /** Full artifact id, including package version */\n public readonly fullName: FullArtifactName,\n /** Normalized source code */\n public readonly src: string,\n /** Path to source file where artifact came from */\n public readonly srcName: string,\n /** List of dependencies */\n public readonly dependencies: TypedArtifactName[],\n /** Additional compiler options detected in source code */\n public readonly compilerOptions: CompilerOption[]\n ) {}\n}\n\nexport function parseSourceFile(\n logger: winston.Logger,\n mode: CompileMode,\n srcFile: string,\n fullSourceName: FullArtifactName,\n normalize: boolean\n): ArtifactSource {\n const src = readFileSync(srcFile).toString();\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(mode, fullSourceName, normalized, srcFile, deps.array, opts);\n}\n\nexport function parseSource(\n logger: winston.Logger,\n mode: CompileMode,\n src: string,\n fullSourceName: FullArtifactName,\n normalize: boolean\n): ArtifactSource {\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(mode, fullSourceName, normalized, '', deps.array, opts);\n}\n\nfunction parseSourceData(\n logger: winston.Logger,\n src: string,\n fullSourceName: FullArtifactName,\n globalizeImports: boolean\n): {\n normalized: string;\n deps: ArtifactMap<TypedArtifactName>;\n opts: CompilerOption[];\n} {\n const dependencySet = createArtifactNameSet();\n const optionList: CompilerOption[] = [];\n\n // iterating over lines\n const lines = src.split('\\n');\n\n // processedLines keep all the original lines from <src>.\n // If <globalizeImport>==true, the parser modifies 'import' and 'getTemplateId' lines\n // with Platforma Tengo lib and template usages, resolving local names (\":<item>\") to\n // global (\"@milaboratory/pkg:<item>\")\n const processedLines: string[] = [];\n let parserContext: sourceParserContext = {\n isInCommentBlock: false,\n canDetectOptions: true,\n tplDepREs: new Map<string, [ArtifactType, RegExp][]>(),\n lineNo: 0\n };\n\n for (const line of lines) {\n parserContext.lineNo++;\n\n try {\n const result = parseSingleSourceLine(\n logger,\n line,\n parserContext,\n fullSourceName.pkg,\n globalizeImports\n );\n processedLines.push(result.line);\n parserContext = result.context;\n\n if (result.artifact) {\n dependencySet.add(result.artifact);\n }\n if (result.option) {\n optionList.push(result.option);\n }\n } catch (error: any) {\n throw new Error(`[line ${parserContext.lineNo}]: ${error.message}\\n\\t${line}`);\n }\n }\n\n return {\n normalized: processedLines.join('\\n'),\n deps: dependencySet,\n opts: optionList\n };\n}\n\ninterface sourceParserContext {\n isInCommentBlock: boolean;\n canDetectOptions: boolean;\n tplDepREs: Map<string, [ArtifactType, RegExp][]>;\n lineNo: number;\n}\n\nfunction parseSingleSourceLine(\n logger: winston.Logger,\n line: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean\n): {\n line: string;\n context: sourceParserContext;\n artifact: TypedArtifactName | undefined;\n option: CompilerOption | undefined;\n} {\n if (context.isInCommentBlock) {\n if (multilineCommentEndRE.exec(line)) {\n context.isInCommentBlock = false;\n }\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (compilerOptionRE.exec(line)) {\n if (!context.canDetectOptions) {\n logger.error(\n `[line ${context.lineNo}]: compiler option '//tengo:' was detected, but it cannot be applied as compiler options can be set only at the file header, before any code line'`\n );\n throw new Error(\"tengo compiler options ('//tengo:' comments) can be set only in file header\");\n }\n return { line, context, artifact: undefined, option: parseComplierOption(line) };\n }\n\n if (wrongCompilerOptionRE.exec(line) && context.canDetectOptions) {\n logger.warn(\n `[line ${context.lineNo}]: text simillar to compiler option ('//tengo:...') was detected, but it has wrong format. Leave it as is, if you did not mean to use a line as compiler option. Or format it to '//tengo:<option>' otherwise (no spaces between '//' and 'tengo', no spaces between ':' and option name)`\n );\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (singlelineCommentRE.exec(line)) {\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (multilineCommentStartRE.exec(line)) {\n context.isInCommentBlock = true;\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (emptyLineRE.exec(line)) {\n return { line, context, artifact: undefined, option: undefined };\n }\n\n context.canDetectOptions = false;\n\n const importInstruction = importRE.exec(line);\n\n if (importInstruction) {\n const iInfo = parseImport(line);\n\n if (iInfo.module === 'plapi') {\n if (!context.tplDepREs.has(iInfo.module)) {\n context.tplDepREs.set(iInfo.module, [\n ['template', newGetTemplateIdRE(iInfo.alias)],\n ['software', newGetSoftwareInfoRE(iInfo.alias)]\n ]);\n }\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (\n iInfo.module === '@milaboratory/tengo-sdk:ll' ||\n iInfo.module === '@platforma-sdk/workflow-tengo:ll' ||\n ((localPackageName === '@milaboratory/tengo-sdk' ||\n localPackageName === '@platforma-sdk/workflow-tengo') &&\n iInfo.module === ':ll')\n ) {\n if (!context.tplDepREs.has(iInfo.module)) {\n context.tplDepREs.set(iInfo.module, [\n ['template', newImportTemplateRE(iInfo.alias)],\n ['software', newImportSoftwareRE(iInfo.alias)]\n ]);\n }\n }\n\n if (\n iInfo.module === '@milaboratory/tengo-sdk:assets' ||\n iInfo.module === '@platforma-sdk/workflow-tengo:assets' ||\n ((localPackageName === '@milaboratory/tengo-sdk' ||\n localPackageName === '@platforma-sdk/workflow-tengo') &&\n iInfo.module === ':assets')\n ) {\n if (!context.tplDepREs.has(iInfo.module)) {\n context.tplDepREs.set(iInfo.module, [\n ['template', newImportTemplateRE(iInfo.alias)],\n ['software', newImportSoftwareRE(iInfo.alias)],\n ['asset', newImportAssetRE(iInfo.alias)]\n ]);\n }\n }\n\n const artifact = parseArtifactName(iInfo.module, 'library', localPackageName);\n if (!artifact) {\n // not a Platforma Tengo library import\n return { line, context, artifact: undefined, option: undefined };\n }\n\n if (globalizeImports) {\n line = line.replace(importInstruction[0], ` := import(\"${artifact.pkg}:${artifact.id}\")`);\n }\n\n return { line, context, artifact, option: undefined };\n }\n\n if (context.tplDepREs.size > 0) {\n for (const [key, artifactRE] of context.tplDepREs) {\n for (const [artifactType, re] of artifactRE) {\n const match = re.exec(line);\n if (!match || !match.groups) {\n continue;\n }\n\n const { fnCall, templateName, fnName } = match.groups;\n\n if (!fnCall || !templateName || !fnName) {\n throw Error(`failed to parse template import statement`);\n }\n\n const artifact = parseArtifactName(templateName, artifactType, localPackageName);\n if (!artifact) {\n throw Error(`failed to parse artifact name in ${fnName} import statement`);\n }\n\n if (globalizeImports) {\n line = line.replace(fnCall, `${fnName}(\"${artifact.pkg}:${artifact.id}\")`);\n }\n\n return { line, context, artifact, option: undefined };\n }\n }\n }\n\n return { line, context, artifact: undefined, option: undefined };\n}\n\ninterface ImportInfo {\n module: string; // the module name without wrapping quotes: import(\"<module>\")\n alias: string; // the name of variable that keeps imported module: <alias> := import(\"<module>\")\n}\n\nfunction parseImport(line: string): ImportInfo {\n const match = importNameRE.exec(line);\n\n if (!match || !match.groups) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n const { importName, moduleName } = match.groups;\n if (!importName || !moduleName) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n return {\n module: moduleName,\n alias: importName\n };\n}\n\nfunction parseArtifactName(\n moduleName: string,\n aType: ArtifactType,\n localPackageName: string\n): TypedArtifactName | undefined {\n const depInfo = dependencyRE.exec(moduleName);\n if (!depInfo) {\n return;\n }\n\n if (!depInfo.groups) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`\n );\n }\n\n const { pkgName, depID } = depInfo.groups;\n if (!depID) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`\n );\n }\n\n return { type: aType, pkg: pkgName ?? localPackageName, id: depID };\n}\n\nfunction parseTemplateUse(match: RegExpExecArray, localPackageName: string): TypedArtifactName {\n const { templateName } = match.groups!;\n\n if (!templateName) {\n throw Error(`failed to parse 'getTemplateId' statement`);\n }\n\n const depInfo = dependencyRE.exec(templateName);\n if (!depInfo || !depInfo.groups) {\n throw Error(\n `failed to parse dependency name inside 'getTemplateId' statement. The dependency name should have format '<package>:<templateName>'`\n );\n }\n\n const { pkgName, depID } = depInfo.groups;\n if (!pkgName || !depID) {\n throw Error(\n `failed to parse dependency name inside 'getTemplateId' statement. The dependency name should have format '<package>:<templateName>'`\n );\n }\n\n return { type: 'template', pkg: pkgName ?? localPackageName, id: depID };\n}\n","#!/usr/bin/env node\n\nimport * as path from 'node:path';\nimport * as fs from 'node:fs';\nimport { findNodeModules, pathType } from './util';\nimport { TemplatesAndLibs, TengoTemplateCompiler } from './compiler';\nimport {\n artifactNameToString,\n CompileMode,\n FullArtifactName,\n fullNameToString,\n typedArtifactNameToString\n} from './package';\nimport { ArtifactSource, parseSourceFile } from './source';\nimport { Template } from './template';\nimport winston from 'winston';\n\ninterface PackageJson {\n name: string;\n version: string;\n type: string;\n}\n\nconst compiledTplSuffix = '.plj.gz';\nconst compiledLibSuffix = '.lib.tengo';\nconst compiledSoftwareSuffix = '.sw.json';\nconst compiledAssetSuffix = '.as.json';\n\n// We need to keep track of dependencies for correct tgo-test CLI utility configuraiton.\n// It is much simpler to do this here, than duplicate all tle logic regarding dependencies\n// in go code.\nconst srcTestSuffix = '.test.tengo';\n\nconst srcTplSuffix = '.tpl.tengo';\nconst srcLibSuffix = '.lib.tengo';\nconst srcSoftwareSuffix = '.sw.json';\nconst srcAssetSuffix = '.as.json';\nconst compilableSuffixes = [srcLibSuffix, srcTplSuffix, srcSoftwareSuffix, srcAssetSuffix];\n\nexport function getPackageInfo(): PackageJson {\n const packageInfo: PackageJson = JSON.parse(fs.readFileSync('package.json').toString());\n return packageInfo;\n}\n\nfunction resolveLibsDst(mode: CompileMode, root: string) {\n return path.resolve(root, mode, 'tengo', 'lib');\n}\n\nfunction resolveTemplatesDst(mode: CompileMode, root: string) {\n return path.resolve(root, mode, 'tengo', 'tpl');\n}\n\nfunction resolveSoftwareDst(mode: CompileMode, root: string) {\n return path.resolve(root, mode, 'tengo', 'software');\n}\n\nfunction resolveAssetsDst(mode: CompileMode, root: string) {\n return path.resolve(root, mode, 'tengo', 'asset');\n}\n\nfunction loadDependencies(\n logger: winston.Logger,\n compiler: TengoTemplateCompiler,\n packageInfo: PackageJson,\n searchIn: string,\n isLink: boolean = false\n): void {\n const packageJsonPath = path.resolve(searchIn, 'package.json');\n\n if (pathType(packageJsonPath) !== 'file') {\n // We're not in package root. Recursively iterate over all folders looking for packages.\n\n for (const f of fs.readdirSync(searchIn)) {\n const isLink = pathType(path.join(searchIn, f)) === 'link';\n const file = path.resolve(searchIn, f);\n const type = pathType(file);\n if (type === 'dir') {\n loadDependencies(logger, compiler, packageInfo, file, isLink);\n }\n }\n\n return;\n }\n\n // we are in package folder\n const libDistFolder = resolveLibsDst('dist', searchIn);\n const tplDistFolder = resolveTemplatesDst('dist', searchIn);\n const softwareDistFolder = resolveSoftwareDst('dist', searchIn);\n const assetDistFolder = resolveAssetsDst('dist', searchIn);\n\n const libDistExists = pathType(libDistFolder) === 'dir';\n const tplDistExists = pathType(tplDistFolder) === 'dir';\n const softwareDistExists = pathType(softwareDistFolder) === 'dir';\n const assetDistExists = pathType(assetDistFolder) === 'dir';\n\n if (!libDistExists && !tplDistExists && !softwareDistExists && !assetDistExists)\n // if neither of tengo-specific folders detected, skipping package\n return;\n\n // we are in tengo dependency folder\n const packageJson: PackageJson = JSON.parse(fs.readFileSync(packageJsonPath).toString());\n\n // in a workspace we will find ourselves in node_modules, ignoring\n if (packageJson.name === packageInfo.name) return;\n\n if (pathType(path.resolve(searchIn, 'node_modules')) === 'dir' && isLink)\n throw new Error(\n `nested node_modules is a sign of library dependencies version incompatibility in ${searchIn}`\n );\n\n if (libDistExists) {\n loadLibsFromDir(logger, packageJson, 'dist', libDistFolder, compiler);\n }\n\n if (tplDistExists) {\n loadTemplatesFromDir(logger, packageJson, 'dist', tplDistFolder, compiler);\n }\n\n if (softwareDistExists) {\n loadSoftwareFromDir(logger, packageJson, 'dist', softwareDistFolder, compiler);\n }\n\n if (assetDistExists) {\n loadAssetsFromDir(logger, packageJson, 'dist', assetDistFolder, compiler);\n }\n}\n\nfunction loadLibsFromDir(\n logger: winston.Logger,\n packageJson: PackageJson,\n mode: CompileMode,\n folder: string,\n compiler: TengoTemplateCompiler\n) {\n for (const f of fs.readdirSync(folder)) {\n const file = path.resolve(folder, f);\n if (!f.endsWith(compiledLibSuffix)) throw new Error(`unexpected file in 'lib' folder: ${file}`);\n const fullName: FullArtifactName = {\n type: 'library',\n pkg: packageJson.name,\n id: f.slice(0, f.length - compiledLibSuffix.length),\n version: packageJson.version\n };\n const src = parseSourceFile(logger, mode, file, fullName, true);\n compiler.addLib(src);\n logger.debug(`Adding dependency ${fullNameToString(fullName)} from ${file}`);\n if (src.dependencies.length > 0) {\n logger.debug('Dependencies:');\n for (const dep of src.dependencies) logger.debug(` - ${typedArtifactNameToString(dep)}`);\n }\n }\n}\n\nfunction loadTemplatesFromDir(\n logger: winston.Logger,\n packageJson: PackageJson,\n mode: CompileMode,\n folder: string,\n compiler: TengoTemplateCompiler\n) {\n // adding templates\n for (const f of fs.readdirSync(folder)) {\n const file = path.resolve(folder, f);\n if (!f.endsWith(compiledTplSuffix)) throw new Error(`unexpected file in 'tpl' folder: ${file}`);\n const fullName: FullArtifactName = {\n type: 'template',\n pkg: packageJson.name,\n id: f.slice(0, f.length - compiledTplSuffix.length),\n version: packageJson.version\n };\n const tpl = new Template(mode, fullName, { content: fs.readFileSync(file) });\n compiler.addTemplate(tpl);\n logger.debug(`Adding dependency ${fullNameToString(fullName)} from ${file}`);\n }\n}\n\nfunction loadSoftwareFromDir(\n logger: winston.Logger,\n packageJson: PackageJson,\n mode: CompileMode,\n folder: string,\n compiler: TengoTemplateCompiler\n) {\n for (const f of fs.readdirSync(folder)) {\n const file = path.resolve(folder, f);\n if (!f.endsWith(compiledSoftwareSuffix))\n throw new Error(`unexpected file in 'software' folder: ${file}`);\n const fullName: FullArtifactName = {\n type: 'software',\n pkg: packageJson.name,\n id: f.slice(0, f.length - compiledSoftwareSuffix.length),\n version: packageJson.version\n };\n\n const software = new ArtifactSource(mode, fullName, fs.readFileSync(file).toString(), file, [], []);\n\n logger.debug(`Adding dependency ${fullNameToString(fullName)} from ${file}`);\n compiler.addSoftware(software);\n }\n}\n\nfunction loadAssetsFromDir(\n logger: winston.Logger,\n packageJson: PackageJson,\n mode: CompileMode,\n folder: string,\n compiler: TengoTemplateCompiler\n) {\n for (const f of fs.readdirSync(folder)) {\n const file = path.resolve(folder, f);\n if (!f.endsWith(compiledAssetSuffix))\n throw new Error(`unexpected file in 'asset' folder: ${file}`);\n const fullName: FullArtifactName = {\n type: 'asset',\n pkg: packageJson.name,\n id: f.slice(0, f.length - compiledAssetSuffix.length),\n version: packageJson.version\n };\n\n const asset = new ArtifactSource(mode, fullName, fs.readFileSync(file).toString(), file, [], []);\n\n logger.debug(`Adding dependency ${fullNameToString(fullName)} from ${file}`);\n compiler.addAsset(asset);\n }\n}\n\nexport function parseSources(\n logger: winston.Logger,\n packageInfo: PackageJson,\n mode: CompileMode,\n root: string,\n subdir: string\n): ArtifactSource[] {\n const sources: ArtifactSource[] = [];\n\n for (const f of fs.readdirSync(path.join(root, subdir))) {\n const inRootPath = path.join(subdir, f); // path to item inside given <root>\n const fullPath = path.join(root, inRootPath); // full path to item from CWD (or abs path, if <root> is abs path)\n\n if (pathType(fullPath) === 'dir') {\n const nested = parseSources(logger, packageInfo, mode, root, inRootPath);\n sources.push(...nested);\n continue;\n }\n\n const artifactName =\n f === 'index.lib.tengo' ? `${path.dirname(inRootPath)}.lib.tengo` : inRootPath;\n\n const fullName = fullNameFromFileName(packageInfo, artifactName.replaceAll(path.sep, '.'));\n if (!fullName) {\n continue; // skip unknown file types\n }\n\n // if (subdir != '') {\n // // prettier-ignore\n // throw new Error(`Templates and libraries should reside only inside '${root}' dir.\n // You are free to have any file and dirs structure inside '${root}' keeping other files where you want,\n // but regarding ${compilableSuffixes.join(', ')}, the flat file structure is mandatory.`);\n // }\n\n const file = path.resolve(root, inRootPath);\n logger.debug(`Parsing ${fullNameToString(fullName)} from ${file}`);\n const newSrc = parseSourceFile(logger, mode, file, fullName, true);\n if (newSrc.dependencies.length > 0) {\n logger.debug('Detected dependencies:');\n for (const dep of newSrc.dependencies) logger.debug(` - ${typedArtifactNameToString(dep)}`);\n }\n\n sources.push(newSrc);\n }\n\n return sources;\n}\n\nexport function newCompiler(\n logger: winston.Logger,\n packageInfo: PackageJson,\n mode: CompileMode\n): TengoTemplateCompiler {\n const compiler = new TengoTemplateCompiler(mode);\n\n // collect all data (templates, libs and software) from dependency tree\n loadDependencies(logger, compiler, packageInfo, findNodeModules());\n\n return compiler;\n}\n\nfunction fullNameFromFileName(\n packageJson: PackageJson,\n artifactName: string\n): FullArtifactName | null {\n const pkgAndVersion = { pkg: packageJson.name, version: packageJson.version };\n if (artifactName.endsWith(srcLibSuffix)) {\n return {\n ...pkgAndVersion,\n id: artifactName.substring(0, artifactName.length - srcLibSuffix.length),\n type: 'library'\n };\n }\n\n if (artifactName.endsWith(srcTplSuffix)) {\n return {\n ...pkgAndVersion,\n id: artifactName.substring(0, artifactName.length - srcTplSuffix.length),\n type: 'template'\n };\n }\n\n if (artifactName.endsWith(srcSoftwareSuffix)) {\n return {\n ...pkgAndVersion,\n id: artifactName.substring(0, artifactName.length - srcSoftwareSuffix.length),\n type: 'software'\n };\n }\n\n if (artifactName.endsWith(srcAssetSuffix)) {\n return {\n ...pkgAndVersion,\n id: artifactName.substring(0, artifactName.length - srcAssetSuffix.length),\n type: 'asset'\n };\n }\n\n if (artifactName.endsWith(srcTestSuffix)) {\n return {\n ...pkgAndVersion,\n id: artifactName.substring(0, artifactName.length - srcTestSuffix.length),\n type: 'test'\n };\n }\n\n return null;\n}\n\nexport function compile(logger: winston.Logger, mode: CompileMode): TemplatesAndLibs {\n const packageInfo = getPackageInfo();\n const compiler = newCompiler(logger, packageInfo, mode);\n const sources = parseSources(logger, packageInfo, mode, 'src', '');\n\n // checking that we have something to do\n if (sources.length === 0) {\n const lookFor: string[] = [];\n for (const suffix of compilableSuffixes) {\n lookFor.push(`*${suffix}`);\n }\n\n logger.error(`Nothing to compile. Looked for ${lookFor.join(', ')}`);\n process.exit(1);\n }\n\n // compilation\n logger.info(`Compiling '${mode}'...`);\n const compiled = compiler.compileAndAdd(sources);\n logger.debug(`Done.`);\n\n return compiled;\n}\n\nexport function savePacks(logger: winston.Logger, compiled: TemplatesAndLibs, mode: CompileMode) {\n // writing libs\n if (compiled.libs.length > 0) {\n const libOutput = resolveLibsDst(mode, '.');\n fs.mkdirSync(libOutput, { recursive: true });\n for (const lib of compiled.libs) {\n const file = path.resolve(libOutput, lib.fullName.id + compiledLibSuffix);\n logger.info(` - writing ${file}`);\n fs.writeFileSync(file, lib.src);\n }\n }\n\n // writing templates\n if (compiled.templates.length > 0) {\n const tplOutput = resolveTemplatesDst(mode, '.');\n fs.mkdirSync(tplOutput, { recursive: true });\n for (const tpl of compiled.templates) {\n const file = path.resolve(tplOutput, tpl.fullName.id + compiledTplSuffix);\n logger.info(` - writing ${file}`);\n fs.writeFileSync(file, tpl.content);\n }\n }\n\n // writing software\n if (compiled.software.length > 0) {\n const swOutput = resolveSoftwareDst(mode, '.');\n fs.mkdirSync(swOutput, { recursive: true });\n for (const sw of compiled.software) {\n const file = path.resolve(swOutput, sw.fullName.id + compiledSoftwareSuffix);\n logger.info(` - writing ${file}`);\n fs.writeFileSync(file, sw.src);\n }\n }\n\n // writing assets\n if (compiled.assets.length > 0) {\n const swOutput = resolveAssetsDst(mode, '.');\n fs.mkdirSync(swOutput, { recursive: true });\n for (const sw of compiled.software) {\n const file = path.resolve(swOutput, sw.fullName.id + compiledAssetSuffix);\n logger.info(` - writing ${file}`);\n fs.writeFileSync(file, sw.src);\n }\n }\n}\n","import { Flags } from '@oclif/core'\n\nexport const GlobalFlags = {\n \"log-level\": Flags.string({\n description: \"logging level\",\n default: \"info\",\n options: [\"error\", \"warn\", \"info\", \"debug\"],\n })\n}\n\nexport const CtagsFlags = {\n \"generate-tags\": Flags.boolean({\n description: \"generate tags, default false\",\n default: false,\n }),\n\n \"tags-file\": Flags.file({\n description: \"where to put \\\".tags\\\" file, it should be a root of VS Code project\",\n default: \"../../.tags\" // usually a user opens a directory with all blocks\n }),\n\n \"tags-additional-args\": Flags.string({\n description: \"additional flags for universal-ctags command: e.g. -e for emacs\",\n default: [],\n multiple: true,\n delimiter: ',',\n })\n}\n","import { SpawnSyncReturns, spawnSync } from 'child_process';\nimport { Command } from '@oclif/core';\nimport { compile, savePacks, getPackageInfo } from '../compiler/main';\nimport { createLogger } from '../compiler/util';\nimport { CtagsFlags, GlobalFlags } from '../shared/basecmd';\nimport * as fs from 'node:fs';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as winston from 'winston';\n\nexport default class Build extends Command {\n static override description = 'build tengo sources into single distributable pack file';\n\n static override examples = ['<%= config.bin %> <%= command.id %>'];\n\n static override flags = {\n ...GlobalFlags,\n ...CtagsFlags\n };\n\n public async run(): Promise<void> {\n const { flags } = await this.parse(Build);\n const logger = createLogger(flags['log-level']);\n\n const packageInfo = getPackageInfo();\n const compiledDist = compile(logger, 'dist');\n savePacks(logger, compiledDist, 'dist');\n logger.info('');\n\n // Building TS bindings for templates\n let dts = `declare type TemplateFromFile = { readonly type: \"from-file\"; readonly path: string; };\\n`;\n dts += `declare type TplName = ${compiledDist.templates\n .map((tpl) => '\"' + tpl.fullName.id + '\"')\n .join(' | ')};\\n`;\n dts += `declare const Templates: Record<TplName, TemplateFromFile>;\\n`;\n dts += `export { Templates };\\n`;\n let cjs = `module.exports = { Templates: {\\n`;\n let mjs = `import { resolve } from 'node:path';\\nexport const Templates = {\\n`;\n const recordsCjs = compiledDist.templates\n .map(\n (tpl) =>\n ` '${tpl.fullName.id}': { type: 'from-file', path: require.resolve('./tengo/tpl/${tpl.fullName.id}.plj.gz') }`\n )\n .join(',\\n');\n const recordsMjs = compiledDist.templates\n .map(\n (tpl) =>\n ` '${tpl.fullName.id}': { type: 'from-file', path: resolve(import.meta.dirname, './tengo/tpl/${tpl.fullName.id}.plj.gz') }`\n )\n .join(',\\n');\n cjs += recordsCjs;\n mjs += recordsMjs;\n cjs += `\\n}};\\n`;\n mjs += `\\n};\\n`;\n\n await fsp.writeFile('dist/index.d.ts', dts);\n if (packageInfo.type === 'module') {\n await fsp.writeFile('dist/index.cjs', cjs);\n await fsp.writeFile('dist/index.js', mjs);\n } else {\n await fsp.writeFile('dist/index.js', cjs);\n await fsp.writeFile('dist/index.mjs', mjs);\n }\n\n mergeTagsEnvs(flags);\n if (flags['generate-tags']) checkAndGenerateCtags(logger, flags);\n\n logger.info('Template Pack build done.');\n }\n}\n\nfunction mergeTagsEnvs(flags: {\n 'generate-tags': boolean;\n 'tags-file': string;\n 'tags-additional-args': string[] | string;\n}) {\n if (process.env.GENERATE_TAGS != undefined) {\n flags['generate-tags'] = process.env.GENERATE_TAGS == 'true';\n }\n\n if (process.env.TAGS_FILE != undefined) {\n flags['tags-file'] = process.env.TAGS_FILE;\n }\n\n if (process.env.TAGS_ADDITIONAL_ARGS != undefined) {\n flags['tags-additional-args'] = process.env.TAGS_ADDITIONAL_ARGS.split(',');\n }\n}\n\nfunction checkAndGenerateCtags(\n logger: winston.Logger,\n flags: {\n 'tags-file': string;\n 'tags-additional-args': string[];\n }\n) {\n const fileName = path.resolve(flags['tags-file']);\n const rootDir = path.dirname(fileName);\n const additionalArgs = flags['tags-additional-args'];\n\n // all tengo files in dirs and subdirs\n const tengoFiles = getTengoFiles(rootDir);\n\n logger.info(\n `Generating tags for tengo autocompletion from \"${rootDir}\" \\\nin \"${fileName}\", additional arguments: \"${additionalArgs}\".\nFound ${tengoFiles.length} tengo files...`\n );\n\n // see https://docs.ctags.io/en/lates// t/man/ctags-optlib.7.html#perl-pod\n const result = spawnSync(\n 'ctags',\n [\n '-f',\n fileName,\n ...additionalArgs,\n '--langdef=tengo',\n '--map-tengo=+.tengo',\n '--kinddef-tengo=f,function,function',\n '--regex-tengo=/^\\\\s*(.*)(:| :=| =) ?func.*/\\\\1/f/',\n '--kinddef-tengo=c,constant,constant',\n '--regex-tengo=/^\\\\s*(.*) := (\"|\\\\{).*/\\\\1/c/',\n '-R',\n ...tengoFiles\n ],\n {\n env: process.env,\n stdio: 'inherit',\n cwd: rootDir\n }\n );\n\n if (result.error?.message.includes('ENOENT')) {\n console.log(`\npl-tengo can create tags for tengo autocompletion,\nbut the program should be installed\nwith \"brew install universal-ctags\" on OSX\nor \"sudo apt install universal-ctags\" on Ubuntu.\n\nFor vscode, you should also install ctags extension:\nhttps://marketplace.visualstudio.com/items?itemName=jaydenlin.ctags-support`);\n\n return;\n }\n\n checkRunError(result, 'failed to generate ctags');\n\n logger.info('Generation of tags is done.');\n}\n\nfunction getTengoFiles(dir: string): string[] {\n const files = fs.readdirSync(dir, { withFileTypes: true, recursive: true });\n const tengoFiles: string[] = [];\n\n files.forEach((file) => {\n if (!file.isDirectory() && file.name.endsWith('.tengo')) {\n // Note that VS Code extension likes only relatives paths to the root of the opened dir.\n const relativePath = path.join(file.parentPath, file.name).replace(dir, '.');\n tengoFiles.push(relativePath);\n }\n });\n\n return tengoFiles;\n}\n\nfunction checkRunError(result: SpawnSyncReturns<Buffer>, message?: string) {\n if (result.error) {\n console.log(result.error);\n }\n\n const msg = message ?? 'failed to run command';\n\n if (result.status !== 0) {\n console.log(`WARN: ${msg} the build will continue as-is`);\n }\n}\n","import winston from 'winston';\nimport { getPackageInfo, newCompiler, parseSources } from '../compiler/main';\nimport { ArtifactType, typedArtifactNameToString } from '../compiler/package';\n\nexport function dumpAll(\n logger: winston.Logger,\n stream: NodeJS.WritableStream\n): void {\n const packageInfo = getPackageInfo();\n\n const sources = parseSources(logger, packageInfo, 'dist', 'src', '');\n\n const compiler = newCompiler(logger, packageInfo, 'dist');\n\n // group output by type:\n // - all libs\n // - all templates\n // - all software\n // - all assets\n // - all tests\n\n // Libs\n\n for (const lib of compiler.allLibs()) {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(lib.fullName)}`\n );\n stream.write(JSON.stringify(lib) + '\\n');\n }\n\n for (const src of sources) {\n if (src.fullName.type === 'library') {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(src.fullName)}`\n );\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n\n // Templates\n\n for (const tpl of compiler.allTemplates()) {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(tpl.fullName)}`\n );\n stream.write(JSON.stringify(tpl) + '\\n');\n }\n\n for (const src of sources) {\n if (src.fullName.type === 'template') {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(src.fullName)} ${\n src.srcName\n }`\n );\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n\n // Software\n\n for (const sw of compiler.allSoftware()) {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(sw.fullName)}`\n );\n stream.write(JSON.stringify(sw) + '\\n');\n }\n\n for (const src of sources) {\n if (src.fullName.type === 'software') {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(src.fullName)}`\n );\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n\n // Assets\n\n for (const asset of compiler.allAssets()) {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(asset.fullName)}`\n );\n stream.write(JSON.stringify(asset) + '\\n');\n }\n\n for (const src of sources) {\n if (src.fullName.type === 'asset') {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(src.fullName)}`\n );\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n\n // Tests\n\n for (const src of sources) {\n if (src.fullName.type === 'test') {\n logger.debug(\n `Dumping to pl-tester: ${typedArtifactNameToString(src.fullName)} ${\n src.srcName\n }`\n );\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n}\n\nexport function dumpLibs(\n logger: winston.Logger,\n dumpDeps: boolean,\n stream: NodeJS.WritableStream\n): void {\n const packageInfo = getPackageInfo();\n\n const sources = parseSources(logger, packageInfo, 'dist', 'src', '');\n\n if (!dumpDeps) {\n for (const src of sources) {\n if (src.fullName.type === 'library') {\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n\n return;\n }\n\n const compiler = newCompiler(logger, packageInfo, 'dist');\n for (const src of sources) {\n if (src.fullName.type === 'library') {\n compiler.addLib(src);\n }\n }\n\n for (const lib of compiler.allLibs()) {\n stream.write(JSON.stringify(lib) + '\\n');\n }\n}\n\nfunction dumpArtifacts(\n logger: winston.Logger,\n stream: NodeJS.WritableStream,\n aType: ArtifactType,\n): void {\n const packageInfo = getPackageInfo();\n\n const sources = parseSources(logger, packageInfo, 'dist', 'src', '');\n\n for (const src of sources) {\n if (src.fullName.type === aType) {\n stream.write(JSON.stringify(src) + '\\n');\n }\n }\n}\n\nexport function dumpTemplates(\n logger: winston.Logger,\n stream: NodeJS.WritableStream\n): void {\n dumpArtifacts(logger, stream, 'template')\n}\n\nexport function dumpSoftware(\n logger: winston.Logger,\n stream: NodeJS.WritableStream\n): void {\n dumpArtifacts(logger, stream, 'software')\n}\n\nexport function dumpAssets(\n logger: winston.Logger,\n stream: NodeJS.WritableStream\n): void {\n dumpArtifacts(logger, stream, 'asset')\n}\n\nexport function dumpTests(\n logger: winston.Logger,\n stream: NodeJS.WritableStream\n): void {\n dumpArtifacts(logger, stream, 'test')\n}\n","import { spawn, ChildProcess, ChildProcessByStdio } from 'child_process';\nimport { Writable } from 'stream';\n\nexport function spawnEmbed(\n cmd: string,\n ...args: string[]\n): ChildProcessByStdio<Writable, null, null> {\n const p = spawn(cmd, args, { stdio: ['pipe', 'inherit', 'inherit'] });\n\n p.stdin.on('error', (err: any) => {\n if (err.code === 'EPIPE') {\n // ignore EPIPE error as it stands for broken command run.\n // The command will write normal problem description by itself.\n }\n });\n\n return p;\n}\n\nexport function waitFor(p: ChildProcess): Promise<number> {\n return new Promise((resolve, reject) => {\n p.on('close', (code: number) => {\n resolve(code);\n });\n p.on('error', (err) => {\n reject(err);\n });\n });\n}\n","import { Command } from '@oclif/core';\nimport { createLogger } from '../compiler/util';\nimport { dumpAll } from '../shared/dump';\nimport { GlobalFlags } from '../shared/basecmd';\nimport { spawnEmbed, waitFor } from '../shared/proc';\nimport { TengoTesterBinaryPath } from '@milaboratories/tengo-tester';\n\nexport default class Check extends Command {\n static override description = 'check tengo sources for language processor an';\n\n // static override args = {\n // \"log-level\": Args.string({description: 'logging level'}),\n // }\n\n static strict = false;\n\n static override flags = { ...GlobalFlags };\n\n static override examples = ['<%= config.bin %> <%= command.id %>'];\n\n public async run(): Promise<void> {\n const { flags, argv } = await this.parse(Check);\n const logger = createLogger(flags['log-level']);\n\n const testerArgs: string[] = argv.length == 0 ? ['./src'] : (argv as string[]);\n\n // prettier-ignore\n const tester = spawnEmbed(\n TengoTesterBinaryPath,\n 'check', '--log-level', flags['log-level'],\n '--artifacts', '-',\n ...testerArgs\n )\n\n try {\n dumpAll(logger, tester.stdin);\n } catch (err: unknown) {\n logger.error(err);\n } finally {\n tester.stdin.end();\n const code = await waitFor(tester);\n process.exit(code);\n }\n }\n}\n","import { Command } from '@oclif/core';\nimport { createLogger } from '../compiler/util';\nimport { dumpAll } from '../shared/dump';\nimport { GlobalFlags } from '../shared/basecmd';\nimport { spawnEmbed, waitFor } from '../shared/proc';\nimport { TengoTesterBinaryPath } from '@milaboratories/tengo-tester';\n\nexport default class Test extends Command {\n static override description = 'run tengo unit tests (.test.tengo)';\n\n static strict = false;\n\n static override flags = { ...GlobalFlags };\n\n static override examples = ['<%= config.bin %> <%= command.id %>'];\n\n public async run(): Promise<void> {\n const { flags } = await this.parse(Test);\n const logger = createLogger(flags['log-level']);\n\n const testerArgs: string[] = this.argv.length == 0 ? ['./src'] : this.argv;\n\n // prettier-ignore\n const tester = spawnEmbed(\n TengoTesterBinaryPath,\n 'run', '--log-level', flags['log-level'],\n '--artifacts', '-',\n ...testerArgs,\n )\n\n try {\n dumpAll(logger, tester.stdin);\n } catch (err: unknown) {\n logger.error(err);\n } finally {\n tester.stdin.end();\n const code = await waitFor(tester);\n process.exit(code);\n }\n }\n}\n","import { Command } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpAll } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpAll extends Command {\n static override description = 'parse sources in current package and dump all found artifacts to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n public async run(): Promise<void> {\n const logger = createLogger()\n dumpAll(logger, stdout)\n }\n}\n","import { Command } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpAssets } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpAssets extends Command {\n static override description = 'parse sources in current package and dump all found tests to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n public async run(): Promise<void> {\n const logger = createLogger()\n dumpAssets(logger, stdout)\n }\n}\n","import { Command, Flags } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpLibs } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpLibs extends Command {\n static override description = 'parse sources in current package and dump all found templates to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n static override flags = {\n deps: Flags.boolean({name: 'deps', description: 'add also all libraries found in node_modules'}),\n }\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(DumpLibs)\n\n const logger = createLogger()\n dumpLibs(logger, flags.deps, stdout)\n }\n}\n\n","import { Command } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpSoftware } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpSoftware extends Command {\n static override description = 'parse sources in current package and dump all found tests to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n public async run(): Promise<void> {\n const logger = createLogger()\n dumpSoftware(logger, stdout)\n }\n}\n","import { Command } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpTemplates } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpTemplates extends Command {\n static override description = 'parse sources in current package and dump all found templates to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n public async run(): Promise<void> {\n const logger = createLogger()\n dumpTemplates(logger, stdout)\n }\n}\n\n","import { Command } from '@oclif/core'\nimport { createLogger } from '../../compiler/util'\nimport { dumpTests } from '../../shared/dump'\nimport { stdout } from 'process'\n\nexport default class DumpTests extends Command {\n static override description = 'parse sources in current package and dump all found tests to stdout'\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n ]\n\n public async run(): Promise<void> {\n const logger = createLogger()\n dumpTests(logger, stdout)\n }\n}\n","// DO NOT EDIT. This file was generated by oclif-index utility.\n\nimport Cmd0 from './commands/build';\nimport Cmd1 from './commands/check';\nimport Cmd2 from './commands/test';\nimport Cmd3 from './commands/dump/all';\nimport Cmd4 from './commands/dump/assets';\nimport Cmd5 from './commands/dump/libs';\nimport Cmd6 from './commands/dump/software';\nimport Cmd7 from './commands/dump/templates';\nimport Cmd8 from './commands/dump/tests';\n\n// prettier-ignore\nexport const COMMANDS = {\n 'build': Cmd0,\n 'check': Cmd1,\n 'test': Cmd2,\n 'dump:all': Cmd3,\n 'dump:assets': Cmd4,\n 'dump:libs': Cmd5,\n 'dump:software': Cmd6,\n 'dump:templates': Cmd7,\n 'dump:tests': Cmd8,\n};\n"],"names":["assertNever","x","createLogger","level","winston","message","findNodeModules","currentDir","possibleNodeModulesPath","path","fs","parentDir","pathType","s","err","isUUID","uuid","artifactKey","name","fullNameToString","typedArtifactNameToString","typedArtifactNamesEquals","name1","name2","artifactNameToString","formatArtefactNameAndVersion","parseArtefactNameAndVersion","nameAndVersion","match","fullNameWithoutTypeToString","Template","compileMode","fullName","body","__publicField","data","content","parseTemplate","serializeTemplate","nameFromData","ArtifactMap","nameExtractor","obj","replace","key","ret","callback","v","createArtifactNameSet","ArtifactStore","mode","k","applyTemplateCompilerOptions","opts","tpl","opt","hashOverride","applyLibraryCompilerOptions","lib","args","override","util.isUUID","TengoTemplateCompiler","src","deps","trace","dep","recursionStart","errorMessage","tplLib","software","asset","tplSrc","tplData","libFromMap","swFromMap","assetFromMap","tplFromMap","sources","current","unprocessed","unsatisfied","u","ArtifactSource","namePattern","functionCallRE","moduleName","fnName","newGetTemplateIdRE","newGetSoftwareInfoRE","newImportTemplateRE","newImportSoftwareRE","newImportAssetRE","emptyLineRE","compilerOptionRE","wrongCompilerOptionRE","singlelineCommentRE","multilineCommentStartRE","multilineCommentEndRE","importRE","importNameRE","dependencyRE","parseComplierOption","parts","namePart","srcName","dependencies","compilerOptions","parseSourceFile","logger","srcFile","fullSourceName","normalize","readFileSync","normalized","parseSourceData","globalizeImports","dependencySet","optionList","lines","processedLines","parserContext","line","result","parseSingleSourceLine","error","context","localPackageName","importInstruction","iInfo","parseImport","artifact","parseArtifactName","artifactRE","artifactType","re","fnCall","templateName","importName","aType","depInfo","pkgName","depID","compiledTplSuffix","compiledLibSuffix","compiledSoftwareSuffix","compiledAssetSuffix","srcTestSuffix","srcTplSuffix","srcLibSuffix","srcSoftwareSuffix","srcAssetSuffix","compilableSuffixes","getPackageInfo","resolveLibsDst","root","resolveTemplatesDst","resolveSoftwareDst","resolveAssetsDst","loadDependencies","compiler","packageInfo","searchIn","isLink","packageJsonPath","f","file","libDistFolder","tplDistFolder","softwareDistFolder","assetDistFolder","libDistExists","tplDistExists","softwareDistExists","assetDistExists","packageJson","loadLibsFromDir","loadTemplatesFromDir","loadSoftwareFromDir","loadAssetsFromDir","folder","parseSources","subdir","inRootPath","fullPath","nested","artifactName","fullNameFromFileName","newSrc","newCompiler","pkgAndVersion","compile","lookFor","suffix","compiled","savePacks","libOutput","tplOutput","swOutput","sw","GlobalFlags","Flags","CtagsFlags","_Build","Command","flags","compiledDist","dts","cjs","mjs","recordsCjs","recordsMjs","fsp","mergeTagsEnvs","checkAndGenerateCtags","Build","fileName","rootDir","additionalArgs","tengoFiles","getTengoFiles","spawnSync","_a","checkRunError","dir","files","relativePath","msg","dumpAll","stream","dumpLibs","dumpDeps","dumpArtifacts","dumpTemplates","dumpSoftware","dumpAssets","dumpTests","spawnEmbed","cmd","p","spawn","waitFor","resolve","reject","code","_Check","argv","testerArgs","tester","TengoTesterBinaryPath","Check","_Test","Test","DumpAll","stdout","DumpAssets","_DumpLibs","DumpLibs","DumpSoftware","DumpTemplates","DumpTests","COMMANDS","Cmd0","Cmd1","Cmd2","Cmd3","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