ecoinvent-interface 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,497 @@
1
+ # ecoinvent-interface
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@onwp/ecoinvent-interface)](https://github.com/onwp/ecoinvent-interface/packages)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
+
6
+ A JavaScript/TypeScript library for accessing ecoinvent Life Cycle Assessment (LCA) data. Works in both Node.js and browser environments.
7
+
8
+ > **Note:** This is an **unofficial** library. It is not affiliated with or endorsed by ecoinvent.
9
+
10
+ ## Quick Start
11
+
12
+ ### Installation
13
+
14
+ ```bash
15
+ npm install @onwp/ecoinvent-interface
16
+ ```
17
+
18
+ Or with yarn:
19
+ ```bash
20
+ yarn add @onwp/ecoinvent-interface
21
+ ```
22
+
23
+ ### Your First Request
24
+
25
+ ```javascript
26
+ import { Settings, EcoinventRelease } from '@onwp/ecoinvent-interface';
27
+
28
+ // 1. Set up credentials
29
+ const settings = new Settings({
30
+ username: 'your-ecoinvent-username',
31
+ password: 'your-ecoinvent-password'
32
+ });
33
+
34
+ // 2. Create interface
35
+ const ei = new EcoinventRelease(settings);
36
+
37
+ // 3. Login and fetch data
38
+ await ei.login();
39
+ const versions = await ei.listVersions();
40
+
41
+ console.log('Available versions:', versions);
42
+ // Output: ['3.10', '3.9.1', '3.9', '3.8', ...]
43
+ ```
44
+
45
+ That's it! You're now connected to ecoinvent.
46
+
47
+ ## Prerequisites
48
+
49
+ You **must** have:
50
+ 1. A valid ecoinvent account from [ecoinvent.org](https://ecoinvent.org)
51
+ 2. Accepted the license agreement on their website
52
+ 3. Your username and password
53
+
54
+ ## Common Use Cases
55
+
56
+ ### 1. List Available Versions
57
+
58
+ ```javascript
59
+ import { Settings, EcoinventRelease } from '@onwp/ecoinvent-interface';
60
+
61
+ const ei = new EcoinventRelease(new Settings({
62
+ username: 'your-username',
63
+ password: 'your-password'
64
+ }));
65
+
66
+ await ei.login();
67
+ const versions = await ei.listVersions();
68
+ console.log(versions);
69
+ ```
70
+
71
+ ### 2. Download a Database Release
72
+
73
+ ```javascript
74
+ import { EcoinventRelease, ReleaseType } from '@onwp/ecoinvent-interface';
75
+
76
+ const ei = new EcoinventRelease(settings);
77
+ await ei.login();
78
+
79
+ // Download the matrix format for version 3.9.1, cutoff system model
80
+ const path = await ei.getRelease('3.9.1', 'cutoff', ReleaseType.MATRIX);
81
+ console.log('Downloaded to:', path);
82
+ ```
83
+
84
+ ### 3. Get Process Information
85
+
86
+ ```javascript
87
+ import { EcoinventProcess, ProcessFileType } from '@onwp/ecoinvent-interface';
88
+
89
+ const process = new EcoinventProcess(settings);
90
+ await process.login();
91
+
92
+ // Select version and process
93
+ await process.setRelease('3.9.1', 'cutoff');
94
+ process.selectProcess('12345'); // dataset ID
95
+
96
+ // Get information
97
+ const info = await process.getBasicInfo();
98
+ const docs = await process.getDocumentation();
99
+
100
+ // Download process file
101
+ const pdfPath = await process.getFile(ProcessFileType.PDF, '/path/to/save');
102
+ ```
103
+
104
+ ### 4. Download Reports
105
+
106
+ ```javascript
107
+ const ei = new EcoinventRelease(settings);
108
+ await ei.login();
109
+
110
+ // List all reports
111
+ const reports = await ei.listReportFiles();
112
+ console.log(Object.keys(reports));
113
+
114
+ // Download a specific report
115
+ const reportPath = await ei.getReport('implementation_report.pdf');
116
+ ```
117
+
118
+ ## Authentication Options
119
+
120
+ ### Option 1: Direct in Code (Quick Start)
121
+
122
+ ```javascript
123
+ const settings = new Settings({
124
+ username: 'your-username',
125
+ password: 'your-password'
126
+ });
127
+ ```
128
+
129
+ ### Option 2: Environment Variables (Recommended for Production)
130
+
131
+ ```bash
132
+ export EI_USERNAME=your-username
133
+ export EI_PASSWORD=your-password
134
+ ```
135
+
136
+ ```javascript
137
+ const settings = new Settings(); // Reads from environment automatically
138
+ ```
139
+
140
+ ### Option 3: Persistent Storage
141
+
142
+ ```javascript
143
+ import { permanentSetting } from '@onwp/ecoinvent-interface';
144
+
145
+ // Store once
146
+ permanentSetting('username', 'your-username');
147
+ permanentSetting('password', 'your-password');
148
+
149
+ // Use anywhere
150
+ const settings = new Settings(); // Reads from storage automatically
151
+ ```
152
+
153
+ ## Available Data Formats
154
+
155
+ ```javascript
156
+ import { ReleaseType } from '@onwp/ecoinvent-interface';
157
+
158
+ // Choose your format:
159
+ ReleaseType.ECOSPOLD // Unit process XML files
160
+ ReleaseType.MATRIX // Universal matrix export (recommended)
161
+ ReleaseType.LCI // Life cycle inventory XML
162
+ ReleaseType.LCIA // Impact assessment XML
163
+ ReleaseType.CUMULATIVE_LCI // Cumulative LCI (Excel)
164
+ ReleaseType.CUMULATIVE_LCIA // Cumulative LCIA (Excel)
165
+ ```
166
+
167
+ ## System Models
168
+
169
+ ```javascript
170
+ // Available system models (use abbreviation):
171
+ 'cutoff' // Allocation cut-off by classification
172
+ 'consequential' // Substitution, consequential, long-term
173
+ 'apos' // Allocation at the Point of Substitution
174
+ 'EN15804' // Allocation, cut-off, EN15804
175
+
176
+ // Example:
177
+ await ei.getRelease('3.9.1', 'cutoff', ReleaseType.MATRIX);
178
+ ```
179
+
180
+ ## Browser Usage
181
+
182
+ Works out of the box in browsers:
183
+
184
+ ```html
185
+ <!DOCTYPE html>
186
+ <html>
187
+ <head>
188
+ <script type="module">
189
+ import { Settings, EcoinventRelease } from '@onwp/ecoinvent-interface';
190
+
191
+ const settings = new Settings({
192
+ username: 'your-username',
193
+ password: 'your-password'
194
+ });
195
+
196
+ const ei = new EcoinventRelease(settings);
197
+ await ei.login();
198
+ const versions = await ei.listVersions();
199
+
200
+ console.log('Versions:', versions);
201
+ </script>
202
+ </head>
203
+ <body>
204
+ <h1>Ecoinvent Browser Example</h1>
205
+ </body>
206
+ </html>
207
+ ```
208
+
209
+ ## React Example
210
+
211
+ ```jsx
212
+ import React, { useState, useEffect } from 'react';
213
+ import { Settings, EcoinventRelease } from '@onwp/ecoinvent-interface';
214
+
215
+ function EcoinventData() {
216
+ const [versions, setVersions] = useState([]);
217
+ const [loading, setLoading] = useState(true);
218
+
219
+ useEffect(() => {
220
+ async function loadVersions() {
221
+ const settings = new Settings({
222
+ username: process.env.REACT_APP_EI_USERNAME,
223
+ password: process.env.REACT_APP_EI_PASSWORD
224
+ });
225
+
226
+ const ei = new EcoinventRelease(settings);
227
+ await ei.login();
228
+ const data = await ei.listVersions();
229
+
230
+ setVersions(data);
231
+ setLoading(false);
232
+ }
233
+
234
+ loadVersions();
235
+ }, []);
236
+
237
+ if (loading) return <div>Loading...</div>;
238
+
239
+ return (
240
+ <div>
241
+ <h1>Available Versions</h1>
242
+ <ul>
243
+ {versions.map(v => <li key={v}>{v}</li>)}
244
+ </ul>
245
+ </div>
246
+ );
247
+ }
248
+ ```
249
+
250
+ ## Advanced Features
251
+
252
+ ### Process Mapping with Fuzzy Matching
253
+
254
+ ```javascript
255
+ import { ProcessMapping } from '@onwp/ecoinvent-interface';
256
+
257
+ const mapping = new ProcessMapping(settings);
258
+
259
+ // Create remote mapping (from API)
260
+ const remoteProcesses = await mapping.createRemoteMapping(
261
+ '3.9.1',
262
+ 'cutoff',
263
+ 100 // max ID to fetch
264
+ );
265
+
266
+ // Create local mapping (from downloaded files)
267
+ const localProcesses = mapping.createLocalMapping(
268
+ 'ecoinvent 3.9.1_cutoff_ecoSpold02'
269
+ );
270
+
271
+ // Find matches using fuzzy matching
272
+ const matches = mapping.matchProcesses(localProcesses, remoteProcesses);
273
+ console.log(`Found ${matches.length} matches`);
274
+
275
+ // Find specific match
276
+ const match = mapping.findClosestMatch(
277
+ localProcesses[0],
278
+ remoteProcesses,
279
+ 10 // Levenshtein distance threshold
280
+ );
281
+ ```
282
+
283
+ ### Get Excel LCIA Files
284
+
285
+ ```javascript
286
+ import { getExcelLciaFileForVersion } from '@onwp/ecoinvent-interface';
287
+
288
+ const excelPath = await getExcelLciaFileForVersion(ei, '3.9.1');
289
+ console.log('LCIA Excel file:', excelPath);
290
+ ```
291
+
292
+ ### Logging and Debugging
293
+
294
+ ```javascript
295
+ import { setLogLevel, LogLevel } from '@onwp/ecoinvent-interface';
296
+
297
+ // Enable debug logging
298
+ setLogLevel(LogLevel.DEBUG);
299
+
300
+ // Now all operations will log detailed information
301
+ const ei = new EcoinventRelease(settings);
302
+ await ei.login(); // Will show detailed login process
303
+ ```
304
+
305
+ ## Cache and Storage
306
+
307
+ Files are automatically cached to avoid re-downloading:
308
+
309
+ **Cache Locations:**
310
+ - **macOS**: `~/Library/Caches/ecoinvent-interface`
311
+ - **Windows**: `%LOCALAPPDATA%\ecoinvent-interface\Cache`
312
+ - **Linux**: `~/.cache/ecoinvent-interface`
313
+ - **Browser**: IndexedDB or localStorage
314
+
315
+ **Custom Cache Directory:**
316
+ ```javascript
317
+ const settings = new Settings({
318
+ username: 'user',
319
+ password: 'pass',
320
+ outputPath: '/custom/cache/path'
321
+ });
322
+ ```
323
+
324
+ ## API Reference
325
+
326
+ ### Classes
327
+
328
+ - **`Settings`** - Authentication and configuration
329
+ - **`EcoinventRelease`** - Access database releases
330
+ - **`EcoinventProcess`** - Access individual processes
331
+ - **`ProcessMapping`** - Map between local and remote processes
332
+ - **`CachedStorage`** - Manage cached files
333
+
334
+ ### Enums
335
+
336
+ - **`ReleaseType`** - Database format types
337
+ - **`ProcessFileType`** - Process file types (UPR, LCI, LCIA, PDF)
338
+ - **`LogLevel`** - Logging levels (ERROR, WARN, INFO, DEBUG)
339
+
340
+ ### Methods
341
+
342
+ #### EcoinventRelease
343
+ - `login()` - Authenticate with ecoinvent
344
+ - `listVersions()` - Get available versions
345
+ - `listSystemModels(version)` - Get system models
346
+ - `getRelease(version, model, type)` - Download database
347
+ - `listReportFiles()` - List available reports
348
+ - `getReport(filename)` - Download report
349
+ - `listExtraFiles(version)` - List extra files
350
+ - `getExtra(version, filename)` - Download extra file
351
+
352
+ #### EcoinventProcess
353
+ - `setRelease(version, model)` - Set version/model
354
+ - `selectProcess(datasetId)` - Select process by ID
355
+ - `getBasicInfo()` - Get process metadata
356
+ - `getDocumentation()` - Get XML documentation
357
+ - `getFile(fileType, directory)` - Download process file
358
+
359
+ #### ProcessMapping
360
+ - `createRemoteMapping(version, model, maxId)` - Fetch from API
361
+ - `createLocalMapping(cacheKey)` - Parse local files
362
+ - `findClosestMatch(local, remotes, threshold)` - Find match
363
+ - `matchProcesses(locals, remotes)` - Match all processes
364
+ - `addMapping(data, version, model)` - Save mapping
365
+
366
+ ## TypeScript Support
367
+
368
+ Full TypeScript definitions included:
369
+
370
+ ```typescript
371
+ import {
372
+ Settings,
373
+ EcoinventRelease,
374
+ ReleaseType,
375
+ EcoinventProcess,
376
+ ProcessFileType,
377
+ ISettings
378
+ } from '@onwp/ecoinvent-interface';
379
+
380
+ const settings: ISettings = {
381
+ username: 'user',
382
+ password: 'pass'
383
+ };
384
+
385
+ const ei: EcoinventRelease = new EcoinventRelease(new Settings(settings));
386
+ ```
387
+
388
+ ## Troubleshooting
389
+
390
+ ### Authentication Errors
391
+
392
+ **Error:** "Missing username" or "Missing password"
393
+
394
+ ```javascript
395
+ // Solution: Make sure credentials are set
396
+ const settings = new Settings({
397
+ username: 'your-username', // ← Don't forget these!
398
+ password: 'your-password'
399
+ });
400
+ ```
401
+
402
+ ### File Not Found
403
+
404
+ **Error:** "Version X.X.X not found"
405
+
406
+ ```javascript
407
+ // Solution: Check available versions first
408
+ const versions = await ei.listVersions();
409
+ console.log('Available:', versions);
410
+ ```
411
+
412
+ ### Network Timeouts
413
+
414
+ ```javascript
415
+ // The library has built-in 20-second timeouts
416
+ // If you need longer, you may need to adjust your network
417
+ ```
418
+
419
+ ## Examples
420
+
421
+ See the `examples/` directory for complete working examples:
422
+
423
+ - `examples/basic-usage.js` - Simple version listing
424
+ - More examples coming soon
425
+
426
+ ## Migration from Python
427
+
428
+ If you're migrating from the Python package:
429
+
430
+ | Python | JavaScript/TypeScript |
431
+ |--------|----------------------|
432
+ | `list_versions()` | `listVersions()` |
433
+ | `get_release()` | `getRelease()` |
434
+ | `system_model` | `systemModel` |
435
+ | `output_path` | `outputPath` |
436
+
437
+ All functionality is available with JavaScript naming conventions (camelCase).
438
+
439
+ ## Requirements
440
+
441
+ - **Node.js**: 14.0 or higher
442
+ - **Browsers**: Modern browsers with ES6 support
443
+ - **ecoinvent Account**: Required for API access
444
+
445
+ ## Development
446
+
447
+ ```bash
448
+ # Install dependencies
449
+ npm install
450
+
451
+ # Run tests
452
+ npm test
453
+
454
+ # Build
455
+ npm run build
456
+
457
+ # Watch mode
458
+ npm run dev
459
+ ```
460
+
461
+ ## License
462
+
463
+ MIT License - see [LICENSE](LICENSE) file
464
+
465
+ ## Support
466
+
467
+ - **Issues**: [GitHub Issues](https://github.com/onwp/ecoinvent-interface/issues)
468
+ - **Documentation**: This README and [MIGRATION_VALIDATION.md](MIGRATION_VALIDATION.md)
469
+ - **ecoinvent Support**: [ecoinvent.org](https://ecoinvent.org)
470
+
471
+ ## Changelog
472
+
473
+ ### Version 1.1.0 (Latest)
474
+ - ✨ Added `getExcelLciaFileForVersion()` utility function
475
+ - ✨ Added `ProcessMapping.addMapping()` for storing mappings
476
+ - ✨ Enhanced fuzzy matching with `findClosestMatch()` and `matchProcesses()`
477
+ - 📚 Comprehensive test suite
478
+ - 📖 Improved documentation
479
+ - 🌐 Full browser compatibility
480
+
481
+ ### Version 1.0.0
482
+ - 🎉 Initial release
483
+ - ✅ Complete feature parity with Python package
484
+ - ✅ TypeScript support
485
+ - ✅ Browser and Node.js support
486
+
487
+ ## Acknowledgments
488
+
489
+ This library is a TypeScript port of the [Python ecoinvent-interface package](https://github.com/brightway-lca/ecoinvent_interface) by Chris Mutel.
490
+
491
+ ## Disclaimer
492
+
493
+ This is an **unofficial and unsupported** library. It is not affiliated with or endorsed by ecoinvent. The library interacts with ecoinvent's API which may change without notice.
494
+
495
+ ---
496
+
497
+ **Made with ❤️ for the LCA community**
@@ -0,0 +1,87 @@
1
+ import { Settings } from './settings';
2
+ import { CachedStorage } from '../storage/cached-storage';
3
+ import { URLS, FileMetadata } from '../types';
4
+ /**
5
+ * Format API response object into a standardized metadata object
6
+ */
7
+ export declare function formatDict(obj: any): FileMetadata;
8
+ /**
9
+ * Base class for ecoinvent API interaction
10
+ */
11
+ export declare class InterfaceBase {
12
+ username: string;
13
+ password: string;
14
+ urls: typeof URLS;
15
+ customHeaders: Record<string, string>;
16
+ storage: CachedStorage;
17
+ accessToken?: string;
18
+ refreshToken?: string;
19
+ lastRefresh?: number;
20
+ /**
21
+ * Create a new InterfaceBase instance
22
+ *
23
+ * @param settings Settings object with authentication credentials
24
+ * @param urls Optional custom API URLs
25
+ * @param customHeaders Optional custom HTTP headers
26
+ */
27
+ constructor(settings: Settings, urls?: typeof URLS, customHeaders?: Record<string, string>);
28
+ /**
29
+ * Log in to the ecoinvent API
30
+ */
31
+ login(): Promise<void>;
32
+ /**
33
+ * Refresh the authentication tokens
34
+ */
35
+ refreshTokens(): Promise<void>;
36
+ /**
37
+ * Get authentication credentials from the API
38
+ *
39
+ * @param postData Data to send in the authentication request
40
+ */
41
+ private _getCredentials;
42
+ /**
43
+ * Get all report files from the API
44
+ */
45
+ _getAllReports(): Promise<any[]>;
46
+ /**
47
+ * Get all files from the API
48
+ */
49
+ _getAllFiles(): Promise<any>;
50
+ /**
51
+ * Download a file from the API via S3
52
+ *
53
+ * @param uuid File UUID
54
+ * @param filename Filename
55
+ * @param urlNamespace URL namespace
56
+ * @param directory Directory to save the file to
57
+ */
58
+ _downloadS3(uuid: string, filename: string, urlNamespace: string, directory: string): Promise<string>;
59
+ /**
60
+ * Download a file with streaming
61
+ *
62
+ * @param url URL to download from
63
+ * @param params URL parameters
64
+ * @param directory Directory to save the file to
65
+ * @param filename Filename
66
+ * @param headers Optional HTTP headers
67
+ * @param zipped Whether the file is gzipped
68
+ */
69
+ _streamingDownload(url: string, params: Record<string, string>, directory: string, filename: string, headers?: Record<string, string>, zipped?: boolean): Promise<void>;
70
+ /**
71
+ * List all available ecoinvent versions
72
+ */
73
+ listVersions(): Promise<string[]>;
74
+ /**
75
+ * List all available system models for a specific version
76
+ *
77
+ * @param version Version identifier
78
+ * @param translate Whether to translate system model names to abbreviations
79
+ */
80
+ listSystemModels(version: string, translate?: boolean): Promise<string[]>;
81
+ /**
82
+ * Get files for a specific version
83
+ *
84
+ * @param version Version identifier
85
+ */
86
+ _getFilesForVersion(version: string): Promise<any>;
87
+ }
@@ -0,0 +1,28 @@
1
+ import { ISettings } from '../types';
2
+ /**
3
+ * Settings class for ecoinvent authentication
4
+ *
5
+ * Handles authentication credentials for ecoinvent API access.
6
+ * Credentials can be provided in three ways:
7
+ * 1. Directly in the constructor
8
+ * 2. Via environment variables (in Node.js)
9
+ * 3. Via stored settings (browser localStorage or Node.js file system)
10
+ */
11
+ export declare class Settings implements ISettings {
12
+ username?: string;
13
+ password?: string;
14
+ outputPath?: string;
15
+ /**
16
+ * Create a new Settings instance
17
+ *
18
+ * @param settings Optional settings object with username, password, and outputPath
19
+ */
20
+ constructor(settings?: ISettings);
21
+ }
22
+ /**
23
+ * Store a setting permanently
24
+ *
25
+ * @param key Setting key (username, password, or outputPath)
26
+ * @param value Setting value
27
+ */
28
+ export declare function permanentSetting(key: string, value: string): void;