@platforma-sdk/tengo-builder 2.1.14 → 2.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/bin/run.js +6 -0
  2. package/dist/commands/build.cjs +172 -0
  3. package/dist/commands/build.cjs.map +1 -0
  4. package/dist/commands/build.d.ts +4 -6
  5. package/dist/commands/build.js +149 -0
  6. package/dist/commands/build.js.map +1 -0
  7. package/dist/commands/check.cjs +39 -0
  8. package/dist/commands/check.cjs.map +1 -0
  9. package/dist/commands/check.d.ts +1 -3
  10. package/dist/commands/check.js +37 -0
  11. package/dist/commands/check.js.map +1 -0
  12. package/dist/commands/dump/all.cjs +20 -0
  13. package/dist/commands/dump/all.cjs.map +1 -0
  14. package/dist/commands/dump/all.d.ts +0 -1
  15. package/dist/commands/dump/all.js +18 -0
  16. package/dist/commands/dump/all.js.map +1 -0
  17. package/dist/commands/dump/assets.cjs +20 -0
  18. package/dist/commands/dump/assets.cjs.map +1 -0
  19. package/dist/commands/dump/assets.d.ts +0 -1
  20. package/dist/commands/dump/assets.js +18 -0
  21. package/dist/commands/dump/assets.js.map +1 -0
  22. package/dist/commands/dump/libs.cjs +24 -0
  23. package/dist/commands/dump/libs.cjs.map +1 -0
  24. package/dist/commands/dump/libs.d.ts +1 -3
  25. package/dist/commands/dump/libs.js +22 -0
  26. package/dist/commands/dump/libs.js.map +1 -0
  27. package/dist/commands/dump/software.cjs +20 -0
  28. package/dist/commands/dump/software.cjs.map +1 -0
  29. package/dist/commands/dump/software.d.ts +0 -1
  30. package/dist/commands/dump/software.js +18 -0
  31. package/dist/commands/dump/software.js.map +1 -0
  32. package/dist/commands/dump/templates.cjs +20 -0
  33. package/dist/commands/dump/templates.cjs.map +1 -0
  34. package/dist/commands/dump/templates.d.ts +0 -1
  35. package/dist/commands/dump/templates.js +18 -0
  36. package/dist/commands/dump/templates.js.map +1 -0
  37. package/dist/commands/dump/tests.cjs +20 -0
  38. package/dist/commands/dump/tests.cjs.map +1 -0
  39. package/dist/commands/dump/tests.d.ts +0 -1
  40. package/dist/commands/dump/tests.js +18 -0
  41. package/dist/commands/dump/tests.js.map +1 -0
  42. package/dist/commands/test.cjs +36 -0
  43. package/dist/commands/test.cjs.map +1 -0
  44. package/dist/commands/test.d.ts +1 -3
  45. package/dist/commands/test.js +34 -0
  46. package/dist/commands/test.js.map +1 -0
  47. package/dist/compiler/artifactset.cjs +75 -0
  48. package/dist/compiler/artifactset.cjs.map +1 -0
  49. package/dist/compiler/artifactset.d.ts +0 -1
  50. package/dist/compiler/artifactset.js +71 -0
  51. package/dist/compiler/artifactset.js.map +1 -0
  52. package/dist/compiler/compiler.cjs +314 -0
  53. package/dist/compiler/compiler.cjs.map +1 -0
  54. package/dist/compiler/compiler.d.ts +0 -1
  55. package/dist/compiler/compiler.js +312 -0
  56. package/dist/compiler/compiler.js.map +1 -0
  57. package/dist/compiler/compileroptions.cjs +45 -0
  58. package/dist/compiler/compileroptions.cjs.map +1 -0
  59. package/dist/compiler/compileroptions.d.ts +0 -1
  60. package/dist/compiler/compileroptions.js +41 -0
  61. package/dist/compiler/compileroptions.js.map +1 -0
  62. package/dist/compiler/main.cjs +387 -0
  63. package/dist/compiler/main.cjs.map +1 -0
  64. package/dist/compiler/main.d.ts +0 -1
  65. package/dist/compiler/main.js +359 -0
  66. package/dist/compiler/main.js.map +1 -0
  67. package/dist/compiler/package.cjs +65 -0
  68. package/dist/compiler/package.cjs.map +1 -0
  69. package/dist/compiler/package.d.ts +0 -1
  70. package/dist/compiler/package.js +55 -0
  71. package/dist/compiler/package.js.map +1 -0
  72. package/dist/compiler/source.cjs +292 -0
  73. package/dist/compiler/source.cjs.map +1 -0
  74. package/dist/compiler/source.d.ts +0 -1
  75. package/dist/compiler/source.js +285 -0
  76. package/dist/compiler/source.js.map +1 -0
  77. package/dist/compiler/template.cjs +48 -0
  78. package/dist/compiler/template.cjs.map +1 -0
  79. package/dist/compiler/template.d.ts +0 -1
  80. package/dist/compiler/template.js +44 -0
  81. package/dist/compiler/template.js.map +1 -0
  82. package/dist/compiler/test.artifacts.d.ts +0 -1
  83. package/dist/compiler/util.cjs +75 -0
  84. package/dist/compiler/util.cjs.map +1 -0
  85. package/dist/compiler/util.d.ts +0 -1
  86. package/dist/compiler/util.js +50 -0
  87. package/dist/compiler/util.js.map +1 -0
  88. package/dist/index.cjs +28 -0
  89. package/dist/index.cjs.map +1 -0
  90. package/dist/index.d.ts +0 -1
  91. package/dist/index.js +23 -41
  92. package/dist/index.js.map +1 -1
  93. package/dist/shared/basecmd.cjs +31 -0
  94. package/dist/shared/basecmd.cjs.map +1 -0
  95. package/dist/shared/basecmd.d.ts +4 -6
  96. package/dist/shared/basecmd.js +28 -0
  97. package/dist/shared/basecmd.js.map +1 -0
  98. package/dist/shared/dump.cjs +117 -0
  99. package/dist/shared/dump.cjs.map +1 -0
  100. package/dist/shared/dump.d.ts +0 -1
  101. package/dist/shared/dump.js +110 -0
  102. package/dist/shared/dump.js.map +1 -0
  103. package/dist/shared/proc.cjs +26 -0
  104. package/dist/shared/proc.cjs.map +1 -0
  105. package/dist/shared/proc.d.ts +0 -1
  106. package/dist/shared/proc.js +23 -0
  107. package/dist/shared/proc.js.map +1 -0
  108. package/package.json +13 -10
  109. package/dist/commands/build.d.ts.map +0 -1
  110. package/dist/commands/check.d.ts.map +0 -1
  111. package/dist/commands/dump/all.d.ts.map +0 -1
  112. package/dist/commands/dump/assets.d.ts.map +0 -1
  113. package/dist/commands/dump/libs.d.ts.map +0 -1
  114. package/dist/commands/dump/software.d.ts.map +0 -1
  115. package/dist/commands/dump/templates.d.ts.map +0 -1
  116. package/dist/commands/dump/tests.d.ts.map +0 -1
  117. package/dist/commands/test.d.ts.map +0 -1
  118. package/dist/compiler/artifactset.d.ts.map +0 -1
  119. package/dist/compiler/compiler.d.ts.map +0 -1
  120. package/dist/compiler/compileroptions.d.ts.map +0 -1
  121. package/dist/compiler/main.d.ts.map +0 -1
  122. package/dist/compiler/package.d.ts.map +0 -1
  123. package/dist/compiler/source.d.ts.map +0 -1
  124. package/dist/compiler/template.d.ts.map +0 -1
  125. package/dist/compiler/test.artifacts.d.ts.map +0 -1
  126. package/dist/compiler/util.d.ts.map +0 -1
  127. package/dist/index.d.ts.map +0 -1
  128. package/dist/index.mjs +0 -1198
  129. package/dist/index.mjs.map +0 -1
  130. package/dist/shared/basecmd.d.ts.map +0 -1
  131. package/dist/shared/dump.d.ts.map +0 -1
  132. package/dist/shared/proc.d.ts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"source.js","sources":["../../src/compiler/source.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport {\n type TypedArtifactName,\n type FullArtifactName,\n type ArtifactType,\n type CompileMode,\n type CompilerOption,\n fullNameToString,\n} from './package';\nimport type { ArtifactMap } from './artifactset';\nimport { createArtifactNameSet } from './artifactset';\nimport { createHash } from 'node:crypto';\nimport type { MiLogger } from '@milaboratories/ts-helpers';\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\nexport const newGetTemplateIdRE = (moduleName: string) => {\n return functionCallRE(moduleName, 'getTemplateId');\n};\nexport const 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 inlineCommentRE = /\\/\\*.*?\\*\\//g; // .*? = non-greedy search\nconst singlelineCommentRE = /^\\s*(\\/\\/)/;\nconst multilineCommentStartRE = /^\\s*\\/\\*/;\nconst multilineCommentEndRE = /\\*\\//;\n\n// import could only be an assignment in a statement,\n// other ways could break a compilation.\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> from 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 /** Hash of the source code */\n public readonly sourceHash: string,\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: MiLogger,\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(\n mode,\n fullSourceName,\n getSha256(normalized),\n normalized,\n srcFile,\n deps.array,\n opts,\n );\n}\n\nexport function parseSource(\n logger: MiLogger,\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, getSha256(normalized), normalized, '', deps.array, opts);\n}\n\n/**\n * Reads src\n * returns normalized source code,\n * gets dependencies from imports,\n * maps imports to global names if globalizeImports is true,\n * and collects compiler options like hashOverride.\n */\nfunction parseSourceData(\n logger: MiLogger,\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 { line: processedLine, context: newContext, artifact, option } = parseSingleSourceLine(\n logger,\n line,\n parserContext,\n fullSourceName.pkg,\n globalizeImports,\n );\n processedLines.push(processedLine);\n parserContext = newContext;\n\n if (artifact) {\n dependencySet.add(artifact);\n }\n if (option) {\n optionList.push(option);\n }\n } catch (error: unknown) {\n const err = error as Error;\n throw new Error(`[line ${parserContext.lineNo} in ${fullNameToString(fullSourceName)}]: ${err.message}\\n\\t${line}`, { cause: err });\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\nexport function parseSingleSourceLine(\n logger: MiLogger,\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 // preprocess line and remove inline comments\n line = line.replaceAll(inlineCommentRE, '');\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.test(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 (line.includes('/*')) {\n throw new Error('malformed multiline comment');\n }\n\n if (emptyLineRE.exec(line)) {\n return { line, context, artifact: undefined, option: undefined };\n }\n\n // options could be only at the top of the file.\n context.canDetectOptions = false;\n\n const importInstruction = importRE.exec(line);\n\n if (importInstruction) {\n const iInfo = parseImport(line);\n\n // If we have plapi, ll or assets, then try to parse\n // getTemplateId, getSoftwareInfo, getSoftware and getAsset calls.\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 [_, 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, // the module name without wrapping quotes: import(\"<module>\")\n alias: importName, // the name of variable that keeps imported module: <alias> := import(\"<module>\")\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\nexport function getSha256(source: string): string {\n return createHash('sha256').update(source).digest('hex');\n}\n"],"names":[],"mappings":";;;;;AAcA;AACA,MAAM,WAAW,GAAG,wBAAwB;AAE5C,MAAM,cAAc,GAAG,CAAC,UAAkB,EAAE,MAAc,KAAI;AAC5D,IAAA,OAAO,IAAI,MAAM,C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AAA,MAAM,KAAK,CACT,CAAA,4HAAA,CAA8H,CAC/H;IACH;IAEA,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC,MAAM;IACzC,IAAI,CAAC,KAAK,EAAE;AACV,QAAA,MAAM,KAAK,CACT,CAAA,4HAAA,CAA8H,CAC/H;IACH;AAEA,IAAA,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,IAAI,gBAAgB,EAAE,EAAE,EAAE,KAAK,EAAE;AACrE;AAEM,SAAU,SAAS,CAAC,MAAc,EAAA;AACtC,IAAA,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;AAC1D;;;;"}
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ var _package = require('./package.cjs');
4
+ var plModelBackend = require('@milaboratories/pl-model-backend');
5
+
6
+ function newTemplateWithSource(compileMode, fullName, data, source) {
7
+ validateTemplateName(fullName, data);
8
+ return {
9
+ compileMode,
10
+ fullName,
11
+ data,
12
+ source,
13
+ };
14
+ }
15
+ function newTemplateFromContent(compileMode, fullName, content) {
16
+ const data = plModelBackend.parseTemplate(content);
17
+ if (data.type !== 'pl.tengo-template.v3') {
18
+ throw new Error('malformed v3 template');
19
+ }
20
+ validateTemplateName(fullName, data);
21
+ return {
22
+ compileMode,
23
+ fullName,
24
+ data,
25
+ content,
26
+ };
27
+ }
28
+ function templateToSource(tpl) {
29
+ return {
30
+ compileMode: tpl.compileMode,
31
+ fullName: tpl.fullName,
32
+ data: tpl.data,
33
+ source: tpl.data.hashToSource[tpl.data.template.sourceHash],
34
+ };
35
+ }
36
+ function validateTemplateName(fullName, data) {
37
+ const nameFromData = _package.parseArtefactNameAndVersion(data.template);
38
+ if (nameFromData.pkg !== fullName.pkg
39
+ || nameFromData.id !== fullName.id
40
+ || nameFromData.version !== fullName.version)
41
+ throw new Error(`Compiled template name don't match it's package and file names: `
42
+ + `${_package.fullNameWithoutTypeToString(nameFromData)} != ${_package.fullNameWithoutTypeToString(fullName)}`);
43
+ }
44
+
45
+ exports.newTemplateFromContent = newTemplateFromContent;
46
+ exports.newTemplateWithSource = newTemplateWithSource;
47
+ exports.templateToSource = templateToSource;
48
+ //# sourceMappingURL=template.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"template.cjs","sources":["../../src/compiler/template.ts"],"sourcesContent":["import type {\n CompileMode,\n FullArtifactName,\n FullArtifactNameWithoutType,\n} from './package';\nimport {\n fullNameWithoutTypeToString,\n parseArtefactNameAndVersion,\n} from './package';\nimport type { CompiledTemplateV3 } from '@milaboratories/pl-model-backend';\nimport {\n parseTemplate,\n serializeTemplate,\n} from '@milaboratories/pl-model-backend';\n\n/** Just a holder for template data, compilation options, full name and source code.\n * It mimics ArtifactSource interface.\n */\nexport type TemplateWithSource = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly source: string;\n readonly data: CompiledTemplateV3;\n};\n\nexport function newTemplateWithSource(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n source: string,\n): TemplateWithSource {\n validateTemplateName(fullName, data);\n\n return {\n compileMode,\n fullName,\n data,\n source,\n };\n}\n\nexport type Template = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly data: CompiledTemplateV3;\n readonly content: Uint8Array;\n};\n\nexport function newTemplateFromData(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n): Template {\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content: serializeTemplate(data),\n };\n}\n\nexport function newTemplateFromContent(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n content: Uint8Array,\n): Template {\n const data = parseTemplate(content);\n if (data.type !== 'pl.tengo-template.v3') {\n throw new Error('malformed v3 template');\n }\n\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content,\n };\n}\n\nexport function templateToSource(tpl: Template): TemplateWithSource {\n return {\n compileMode: tpl.compileMode,\n fullName: tpl.fullName,\n data: tpl.data,\n source: tpl.data.hashToSource[tpl.data.template.sourceHash],\n };\n}\nfunction validateTemplateName(fullName: FullArtifactName, data: CompiledTemplateV3) {\n const nameFromData: FullArtifactNameWithoutType = parseArtefactNameAndVersion(data.template);\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: `\n + `${fullNameWithoutTypeToString(nameFromData)} != ${fullNameWithoutTypeToString(fullName)}`,\n );\n}\n"],"names":["parseTemplate","parseArtefactNameAndVersion","fullNameWithoutTypeToString"],"mappings":";;;;;AAyBM,SAAU,qBAAqB,CACnC,WAAwB,EACxB,QAA0B,EAC1B,IAAwB,EACxB,MAAc,EAAA;AAEd,IAAA,oBAAoB,CAAC,QAAQ,EAAE,IAAI,CAAC;IAEpC,OAAO;QACL,WAAW;QACX,QAAQ;QACR,IAAI;QACJ,MAAM;KACP;AACH;SAuBgB,sBAAsB,CACpC,WAAwB,EACxB,QAA0B,EAC1B,OAAmB,EAAA;AAEnB,IAAA,MAAM,IAAI,GAAGA,4BAAa,CAAC,OAAO,CAAC;AACnC,IAAA,IAAI,IAAI,CAAC,IAAI,KAAK,sBAAsB,EAAE;AACxC,QAAA,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC;IAC1C;AAEA,IAAA,oBAAoB,CAAC,QAAQ,EAAE,IAAI,CAAC;IACpC,OAAO;QACL,WAAW;QACX,QAAQ;QACR,IAAI;QACJ,OAAO;KACR;AACH;AAEM,SAAU,gBAAgB,CAAC,GAAa,EAAA;IAC5C,OAAO;QACL,WAAW,EAAE,GAAG,CAAC,WAAW;QAC5B,QAAQ,EAAE,GAAG,CAAC,QAAQ;QACtB,IAAI,EAAE,GAAG,CAAC,IAAI;AACd,QAAA,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;KAC5D;AACH;AACA,SAAS,oBAAoB,CAAC,QAA0B,EAAE,IAAwB,EAAA;IAChF,MAAM,YAAY,GAAgCC,oCAA2B,CAAC,IAAI,CAAC,QAAQ,CAAC;AAE5F,IAAA,IACE,YAAY,CAAC,GAAG,KAAK,QAAQ,CAAC;AAC3B,WAAA,YAAY,CAAC,EAAE,KAAK,QAAQ,CAAC;AAC7B,WAAA,YAAY,CAAC,OAAO,KAAK,QAAQ,CAAC,OAAO;QAE5C,MAAM,IAAI,KAAK,CACb,CAAA,gEAAA;cACE,CAAA,EAAGC,oCAA2B,CAAC,YAAY,CAAC,CAAA,IAAA,EAAOA,oCAA2B,CAAC,QAAQ,CAAC,CAAA,CAAE,CAC7F;AACL;;;;;;"}
@@ -19,4 +19,3 @@ export type Template = {
19
19
  export declare function newTemplateFromData(compileMode: CompileMode, fullName: FullArtifactName, data: CompiledTemplateV3): Template;
20
20
  export declare function newTemplateFromContent(compileMode: CompileMode, fullName: FullArtifactName, content: Uint8Array): Template;
21
21
  export declare function templateToSource(tpl: Template): TemplateWithSource;
22
- //# sourceMappingURL=template.d.ts.map
@@ -0,0 +1,44 @@
1
+ import { parseArtefactNameAndVersion, fullNameWithoutTypeToString } from './package.js';
2
+ import { parseTemplate } from '@milaboratories/pl-model-backend';
3
+
4
+ function newTemplateWithSource(compileMode, fullName, data, source) {
5
+ validateTemplateName(fullName, data);
6
+ return {
7
+ compileMode,
8
+ fullName,
9
+ data,
10
+ source,
11
+ };
12
+ }
13
+ function newTemplateFromContent(compileMode, fullName, content) {
14
+ const data = parseTemplate(content);
15
+ if (data.type !== 'pl.tengo-template.v3') {
16
+ throw new Error('malformed v3 template');
17
+ }
18
+ validateTemplateName(fullName, data);
19
+ return {
20
+ compileMode,
21
+ fullName,
22
+ data,
23
+ content,
24
+ };
25
+ }
26
+ function templateToSource(tpl) {
27
+ return {
28
+ compileMode: tpl.compileMode,
29
+ fullName: tpl.fullName,
30
+ data: tpl.data,
31
+ source: tpl.data.hashToSource[tpl.data.template.sourceHash],
32
+ };
33
+ }
34
+ function validateTemplateName(fullName, data) {
35
+ const nameFromData = parseArtefactNameAndVersion(data.template);
36
+ if (nameFromData.pkg !== fullName.pkg
37
+ || nameFromData.id !== fullName.id
38
+ || nameFromData.version !== fullName.version)
39
+ throw new Error(`Compiled template name don't match it's package and file names: `
40
+ + `${fullNameWithoutTypeToString(nameFromData)} != ${fullNameWithoutTypeToString(fullName)}`);
41
+ }
42
+
43
+ export { newTemplateFromContent, newTemplateWithSource, templateToSource };
44
+ //# sourceMappingURL=template.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"template.js","sources":["../../src/compiler/template.ts"],"sourcesContent":["import type {\n CompileMode,\n FullArtifactName,\n FullArtifactNameWithoutType,\n} from './package';\nimport {\n fullNameWithoutTypeToString,\n parseArtefactNameAndVersion,\n} from './package';\nimport type { CompiledTemplateV3 } from '@milaboratories/pl-model-backend';\nimport {\n parseTemplate,\n serializeTemplate,\n} from '@milaboratories/pl-model-backend';\n\n/** Just a holder for template data, compilation options, full name and source code.\n * It mimics ArtifactSource interface.\n */\nexport type TemplateWithSource = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly source: string;\n readonly data: CompiledTemplateV3;\n};\n\nexport function newTemplateWithSource(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n source: string,\n): TemplateWithSource {\n validateTemplateName(fullName, data);\n\n return {\n compileMode,\n fullName,\n data,\n source,\n };\n}\n\nexport type Template = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly data: CompiledTemplateV3;\n readonly content: Uint8Array;\n};\n\nexport function newTemplateFromData(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n): Template {\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content: serializeTemplate(data),\n };\n}\n\nexport function newTemplateFromContent(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n content: Uint8Array,\n): Template {\n const data = parseTemplate(content);\n if (data.type !== 'pl.tengo-template.v3') {\n throw new Error('malformed v3 template');\n }\n\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content,\n };\n}\n\nexport function templateToSource(tpl: Template): TemplateWithSource {\n return {\n compileMode: tpl.compileMode,\n fullName: tpl.fullName,\n data: tpl.data,\n source: tpl.data.hashToSource[tpl.data.template.sourceHash],\n };\n}\nfunction validateTemplateName(fullName: FullArtifactName, data: CompiledTemplateV3) {\n const nameFromData: FullArtifactNameWithoutType = parseArtefactNameAndVersion(data.template);\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: `\n + `${fullNameWithoutTypeToString(nameFromData)} != ${fullNameWithoutTypeToString(fullName)}`,\n );\n}\n"],"names":[],"mappings":";;;AAyBM,SAAU,qBAAqB,CACnC,WAAwB,EACxB,QAA0B,EAC1B,IAAwB,EACxB,MAAc,EAAA;AAEd,IAAA,oBAAoB,CAAC,QAAQ,EAAE,IAAI,CAAC;IAEpC,OAAO;QACL,WAAW;QACX,QAAQ;QACR,IAAI;QACJ,MAAM;KACP;AACH;SAuBgB,sBAAsB,CACpC,WAAwB,EACxB,QAA0B,EAC1B,OAAmB,EAAA;AAEnB,IAAA,MAAM,IAAI,GAAG,aAAa,CAAC,OAAO,CAAC;AACnC,IAAA,IAAI,IAAI,CAAC,IAAI,KAAK,sBAAsB,EAAE;AACxC,QAAA,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC;IAC1C;AAEA,IAAA,oBAAoB,CAAC,QAAQ,EAAE,IAAI,CAAC;IACpC,OAAO;QACL,WAAW;QACX,QAAQ;QACR,IAAI;QACJ,OAAO;KACR;AACH;AAEM,SAAU,gBAAgB,CAAC,GAAa,EAAA;IAC5C,OAAO;QACL,WAAW,EAAE,GAAG,CAAC,WAAW;QAC5B,QAAQ,EAAE,GAAG,CAAC,QAAQ;QACtB,IAAI,EAAE,GAAG,CAAC,IAAI;AACd,QAAA,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;KAC5D;AACH;AACA,SAAS,oBAAoB,CAAC,QAA0B,EAAE,IAAwB,EAAA;IAChF,MAAM,YAAY,GAAgC,2BAA2B,CAAC,IAAI,CAAC,QAAQ,CAAC;AAE5F,IAAA,IACE,YAAY,CAAC,GAAG,KAAK,QAAQ,CAAC;AAC3B,WAAA,YAAY,CAAC,EAAE,KAAK,QAAQ,CAAC;AAC7B,WAAA,YAAY,CAAC,OAAO,KAAK,QAAQ,CAAC,OAAO;QAE5C,MAAM,IAAI,KAAK,CACb,CAAA,gEAAA;cACE,CAAA,EAAG,2BAA2B,CAAC,YAAY,CAAC,CAAA,IAAA,EAAO,2BAA2B,CAAC,QAAQ,CAAC,CAAA,CAAE,CAC7F;AACL;;;;"}
@@ -41,4 +41,3 @@ export declare const testPackage1Tpl3: TestArtifactSource;
41
41
  export declare const testPackage1: TestArtifactSource[];
42
42
  export declare const testPackage2: TestArtifactSource[];
43
43
  export declare const testPackage2BrokenHash: TestArtifactSource[];
44
- //# sourceMappingURL=test.artifacts.d.ts.map
@@ -0,0 +1,75 @@
1
+ 'use strict';
2
+
3
+ var fs = require('node:fs');
4
+ var winston = require('winston');
5
+
6
+ function _interopNamespaceDefault(e) {
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n.default = e;
20
+ return Object.freeze(n);
21
+ }
22
+
23
+ var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
24
+ var winston__namespace = /*#__PURE__*/_interopNamespaceDefault(winston);
25
+
26
+ function assertNever(x) {
27
+ // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
28
+ throw new Error('Unexpected object: ' + x);
29
+ }
30
+ function createLogger(level = 'debug') {
31
+ return winston__namespace.createLogger({
32
+ level: level,
33
+ format: winston__namespace.format.combine(winston__namespace.format.errors({ stack: true }), winston__namespace.format.printf(({ level, message, stack }) => {
34
+ const baseMessage = `${level.padStart(6, ' ')}: ${message}`;
35
+ return stack ? `${baseMessage}\n${stack}` : baseMessage;
36
+ })),
37
+ transports: [
38
+ new winston__namespace.transports.Console({
39
+ stderrLevels: ['error', 'warn', 'info', 'debug'],
40
+ handleExceptions: true,
41
+ }),
42
+ ],
43
+ });
44
+ }
45
+ function pathType(path) {
46
+ try {
47
+ const s = fs__namespace.statSync(path);
48
+ if (s.isDirectory())
49
+ return 'dir';
50
+ if (s.isFile())
51
+ return 'file';
52
+ if (s.isSymbolicLink())
53
+ return 'link';
54
+ return 'unknown';
55
+ }
56
+ catch (error) {
57
+ const err = error;
58
+ if (err.code == 'ENOENT')
59
+ return 'absent';
60
+ if (err.code == 'ENOTDIR')
61
+ return 'absent';
62
+ else
63
+ throw err;
64
+ }
65
+ }
66
+ function isUUID(uuid) {
67
+ 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;
68
+ return uuidRegex.test(uuid.toLowerCase());
69
+ }
70
+
71
+ exports.assertNever = assertNever;
72
+ exports.createLogger = createLogger;
73
+ exports.isUUID = isUUID;
74
+ exports.pathType = pathType;
75
+ //# sourceMappingURL=util.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.cjs","sources":["../../src/compiler/util.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 // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\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.combine(\n winston.format.errors({ stack: true }),\n winston.format.printf(({ level, message, stack }) => {\n const baseMessage = `${level.padStart(6, ' ')}: ${message as string}`;\n return stack ? `${baseMessage}\\n${stack as string}` : baseMessage;\n }),\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 (error: unknown) {\n const err = error as NodeJS.ErrnoException;\n if (err.code == 'ENOENT') return 'absent';\n if (err.code == 'ENOTDIR') 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"],"names":["winston","fs"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAIM,SAAU,WAAW,CAAC,CAAQ,EAAA;;AAElC,IAAA,MAAM,IAAI,KAAK,CAAC,qBAAqB,GAAG,CAAC,CAAC;AAC5C;AAEM,SAAU,YAAY,CAAC,KAAA,GAAgB,OAAO,EAAA;IAClD,OA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,QAAQ;AACzC,QAAA,IAAI,GAAG,CAAC,IAAI,IAAI,SAAS;AAAE,YAAA,OAAO,QAAQ;;AACrC,YAAA,MAAM,GAAG;IAChB;AACF;AAEM,SAAU,MAAM,CAAC,IAAY,EAAA;IACjC,MAAM,SAAS,GAAG,4EAA4E;IAC9F,OAAO,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;AAC3C;;;;;;;"}
@@ -5,4 +5,3 @@ export declare function findNodeModules(): string;
5
5
  export type PathType = 'absent' | 'file' | 'dir' | 'link' | 'unknown';
6
6
  export declare function pathType(path: string): PathType;
7
7
  export declare function isUUID(uuid: string): boolean;
8
- //# sourceMappingURL=util.d.ts.map
@@ -0,0 +1,50 @@
1
+ import * as fs from 'node:fs';
2
+ import * as winston from 'winston';
3
+
4
+ function assertNever(x) {
5
+ // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
6
+ throw new Error('Unexpected object: ' + x);
7
+ }
8
+ function createLogger(level = 'debug') {
9
+ return winston.createLogger({
10
+ level: level,
11
+ format: winston.format.combine(winston.format.errors({ stack: true }), winston.format.printf(({ level, message, stack }) => {
12
+ const baseMessage = `${level.padStart(6, ' ')}: ${message}`;
13
+ return stack ? `${baseMessage}\n${stack}` : baseMessage;
14
+ })),
15
+ transports: [
16
+ new winston.transports.Console({
17
+ stderrLevels: ['error', 'warn', 'info', 'debug'],
18
+ handleExceptions: true,
19
+ }),
20
+ ],
21
+ });
22
+ }
23
+ function pathType(path) {
24
+ try {
25
+ const s = fs.statSync(path);
26
+ if (s.isDirectory())
27
+ return 'dir';
28
+ if (s.isFile())
29
+ return 'file';
30
+ if (s.isSymbolicLink())
31
+ return 'link';
32
+ return 'unknown';
33
+ }
34
+ catch (error) {
35
+ const err = error;
36
+ if (err.code == 'ENOENT')
37
+ return 'absent';
38
+ if (err.code == 'ENOTDIR')
39
+ return 'absent';
40
+ else
41
+ throw err;
42
+ }
43
+ }
44
+ function isUUID(uuid) {
45
+ 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;
46
+ return uuidRegex.test(uuid.toLowerCase());
47
+ }
48
+
49
+ export { assertNever, createLogger, isUUID, pathType };
50
+ //# sourceMappingURL=util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.js","sources":["../../src/compiler/util.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 // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\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.combine(\n winston.format.errors({ stack: true }),\n winston.format.printf(({ level, message, stack }) => {\n const baseMessage = `${level.padStart(6, ' ')}: ${message as string}`;\n return stack ? `${baseMessage}\\n${stack as string}` : baseMessage;\n }),\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 (error: unknown) {\n const err = error as NodeJS.ErrnoException;\n if (err.code == 'ENOENT') return 'absent';\n if (err.code == 'ENOTDIR') return 'absent';\n else throw err;\n }\n}\n\nexport function isUUID(u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AAC,WAAW,EAAE;AAAE,YAAA,OAAO,KAAK;QACjC,IAAI,CAAC,CAAC,MAAM,EAAE;AAAE,YAAA,OAAO,MAAM;QAC7B,IAAI,CAAC,CAAC,cAAc,EAAE;AAAE,YAAA,OAAO,MAAM;AACrC,QAAA,OAAO,SAAS;IAClB;IAAE,OAAO,KAAc,EAAE;QACvB,MAAM,GAAG,GAAG,KAA8B;AAC1C,QAAA,IAAI,GAAG,CAAC,IAAI,IAAI,QAAQ;AAAE,YAAA,OAAO,QAAQ;AACzC,QAAA,IAAI,GAAG,CAAC,IAAI,IAAI,SAAS;AAAE,YAAA,OAAO,QAAQ;;AACrC,YAAA,MAAM,GAAG;IAChB;AACF;AAEM,SAAU,MAAM,CAAC,IAAY,EAAA;IACjC,MAAM,SAAS,GAAG,4EAA4E;IAC9F,OAAO,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;AAC3C;;;;"}
package/dist/index.cjs ADDED
@@ -0,0 +1,28 @@
1
+ 'use strict';
2
+
3
+ var build = require('./commands/build.cjs');
4
+ var check = require('./commands/check.cjs');
5
+ var test = require('./commands/test.cjs');
6
+ var all = require('./commands/dump/all.cjs');
7
+ var assets = require('./commands/dump/assets.cjs');
8
+ var libs = require('./commands/dump/libs.cjs');
9
+ var software = require('./commands/dump/software.cjs');
10
+ var templates = require('./commands/dump/templates.cjs');
11
+ var tests = require('./commands/dump/tests.cjs');
12
+
13
+ // DO NOT EDIT. This file was generated by oclif-index utility.
14
+ // prettier-ignore
15
+ const COMMANDS = {
16
+ 'build': build,
17
+ 'check': check,
18
+ 'test': test,
19
+ 'dump:all': all,
20
+ 'dump:assets': assets,
21
+ 'dump:libs': libs,
22
+ 'dump:software': software,
23
+ 'dump:templates': templates,
24
+ 'dump:tests': tests,
25
+ };
26
+
27
+ exports.COMMANDS = COMMANDS;
28
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["// 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":["Cmd0","Cmd1","Cmd2","Cmd3","Cmd4","Cmd5","Cmd6","Cmd7","Cmd8"],"mappings":";;;;;;;;;;;;AAAA;AAYA;AACO,MAAM,QAAQ,GAAG;AACtB,IAAA,OAAO,EAAEA,KAAI;AACb,IAAA,OAAO,EAAEC,KAAI;AACb,IAAA,MAAM,EAAEC,IAAI;AACZ,IAAA,UAAU,EAAEC,GAAI;AAChB,IAAA,aAAa,EAAEC,MAAI;AACnB,IAAA,WAAW,EAAEC,IAAI;AACjB,IAAA,eAAe,EAAEC,QAAI;AACrB,IAAA,gBAAgB,EAAEC,SAAI;AACtB,IAAA,YAAY,EAAEC,KAAI;;;;;"}
package/dist/index.d.ts CHANGED
@@ -18,4 +18,3 @@ export declare const COMMANDS: {
18
18
  'dump:templates': typeof Cmd7;
19
19
  'dump:tests': typeof Cmd8;
20
20
  };
21
- //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,44 +1,26 @@
1
- "use strict";var Ce=Object.defineProperty;var Me=(s,e,t)=>e in s?Ce(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var l=(s,e,t)=>Me(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ye=require("node:child_process"),w=require("@oclif/core"),Le=require("node:path"),be=require("node:fs"),Ie=require("winston"),ve=require("@milaboratories/pl-model-backend"),Pe=require("node:crypto"),ce=require("@milaboratories/resolve-helper"),_e=require("node:fs/promises"),Ee=require("@milaboratories/tengo-tester"),D=require("node:process");function P(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const d=P(Le),p=P(be),O=P(Ie),F=P(_e);function x(s){throw new Error("Unexpected object: "+s)}function E(s="debug"){return O.createLogger({level:s,format:O.format.combine(O.format.errors({stack:!0}),O.format.printf(({level:e,message:t,stack:r})=>{const i=`${e.padStart(6," ")}: ${t}`;return r?`${i}
2
- ${r}`:i})),transports:[new O.transports.Console({stderrLevels:["error","warn","info","debug"],handleExceptions:!0})]})}function S(s){try{const e=p.statSync(s);return e.isDirectory()?"dir":e.isFile()?"file":e.isSymbolicLink()?"link":"unknown"}catch(e){const t=e;if(t.code=="ENOENT"||t.code=="ENOTDIR")return"absent";throw t}}function Je(s){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(s.toLowerCase())}function le(s){return`${s.type}||${s.pkg}||${s.id}`}function u(s){return`${s.type}:${s.pkg}:${s.id}:${s.version}`}function h(s){return`${s.type}:${s.pkg}:${s.id}`}function de(s,e){return s.type==e.type&&s.pkg==e.pkg&&s.id==e.id}function M(s,e){return s.type==e.type&&s.pkg==e.pkg&&s.id==e.id&&s.version==e.version}function y(s){return`${s.pkg}:${s.id}`}function L(s){return{name:y(s),version:s.version}}function He(s){const e=s.name.match(/^(?<pkg>[^:]*):(?<id>[^:]*)$/);if(!e)throw new Error(`malformed artifact name: ${s.name}`);return{pkg:e.groups.pkg,id:e.groups.id,version:s.version}}function fe(s){return`${s.pkg}:${s.id}:${s.version}`}function Ge(s,e,t,r){return $e(e,t),{compileMode:s,fullName:e,data:t,source:r}}function qe(s,e,t){const r=ve.parseTemplate(t);if(r.type!=="pl.tengo-template.v3")throw new Error("malformed v3 template");return $e(e,r),{compileMode:s,fullName:e,data:r,content:t}}function We(s){return{compileMode:s.compileMode,fullName:s.fullName,data:s.data,source:s.data.hashToSource[s.data.template.sourceHash]}}function $e(s,e){const t=He(e.template);if(t.pkg!==s.pkg||t.id!==s.id||t.version!==s.version)throw new Error(`Compiled template name don't match it's package and file names: ${fe(t)} != ${fe(s)}`)}class Ne{constructor(e){l(this,"map",new Map);this.nameExtractor=e}add(e,t=!0){const r=le(this.nameExtractor(e)),i=this.map.get(r);return i&&!t||this.map.set(r,e),i}get(e){return this.map.get(le(e))}get array(){const e=[];return this.map.forEach(t=>e.push(t)),e}forEach(e){this.map.forEach(t=>e(t,this.nameExtractor(t)))}}function Ue(){return new Ne(s=>s)}class I{constructor(e){l(this,"dist");this.dist=new Ne(e)}add(e,t,r=!0){switch(e){case"dist":return this.dist.add(t,r);default:x(e)}}get(e,t){switch(e){case"dist":return this.dist.get(t);default:x(e)}}array(e){const t=[];return this.forEach(e,r=>t.push(r)),t}forEach(e,t){this.dist.forEach((r,i)=>t(this.get(e,i)??r,i))}}function ze(s,e){for(const t of s)switch(t.name){case"hash_override":{e.hashOverride=Ke(t.args);break}}}function Be(s,e){for(const t of s)switch(t.name){case"hash_override":throw new Error("hash_override compiler option can be used ONLY on template level. Even in templates it is already dangerous enough to potentially break everything in Platforma Backend. In libraries with the transitive dependencies resolution and flattening of libraries list on template level, it becomes so unpredictibally disasterous, that we are doomed to never find the ends of a knot if anything goes wrong.")}}function Ke(s){if(s.length!=1)throw new Error("hash_override compiler option expects exactly one argument: hash_override <some string>. Note, you can use only UUID as a value.");const e=s[0].toLowerCase();if(!Je(e))throw new Error(`hash_override must contain valid UUID as an override. As hash_override affects deduplication, it becomes completely not possible to distinguish several different templates from each other on backend's side. This means, if you set hash_override to a simple value (say, letter "a") on two completely different templates, they will be marked as interchangeable on backend's side with unpredictable consequences. UUID looks like a safe enough tradeoff between the feature usage simplicity and duplication safety`);return e}class Ve{constructor(e){l(this,"libs",new I(e=>e.fullName));l(this,"software",new I(e=>e.fullName));l(this,"assets",new I(e=>e.fullName));l(this,"templates",new I(e=>e.fullName));this.compileMode=e}populateTemplateDataFromDependencies(e,t,r,i){for(const o of r)switch(o.type){case"library":{const n=this.getLibOrError(o),a=i.indexOf(y(o));if(a>=0){const f=`library import recursion detected: ${i.slice(a).join(" -> ")} -> ${y(o)}`;throw new Error(f)}const c={...L(n.fullName),sourceHash:n.sourceHash};Be(n.compilerOptions),t.template.libs[y(o)]=c,t.hashToSource[c.sourceHash]=n.src,this.populateTemplateDataFromDependencies(e,t,n.dependencies,[...i,y(o)]);break}case"software":{const n=this.getSoftwareOrError(o);t.template.software[y(o)]={...L(n.fullName),sourceHash:n.sourceHash},t.hashToSource[n.sourceHash]=n.src;break}case"asset":{const n=this.getAssetOrError(o);t.template.software[y(o)]={...L(n.fullName),sourceHash:n.sourceHash},t.hashToSource[n.sourceHash]=n.src;break}case"template":{if(de(e,o))continue;const n=this.getTemplateOrError(o);t.template.templates[y(o)]=n.data.template,t.hashToSource[n.data.template.sourceHash]=n.source;for(const[a,c]of Object.entries(n.data.hashToSource))t.hashToSource[a]=c;break}case"test":throw new Error(`dependencies tree error: tests should never be part of template: ${h(o)} is dependency of ${y(e)}`);default:x(o.type)}}compileAndAddTemplate(e){if(e.fullName.type!=="template")throw new Error("unexpected source type");const t={type:"pl.tengo-template.v3",hashToSource:{[e.sourceHash]:e.src},template:{...L(e.fullName),templates:{},libs:{},software:{},assets:{},sourceHash:e.sourceHash}};return ze(e.compilerOptions,t.template),this.populateTemplateDataFromDependencies(e.fullName,t,e.dependencies,[]),t}addLib(e){const t=this.libs.add(e.compileMode,e,!1);if(t&&!M(e.fullName,t.fullName))throw new Error(`compiler already contain such library: adding = ${u(e.fullName)}, contains = ${u(t.fullName)}`)}allLibs(){return this.libs.array(this.compileMode)}getLib(e){if(e.type!=="library")throw new Error(`illegal artifact type: got ${e.type} instead of 'library`);return this.libs.get(this.compileMode,e)}getLibOrError(e){const t=this.getLib(e);if(!t)throw new Error(`library not found: ${y(e)}`);return t}checkLibs(){this.libs.forEach(this.compileMode,e=>{for(const t of e.dependencies){if(t.type==="test")throw new Error(`test should never be dependency of production code: ${h(t)} test is dependency of ${u(e.fullName)}`);if(!this.getArtefact(t))throw new Error(`unresolved dependency ${h(t)} for ${u(e.fullName)}`)}})}addSoftware(e){const t=this.software.add(e.compileMode,e,!1);if(t&&!M(e.fullName,t.fullName))throw new Error(`compiler already contain info for software: adding = ${u(e.fullName)}, contains = ${u(t.fullName)}`)}allSoftware(){return this.software.array(this.compileMode)}getSoftware(e){if(e.type!=="software")throw new Error(`illegal artifact type: got ${e.type} instead of 'software`);return this.software.get(this.compileMode,e)}getSoftwareOrError(e){const t=this.getSoftware(e);if(!t)throw new Error(`software info not found: ${y(e)}`);return t}addAsset(e){const t=this.assets.add(e.compileMode,e,!1);if(t&&!M(e.fullName,t.fullName))throw new Error(`compiler already contain info for asset: adding = ${u(e.fullName)}, contains = ${u(t.fullName)}`)}allAssets(){return this.assets.array(this.compileMode)}getAsset(e){if(e.type!=="asset")throw new Error(`illegal artifact type: got ${e.type} instead of 'asset`);return this.assets.get(this.compileMode,e)}getAssetOrError(e){const t=this.getAsset(e);if(!t)throw new Error(`asset info not found: ${y(e)}`);return t}addTemplate(e){const t=this.templates.add(e.compileMode,e,!1);if(t&&!M(e.fullName,t.fullName))throw new Error(`compiler already contain such template: adding = ${u(e.fullName)}, contains = ${u(t.fullName)}`)}allTemplates(){return this.templates.array(this.compileMode)}getTemplate(e){if(e.type!=="template")throw new Error(`illegal artifact type: got ${e.type} instead of 'template`);return this.templates.get(this.compileMode,e)}getTemplateOrError(e){const t=this.getTemplate(e);if(!t)throw new Error(`template not found: ${y(e)}`);return t}getArtefact(e){switch(e.type){case"template":return this.getTemplate(e);case"library":return this.getLib(e);case"software":return this.getSoftware(e);case"asset":return this.getAsset(e);case"test":return;default:x(e.type)}}compileAndAdd(e){const t={templates:[],libs:[],software:[],assets:[]};let r=[];for(const i of e)i.fullName.type==="library"?(this.addLib(i),t.libs.push(i)):i.fullName.type==="software"?(this.addSoftware(i),t.software.push(i)):i.fullName.type==="asset"?(this.addAsset(i),t.assets.push(i)):r.push(i);for(;r.length>0;){const i=[];for(const o of r){const n=o.dependencies.filter(a=>!this.getArtefact(a)&&!(o.fullName.type==="template"&&de(o.fullName,a)));if(n.length>0){let a=`Unsatisfied dependencies in ${u(o.fullName)}:
3
- `;for(const c of n)a+=` - ${h(c)}
4
- `;i.push({src:o,err:new Error(a)});continue}switch(o.fullName.type){case"library":this.addLib(o),t.libs.push(o);break;case"software":this.addSoftware(o),t.software.push(o);break;case"asset":this.addAsset(o),t.assets.push(o);break;case"template":try{const a=this.compileAndAddTemplate(o),c=Ge(o.compileMode,o.fullName,a,o.src);this.addTemplate(c),t.templates.push(c)}catch(a){const c=a;let f=`Unsatisfied dependencies in ${u(o.fullName)}:
5
- `;f+=` - ${c.message}
6
- `,i.push({src:o,err:Error(f)})}break;case"test":break;default:x(o.fullName.type)}}if(r.length===i.length){let o="";for(const n of i)o+=`
7
- ${n.err.message}`;throw new Error(o)}r=i.map(({src:o})=>o)}return t}}const pe="[_a-zA-Z][_a-zA-Z0-9]*",R=(s,e)=>new RegExp(`\\b${s}\\.(?<fnCall>(?<fnName>`+e+')\\s*\\(\\s*"(?<templateName>[^"]+)"\\s*\\))'),Xe=s=>R(s,"getTemplateId"),Ze=s=>R(s,"getSoftwareInfo"),ue=s=>R(s,"importTemplate"),me=s=>R(s,"importSoftware"),Ye=s=>R(s,"importAsset"),Qe=/^\s*$/,et=/^\/\/tengo:[\w]/,tt=/^\s*\/\/\s*tengo:\s*./,st=/\/\*.*?\*\//g,ot=/^\s*(\/\/)/,rt=/^\s*\/\*/,nt=/\*\//,Se=/\s*:=\s*import\s*\(\s*"(?<moduleName>[^"]+)"\s*\)/,it=new RegExp(`\\b(?<importName>${pe}(\\.${pe})*)${Se.source}`),at=/(?<pkgName>[^"]+)?:(?<depID>[^"]+)/,ct=s=>{const e=s.split(" "),t=e[0].split(":");if(t.length!=2)throw new Error("compiler option format is wrong: expect to have option name after 'tengo:' prefix, like 'tengo:MyOption'");return{name:t[1],args:e.slice(1)}};class oe{constructor(e,t,r,i,o,n,a){this.compileMode=e,this.fullName=t,this.sourceHash=r,this.src=i,this.srcName=o,this.dependencies=n,this.compilerOptions=a}}function ke(s,e,t,r,i){const o=be.readFileSync(t).toString(),{deps:n,normalized:a,opts:c}=lt(s,o,r,i);return new oe(e,r,re(a),a,t,n.array,c)}function lt(s,e,t,r){const i=Ue(),o=[],n=e.split(`
8
- `),a=[];let c={isInCommentBlock:!1,canDetectOptions:!0,tplDepREs:new Map,lineNo:0};for(const f of n){c.lineNo++;try{const{line:g,context:m,artifact:b,option:v}=dt(s,f,c,t.pkg,r);a.push(g),c=m,b&&i.add(b),v&&o.push(v)}catch(g){const m=g;throw new Error(`[line ${c.lineNo} in ${u(t)}]: ${m.message}
9
- ${f}`,{cause:m})}}return{normalized:a.join(`
10
- `),deps:i,opts:o}}function dt(s,e,t,r,i){if(e=e.replaceAll(st,""),t.isInCommentBlock)return nt.exec(e)&&(t.isInCommentBlock=!1),{line:"",context:t,artifact:void 0,option:void 0};if(et.exec(e)){if(!t.canDetectOptions)throw s.error(`[line ${t.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'`),new Error("tengo compiler options ('//tengo:' comments) can be set only in file header");return{line:e,context:t,artifact:void 0,option:ct(e)}}if(tt.exec(e)&&t.canDetectOptions)return s.warn(`[line ${t.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)`),{line:e,context:t,artifact:void 0,option:void 0};if(ot.test(e))return{line:"",context:t,artifact:void 0,option:void 0};if(rt.exec(e))return t.isInCommentBlock=!0,{line:"",context:t,artifact:void 0,option:void 0};if(e.includes("/*"))throw new Error("malformed multiline comment");if(Qe.exec(e))return{line:e,context:t,artifact:void 0,option:void 0};t.canDetectOptions=!1;const o=Se.exec(e);if(o){const n=ft(e);if(n.module==="plapi")return t.tplDepREs.has(n.module)||t.tplDepREs.set(n.module,[["template",Xe(n.alias)],["software",Ze(n.alias)]]),{line:e,context:t,artifact:void 0,option:void 0};(n.module==="@milaboratory/tengo-sdk:ll"||n.module==="@platforma-sdk/workflow-tengo:ll"||(r==="@milaboratory/tengo-sdk"||r==="@platforma-sdk/workflow-tengo")&&n.module===":ll")&&(t.tplDepREs.has(n.module)||t.tplDepREs.set(n.module,[["template",ue(n.alias)],["software",me(n.alias)]])),(n.module==="@milaboratory/tengo-sdk:assets"||n.module==="@platforma-sdk/workflow-tengo:assets"||(r==="@milaboratory/tengo-sdk"||r==="@platforma-sdk/workflow-tengo")&&n.module===":assets")&&(t.tplDepREs.has(n.module)||t.tplDepREs.set(n.module,[["template",ue(n.alias)],["software",me(n.alias)],["asset",Ye(n.alias)]]));const a=he(n.module,"library",r);return a?(e=e.replace(o[0],` := import("${a.pkg}:${a.id}")`),{line:e,context:t,artifact:a,option:void 0}):{line:e,context:t,artifact:void 0,option:void 0}}if(t.tplDepREs.size>0)for(const[n,a]of t.tplDepREs)for(const[c,f]of a){const g=f.exec(e);if(!g||!g.groups)continue;const{fnCall:m,templateName:b,fnName:v}=g.groups;if(!m||!b||!v)throw Error("failed to parse template import statement");const C=he(b,c,r);if(!C)throw Error(`failed to parse artifact name in ${v} import statement`);return e=e.replace(m,`${v}("${C.pkg}:${C.id}")`),{line:e,context:t,artifact:C,option:void 0}}return{line:e,context:t,artifact:void 0,option:void 0}}function ft(s){const e=it.exec(s);if(!e||!e.groups)throw Error("failed to parse 'import' statement");const{importName:t,moduleName:r}=e.groups;if(!t||!r)throw Error("failed to parse 'import' statement");return{module:r,alias:t}}function he(s,e,t){const r=at.exec(s);if(!r)return;if(!r.groups)throw Error("failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'");const{pkgName:i,depID:o}=r.groups;if(!o)throw Error("failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'");return{type:e,pkg:i??t,id:o}}function re(s){return Pe.createHash("sha256").update(s).digest("hex")}const J=".plj.gz",H=".lib.tengo",G=".sw.json",q=".as.json",ge=".test.tengo",W=".tpl.tengo",U=".lib.tengo",z=".sw.json",B=".as.json",pt=[U,W,z,B];function we(s,e){if(!d.isAbsolute(s))throw new Error(`Root path must be absolute: ${s}`);let t=ce.tryResolve(s,e);if(t){let i=0;do{const o=d.join(t,"package.json");if(S(o)==="file")return o;i++,t=d.dirname(t)}while(i<7&&d.basename(t)!=="node_modules")}const r=ce.tryResolveOrError(s,`${e}/package.json`);if(r.result===void 0){if(r.err==="ERR_PACKAGE_PATH_NOT_EXPORTED")return;throw new Error(`Can't resolve package.json for package ${e??"."} relative to ${s}`)}return r.result}function ut(s){if(!d.isAbsolute(s))throw new Error(`Root path must be absolute: ${s}`);const e=d.join(s,"package.json");if(S(e)==="file")return e;throw new Error(`Can't resolve package.json in ${s}`)}function A(s,e,t="root"){const r=ut(s),i=JSON.parse(p.readFileSync(r).toString()),o=[];if(i.dependencies&&t!=="devDependency")for(const n of Object.keys(i.dependencies)){const a=we(s,n);if(a===void 0)throw new Error(`Can't resolve package.json for dependency ${n} of ${s}`);const c=d.dirname(a);o.push(A(c,e,"dependency"))}if(i.devDependencies&&t==="root")for(const n of Object.keys(i.devDependencies)){const a=we(s,n);if(a===void 0){e.warn(`Can't resolve package.json for dev dependency ${n} of ${s}`);continue}const c=d.dirname(a);o.push(A(c,e,"devDependency"))}return{name:i.name,version:i.version,type:i.type,dependencies:o,root:s,context:t}}function Te(s,e){return d.resolve(e,s,"tengo","lib")}function Ae(s,e){return d.resolve(e,s,"tengo","tpl")}function De(s,e){return d.resolve(e,s,"tengo","software")}function Oe(s,e){return d.resolve(e,s,"tengo","asset")}function Fe(s,e,t){for(const b of t.dependencies)Fe(s,e,b);if(t.context==="root")return;const r=Te("dist",t.root),i=Ae("dist",t.root),o=De("dist",t.root),n=Oe("dist",t.root),a=S(r)==="dir",c=S(i)==="dir",f=S(o)==="dir",g=S(n)==="dir";if(!a&&!c&&!f&&!g)return;const m={name:t.name,version:t.version};a&&mt(s,m,"dist",r,e),c&&ht(s,m,"dist",i,e),f&&gt(s,m,"dist",o,e),g&&wt(s,m,"dist",n,e)}function mt(s,e,t,r,i){for(const o of p.readdirSync(r)){const n=d.resolve(r,o);if(!o.endsWith(H))throw new Error(`unexpected file in 'lib' folder: ${n}`);const a={type:"library",pkg:e.name,id:o.slice(0,o.length-H.length),version:e.version},c=ke(s,t,n,a,!0);if(i.addLib(c),s.debug(`Adding dependency ${u(a)} from ${n}`),c.dependencies.length>0){s.debug("Dependencies:");for(const f of c.dependencies)s.debug(` - ${h(f)}`)}}}function ht(s,e,t,r,i){for(const o of p.readdirSync(r)){const n=d.resolve(r,o);if(!o.endsWith(J))throw new Error(`unexpected file in 'tpl' folder: ${n}`);const a={type:"template",pkg:e.name,id:o.slice(0,o.length-J.length),version:e.version},c=qe(t,a,p.readFileSync(n));i.addTemplate(We(c)),s.debug(`Adding dependency ${u(a)} from ${n}`)}}function gt(s,e,t,r,i){for(const o of p.readdirSync(r)){const n=d.resolve(r,o);if(!o.endsWith(G))throw new Error(`unexpected file in 'software' folder: ${n}`);const a={type:"software",pkg:e.name,id:o.slice(0,o.length-G.length),version:e.version},c=p.readFileSync(n).toString(),f=new oe(t,a,re(c),c,n,[],[]);s.debug(`Adding dependency ${u(a)} from ${n}`),i.addSoftware(f)}}function wt(s,e,t,r,i){for(const o of p.readdirSync(r)){const n=d.resolve(r,o);if(!o.endsWith(q))throw new Error(`unexpected file in 'asset' folder: ${n}`);const a={type:"asset",pkg:e.name,id:o.slice(0,o.length-q.length),version:e.version},c=p.readFileSync(n).toString(),f=new oe(t,a,re(c),c,n,[],[]);s.debug(`Adding dependency ${u(a)} from ${n}`),i.addAsset(f)}}function j(s,e,t,r,i){const o=[];for(const n of p.readdirSync(d.join(r,i))){const a=d.join(i,n),c=d.join(r,a);if(S(c)==="dir"){const v=j(s,e,t,r,a);o.push(...v);continue}const f=n==="index.lib.tengo"?`${d.dirname(a)}.lib.tengo`:a,g=yt(e,f.replaceAll(d.sep,"."));if(!g){s.info(`Skipping unknown file type: ${f}`);continue}const m=d.resolve(r,a);s.debug(`Parsing ${u(g)} from ${m}`);const b=ke(s,t,m,g,!0);if(b.dependencies.length>0){s.debug("Detected dependencies:");for(const v of b.dependencies)s.debug(` - ${h(v)}`)}o.push(b)}return o}function ne(s,e,t){const r=new Ve(t);return Fe(s,r,e),r}function yt(s,e){const t={pkg:s.name,version:s.version};return e.endsWith(U)?{...t,id:e.substring(0,e.length-U.length),type:"library"}:e.endsWith(W)?{...t,id:e.substring(0,e.length-W.length),type:"template"}:e.endsWith(z)?{...t,id:e.substring(0,e.length-z.length),type:"software"}:e.endsWith(B)?{...t,id:e.substring(0,e.length-B.length),type:"asset"}:e.endsWith(ge)?{...t,id:e.substring(0,e.length-ge.length),type:"test"}:null}function bt(s,e,t){const r=ne(s,e,t),i=j(s,e,t,"src","");if(i.length===0){const n=[];for(const a of pt)n.push(`*${a}`);s.error(`Nothing to compile. Looked for ${n.join(", ")}`),process.exit(1)}s.info(`Compiling '${t}'...`);const o=r.compileAndAdd(i);return s.debug("Done."),o}function vt(s,e,t){if(e.libs.length>0){const r=Te(t,".");p.mkdirSync(r,{recursive:!0});for(const i of e.libs){const o=d.resolve(r,i.fullName.id+H);s.info(` - writing ${o}`),p.writeFileSync(o,i.src)}}if(e.templates.length>0){const r=Ae(t,".");p.mkdirSync(r,{recursive:!0});for(const i of e.templates){const o=d.resolve(r,i.fullName.id+J);s.info(` - writing ${o}`),p.writeFileSync(o,ve.serializeTemplate(i.data))}}if(e.software.length>0){const r=De(t,".");p.mkdirSync(r,{recursive:!0});for(const i of e.software){const o=d.resolve(r,i.fullName.id+G);s.info(` - writing ${o}`),p.writeFileSync(o,i.src)}}if(e.assets.length>0){const r=Oe(t,".");p.mkdirSync(r,{recursive:!0});for(const i of e.software){const o=d.resolve(r,i.fullName.id+q);s.info(` - writing ${o}`),p.writeFileSync(o,i.src)}}}const ie={"log-level":w.Flags.string({description:"logging level",default:"info",options:["error","warn","info","debug"]})},Et={"generate-tags":w.Flags.boolean({description:"generate tags, default false",default:!1}),"tags-file":w.Flags.file({description:'where to put ".tags" file, it should be a root of VS Code project',default:"../../.tags"}),"tags-additional-args":w.Flags.string({description:"additional flags for universal-ctags command: e.g. -e for emacs",default:[],multiple:!0,delimiter:","})},k=class k extends w.Command{async run(){const{flags:e}=await this.parse(k),t=E(e["log-level"]),r=A(process.cwd(),t),i=bt(t,r,"dist");vt(t,i,"dist"),t.info("Template Pack build done.");const{dts:o,cjs:n,mjs:a}=$t(i);await F.writeFile("dist/index.d.ts",o),r.type==="module"?(await F.writeFile("dist/index.cjs",n),await F.writeFile("dist/index.js",a)):(await F.writeFile("dist/index.js",n),await F.writeFile("dist/index.mjs",a)),Nt(e),e["generate-tags"]&&St(t,e),t.info("Template Pack build done.")}};l(k,"description","build tengo sources into single distributable pack file"),l(k,"examples",["<%= config.bin %> <%= command.id %>"]),l(k,"flags",{...ie,...Et});let K=k;function $t(s){let e=`declare type TemplateFromFile = { readonly type: "from-file"; readonly path: string; };
11
- `;e+=`declare type TplName = ${s.templates.map(n=>'"'+n.fullName.id+'"').join(" | ")};
12
- `,e+=`declare const Templates: Record<TplName, TemplateFromFile>;
13
- `,e+=`export { Templates };
14
- `;let t=`module.exports = { Templates: {
15
- `,r=`import { resolve } from 'node:path';
16
- export const Templates = {
17
- `;const i=s.templates.map(n=>` '${n.fullName.id}': { type: 'from-file', path: require.resolve('./tengo/tpl/${n.fullName.id}.plj.gz') }`).join(`,
18
- `),o=s.templates.map(n=>` '${n.fullName.id}': { type: 'from-file', path: resolve(import.meta.dirname, './tengo/tpl/${n.fullName.id}.plj.gz') }`).join(`,
19
- `);return t+=i,r+=o,t+=`
20
- }};
21
- `,r+=`
1
+ import Build from './commands/build.js';
2
+ import Check from './commands/check.js';
3
+ import Test from './commands/test.js';
4
+ import DumpAll from './commands/dump/all.js';
5
+ import DumpAssets from './commands/dump/assets.js';
6
+ import DumpLibs from './commands/dump/libs.js';
7
+ import DumpSoftware from './commands/dump/software.js';
8
+ import DumpTemplates from './commands/dump/templates.js';
9
+ import DumpTests from './commands/dump/tests.js';
10
+
11
+ // DO NOT EDIT. This file was generated by oclif-index utility.
12
+ // prettier-ignore
13
+ const COMMANDS = {
14
+ 'build': Build,
15
+ 'check': Check,
16
+ 'test': Test,
17
+ 'dump:all': DumpAll,
18
+ 'dump:assets': DumpAssets,
19
+ 'dump:libs': DumpLibs,
20
+ 'dump:software': DumpSoftware,
21
+ 'dump:templates': DumpTemplates,
22
+ 'dump:tests': DumpTests,
22
23
  };
23
- `,{dts:e,cjs:t,mjs:r}}function Nt(s){process.env.GENERATE_TAGS!=null&&(s["generate-tags"]=process.env.GENERATE_TAGS=="true"),process.env.TAGS_FILE!=null&&(s["tags-file"]=process.env.TAGS_FILE),process.env.TAGS_ADDITIONAL_ARGS!=null&&(s["tags-additional-args"]=process.env.TAGS_ADDITIONAL_ARGS.split(","))}function St(s,e){var a;const t=d.resolve(e["tags-file"]),r=d.dirname(t),i=e["tags-additional-args"],o=kt(r,xe(r,9));s.info(`Generating tags for tengo autocompletion from "${r}" in "${t}", additional arguments: "${i.join('" "')}".
24
- Found ${o.length} tengo files...`);const n=ye.spawnSync("ctags",["-f",t,...i,"--langdef=tengo","--map-tengo=+.tengo","--kinddef-tengo=f,function,function","--regex-tengo=/^\\s*(.*)(:| :=| =) ?func.*/\\1/f/","--kinddef-tengo=c,constant,constant",'--regex-tengo=/^\\s*(.*) := ("|\\{).*/\\1/c/',"-R",...o],{env:process.env,stdio:"inherit",cwd:r});if((a=n.error)!=null&&a.message.includes("ENOENT")){console.log(`
25
- pl-tengo can create tags for tengo autocompletion,
26
- but the program should be installed
27
- with "brew install universal-ctags" on OSX
28
- or "sudo apt install universal-ctags" on Ubuntu.
29
24
 
30
- For vscode, you should also install ctags extension:
31
- https://marketplace.visualstudio.com/items?itemName=jaydenlin.ctags-support`);return}Tt(n,"failed to generate ctags"),s.info("Generation of tags is done.")}function xe(s,e){if(e===0)return[];const t=p.readdirSync(s,{withFileTypes:!0});let r=[];return t.forEach(i=>{const o=d.join(s,i.name);i.isDirectory()&&(r=r.concat(xe(o,e-1))),!i.isDirectory()&&i.name.endsWith(".tengo")&&r.push(o)}),r}function kt(s,e){return e.map(t=>t.replace(s,"."))}function Tt(s,e){s.error&&console.log(s.error);const t=e;s.status!==0&&console.log(`WARN: ${t} the build will continue as-is`)}function ae(s,e){const t=A(process.cwd(),s),r=j(s,t,"dist","src",""),i=ne(s,t,"dist");for(const o of i.allLibs())s.debug(`Dumping to pl-tester: ${h(o.fullName)}`),e.write(JSON.stringify(o)+`
32
- `);for(const o of r)o.fullName.type==="library"&&(s.debug(`Dumping to pl-tester: ${h(o.fullName)}`),e.write(JSON.stringify(o)+`
33
- `));for(const o of i.allTemplates())s.debug(`Dumping to pl-tester: ${h(o.fullName)}`),e.write(JSON.stringify(o)+`
34
- `);for(const o of r)o.fullName.type==="template"&&(s.debug(`Dumping to pl-tester: ${h(o.fullName)} ${o.srcName}`),e.write(JSON.stringify(o)+`
35
- `));for(const o of i.allSoftware())s.debug(`Dumping to pl-tester: ${h(o.fullName)}`),e.write(JSON.stringify(o)+`
36
- `);for(const o of r)o.fullName.type==="software"&&(s.debug(`Dumping to pl-tester: ${h(o.fullName)}`),e.write(JSON.stringify(o)+`
37
- `));for(const o of i.allAssets())s.debug(`Dumping to pl-tester: ${h(o.fullName)}`),e.write(JSON.stringify(o)+`
38
- `);for(const o of r)o.fullName.type==="asset"&&(s.debug(`Dumping to pl-tester: ${h(o.fullName)}`),e.write(JSON.stringify(o)+`
39
- `));for(const o of r)o.fullName.type==="test"&&(s.debug(`Dumping to pl-tester: ${h(o.fullName)} ${o.srcName}`),e.write(JSON.stringify(o)+`
40
- `))}function At(s,e,t){const r=A(process.cwd(),s),i=j(s,r,"dist","src","");if(!e){for(const n of i)n.fullName.type==="library"&&t.write(JSON.stringify(n)+`
41
- `);return}const o=ne(s,r,"dist");for(const n of i)n.fullName.type==="library"&&o.addLib(n);for(const n of o.allLibs())t.write(JSON.stringify(n)+`
42
- `)}function _(s,e,t){const r=A(process.cwd(),s),i=j(s,r,"dist","src","");for(const o of i)o.fullName.type===t&&e.write(JSON.stringify(o)+`
43
- `)}function Dt(s,e){_(s,e,"template")}function Ot(s,e){_(s,e,"software")}function Ft(s,e){_(s,e,"asset")}function xt(s,e){_(s,e,"test")}function Re(s,...e){const t=ye.spawn(s,e,{stdio:["pipe","inherit","inherit"]});return t.stdin.on("error",r=>{r.code}),t}function je(s){return new Promise((e,t)=>{s.on("close",r=>{e(r)}),s.on("error",r=>{t(r)})})}const $=class $ extends w.Command{async run(){const{flags:e,argv:t}=await this.parse($),r=E(e["log-level"]),i=t.length==0?["./src"]:t,o=Re(Ee.TengoTesterBinaryPath,"check","--log-level",e["log-level"],"--artifacts","-",...i);try{ae(r,o.stdin)}catch(n){r.error(n)}finally{o.stdin.end();const n=await je(o);process.exit(n)}}};l($,"description","check tengo sources for language processor an"),l($,"strict",!1),l($,"flags",{...ie}),l($,"examples",["<%= config.bin %> <%= command.id %>"]);let V=$;const N=class N extends w.Command{async run(){const{flags:e}=await this.parse(N),t=E(e["log-level"]),r=this.argv.length==0?["./src"]:this.argv,i=Re(Ee.TengoTesterBinaryPath,"run","--log-level",e["log-level"],"--artifacts","-",...r);try{ae(t,i.stdin)}catch(o){t.error(o)}finally{i.stdin.end();const o=await je(i);process.exit(o)}}};l(N,"description","run tengo unit tests (.test.tengo)"),l(N,"strict",!1),l(N,"flags",{...ie}),l(N,"examples",["<%= config.bin %> <%= command.id %>"]);let X=N;class Z extends w.Command{async run(){const e=E();ae(e,D.stdout)}}l(Z,"description","parse sources in current package and dump all found artifacts to stdout"),l(Z,"examples",["<%= config.bin %> <%= command.id %>"]);class Y extends w.Command{async run(){const e=E();Ft(e,D.stdout)}}l(Y,"description","parse sources in current package and dump all found assets to stdout"),l(Y,"examples",["<%= config.bin %> <%= command.id %>"]);const T=class T extends w.Command{async run(){const{flags:e}=await this.parse(T),t=E();At(t,e.deps,D.stdout)}};l(T,"description","parse sources in current package and dump all found libs to stdout"),l(T,"examples",["<%= config.bin %> <%= command.id %>"]),l(T,"flags",{deps:w.Flags.boolean({name:"deps",description:"add also all libraries found in node_modules"})});let Q=T;class ee extends w.Command{async run(){const e=E();Ot(e,D.stdout)}}l(ee,"description","parse sources in current package and dump all found software to stdout"),l(ee,"examples",["<%= config.bin %> <%= command.id %>"]);class te extends w.Command{async run(){const e=E();Dt(e,D.stdout)}}l(te,"description","parse sources in current package and dump all found templates to stdout"),l(te,"examples",["<%= config.bin %> <%= command.id %>"]);class se extends w.Command{async run(){const e=E();xt(e,D.stdout)}}l(se,"description","parse sources in current package and dump all found tests to stdout"),l(se,"examples",["<%= config.bin %> <%= command.id %>"]);const Rt={build:K,check:V,test:X,"dump:all":Z,"dump:assets":Y,"dump:libs":Q,"dump:software":ee,"dump:templates":te,"dump:tests":se};exports.COMMANDS=Rt;
25
+ export { COMMANDS };
44
26
  //# sourceMappingURL=index.js.map