@socketsecurity/sdk 1.5.1 → 1.7.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/CHANGELOG.md +43 -0
- package/README.md +203 -28
- package/dist/constants.d.ts +8 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +128 -0
- package/dist/constants.js.map +1 -0
- package/dist/file-upload.d.ts +22 -0
- package/dist/file-upload.d.ts.map +1 -0
- package/dist/file-upload.js +152 -0
- package/dist/file-upload.js.map +1 -0
- package/dist/http-client.d.ts +79 -0
- package/dist/http-client.d.ts.map +1 -0
- package/dist/http-client.js +262 -0
- package/dist/http-client.js.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +39 -1031
- package/dist/index.js.map +1 -1
- package/dist/socket-sdk-class.d.ts +422 -0
- package/dist/socket-sdk-class.d.ts.map +1 -0
- package/dist/socket-sdk-class.js +1342 -0
- package/dist/socket-sdk-class.js.map +1 -0
- package/dist/types.d.ts +155 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +4 -0
- package/dist/types.js.map +1 -0
- package/dist/user-agent.d.ts +14 -0
- package/dist/user-agent.d.ts.map +1 -0
- package/dist/user-agent.js +18 -0
- package/dist/user-agent.js.map +1 -0
- package/dist/utils.d.ts +29 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +94 -0
- package/dist/utils.js.map +1 -0
- package/package.json +58 -71
- package/types/api.d.ts +125 -127
- package/dist/index.cjs +0 -1043
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -134
- package/dist/index.d.cts.map +0 -1
- package/dist/index.d.mts +0 -134
- package/dist/index.d.mts.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,49 @@ All notable changes to this project will be documented in this file.
|
|
|
4
4
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
6
6
|
|
|
7
|
+
## [1.7.0](https://github.com/SocketDev/socket-sdk-js/releases/tag/v1.7.0) - 2025-09-26
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
- `getApi` method for raw GET requests with configurable response handling
|
|
11
|
+
- `sendApi` method for POST/PUT requests with JSON body support
|
|
12
|
+
- `CResult` type pattern for non-throwing API operations
|
|
13
|
+
- `CustomResponseType` type export for response type options
|
|
14
|
+
- Support for custom response types (`response`, `text`, `json`) in `getApi`
|
|
15
|
+
- Enhanced error handling with detailed error context from `error.details` field
|
|
16
|
+
- Socket API `error.details` parsing for richer error information
|
|
17
|
+
- `getEntitlements` method for retrieving organization entitlements
|
|
18
|
+
- `getEnabledEntitlements` method for getting enabled entitlement keys
|
|
19
|
+
- `viewPatch` method for retrieving patch details by UUID
|
|
20
|
+
- `streamPatchesFromScan` method for streaming patches from scan results
|
|
21
|
+
- `Entitlement` and `EntitlementsResponse` types for entitlements API
|
|
22
|
+
- `PatchFile`, `Vulnerability`, `SecurityAlert`, `PatchRecord`, `PatchViewResponse`, and `ArtifactPatches` types for patches API
|
|
23
|
+
- Support for NDJSON streaming responses in patches API
|
|
24
|
+
- Comprehensive test coverage improvements (484 total tests, 99.92% line coverage, 99.39% branch coverage)
|
|
25
|
+
- Enhanced error handling tests for JSON parsing edge cases in streaming
|
|
26
|
+
- Additional coverage tests for invalid JSON line handling in NDJSON streams
|
|
27
|
+
|
|
28
|
+
### Changed
|
|
29
|
+
- Improved error message formatting and JSON parsing error handling
|
|
30
|
+
- Enhanced type safety with better generic constraints
|
|
31
|
+
- Renamed option types to `GetOptions` and `SendOptions` for consistency
|
|
32
|
+
- Reorganized test files into focused, functionality-based modules
|
|
33
|
+
- Raised coverage thresholds to match achieved levels (100% statements, functions, lines)
|
|
34
|
+
- Removed duplicate tests while maintaining coverage integrity
|
|
35
|
+
- Renamed `getIssuesByNPMPackage` to `getIssuesByNpmPackage` for consistent naming convention
|
|
36
|
+
- Improved method alphabetical ordering in source code
|
|
37
|
+
- Enhanced test coverage from 99.77% to 99.92% line coverage
|
|
38
|
+
- Improved branch coverage from 99.08% to 99.39%
|
|
39
|
+
|
|
40
|
+
## [1.6.1](https://github.com/SocketDev/socket-sdk-js/releases/tag/v1.6.1) - 2025-09-24
|
|
41
|
+
|
|
42
|
+
### Changed
|
|
43
|
+
- Updated to use trusted publisher for npm package provenance
|
|
44
|
+
|
|
45
|
+
## [1.6.0](https://github.com/SocketDev/socket-sdk-js/releases/tag/v1.6.0) - 2025-09-24
|
|
46
|
+
|
|
47
|
+
### Changed
|
|
48
|
+
- **BREAKING:** Converted to single CommonJS export type, removing dual ESM/CJS support
|
|
49
|
+
|
|
7
50
|
## [1.5.1](https://github.com/SocketDev/socket-sdk-js/releases/tag/v1.5.1) - 2025-09-24
|
|
8
51
|
|
|
9
52
|
### Fixed
|
package/README.md
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
[](https://www.npmjs.com/package/@socketsecurity/sdk)
|
|
6
6
|
[](https://github.com/SocketDev/eslint-config)
|
|
7
7
|
[](https://twitter.com/SocketSecurity)
|
|
8
|
+
[](https://bsky.app/profile/socket.dev)
|
|
8
9
|
|
|
9
10
|
SDK for the Socket API client, generated by `api`.
|
|
10
11
|
|
|
@@ -35,36 +36,210 @@ if (res.success) {
|
|
|
35
36
|
const { SocketSdk } = require('@socketsecurity/sdk')
|
|
36
37
|
```
|
|
37
38
|
|
|
39
|
+
## API Overview
|
|
40
|
+
|
|
41
|
+
The Socket SDK provides programmatic access to Socket.dev's security analysis platform through 60+ API methods organized into functional categories:
|
|
42
|
+
|
|
43
|
+
### Package Analysis
|
|
44
|
+
- **Package Security**: Get vulnerability reports, security scores, and issue details for npm packages
|
|
45
|
+
- **Batch Processing**: Analyze multiple packages efficiently with streaming and concurrent processing
|
|
46
|
+
- **PURL Support**: Process Package URLs for comprehensive package identification
|
|
47
|
+
|
|
48
|
+
### Organization Management
|
|
49
|
+
- **Organizations**: List, manage, and configure organization settings
|
|
50
|
+
- **Repositories**: Create, update, and delete organization repositories
|
|
51
|
+
- **Labels**: Manage repository categorization and tagging systems
|
|
52
|
+
|
|
53
|
+
### Security Scanning & Analysis
|
|
54
|
+
- **Full Scans**: Create comprehensive security scans from manifest files
|
|
55
|
+
- **Diff Scans**: Compare scans to identify changes and new vulnerabilities
|
|
56
|
+
- **Dependencies**: Upload and analyze project dependency files
|
|
57
|
+
- **Reports**: Generate, retrieve, and manage detailed security reports
|
|
58
|
+
|
|
59
|
+
### Policy & Compliance
|
|
60
|
+
- **Security Policies**: Configure and update organization security policies
|
|
61
|
+
- **License Policies**: Manage allowed/restricted license types
|
|
62
|
+
- **Alert Triage**: Review and manage security alert statuses
|
|
63
|
+
- **Audit Logs**: Access chronological security and administrative events
|
|
64
|
+
|
|
65
|
+
### Data Export & Integration
|
|
66
|
+
- **SBOM Export**: Generate CycloneDX and SPDX Software Bill of Materials
|
|
67
|
+
- **Streaming**: Efficient data streaming for large datasets
|
|
68
|
+
- **Analytics**: Access usage metrics and security trend data
|
|
69
|
+
|
|
70
|
+
### Authentication & Access
|
|
71
|
+
- **API Tokens**: Create, rotate, update, and revoke organization API tokens
|
|
72
|
+
- **Entitlements**: View enabled Socket products and features
|
|
73
|
+
- **Quota Management**: Monitor API usage limits and quotas
|
|
74
|
+
|
|
75
|
+
### Advanced Features
|
|
76
|
+
- **Patches**: View and stream security patches for vulnerabilities
|
|
77
|
+
- **Custom Queries**: Raw API access with configurable response handling
|
|
78
|
+
- **Cross-platform**: Full Windows, macOS, and Linux compatibility
|
|
79
|
+
|
|
38
80
|
## SocketSdk Methods
|
|
39
81
|
|
|
40
|
-
### Package
|
|
41
|
-
|
|
42
|
-
* `
|
|
43
|
-
*
|
|
44
|
-
|
|
45
|
-
*
|
|
46
|
-
|
|
47
|
-
*
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
*
|
|
55
|
-
* `
|
|
56
|
-
*
|
|
57
|
-
* `
|
|
58
|
-
*
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
*
|
|
63
|
-
* `
|
|
64
|
-
*
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
82
|
+
### Package Analysis Methods
|
|
83
|
+
|
|
84
|
+
* `batchPackageFetch(componentsObj, queryParams?)` - Analyze multiple packages in batch
|
|
85
|
+
* Returns all results at once after processing is complete
|
|
86
|
+
* `batchPackageStream(componentsObj, options?)` - Stream package analysis with concurrency control
|
|
87
|
+
* Returns results as they become available via async generator
|
|
88
|
+
* `getIssuesByNpmPackage(packageName, version)` - Get security issues for a specific npm package
|
|
89
|
+
* Returns detailed vulnerability and security alert information
|
|
90
|
+
* `getScoreByNpmPackage(packageName, version)` - Get security score for a package
|
|
91
|
+
* Returns numerical security rating and scoring breakdown
|
|
92
|
+
|
|
93
|
+
### Scanning & Analysis Methods
|
|
94
|
+
|
|
95
|
+
* `createDependenciesSnapshot(filepaths, pathsRelativeTo='.', queryParams?)` - Create dependency snapshot
|
|
96
|
+
* Analyzes dependency files to generate comprehensive security report
|
|
97
|
+
* `createOrgFullScan(orgSlug, filepaths, pathsRelativeTo='.', queryParams?)` - Create full organization scan
|
|
98
|
+
* Uploads project files and initiates complete security analysis
|
|
99
|
+
* `createScanFromFilepaths(filePaths, pathsRelativeTo='.', issueRules?)` - Create security scan from files
|
|
100
|
+
* Analyzes uploaded files for security vulnerabilities and policy violations
|
|
101
|
+
* `getScan(id)` - Get detailed scan results
|
|
102
|
+
* Returns complete scan analysis including vulnerabilities and alerts
|
|
103
|
+
* `getScanList()` - List all accessible scans
|
|
104
|
+
* Returns paginated list of scan metadata and status
|
|
105
|
+
* `getSupportedScanFiles()` - Get supported file formats
|
|
106
|
+
* Returns supported manifest files, lockfiles, and configuration formats
|
|
107
|
+
|
|
108
|
+
### Organization Management Methods
|
|
109
|
+
|
|
110
|
+
* `createOrgRepo(orgSlug, queryParams?)` - Create new repository
|
|
111
|
+
* Registers repository for monitoring and security scanning
|
|
112
|
+
* `deleteOrgRepo(orgSlug, repoSlug)` - Delete repository
|
|
113
|
+
* Removes repository monitoring and associated scan data
|
|
114
|
+
* `getOrganizations()` - List accessible organizations
|
|
115
|
+
* Returns organization details and access permissions
|
|
116
|
+
* `getOrgRepo(orgSlug, repoSlug)` - Get repository details
|
|
117
|
+
* Returns repository configuration, monitoring status, and metadata
|
|
118
|
+
* `getOrgRepoList(orgSlug, queryParams?)` - List organization repositories
|
|
119
|
+
* Returns paginated list of repository metadata and status
|
|
120
|
+
* `updateOrgRepo(orgSlug, repoSlug, queryParams?)` - Update repository configuration
|
|
121
|
+
* Modifies monitoring settings, branch configuration, and scan preferences
|
|
122
|
+
|
|
123
|
+
### Full Scan Management Methods
|
|
124
|
+
|
|
125
|
+
* `deleteOrgFullScan(orgSlug, fullScanId)` - Delete full scan
|
|
126
|
+
* Permanently removes scan data and results
|
|
127
|
+
* `getOrgFullScanBuffered(orgSlug, fullScanId)` - Get complete scan results in memory
|
|
128
|
+
* Returns entire scan data as JSON for programmatic processing
|
|
129
|
+
* `getOrgFullScanList(orgSlug, queryParams?)` - List organization full scans
|
|
130
|
+
* Returns paginated list of scan metadata and status
|
|
131
|
+
* `getOrgFullScanMetadata(orgSlug, fullScanId)` - Get scan metadata
|
|
132
|
+
* Returns scan configuration, status, and summary information
|
|
133
|
+
* `streamOrgFullScan(orgSlug, fullScanId, output?)` - Stream scan results
|
|
134
|
+
* Provides efficient streaming for large scan datasets to file or stdout
|
|
135
|
+
|
|
136
|
+
### Policy & Settings Methods
|
|
137
|
+
|
|
138
|
+
* `getOrgLicensePolicy(orgSlug)` - Get license policy configuration
|
|
139
|
+
* Returns allowed, restricted, and monitored license types
|
|
140
|
+
* `getOrgSecurityPolicy(orgSlug)` - Get organization security policy
|
|
141
|
+
* Returns alert rules, severity thresholds, and enforcement settings
|
|
142
|
+
* `postSettings(selectors)` - Update user or organization settings
|
|
143
|
+
* Configures preferences, notifications, and security policies
|
|
144
|
+
* `updateOrgLicensePolicy(orgSlug, policyData, queryParams?)` - Update license policy
|
|
145
|
+
* Modifies allowed, restricted, and monitored license types
|
|
146
|
+
* `updateOrgSecurityPolicy(orgSlug, policyData)` - Update security policy
|
|
147
|
+
* Modifies alert rules, severity thresholds, and enforcement settings
|
|
148
|
+
|
|
149
|
+
### Analytics & Monitoring Methods
|
|
150
|
+
|
|
151
|
+
* `getAuditLogEvents(orgSlug, queryParams?)` - Get audit log events
|
|
152
|
+
* Returns chronological log of security and administrative actions
|
|
153
|
+
* `getOrgAnalytics(time)` - Get organization analytics
|
|
154
|
+
* Returns statistical analysis for specified time period
|
|
155
|
+
* `getQuota()` - Get current API quota usage
|
|
156
|
+
* Returns remaining requests, rate limits, and quota reset times
|
|
157
|
+
* `getRepoAnalytics(repo, time)` - Get repository analytics
|
|
158
|
+
* Returns security metrics, dependency trends, and vulnerability statistics
|
|
159
|
+
|
|
160
|
+
### Authentication & Access Methods
|
|
161
|
+
|
|
162
|
+
* `getAPITokens(orgSlug)` - List organization API tokens
|
|
163
|
+
* Returns organization API tokens with metadata and permissions
|
|
164
|
+
* `postAPIToken(orgSlug, tokenData)` - Create new API token
|
|
165
|
+
* Generates API token with specified scopes and metadata
|
|
166
|
+
* `postAPITokensRevoke(orgSlug, tokenId)` - Revoke API token
|
|
167
|
+
* Permanently disables the token and removes access
|
|
168
|
+
* `postAPITokensRotate(orgSlug, tokenId)` - Rotate API token
|
|
169
|
+
* Generates new token value while preserving token metadata
|
|
170
|
+
* `postAPITokenUpdate(orgSlug, tokenId, updateData)` - Update API token
|
|
171
|
+
* Modifies token metadata, scopes, or other properties
|
|
172
|
+
|
|
173
|
+
### Export & Integration Methods
|
|
174
|
+
|
|
175
|
+
* `exportCDX(orgSlug, fullScanId)` - Export CycloneDX SBOM
|
|
176
|
+
* Returns Software Bill of Materials compliant with CycloneDX standard
|
|
177
|
+
* `exportSPDX(orgSlug, fullScanId)` - Export SPDX SBOM
|
|
178
|
+
* Returns Software Bill of Materials compliant with SPDX standard
|
|
179
|
+
* `searchDependencies(queryParams?)` - Search monitored dependencies
|
|
180
|
+
* Returns matching packages with security information and usage patterns
|
|
181
|
+
* `uploadManifestFiles(orgSlug, filepaths, pathsRelativeTo='.')` - Upload manifest files
|
|
182
|
+
* Processes package files to create dependency snapshots and security analysis
|
|
183
|
+
|
|
184
|
+
### Alert & Triage Methods
|
|
185
|
+
|
|
186
|
+
* `getOrgTriage(orgSlug)` - Get organization triage settings
|
|
187
|
+
* Returns alert triage configuration and current state
|
|
188
|
+
* `updateOrgAlertTriage(orgSlug, alertId, triageData)` - Update alert triage
|
|
189
|
+
* Modifies alert resolution status and triage decisions
|
|
190
|
+
|
|
191
|
+
### Repository Label Methods
|
|
192
|
+
|
|
193
|
+
* `createOrgRepoLabel(orgSlug, repoSlug, labelData)` - Create repository label
|
|
194
|
+
* Adds label for repository categorization and management
|
|
195
|
+
* `deleteOrgRepoLabel(orgSlug, repoSlug, labelSlug)` - Delete repository label
|
|
196
|
+
* Removes label and associated configuration
|
|
197
|
+
* `getOrgRepoLabel(orgSlug, repoSlug, labelSlug)` - Get label details
|
|
198
|
+
* Returns label configuration and metadata
|
|
199
|
+
* `getOrgRepoLabelList(orgSlug, repoSlug)` - List repository labels
|
|
200
|
+
* Returns all labels configured for repository management
|
|
201
|
+
* `updateOrgRepoLabel(orgSlug, repoSlug, labelSlug, labelData)` - Update repository label
|
|
202
|
+
* Modifies label properties and configuration
|
|
203
|
+
|
|
204
|
+
### Diff Scan Methods
|
|
205
|
+
|
|
206
|
+
* `createOrgDiffScanFromIds(orgSlug, queryParams?)` - Create diff scan from IDs
|
|
207
|
+
* Compares two existing full scans to identify changes
|
|
208
|
+
* `deleteOrgDiffScan(orgSlug, diffScanId)` - Delete diff scan
|
|
209
|
+
* Permanently removes diff scan data and results
|
|
210
|
+
* `getDiffScanById(orgSlug, diffScanId)` - Get diff scan details
|
|
211
|
+
* Returns comparison between two full scans with artifact changes
|
|
212
|
+
* `listOrgDiffScans(orgSlug)` - List organization diff scans
|
|
213
|
+
* Returns paginated list of diff scan metadata and status
|
|
214
|
+
|
|
215
|
+
### Patch & Vulnerability Methods
|
|
216
|
+
|
|
217
|
+
* `streamPatchesFromScan(orgSlug, scanId)` - Stream patches from scan
|
|
218
|
+
* Returns ReadableStream for processing large patch datasets
|
|
219
|
+
* `viewPatch(orgSlug, uuid)` - View patch details
|
|
220
|
+
* Retrieves comprehensive patch information including files and vulnerabilities
|
|
221
|
+
|
|
222
|
+
### Entitlement Methods
|
|
223
|
+
|
|
224
|
+
* `getEnabledEntitlements(orgSlug)` - Get enabled entitlements
|
|
225
|
+
* Returns array of enabled Socket product keys
|
|
226
|
+
* `getEntitlements(orgSlug)` - Get all organization entitlements
|
|
227
|
+
* Returns complete list of entitlements with their status
|
|
228
|
+
|
|
229
|
+
### Advanced Query Methods
|
|
230
|
+
|
|
231
|
+
* `getApi<T>(urlPath, options?)` - Execute raw GET request
|
|
232
|
+
* Direct API access with configurable response type (response, json, text)
|
|
233
|
+
* `sendApi<T>(urlPath, options?)` - Send POST/PUT with JSON body
|
|
234
|
+
* Direct API access for POST/PUT operations with JSON responses
|
|
235
|
+
|
|
236
|
+
### Legacy Methods (Deprecated Names)
|
|
237
|
+
|
|
238
|
+
* `createReportFromFilepaths()` → Use `createScanFromFilepaths()`
|
|
239
|
+
* `deleteReport(reportId)` → Use scan-specific delete methods
|
|
240
|
+
* `getReport(id)` → Use `getScan(id)`
|
|
241
|
+
* `getReportList()` → Use `getScanList()`
|
|
242
|
+
* `getReportSupportedFiles()` → Use `getSupportedScanFiles()`
|
|
68
243
|
|
|
69
244
|
## Additional exports
|
|
70
245
|
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ALERT_ACTION } from './types';
|
|
2
|
+
export declare const DEFAULT_USER_AGENT: string;
|
|
3
|
+
// https://github.com/sindresorhus/got/blob/v14.4.6/documentation/2-options.md#agent
|
|
4
|
+
// Valid HTTP agent names for Got-style agent configuration compatibility.
|
|
5
|
+
export declare const httpAgentNames: Set<string>;
|
|
6
|
+
// Public security policy.
|
|
7
|
+
export declare const publicPolicy: Map<"ambiguousClassifier" | "badEncoding" | "badSemver" | "badSemverDependency" | "bidi" | "binScriptConfusion" | "chromeContentScript" | "chromeHostPermission" | "chromePermission" | "chromeWildcardHostPermission" | "chronoAnomaly" | "compromisedSSHKey" | "copyleftLicense" | "criticalCVE" | "cve" | "debugAccess" | "deprecated" | "deprecatedException" | "deprecatedLicense" | "didYouMean" | "dynamicRequire" | "emptyPackage" | "envVars" | "explicitlyUnlicensedItem" | "extraneousDependency" | "fileDependency" | "filesystemAccess" | "floatingDependency" | "generic" | "gitDependency" | "gitHubDependency" | "gptAnomaly" | "gptDidYouMean" | "gptMalware" | "gptSecurity" | "hasNativeCode" | "highEntropyStrings" | "homoglyphs" | "httpDependency" | "installScripts" | "invalidPackageJSON" | "invisibleChars" | "licenseChange" | "licenseException" | "licenseSpdxDisj" | "longStrings" | "majorRefactor" | "malware" | "manifestConfusion" | "mediumCVE" | "mildCVE" | "minifiedFile" | "miscLicenseIssues" | "missingAuthor" | "missingDependency" | "missingLicense" | "missingTarball" | "mixedLicense" | "modifiedException" | "modifiedLicense" | "networkAccess" | "newAuthor" | "noAuthorData" | "noBugTracker" | "noLicenseFound" | "noREADME" | "noRepository" | "noTests" | "noV1" | "noWebsite" | "nonOSILicense" | "nonSPDXLicense" | "nonpermissiveLicense" | "notice" | "obfuscatedFile" | "obfuscatedRequire" | "peerDependency" | "potentialVulnerability" | "semverAnomaly" | "shellAccess" | "shellScriptOverride" | "shrinkwrap" | "socketUpgradeAvailable" | "suspiciousStarActivity" | "suspiciousString" | "telemetry" | "trivialPackage" | "troll" | "typeModuleCompatibility" | "uncaughtOptionalDependency" | "unclearLicense" | "unidentifiedLicense" | "unmaintained" | "unpopularPackage" | "unpublished" | "unresolvedRequire" | "unsafeCopyright" | "unstableOwnership" | "unusedDependency" | "urlStrings" | "usesEval" | "zeroWidth", ALERT_ACTION>;
|
|
8
|
+
//# sourceMappingURL=constants.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,YAAY,EAAc,MAAM,SAAS,CAAA;AAEvD,eAAO,MAAM,kBAAkB,QAA0C,CAAA;AAEzE,oFAAoF;AACpF,0EAA0E;AAC1E,eAAO,MAAM,cAAc,aAAsC,CAAA;AAEjE,0BAA0B;AAC1B,eAAO,MAAM,YAAY,g5DA0GvB,CAAA"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.publicPolicy = exports.httpAgentNames = exports.DEFAULT_USER_AGENT = void 0;
|
|
7
|
+
/**
|
|
8
|
+
* @fileoverview Configuration constants and enums for the Socket SDK.
|
|
9
|
+
* Provides default values, HTTP agents, and public policy configurations for API interactions.
|
|
10
|
+
*/
|
|
11
|
+
// Import attributes are only supported when the '--module' option is set to
|
|
12
|
+
// 'esnext', 'node18', 'node20', 'nodenext', or 'preserve'.
|
|
13
|
+
// @ts-ignore: Avoid TS import attributes error.
|
|
14
|
+
const package_json_1 = __importDefault(require("../package.json"));
|
|
15
|
+
const user_agent_1 = require("./user-agent");
|
|
16
|
+
exports.DEFAULT_USER_AGENT = (0, user_agent_1.createUserAgentFromPkgJson)(package_json_1.default);
|
|
17
|
+
// https://github.com/sindresorhus/got/blob/v14.4.6/documentation/2-options.md#agent
|
|
18
|
+
// Valid HTTP agent names for Got-style agent configuration compatibility.
|
|
19
|
+
exports.httpAgentNames = new Set(['http', 'https', 'http2']);
|
|
20
|
+
// Public security policy.
|
|
21
|
+
exports.publicPolicy = new Map([
|
|
22
|
+
// error (1):
|
|
23
|
+
['malware', 'error'],
|
|
24
|
+
// warn (7):
|
|
25
|
+
['criticalCVE', 'warn'],
|
|
26
|
+
['didYouMean', 'warn'],
|
|
27
|
+
['gitDependency', 'warn'],
|
|
28
|
+
['httpDependency', 'warn'],
|
|
29
|
+
['licenseSpdxDisj', 'warn'],
|
|
30
|
+
['obfuscatedFile', 'warn'],
|
|
31
|
+
['troll', 'warn'],
|
|
32
|
+
// monitor (7):
|
|
33
|
+
['deprecated', 'monitor'],
|
|
34
|
+
['mediumCVE', 'monitor'],
|
|
35
|
+
['mildCVE', 'monitor'],
|
|
36
|
+
['shrinkwrap', 'monitor'],
|
|
37
|
+
['telemetry', 'monitor'],
|
|
38
|
+
['unpopularPackage', 'monitor'],
|
|
39
|
+
['unstableOwnership', 'monitor'],
|
|
40
|
+
// ignore (85):
|
|
41
|
+
['ambiguousClassifier', 'ignore'],
|
|
42
|
+
['badEncoding', 'ignore'],
|
|
43
|
+
['badSemver', 'ignore'],
|
|
44
|
+
['badSemverDependency', 'ignore'],
|
|
45
|
+
['bidi', 'ignore'],
|
|
46
|
+
['binScriptConfusion', 'ignore'],
|
|
47
|
+
['chromeContentScript', 'ignore'],
|
|
48
|
+
['chromeHostPermission', 'ignore'],
|
|
49
|
+
['chromePermission', 'ignore'],
|
|
50
|
+
['chromeWildcardHostPermission', 'ignore'],
|
|
51
|
+
['chronoAnomaly', 'ignore'],
|
|
52
|
+
['compromisedSSHKey', 'ignore'],
|
|
53
|
+
['copyleftLicense', 'ignore'],
|
|
54
|
+
['cve', 'ignore'],
|
|
55
|
+
['debugAccess', 'ignore'],
|
|
56
|
+
['deprecatedLicense', 'ignore'],
|
|
57
|
+
['deprecatedException', 'ignore'],
|
|
58
|
+
['dynamicRequire', 'ignore'],
|
|
59
|
+
['emptyPackage', 'ignore'],
|
|
60
|
+
['envVars', 'ignore'],
|
|
61
|
+
['explicitlyUnlicensedItem', 'ignore'],
|
|
62
|
+
['extraneousDependency', 'ignore'],
|
|
63
|
+
['fileDependency', 'ignore'],
|
|
64
|
+
['filesystemAccess', 'ignore'],
|
|
65
|
+
['floatingDependency', 'ignore'],
|
|
66
|
+
['gitHubDependency', 'ignore'],
|
|
67
|
+
['gptAnomaly', 'ignore'],
|
|
68
|
+
['gptDidYouMean', 'ignore'],
|
|
69
|
+
['gptMalware', 'ignore'],
|
|
70
|
+
['gptSecurity', 'ignore'],
|
|
71
|
+
['hasNativeCode', 'ignore'],
|
|
72
|
+
['highEntropyStrings', 'ignore'],
|
|
73
|
+
['homoglyphs', 'ignore'],
|
|
74
|
+
['installScripts', 'ignore'],
|
|
75
|
+
['invalidPackageJSON', 'ignore'],
|
|
76
|
+
['invisibleChars', 'ignore'],
|
|
77
|
+
['licenseChange', 'ignore'],
|
|
78
|
+
['licenseException', 'ignore'],
|
|
79
|
+
['longStrings', 'ignore'],
|
|
80
|
+
['majorRefactor', 'ignore'],
|
|
81
|
+
['manifestConfusion', 'ignore'],
|
|
82
|
+
['minifiedFile', 'ignore'],
|
|
83
|
+
['miscLicenseIssues', 'ignore'],
|
|
84
|
+
['missingAuthor', 'ignore'],
|
|
85
|
+
['missingDependency', 'ignore'],
|
|
86
|
+
['missingLicense', 'ignore'],
|
|
87
|
+
['missingTarball', 'ignore'],
|
|
88
|
+
['mixedLicense', 'ignore'],
|
|
89
|
+
['modifiedException', 'ignore'],
|
|
90
|
+
['modifiedLicense', 'ignore'],
|
|
91
|
+
['networkAccess', 'ignore'],
|
|
92
|
+
['newAuthor', 'ignore'],
|
|
93
|
+
['noAuthorData', 'ignore'],
|
|
94
|
+
['noBugTracker', 'ignore'],
|
|
95
|
+
['noLicenseFound', 'ignore'],
|
|
96
|
+
['noREADME', 'ignore'],
|
|
97
|
+
['noRepository', 'ignore'],
|
|
98
|
+
['noTests', 'ignore'],
|
|
99
|
+
['noV1', 'ignore'],
|
|
100
|
+
['noWebsite', 'ignore'],
|
|
101
|
+
['nonOSILicense', 'ignore'],
|
|
102
|
+
['nonSPDXLicense', 'ignore'],
|
|
103
|
+
['nonpermissiveLicense', 'ignore'],
|
|
104
|
+
['notice', 'ignore'],
|
|
105
|
+
['obfuscatedRequire', 'ignore'],
|
|
106
|
+
['peerDependency', 'ignore'],
|
|
107
|
+
['potentialVulnerability', 'ignore'],
|
|
108
|
+
['semverAnomaly', 'ignore'],
|
|
109
|
+
['shellAccess', 'ignore'],
|
|
110
|
+
['shellScriptOverride', 'ignore'],
|
|
111
|
+
['socketUpgradeAvailable', 'ignore'],
|
|
112
|
+
['suspiciousStarActivity', 'ignore'],
|
|
113
|
+
['suspiciousString', 'ignore'],
|
|
114
|
+
['trivialPackage', 'ignore'],
|
|
115
|
+
['typeModuleCompatibility', 'ignore'],
|
|
116
|
+
['uncaughtOptionalDependency', 'ignore'],
|
|
117
|
+
['unclearLicense', 'ignore'],
|
|
118
|
+
['unidentifiedLicense', 'ignore'],
|
|
119
|
+
['unmaintained', 'ignore'],
|
|
120
|
+
['unpublished', 'ignore'],
|
|
121
|
+
['unresolvedRequire', 'ignore'],
|
|
122
|
+
['unsafeCopyright', 'ignore'],
|
|
123
|
+
['unusedDependency', 'ignore'],
|
|
124
|
+
['urlStrings', 'ignore'],
|
|
125
|
+
['usesEval', 'ignore'],
|
|
126
|
+
['zeroWidth', 'ignore'],
|
|
127
|
+
]);
|
|
128
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;;;;AAAA;;;GAGG;AAEH,4EAA4E;AAC5E,2DAA2D;AAC3D,gDAAgD;AAChD,mEAA+D;AAC/D,6CAAyD;AAI5C,QAAA,kBAAkB,GAAG,IAAA,uCAA0B,EAAC,sBAAW,CAAC,CAAA;AAEzE,oFAAoF;AACpF,0EAA0E;AAC7D,QAAA,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAA;AAEjE,0BAA0B;AAC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E,QAAQ,CAAC;IACjC,CAAC,cAAc,EAAE,QAAQ,CAAC;IAC1B,CAAC,aAAa,EAAE,QAAQ,CAAC;IACzB,CAAC,mBAAmB,EAAE,QAAQ,CAAC;IAC/B,CAAC,iBAAiB,EAAE,QAAQ,CAAC;IAC7B,CAAC,kBAAkB,EAAE,QAAQ,CAAC;IAC9B,CAAC,YAAY,EAAE,QAAQ,CAAC;IACxB,CAAC,UAAU,EAAE,QAAQ,CAAC;IACtB,CAAC,WAAW,EAAE,QAAQ,CAAC;CACxB,CAAC,CAAA"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
2
|
+
import type { RequestOptions } from './types';
|
|
3
|
+
import type { ReadStream } from 'node:fs';
|
|
4
|
+
import type { IncomingMessage } from 'node:http';
|
|
5
|
+
/**
|
|
6
|
+
* Create multipart form-data body parts for file uploads.
|
|
7
|
+
* Converts file paths to readable streams with proper multipart headers.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createRequestBodyForFilepaths(filepaths: string[], basePath: string): Array<Array<string | ReadStream>>;
|
|
10
|
+
/**
|
|
11
|
+
* Create multipart form-data body part for JSON data.
|
|
12
|
+
* Converts JSON object to readable stream with appropriate headers.
|
|
13
|
+
*/
|
|
14
|
+
export declare function createRequestBodyForJson(jsonData: unknown, basename?: string): Array<string | Readable>;
|
|
15
|
+
/**
|
|
16
|
+
* Create and execute a multipart/form-data upload request.
|
|
17
|
+
* Streams large files efficiently with backpressure handling and early server validation.
|
|
18
|
+
*
|
|
19
|
+
* @throws {Error} When network errors occur or stream processing fails
|
|
20
|
+
*/
|
|
21
|
+
export declare function createUploadRequest(baseUrl: string, urlPath: string, requestBodyNoBoundaries: Array<string | Readable | Array<string | Readable>>, options: RequestOptions): Promise<IncomingMessage>;
|
|
22
|
+
//# sourceMappingURL=file-upload.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"file-upload.d.ts","sourceRoot":"","sources":["../src/file-upload.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAMtC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAC7C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACzC,OAAO,KAAK,EAAiB,eAAe,EAAE,MAAM,WAAW,CAAA;AAG/D;;;GAGG;AACH,wBAAgB,6BAA6B,CAC3C,SAAS,EAAE,MAAM,EAAE,EACnB,QAAQ,EAAE,MAAM,GACf,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,UAAU,CAAC,CAAC,CAYnC;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,OAAO,EACjB,QAAQ,SAAc,GACrB,KAAK,CAAC,MAAM,GAAG,QAAQ,CAAC,CAS1B;AAED;;;;;GAKG;AACH,wBAAsB,mBAAmB,CACvC,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,uBAAuB,EAAE,KAAK,CAAC,MAAM,GAAG,QAAQ,GAAG,KAAK,CAAC,MAAM,GAAG,QAAQ,CAAC,CAAC,EAC5E,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,eAAe,CAAC,CAuG1B"}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.createRequestBodyForFilepaths = createRequestBodyForFilepaths;
|
|
7
|
+
exports.createRequestBodyForJson = createRequestBodyForJson;
|
|
8
|
+
exports.createUploadRequest = createUploadRequest;
|
|
9
|
+
/** @fileoverview File upload utilities for Socket API with multipart form data support. */
|
|
10
|
+
const node_events_1 = __importDefault(require("node:events"));
|
|
11
|
+
const node_fs_1 = require("node:fs");
|
|
12
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
13
|
+
const node_stream_1 = require("node:stream");
|
|
14
|
+
const path_1 = require("@socketsecurity/registry/lib/path");
|
|
15
|
+
const http_client_1 = require("./http-client");
|
|
16
|
+
/**
|
|
17
|
+
* Create multipart form-data body parts for file uploads.
|
|
18
|
+
* Converts file paths to readable streams with proper multipart headers.
|
|
19
|
+
*/
|
|
20
|
+
function createRequestBodyForFilepaths(filepaths, basePath) {
|
|
21
|
+
const requestBody = [];
|
|
22
|
+
for (const absPath of filepaths) {
|
|
23
|
+
const relPath = (0, path_1.normalizePath)(node_path_1.default.relative(basePath, absPath));
|
|
24
|
+
const filename = node_path_1.default.basename(absPath);
|
|
25
|
+
requestBody.push([
|
|
26
|
+
`Content-Disposition: form-data; name="${relPath}"; filename="${filename}"\r\n`,
|
|
27
|
+
`Content-Type: application/octet-stream\r\n\r\n`,
|
|
28
|
+
(0, node_fs_1.createReadStream)(absPath, { highWaterMark: 1024 * 1024 }),
|
|
29
|
+
]);
|
|
30
|
+
}
|
|
31
|
+
return requestBody;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Create multipart form-data body part for JSON data.
|
|
35
|
+
* Converts JSON object to readable stream with appropriate headers.
|
|
36
|
+
*/
|
|
37
|
+
function createRequestBodyForJson(jsonData, basename = 'data.json') {
|
|
38
|
+
const ext = node_path_1.default.extname(basename);
|
|
39
|
+
const name = node_path_1.default.basename(basename, ext);
|
|
40
|
+
return [
|
|
41
|
+
`Content-Disposition: form-data; name="${name}"; filename="${basename}"\r\n` +
|
|
42
|
+
`Content-Type: application/json\r\n\r\n`,
|
|
43
|
+
node_stream_1.Readable.from(JSON.stringify(jsonData), { highWaterMark: 1024 * 1024 }),
|
|
44
|
+
'\r\n',
|
|
45
|
+
];
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Create and execute a multipart/form-data upload request.
|
|
49
|
+
* Streams large files efficiently with backpressure handling and early server validation.
|
|
50
|
+
*
|
|
51
|
+
* @throws {Error} When network errors occur or stream processing fails
|
|
52
|
+
*/
|
|
53
|
+
async function createUploadRequest(baseUrl, urlPath, requestBodyNoBoundaries, options) {
|
|
54
|
+
// This function constructs and sends a multipart/form-data HTTP POST request
|
|
55
|
+
// where each part is streamed to the server. It supports string payloads
|
|
56
|
+
// and readable streams (e.g., large file uploads).
|
|
57
|
+
// The body is streamed manually with proper backpressure support to avoid
|
|
58
|
+
// overwhelming Node.js memory (i.e., avoiding out-of-memory crashes for large inputs).
|
|
59
|
+
// We call `flushHeaders()` early to ensure headers are sent before body transmission
|
|
60
|
+
// begins. If the server rejects the request (e.g., bad org or auth), it will likely
|
|
61
|
+
// respond immediately. We listen for that response while still streaming the body.
|
|
62
|
+
//
|
|
63
|
+
// This protects against cases where the server closes the connection (EPIPE/ECONNRESET)
|
|
64
|
+
// mid-stream, which would otherwise cause hard-to-diagnose failures during file upload.
|
|
65
|
+
//
|
|
66
|
+
// Example failure this mitigates: `socket scan create --org badorg`
|
|
67
|
+
// eslint-disable-next-line no-async-promise-executor
|
|
68
|
+
return await new Promise(async (pass, fail) => {
|
|
69
|
+
const boundary = `NodeMultipartBoundary${Date.now()}`;
|
|
70
|
+
const boundarySep = `--${boundary}\r\n`;
|
|
71
|
+
const finalBoundary = `--${boundary}--\r\n`;
|
|
72
|
+
const requestBody = [
|
|
73
|
+
...requestBodyNoBoundaries.flatMap(part => [
|
|
74
|
+
boundarySep,
|
|
75
|
+
/* c8 ignore next - Array.isArray branch for part is defensive coding for edge cases. */
|
|
76
|
+
...(Array.isArray(part) ? part : [part]),
|
|
77
|
+
]),
|
|
78
|
+
finalBoundary,
|
|
79
|
+
];
|
|
80
|
+
const url = new URL(urlPath, baseUrl);
|
|
81
|
+
const req = (0, http_client_1.getHttpModule)(baseUrl).request(url, {
|
|
82
|
+
method: 'POST',
|
|
83
|
+
...options,
|
|
84
|
+
headers: {
|
|
85
|
+
...options?.headers,
|
|
86
|
+
'Content-Type': `multipart/form-data; boundary=${boundary}`,
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
// Send headers early to prompt server validation (auth, URL, quota, etc.).
|
|
90
|
+
req.flushHeaders();
|
|
91
|
+
// Concurrently wait for response while we stream body.
|
|
92
|
+
(0, http_client_1.getResponse)(req).then(pass, fail);
|
|
93
|
+
let aborted = false;
|
|
94
|
+
req.on('error', () => (aborted = true));
|
|
95
|
+
req.on('close', () => (aborted = true));
|
|
96
|
+
try {
|
|
97
|
+
for (const part of requestBody) {
|
|
98
|
+
/* c8 ignore next 3 - aborted state is difficult to test reliably */
|
|
99
|
+
if (aborted) {
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
if (typeof part === 'string') {
|
|
103
|
+
/* c8 ignore next 5 - backpressure handling requires specific stream conditions */
|
|
104
|
+
if (!req.write(part)) {
|
|
105
|
+
// Wait for 'drain' if backpressure is signaled.
|
|
106
|
+
// eslint-disable-next-line no-await-in-loop
|
|
107
|
+
await node_events_1.default.once(req, 'drain');
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
else if (typeof part?.pipe === 'function') {
|
|
111
|
+
// Stream data chunk-by-chunk with backpressure support.
|
|
112
|
+
const stream = part;
|
|
113
|
+
// eslint-disable-next-line no-await-in-loop
|
|
114
|
+
for await (const chunk of stream) {
|
|
115
|
+
/* c8 ignore next 3 - aborted state during streaming is difficult to test reliably */
|
|
116
|
+
if (aborted) {
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
/* c8 ignore next 3 - backpressure handling requires specific stream conditions */
|
|
120
|
+
if (!req.write(chunk)) {
|
|
121
|
+
await node_events_1.default.once(req, 'drain');
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
// Ensure trailing CRLF after file part.
|
|
125
|
+
/* c8 ignore next 4 - trailing CRLF backpressure handling is edge case */
|
|
126
|
+
if (!aborted && !req.write('\r\n')) {
|
|
127
|
+
// eslint-disable-next-line no-await-in-loop
|
|
128
|
+
await node_events_1.default.once(req, 'drain');
|
|
129
|
+
}
|
|
130
|
+
// Cleanup stream to free memory buffers.
|
|
131
|
+
if (typeof part.destroy === 'function') {
|
|
132
|
+
part.destroy();
|
|
133
|
+
}
|
|
134
|
+
/* c8 ignore next 3 - defensive check for non-string/stream types */
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
throw new TypeError('Expected string or stream');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
catch (e) {
|
|
142
|
+
req.destroy(e);
|
|
143
|
+
fail(e);
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
if (!aborted) {
|
|
147
|
+
req.end();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
//# sourceMappingURL=file-upload.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"file-upload.js","sourceRoot":"","sources":["../src/file-upload.ts"],"names":[],"mappings":";;;;;;;;AAAA,2FAA2F;AAC3F,8DAAgC;AAChC,qCAA0C;AAC1C,0DAA4B;AAC5B,6CAAsC;AAEtC,4DAAiE;AAEjE,+CAA0D;AAO1D;;;GAGG;AACH,uCACE,SAAmB,EACnB,QAAgB,EACmB;IACnC,MAAM,WAAW,GAAsC,EAAE,CAAA;IACzD,KAAK,MAAM,OAAO,IAAI,SAAS,EAAE,CAAC;QAChC,MAAM,OAAO,GAAG,IAAA,oBAAa,EAAC,mBAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAA;QAC/D,MAAM,QAAQ,GAAG,mBAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAA;QACvC,WAAW,CAAC,IAAI,CAAC;YACf,yCAAyC,OAAO,gBAAgB,QAAQ,OAAO;YAC/E,gDAAgD;YAChD,IAAA,0BAAgB,EAAC,OAAO,EAAE,EAAE,aAAa,EAAE,IAAI,GAAG,IAAI,EAAE,CAAC;SAC1D,CAAC,CAAA;IACJ,CAAC;IACD,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