@trustify-da/trustify-da-javascript-client 0.3.0-ea.a783c26 → 0.3.0-ea.a87208f

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 (81) hide show
  1. package/README.md +177 -3
  2. package/dist/package.json +27 -22
  3. package/dist/src/analysis.d.ts +14 -7
  4. package/dist/src/analysis.js +29 -13
  5. package/dist/src/cli.js +106 -2
  6. package/dist/src/cyclone_dx_sbom.d.ts +20 -1
  7. package/dist/src/cyclone_dx_sbom.js +68 -9
  8. package/dist/src/index.d.ts +74 -11
  9. package/dist/src/index.js +83 -29
  10. package/dist/src/license/index.d.ts +3 -3
  11. package/dist/src/license/index.js +4 -1
  12. package/dist/src/license/license_utils.js +4 -1
  13. package/dist/src/license/licenses_api.d.ts +2 -2
  14. package/dist/src/oci_image/images.d.ts +1 -1
  15. package/dist/src/oci_image/images.js +15 -1
  16. package/dist/src/oci_image/utils.d.ts +5 -5
  17. package/dist/src/package_version.d.ts +8 -0
  18. package/dist/src/package_version.js +31 -0
  19. package/dist/src/provider.d.ts +4 -3
  20. package/dist/src/provider.js +6 -2
  21. package/dist/src/providers/base_java.d.ts +67 -12
  22. package/dist/src/providers/base_java.js +82 -61
  23. package/dist/src/providers/base_javascript.d.ts +74 -9
  24. package/dist/src/providers/base_javascript.js +115 -6
  25. package/dist/src/providers/base_pyproject.d.ts +15 -6
  26. package/dist/src/providers/base_pyproject.js +12 -4
  27. package/dist/src/providers/containerfile_parser.d.ts +5 -0
  28. package/dist/src/providers/containerfile_parser.js +20 -0
  29. package/dist/src/providers/golang_gomodules.d.ts +11 -1
  30. package/dist/src/providers/golang_gomodules.js +108 -10
  31. package/dist/src/providers/java_gradle.d.ts +19 -0
  32. package/dist/src/providers/java_gradle.js +116 -2
  33. package/dist/src/providers/java_gradle_groovy.d.ts +1 -1
  34. package/dist/src/providers/java_gradle_kotlin.d.ts +1 -1
  35. package/dist/src/providers/java_maven.d.ts +38 -5
  36. package/dist/src/providers/java_maven.js +261 -8
  37. package/dist/src/providers/javascript_bun.d.ts +22 -0
  38. package/dist/src/providers/javascript_bun.js +141 -0
  39. package/dist/src/providers/javascript_npm.d.ts +19 -1
  40. package/dist/src/providers/javascript_npm.js +40 -1
  41. package/dist/src/providers/javascript_pnpm.d.ts +13 -0
  42. package/dist/src/providers/javascript_pnpm.js +53 -3
  43. package/dist/src/providers/javascript_yarn.d.ts +12 -0
  44. package/dist/src/providers/javascript_yarn.js +75 -2
  45. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  46. package/dist/src/providers/marker_evaluator.js +191 -0
  47. package/dist/src/providers/oci_dockerfile.d.ts +51 -0
  48. package/dist/src/providers/oci_dockerfile.js +177 -0
  49. package/dist/src/providers/processors/yarn_berry_processor.d.ts +6 -2
  50. package/dist/src/providers/processors/yarn_berry_processor.js +3 -2
  51. package/dist/src/providers/processors/yarn_classic_processor.d.ts +6 -2
  52. package/dist/src/providers/processors/yarn_classic_processor.js +8 -6
  53. package/dist/src/providers/python_controller.d.ts +5 -1
  54. package/dist/src/providers/python_controller.js +62 -5
  55. package/dist/src/providers/python_pip.d.ts +5 -0
  56. package/dist/src/providers/python_pip.js +5 -5
  57. package/dist/src/providers/python_pip_pyproject.js +3 -1
  58. package/dist/src/providers/python_poetry.d.ts +63 -8
  59. package/dist/src/providers/python_poetry.js +132 -21
  60. package/dist/src/providers/python_uv.d.ts +20 -1
  61. package/dist/src/providers/python_uv.js +122 -2
  62. package/dist/src/providers/rust_cargo.d.ts +6 -2
  63. package/dist/src/providers/rust_cargo.js +105 -19
  64. package/dist/src/providers/tree-sitter-containerfile.wasm +0 -0
  65. package/dist/src/remediate.d.ts +21 -0
  66. package/dist/src/remediate.js +149 -0
  67. package/dist/src/remediation.d.ts +57 -0
  68. package/dist/src/remediation.js +436 -0
  69. package/dist/src/remediation_report.d.ts +40 -0
  70. package/dist/src/remediation_report.js +159 -0
  71. package/dist/src/sbom.d.ts +18 -1
  72. package/dist/src/sbom.js +14 -2
  73. package/dist/src/tools.d.ts +28 -2
  74. package/dist/src/tools.js +82 -1
  75. package/dist/src/updaters/maven_updater.d.ts +26 -0
  76. package/dist/src/updaters/maven_updater.js +322 -0
  77. package/dist/src/updaters/toml_updater.d.ts +33 -0
  78. package/dist/src/updaters/toml_updater.js +244 -0
  79. package/dist/src/workspace.d.ts +9 -0
  80. package/dist/src/workspace.js +1 -1
  81. package/package.json +28 -23
@@ -0,0 +1,141 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parse } from 'jsonc-parser';
4
+ import Base_javascript, { sriToHash } from './base_javascript.js';
5
+ export default class Javascript_bun extends Base_javascript {
6
+ _lockFileName() {
7
+ return "bun.lock";
8
+ }
9
+ /**
10
+ * Parses `bun.lock` into a hash map keyed by `name@version`. Each entry in
11
+ * the `packages` section is an array whose first element is the resolved id
12
+ * (`name@version`) and whose fourth element is the SRI integrity string.
13
+ * @param {string} lockDir - Directory containing bun.lock
14
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
15
+ * @protected
16
+ */
17
+ _parseLockFileHashes(lockDir) {
18
+ const map = new Map();
19
+ const lockPath = path.join(lockDir, this._lockFileName());
20
+ if (!fs.existsSync(lockPath)) {
21
+ return map;
22
+ }
23
+ let lockData;
24
+ try {
25
+ lockData = parse(fs.readFileSync(lockPath, 'utf-8'));
26
+ }
27
+ catch (_) {
28
+ return map;
29
+ }
30
+ const packages = lockData?.packages || {};
31
+ for (const entry of Object.values(packages)) {
32
+ if (!Array.isArray(entry) || typeof entry[0] !== 'string' || typeof entry[3] !== 'string') {
33
+ continue;
34
+ }
35
+ const id = entry[0];
36
+ const at = id.lastIndexOf('@');
37
+ if (at <= 0) {
38
+ continue;
39
+ }
40
+ const name = id.slice(0, at);
41
+ const version = id.slice(at + 1);
42
+ const hash = sriToHash(entry[3]);
43
+ if (name && version && hash) {
44
+ map.set(`${name}@${version}`, [hash]);
45
+ }
46
+ }
47
+ return map;
48
+ }
49
+ _cmdName() {
50
+ return "bun";
51
+ }
52
+ _listCmdArgs() {
53
+ throw new Error("not supported by Bun");
54
+ }
55
+ _updateLockFileCmdArgs() {
56
+ return ['install', '--lockfile-only'];
57
+ }
58
+ _buildDependencyTree(includeTransitive, opts = {}) {
59
+ this._version();
60
+ const manifestDir = path.dirname(this._getManifest().manifestPath);
61
+ const lockDir = this._findLockFileDir(manifestDir, opts) || manifestDir;
62
+ this._createLockFile(lockDir);
63
+ this._loadHashes(lockDir);
64
+ const lockContent = fs.readFileSync(path.join(lockDir, 'bun.lock'), 'utf-8');
65
+ const lockData = parse(lockContent);
66
+ const packages = lockData.packages || {};
67
+ const memberName = this._getManifest().name;
68
+ const workspaceEntry = this.#findWorkspaceEntry(lockData, lockDir, manifestDir, memberName);
69
+ const directDeps = workspaceEntry?.dependencies || {};
70
+ const tree = { name: memberName, version: this._getManifest().version, dependencies: {} };
71
+ const visited = new Set();
72
+ for (const depName of Object.keys(directDeps)) {
73
+ const resolved = this.#resolvePackage(depName, '', packages);
74
+ if (resolved) {
75
+ tree.dependencies[depName] = this.#buildNode(depName, resolved, packages, includeTransitive, visited);
76
+ }
77
+ }
78
+ return tree;
79
+ }
80
+ #findWorkspaceEntry(lockData, lockDir, manifestDir, memberName) {
81
+ const workspaces = lockData.workspaces || {};
82
+ const relPath = path.relative(lockDir, path.resolve(manifestDir));
83
+ if (!relPath || relPath === '.') {
84
+ return workspaces[''] || {};
85
+ }
86
+ const normalised = relPath.split(path.sep).join('/');
87
+ if (workspaces[normalised]) {
88
+ return workspaces[normalised];
89
+ }
90
+ for (const [wsPath, entry] of Object.entries(workspaces)) {
91
+ if (entry.name === memberName && wsPath !== '') {
92
+ return entry;
93
+ }
94
+ }
95
+ return workspaces[''] || {};
96
+ }
97
+ #resolvePackage(depName, parentKey, packages) {
98
+ if (parentKey) {
99
+ const scopedKey = `${parentKey}/${depName}`;
100
+ if (packages[scopedKey]) {
101
+ return packages[scopedKey];
102
+ }
103
+ }
104
+ return packages[depName] || null;
105
+ }
106
+ #buildNode(depName, resolved, packages, includeTransitive, visited) {
107
+ const resolvedId = Array.isArray(resolved) ? resolved[0] : resolved;
108
+ const version = this.#extractVersion(resolvedId);
109
+ const node = { version };
110
+ if (!includeTransitive) {
111
+ return node;
112
+ }
113
+ const metadata = Array.isArray(resolved) ? (resolved[2] || {}) : {};
114
+ const subDeps = metadata.dependencies || {};
115
+ if (Object.keys(subDeps).length > 0) {
116
+ const visitKey = `${depName}@${version}`;
117
+ if (visited.has(visitKey)) {
118
+ return node;
119
+ }
120
+ visited.add(visitKey);
121
+ node.dependencies = {};
122
+ for (const subName of Object.keys(subDeps)) {
123
+ const subResolved = this.#resolvePackage(subName, depName, packages);
124
+ if (subResolved) {
125
+ node.dependencies[subName] = this.#buildNode(subName, subResolved, packages, true, visited);
126
+ }
127
+ }
128
+ }
129
+ return node;
130
+ }
131
+ #extractVersion(resolvedId) {
132
+ if (typeof resolvedId !== 'string') {
133
+ return '0.0.0';
134
+ }
135
+ const atIdx = resolvedId.lastIndexOf('@');
136
+ if (atIdx > 0) {
137
+ return resolvedId.substring(atIdx + 1);
138
+ }
139
+ return '0.0.0';
140
+ }
141
+ }
@@ -1,5 +1,23 @@
1
1
  export default class Javascript_npm extends Base_javascript {
2
+ /**
3
+ * Parses `package-lock.json` (lockfileVersion 2/3) into a hash map keyed by
4
+ * `name@version`. Each `packages` entry is keyed by its install path
5
+ * (e.g. `node_modules/@hapi/joi`); the package name is the segment after the
6
+ * final `node_modules/`. The `integrity` field holds an SRI string.
7
+ * @param {string} lockDir - Directory containing package-lock.json
8
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
9
+ * @protected
10
+ */
11
+ protected _parseLockFileHashes(lockDir: string): Map<string, Array<{
12
+ alg: string;
13
+ content: string;
14
+ }>>;
2
15
  _listCmdArgs(includeTransitive: any): string[];
3
- _buildDependencyTree(includeTransitive: any, opts?: {}): any;
16
+ _buildDependencyTree(includeTransitive: any, opts?: {}): Object | {
17
+ name: any;
18
+ version: any;
19
+ dependencies: any;
20
+ optionalDependencies: any;
21
+ };
4
22
  }
5
23
  import Base_javascript from './base_javascript.js';
@@ -1,8 +1,47 @@
1
- import Base_javascript from './base_javascript.js';
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import Base_javascript, { sriToHash } from './base_javascript.js';
2
4
  export default class Javascript_npm extends Base_javascript {
3
5
  _lockFileName() {
4
6
  return "package-lock.json";
5
7
  }
8
+ /**
9
+ * Parses `package-lock.json` (lockfileVersion 2/3) into a hash map keyed by
10
+ * `name@version`. Each `packages` entry is keyed by its install path
11
+ * (e.g. `node_modules/@hapi/joi`); the package name is the segment after the
12
+ * final `node_modules/`. The `integrity` field holds an SRI string.
13
+ * @param {string} lockDir - Directory containing package-lock.json
14
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
15
+ * @protected
16
+ */
17
+ _parseLockFileHashes(lockDir) {
18
+ const map = new Map();
19
+ const lockPath = path.join(lockDir, this._lockFileName());
20
+ if (!fs.existsSync(lockPath)) {
21
+ return map;
22
+ }
23
+ let lock;
24
+ try {
25
+ lock = JSON.parse(fs.readFileSync(lockPath, 'utf-8'));
26
+ }
27
+ catch (_) {
28
+ return map;
29
+ }
30
+ const packages = lock.packages || {};
31
+ for (const [pkgPath, entry] of Object.entries(packages)) {
32
+ if (!pkgPath || !entry || !entry.integrity || !entry.version) {
33
+ continue;
34
+ }
35
+ const marker = 'node_modules/';
36
+ const idx = pkgPath.lastIndexOf(marker);
37
+ const name = idx < 0 ? pkgPath : pkgPath.slice(idx + marker.length);
38
+ const hash = sriToHash(entry.integrity);
39
+ if (name && hash) {
40
+ map.set(`${name}@${entry.version}`, [hash]);
41
+ }
42
+ }
43
+ return map;
44
+ }
6
45
  _cmdName() {
7
46
  return "npm";
8
47
  }
@@ -1,4 +1,17 @@
1
1
  export default class Javascript_pnpm extends Base_javascript {
2
+ /**
3
+ * Parses `pnpm-lock.yaml` (lockfileVersion 9) into a hash map keyed by
4
+ * `name@version`. Entries in the `packages` section are keyed by
5
+ * `<name>@<version>` (optionally followed by a `(peer@x)` suffix); the
6
+ * `resolution.integrity` field holds an SRI string.
7
+ * @param {string} lockDir - Directory containing pnpm-lock.yaml
8
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
9
+ * @protected
10
+ */
11
+ protected _parseLockFileHashes(lockDir: string): Map<string, Array<{
12
+ alg: string;
13
+ content: string;
14
+ }>>;
2
15
  _listCmdArgs(includeTransitive: any): string[];
3
16
  _buildDependencyTree(includeTransitive: any, opts?: {}): any;
4
17
  }
@@ -1,21 +1,71 @@
1
- import Base_javascript from './base_javascript.js';
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { load as yamlLoad } from 'js-yaml';
4
+ import Base_javascript, { sriToHash } from './base_javascript.js';
2
5
  export default class Javascript_pnpm extends Base_javascript {
3
6
  _lockFileName() {
4
7
  return "pnpm-lock.yaml";
5
8
  }
9
+ /**
10
+ * Parses `pnpm-lock.yaml` (lockfileVersion 9) into a hash map keyed by
11
+ * `name@version`. Entries in the `packages` section are keyed by
12
+ * `<name>@<version>` (optionally followed by a `(peer@x)` suffix); the
13
+ * `resolution.integrity` field holds an SRI string.
14
+ * @param {string} lockDir - Directory containing pnpm-lock.yaml
15
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
16
+ * @protected
17
+ */
18
+ _parseLockFileHashes(lockDir) {
19
+ const map = new Map();
20
+ const lockPath = path.join(lockDir, this._lockFileName());
21
+ if (!fs.existsSync(lockPath)) {
22
+ return map;
23
+ }
24
+ let lock;
25
+ try {
26
+ lock = yamlLoad(fs.readFileSync(lockPath, 'utf-8'));
27
+ }
28
+ catch (_) {
29
+ return map;
30
+ }
31
+ const packages = lock?.packages || {};
32
+ for (const [key, entry] of Object.entries(packages)) {
33
+ const integrity = entry?.resolution?.integrity;
34
+ if (!key || !integrity) {
35
+ continue;
36
+ }
37
+ // Strip any peer-dependency suffix, then split name from version
38
+ const base = key.split('(')[0];
39
+ const at = base.lastIndexOf('@');
40
+ if (at <= 0) {
41
+ continue;
42
+ }
43
+ const name = base.slice(0, at);
44
+ const version = base.slice(at + 1);
45
+ const hash = sriToHash(integrity);
46
+ if (name && version && hash) {
47
+ map.set(`${name}@${version}`, [hash]);
48
+ }
49
+ }
50
+ return map;
51
+ }
6
52
  _cmdName() {
7
53
  return "pnpm";
8
54
  }
9
55
  _listCmdArgs(includeTransitive) {
10
- return ['ls', includeTransitive ? '--depth=Infinity' : '--depth=0', '--prod', '--json'];
56
+ return ['ls', includeTransitive ? '--depth=Infinity' : '--depth=0', '--prod', '--json', '-r'];
11
57
  }
12
58
  _updateLockFileCmdArgs() {
13
59
  return ['install', '--frozen-lockfile'];
14
60
  }
15
61
  _buildDependencyTree(includeTransitive, opts = {}) {
62
+ // pnpm ls --json returns an array with one entry per workspace package.
63
+ // When analyzing a workspace member, find its entry by name instead of
64
+ // blindly taking the first element (which is the workspace root).
16
65
  const tree = super._buildDependencyTree(includeTransitive, opts);
17
66
  if (Array.isArray(tree) && tree.length > 0) {
18
- return tree[0];
67
+ const memberName = this._getManifest().name;
68
+ return tree.find(pkg => pkg.name === memberName) || tree[0];
19
69
  }
20
70
  return {};
21
71
  }
@@ -1,5 +1,17 @@
1
1
  export default class Javascript_yarn extends Base_javascript {
2
2
  static VERSION_PATTERN: RegExp;
3
+ /**
4
+ * Parses `yarn.lock` into a hash map keyed by `name@version`. Supports both
5
+ * Yarn Classic (v1) entries with an `integrity` SRI field and Yarn Berry
6
+ * (v2+) entries with a `checksum` field.
7
+ * @param {string} lockDir - Directory containing yarn.lock
8
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
9
+ * @protected
10
+ */
11
+ protected _parseLockFileHashes(lockDir: string): Map<string, Array<{
12
+ alg: string;
13
+ content: string;
14
+ }>>;
3
15
  _listCmdArgs(includeTransitive: any, manifestDir: any): any;
4
16
  _updateLockFileCmdArgs(manifestDir: any): any;
5
17
  _setUp(manifestPath: any, opts: any): void;
@@ -1,12 +1,85 @@
1
- import Base_javascript from './base_javascript.js';
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parseSyml } from '@yarnpkg/parsers';
4
+ import Base_javascript, { sriToHash } from './base_javascript.js';
2
5
  import Yarn_berry_processor from './processors/yarn_berry_processor.js';
3
6
  import Yarn_classic_processor from './processors/yarn_classic_processor.js';
7
+ /**
8
+ * Converts a Yarn Berry `checksum` value to a CycloneDX hash object. Berry
9
+ * checksums are formatted as `<cacheKey>/<hex-sha512>`; the digest is the
10
+ * hex-encoded SHA-512 following the final slash.
11
+ * @param {string} checksum - The checksum field value
12
+ * @returns {{alg: string, content: string}|null} CycloneDX hash, or null
13
+ */
14
+ function berryChecksumToHash(checksum) {
15
+ if (typeof checksum !== 'string') {
16
+ return null;
17
+ }
18
+ const slash = checksum.lastIndexOf('/');
19
+ const hex = (slash >= 0 ? checksum.slice(slash + 1) : checksum).trim();
20
+ if (!/^[0-9a-f]+$/i.test(hex)) {
21
+ return null;
22
+ }
23
+ return { alg: 'SHA-512', content: hex.toLowerCase() };
24
+ }
4
25
  export default class Javascript_yarn extends Base_javascript {
5
26
  static VERSION_PATTERN = /^([0-9]+)\./;
6
27
  #processor;
7
28
  _lockFileName() {
8
29
  return "yarn.lock";
9
30
  }
31
+ /**
32
+ * Parses `yarn.lock` into a hash map keyed by `name@version`. Supports both
33
+ * Yarn Classic (v1) entries with an `integrity` SRI field and Yarn Berry
34
+ * (v2+) entries with a `checksum` field.
35
+ * @param {string} lockDir - Directory containing yarn.lock
36
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
37
+ * @protected
38
+ */
39
+ _parseLockFileHashes(lockDir) {
40
+ const map = new Map();
41
+ const lockPath = path.join(lockDir, this._lockFileName());
42
+ if (!fs.existsSync(lockPath)) {
43
+ return map;
44
+ }
45
+ let content;
46
+ try {
47
+ content = fs.readFileSync(lockPath, 'utf-8');
48
+ }
49
+ catch (_) {
50
+ return map;
51
+ }
52
+ const parsed = parseSyml(content);
53
+ for (const [spec, entry] of Object.entries(parsed)) {
54
+ if (spec === '__metadata') {
55
+ continue;
56
+ }
57
+ const version = entry.version;
58
+ if (!version) {
59
+ continue;
60
+ }
61
+ let hash = null;
62
+ if (entry.integrity) {
63
+ hash = sriToHash(entry.integrity);
64
+ }
65
+ else if (entry.checksum) {
66
+ hash = berryChecksumToHash(entry.checksum);
67
+ }
68
+ if (!hash) {
69
+ continue;
70
+ }
71
+ // Handle comma-separated specifiers (e.g., "pkg@^1.0.0, pkg@^2.0.0")
72
+ for (const rawSpec of spec.split(',')) {
73
+ const trimmed = rawSpec.trim();
74
+ const atIndex = trimmed.lastIndexOf('@');
75
+ if (atIndex > 0) {
76
+ const name = trimmed.slice(0, atIndex);
77
+ map.set(`${name}@${version}`, [hash]);
78
+ }
79
+ }
80
+ }
81
+ return map;
82
+ }
10
83
  _cmdName() {
11
84
  return "yarn";
12
85
  }
@@ -34,6 +107,6 @@ export default class Javascript_yarn extends Base_javascript {
34
107
  return this.#processor.parseDepTreeOutput(output);
35
108
  }
36
109
  _addDependenciesToSbom(sbom, depTree) {
37
- this.#processor.addDependenciesToSbom(sbom, depTree);
110
+ this.#processor.addDependenciesToSbom(sbom, depTree, purl => this._hashesForPurl(purl));
38
111
  }
39
112
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Maps Node.js/OS values to PEP 508 marker variables.
3
+ * Example: on Linux, sys_platform='linux', platform_system='Linux', os_name='posix'
4
+ * @returns {Record<string, string>}
5
+ */
6
+ export function getEnvironmentMarkers(): Record<string, string>;
7
+ /**
8
+ * Evaluates a full PEP 508 marker expression against the current platform.
9
+ * Example: "sys_platform == 'win32' and python_version >= '3.8'" → false on Linux
10
+ * Empty/missing markers return true (unconditional dependency).
11
+ * @param {string} markerExpr
12
+ * @returns {boolean}
13
+ */
14
+ export function evaluateMarker(markerExpr: string): boolean;
@@ -0,0 +1,191 @@
1
+ // PEP 508 environment marker evaluator.
2
+ // Filters Python dependencies by platform/version markers so that e.g.
3
+ // "pywin32 ; sys_platform == 'win32'" is excluded on Linux/macOS.
4
+ // See https://peps.python.org/pep-0508/#environment-markers
5
+ import os from 'node:os';
6
+ import { getCustomPath, invokeCommand } from '../tools.js';
7
+ let cachedPythonVersions = undefined;
8
+ function getPythonVersions() {
9
+ if (cachedPythonVersions !== undefined) {
10
+ return cachedPythonVersions;
11
+ }
12
+ try {
13
+ let python = getCustomPath('python3');
14
+ let out = invokeCommand(python, ['-c', "import sys; v=sys.version_info; print(f'{v.major}.{v.minor} {v.major}.{v.minor}.{v.micro}')"], { timeout: 5000 }).toString().trim();
15
+ let [short, full] = out.split(' ');
16
+ cachedPythonVersions = { short, full };
17
+ }
18
+ catch {
19
+ cachedPythonVersions = null;
20
+ }
21
+ return cachedPythonVersions;
22
+ }
23
+ /**
24
+ * Maps Node.js/OS values to PEP 508 marker variables.
25
+ * Example: on Linux, sys_platform='linux', platform_system='Linux', os_name='posix'
26
+ * @returns {Record<string, string>}
27
+ */
28
+ export function getEnvironmentMarkers() {
29
+ let platform = process.platform;
30
+ let systemMap = { win32: 'Windows', linux: 'Linux', darwin: 'Darwin' };
31
+ let machine = typeof os.machine === 'function' ? os.machine() : process.arch;
32
+ let pyVer = getPythonVersions();
33
+ return {
34
+ sys_platform: platform,
35
+ platform_system: systemMap[platform] || platform,
36
+ os_name: platform === 'win32' ? 'nt' : 'posix',
37
+ platform_machine: machine,
38
+ platform_release: os.release(),
39
+ platform_version: os.version?.() || '',
40
+ python_version: pyVer?.short || '',
41
+ python_full_version: pyVer?.full || '',
42
+ implementation_name: 'cpython',
43
+ };
44
+ }
45
+ function compareVersions(left, right) {
46
+ let lParts = left.split('.').map(Number);
47
+ let rParts = right.split('.').map(Number);
48
+ let len = Math.max(lParts.length, rParts.length);
49
+ for (let i = 0; i < len; i++) {
50
+ let l = lParts[i] || 0;
51
+ let r = rParts[i] || 0;
52
+ if (l < r) {
53
+ return -1;
54
+ }
55
+ if (l > r) {
56
+ return 1;
57
+ }
58
+ }
59
+ return 0;
60
+ }
61
+ // Evaluates a single comparison like sys_platform == 'win32' or python_version >= '3.8'.
62
+ // Version-bearing variables (python_version, python_full_version) use numeric comparison;
63
+ // all others use string equality. Returns false when the env value is missing.
64
+ function evaluateComparison(variable, op, value, env) {
65
+ let envVal = env[variable];
66
+ if (envVal === undefined || envVal === '') {
67
+ return false;
68
+ }
69
+ let isVersion = variable.includes('version');
70
+ if (isVersion) {
71
+ let cmp = compareVersions(envVal, value);
72
+ switch (op) {
73
+ case '==': return cmp === 0;
74
+ case '!=': return cmp !== 0;
75
+ case '>=': return cmp >= 0;
76
+ case '<=': return cmp <= 0;
77
+ case '>': return cmp > 0;
78
+ case '<': return cmp < 0;
79
+ case '~=': {
80
+ let parts = value.split('.');
81
+ parts.pop();
82
+ let prefix = parts.join('.');
83
+ return envVal.startsWith(prefix) && cmp >= 0;
84
+ }
85
+ default: return true;
86
+ }
87
+ }
88
+ switch (op) {
89
+ case '==': return envVal === value;
90
+ case '!=': return envVal !== value;
91
+ case 'in': return value.includes(envVal);
92
+ case 'not in': return !value.includes(envVal);
93
+ default: return envVal === value;
94
+ }
95
+ }
96
+ // Parses a single marker comparison into {variable, op, value}.
97
+ // Handles both normal and reversed forms:
98
+ // "sys_platform == 'linux'" → { variable: 'sys_platform', op: '==', value: 'linux' }
99
+ // "'linux' == sys_platform" → { variable: 'sys_platform', op: '==', value: 'linux' }
100
+ function parseAtom(expr) {
101
+ // Normal form: variable op 'value'
102
+ let m = expr.match(/^\s*([\w.]+)\s*(~=|!=|==|>=|<=|>|<|not\s+in|in)\s*["']([^"']*)["']\s*$/);
103
+ if (m) {
104
+ return { variable: m[1], op: m[2].replace(/\s+/g, ' '), value: m[3] };
105
+ }
106
+ // Reversed form: 'value' op variable — reverse directional operators
107
+ let mReverse = expr.match(/^\s*["']([^"']*)['"]\s*(~=|!=|==|>=|<=|>|<|not\s+in|in)\s*([\w.]+)\s*$/);
108
+ if (mReverse) {
109
+ let reverseOp = { '<': '>', '>': '<', '<=': '>=', '>=': '<=' };
110
+ let op = mReverse[2].replace(/\s+/g, ' ');
111
+ return { variable: mReverse[3], op: reverseOp[op] || op, value: mReverse[1] };
112
+ }
113
+ return null;
114
+ }
115
+ /**
116
+ * Evaluates a full PEP 508 marker expression against the current platform.
117
+ * Example: "sys_platform == 'win32' and python_version >= '3.8'" → false on Linux
118
+ * Empty/missing markers return true (unconditional dependency).
119
+ * @param {string} markerExpr
120
+ * @returns {boolean}
121
+ */
122
+ export function evaluateMarker(markerExpr) {
123
+ if (!markerExpr || !markerExpr.trim()) {
124
+ return true;
125
+ }
126
+ let env = getEnvironmentMarkers();
127
+ return evaluateExpr(markerExpr.trim(), env);
128
+ }
129
+ function evaluateExpr(expr, env) {
130
+ let orParts = splitLogical(expr, ' or ');
131
+ if (orParts.length > 1) {
132
+ return orParts.some(part => evaluateExpr(part, env));
133
+ }
134
+ let andParts = splitLogical(expr, ' and ');
135
+ if (andParts.length > 1) {
136
+ return andParts.every(part => evaluateExpr(part, env));
137
+ }
138
+ let trimmed = expr.trim();
139
+ if (trimmed.startsWith('(') && trimmed.endsWith(')')) {
140
+ return evaluateExpr(trimmed.slice(1, -1), env);
141
+ }
142
+ let atom = parseAtom(trimmed);
143
+ if (!atom) {
144
+ return true;
145
+ }
146
+ return evaluateComparison(atom.variable, atom.op, atom.value, env);
147
+ }
148
+ // Splits an expression by " and " or " or " at the top level, skipping
149
+ // separators inside parentheses or quoted strings.
150
+ // Example: splitLogical("a == 'x' and (b == 'y' or c == 'z')", " and ")
151
+ // → ["a == 'x'", "(b == 'y' or c == 'z')"]
152
+ function splitLogical(expr, sep) {
153
+ let parts = [];
154
+ let depth = 0;
155
+ let current = '';
156
+ let i = 0;
157
+ let quoteChar = null;
158
+ while (i < expr.length) {
159
+ let ch = expr[i];
160
+ if (quoteChar) {
161
+ if (ch === quoteChar) {
162
+ quoteChar = null;
163
+ }
164
+ current += ch;
165
+ i++;
166
+ continue;
167
+ }
168
+ if (ch === '"' || ch === "'") {
169
+ quoteChar = ch;
170
+ current += ch;
171
+ i++;
172
+ continue;
173
+ }
174
+ if (ch === '(') {
175
+ depth++;
176
+ }
177
+ if (ch === ')') {
178
+ depth--;
179
+ }
180
+ if (depth === 0 && expr.substring(i, i + sep.length) === sep) {
181
+ parts.push(current);
182
+ current = '';
183
+ i += sep.length;
184
+ continue;
185
+ }
186
+ current += ch;
187
+ i++;
188
+ }
189
+ parts.push(current);
190
+ return parts.filter(p => p.trim());
191
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Parse all FROM instructions from a Dockerfile using tree-sitter to extract base image references.
3
+ * In multi-stage builds, every FROM line is returned so each image can be analyzed independently.
4
+ * ARG substitutions are resolved using declared default values. FROM lines with unresolvable
5
+ * variables (ARGs without defaults) are silently skipped.
6
+ * @param {string} manifestContent the content of the Dockerfile
7
+ * @returns {Promise<string[]>} array of image references from all resolvable FROM instructions
8
+ * @throws {Error} when no FROM instruction is found or when no FROM lines can be resolved
9
+ */
10
+ export function parseAllFromImages(manifestContent: string): Promise<string[]>;
11
+ declare namespace _default {
12
+ export { isSupported };
13
+ export { validateLockFile };
14
+ export { provideComponent };
15
+ export { provideStack };
16
+ export { readLicenseFromManifest };
17
+ export function packageManagerName(): string;
18
+ }
19
+ export default _default;
20
+ export type Provided = any;
21
+ /**
22
+ * Check if the given manifest name is a Dockerfile or Containerfile.
23
+ * Supports dot-suffixed variants such as Dockerfile.dev or Containerfile.prod.
24
+ * @param {string} manifestName the manifest file name to check
25
+ * @returns {boolean} true if the manifest is a Dockerfile or Containerfile
26
+ */
27
+ declare function isSupported(manifestName: string): boolean;
28
+ /**
29
+ * Dockerfiles have no lock file, so validation always passes.
30
+ * @returns {boolean} always true
31
+ */
32
+ declare function validateLockFile(): boolean;
33
+ /**
34
+ * Provide content and content type for Dockerfile component analysis.
35
+ * @param {string} manifest path to the Dockerfile
36
+ * @param {{}} [opts={}] optional various options to pass along the application
37
+ * @returns {Promise<Provided>}
38
+ */
39
+ declare function provideComponent(manifest: string, opts?: {}): Promise<Provided>;
40
+ /**
41
+ * Provide content and content type for Dockerfile stack analysis.
42
+ * @param {string} manifest path to the Dockerfile
43
+ * @param {{}} [opts={}] optional various options to pass along the application
44
+ * @returns {Promise<Provided>}
45
+ */
46
+ declare function provideStack(manifest: string, opts?: {}): Promise<Provided>;
47
+ /**
48
+ * Dockerfiles contain no license information.
49
+ * @returns {null} always null
50
+ */
51
+ declare function readLicenseFromManifest(): null;