@be-link/cos 1.12.12 → 1.12.13

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.
@@ -38,4 +38,9 @@ export declare function getBucketConfig(mode: EnvMode, projectName?: string): Bu
38
38
  export declare function getRegion(bucketConfig: BucketConfig): string;
39
39
  /** COS 存储桶所在地域(南京) */
40
40
  export declare const REGION: "ap-nanjing";
41
+ /**
42
+ * 云函数 URL 配置
43
+ * 用于获取 COS 临时密钥
44
+ */
45
+ export declare const CLOUD_FUNCTION_URLS: Record<EnvMode, string>;
41
46
  //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/shared/config.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,MAAM,OAAO,GAAG,aAAa,GAAG,MAAM,GAAG,YAAY,CAAC;AAE5D;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,YAAY;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,cAAc;IACd,IAAI,EAAE,MAAM,CAAC;IACb,WAAW;IACX,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,OAAO,EAAE,YAAY,CAgBxD,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAQzF,CAAC;AAEF;;;GAGG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,OAAO,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,YAAY,CAKjF;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,YAAY,EAAE,YAAY,GAAG,MAAM,CAK5D;AAED,sBAAsB;AACtB,eAAO,MAAM,MAAM,EAAG,YAAqB,CAAC;AAE5C;;;GAGG;AACH,eAAO,MAAM,mBAAmB,EAAE,MAAM,CAAC,OAAO,EAAE,MAAM,CAIvD,CAAC"}
@@ -0,0 +1,8 @@
1
+ import { type EnvMode } from './config';
2
+ import type { TempCredentials } from './types';
3
+ /**
4
+ * 通过云函数获取 COS 临时密钥
5
+ * 浏览器端和 Node CLI 共用
6
+ */
7
+ export declare function getTempCredentials(mode: EnvMode): Promise<TempCredentials>;
8
+ //# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../../src/shared/credentials.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,KAAK,OAAO,EAAE,MAAM,UAAU,CAAC;AAC7D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/C;;;GAGG;AACH,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,eAAe,CAAC,CAmBhF"}
@@ -0,0 +1,4 @@
1
+ export * from './config';
2
+ export * from './types';
3
+ export * from './credentials';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/shared/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,eAAe,CAAC"}
@@ -1,18 +1,10 @@
1
1
  import type { EnvMode } from './config';
2
2
  /**
3
3
  * COS 初始化配置
4
- *
5
- * 支持两种使用方式:
6
- * 1. 构造函数传入配置,立即初始化
7
- * 2. 稍后调用 init() 方法初始化(支持异步配置)
8
4
  */
9
5
  export interface InitConfig {
10
6
  /**
11
7
  * 环境模式(必填)
12
- *
13
- * - development: 开发环境
14
- * - test: 测试环境
15
- * - production: 生产环境
16
8
  */
17
9
  mode: EnvMode;
18
10
  /** 项目名称(可选),用于特定项目的桶配置 */
@@ -44,10 +36,20 @@ export interface UploadResult {
44
36
  /** 文件的访问地址 */
45
37
  Location: string;
46
38
  /** HTTP 状态码 */
47
- statusCode: number;
39
+ statusCode?: number;
48
40
  /** 响应头 */
49
- headers: Record<string, any>;
41
+ headers?: Record<string, any>;
50
42
  /** 完整的 URL 地址 */
51
43
  url: string;
52
44
  }
45
+ /**
46
+ * 临时密钥凭证
47
+ */
48
+ export interface TempCredentials {
49
+ TmpSecretId: string;
50
+ TmpSecretKey: string;
51
+ SecurityToken: string;
52
+ StartTime: number;
53
+ ExpiredTime: number;
54
+ }
53
55
  //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/shared/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAExC;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB;;OAEG;IACH,IAAI,EAAE,OAAO,CAAC;IAEd,0BAA0B;IAC1B,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB,iBAAiB;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAE9B,iCAAiC;IACjC,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB,4BAA4B;IAC5B,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,aAAa;IACb,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC9B,aAAa;IACb,kBAAkB,CAAC,EAAE,CAAC,YAAY,EAAE,GAAG,KAAK,IAAI,CAAC;IACjD,uBAAuB;IACvB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,eAAe;IACf,IAAI,EAAE,MAAM,CAAC;IACb,cAAc;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU;IACV,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC9B,iBAAiB;IACjB,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@be-link/cos",
3
- "version": "1.12.12",
3
+ "version": "1.12.13",
4
4
  "description": "前端项目产物上传cos",
5
5
  "homepage": "https://github.com/snowmountain-top/be-link#readme",
6
6
  "author": "zhuiyi",
@@ -23,19 +23,12 @@
23
23
  "cos": "./bin/cos.js"
24
24
  },
25
25
  "dependencies": {
26
- "cos-nodejs-sdk-v5": "^2.14.3",
27
- "@types/crypto-js": "^4.2.2",
28
- "cos-js-sdk-v5": "^1.8.6",
29
- "crypto-js": "^4.2.0"
30
- },
31
- "peerDependencies": {
32
26
  "cos-js-sdk-v5": "^1.8.6",
27
+ "cos-nodejs-sdk-v5": "^2.14.3",
33
28
  "crypto-js": "^4.2.0"
34
29
  },
35
30
  "devDependencies": {
36
- "@types/crypto-js": "^4.2.2",
37
- "cos-js-sdk-v5": "^1.8.6",
38
- "crypto-js": "^4.2.0"
31
+ "@types/crypto-js": "^4.2.2"
39
32
  },
40
33
  "publishConfig": {
41
34
  "access": "public"
package/bin/upload.js DELETED
@@ -1,333 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- const fs = require('fs');
5
- const path = require('path');
6
- const COS = require('cos-nodejs-sdk-v5');
7
- const { getBucketConfig, getRegion } = require('../dist/index.cjs.js');
8
-
9
- // 解析命令行参数
10
- const argv = process.argv.slice(2);
11
- let mode = 'development';
12
- let projectName = undefined;
13
-
14
- // 支持两种方式传递参数:
15
- // 方式1: node_modules/.bin/cos production --project be-link-live-h5
16
- // 方式2: node_modules/.bin/cos production -p be-link-live-h5
17
- // 方式3: node_modules/.bin/cos production (使用默认配置)
18
- for (let i = 0; i < argv.length; i++) {
19
- const arg = argv[i];
20
- if (arg === '--project' || arg === '-p') {
21
- projectName = argv[i + 1];
22
- i++; // 跳过下一个参数(项目名称)
23
- } else if (arg === '--mode' || arg === '-m') {
24
- mode = argv[i + 1];
25
- i++;
26
- } else if (!arg.startsWith('-') && ['development', 'test', 'production'].includes(arg)) {
27
- // 兼容旧版本:第一个参数是 mode
28
- mode = arg;
29
- }
30
- }
31
-
32
- console.log('🚀 上传模式:', mode);
33
- if (projectName) {
34
- console.log('📦 项目标识:', projectName);
35
- }
36
-
37
- // 获取项目名称(用于远程路径)
38
- const baseUrl = mode === 'production' ? 'project/prod/' : 'project/dev/';
39
- const packageUrl = path.resolve(process.cwd(), './package.json');
40
- const projectPackage = fs.readFileSync(packageUrl, { encoding: 'utf-8' });
41
- const packageProjectName = JSON.parse(projectPackage).name;
42
- const projectRemoteUrl = baseUrl + packageProjectName;
43
-
44
- // 获取桶配置和地域
45
- const bucketConfig = getBucketConfig(mode, projectName);
46
- const region = getRegion(bucketConfig);
47
-
48
- // 构建参数输出的地址
49
- const distDirUrl = process.cwd() + '/dist';
50
-
51
- // COS 实例(延迟初始化)
52
- let cos = null;
53
-
54
- /**
55
- * 通过云函数获取临时密钥(参照浏览器端实现)
56
- */
57
- async function getTempCredentials(mode) {
58
- const url =
59
- mode === 'production'
60
- ? 'https://shield-60660-10-1304510571.sh.run.tcloudbase.com/config/get-cos-temp-secret'
61
- : 'https://shield-74680-5-1304510571.sh.run.tcloudbase.com/config/get-cos-temp-secret';
62
-
63
- try {
64
- const response = await fetch(url, { method: 'POST' });
65
- console.error('🔐 响应:', response);
66
- const result = await response.json();
67
- const data = result?.data || {};
68
- const credentials = data?.credentials;
69
- console.error('🔐 结果:', result);
70
-
71
- if (!credentials) {
72
- throw new Error('获取临时密钥失败:返回数据格式错误');
73
- }
74
-
75
- return {
76
- TmpSecretId: credentials.tmpSecretId,
77
- TmpSecretKey: credentials.tmpSecretKey,
78
- SecurityToken: credentials.sessionToken,
79
- StartTime: data.startTime,
80
- ExpiredTime: data.expiredTime,
81
- };
82
- } catch (error) {
83
- throw new Error('获取临时密钥失败:' + error.message);
84
- }
85
- }
86
-
87
- /**
88
- * 初始化 COS 实例
89
- * 优先使用云函数临时密钥,降级到环境变量
90
- */
91
- async function initCOS() {
92
- if (cos) {
93
- return cos;
94
- }
95
-
96
- try {
97
- // 方式1:尝试通过云函数获取临时密钥(推荐)
98
- console.log('🔐 正在获取临时密钥...');
99
- const credentials = await getTempCredentials(mode || 'development');
100
- console.log('✅ 临时密钥获取成功');
101
- console.log(' 有效期至:', new Date(credentials.ExpiredTime * 1000).toLocaleString());
102
-
103
- cos = new COS({
104
- getAuthorization: (options, callback) => {
105
- callback({
106
- TmpSecretId: credentials.TmpSecretId,
107
- TmpSecretKey: credentials.TmpSecretKey,
108
- SecurityToken: credentials.SecurityToken,
109
- StartTime: credentials.StartTime,
110
- ExpiredTime: credentials.ExpiredTime,
111
- });
112
- },
113
- });
114
-
115
- return cos;
116
- } catch (err) {
117
- // 方式2:降级到环境变量(用于本地开发或特殊情况)
118
- console.warn('⚠️ 临时密钥获取失败:', err.message);
119
- console.warn('⚠️ 尝试使用环境变量 COS_SECRET_ID 和 COS_SECRET_KEY');
120
-
121
- const secretId = process.env.COS_SECRET_ID;
122
- const secretKey = process.env.COS_SECRET_KEY;
123
-
124
- if (!secretId || !secretKey) {
125
- console.error('❌ 错误:未找到 COS 密钥配置');
126
- console.error(' 请设置环境变量:');
127
- console.error(' - COS_SECRET_ID');
128
- console.error(' - COS_SECRET_KEY');
129
- process.exit(1);
130
- }
131
-
132
- console.log('✅ 使用环境变量中的密钥');
133
- cos = new COS({
134
- SecretId: secretId,
135
- SecretKey: secretKey,
136
- });
137
-
138
- return cos;
139
- }
140
- }
141
-
142
- /**
143
- * 上传单个文件(支持 Promise 和重试)
144
- */
145
- function upload(url, filename, retryCount = 0, maxRetries = 3) {
146
- return new Promise((resolve, reject) => {
147
- if (!url || !filename) {
148
- reject(new Error('上传参数错误:url 和 filename 不能为空'));
149
- return;
150
- }
151
- cos.putObject(
152
- {
153
- Bucket: bucketConfig.name,
154
- Region: region,
155
- Key: projectRemoteUrl + filename /* 必须 */,
156
- StorageClass: 'STANDARD',
157
- ACL: 'public-read', // 设置为公开读,确保文件可访问
158
- Body: fs.createReadStream(url), // 上传文件对象
159
- // onProgress: function (progressData) {
160
- // // 可选:显示上传进度
161
- // // console.log('上传进度:', JSON.stringify(progressData))
162
- // },
163
- },
164
- function (err, data) {
165
- if (err) {
166
- // 重试逻辑
167
- console.log(`❕ 上传失败: ${JSON.stringify(err)}`);
168
- if (retryCount < maxRetries) {
169
- console.log(` ⚠️ 上传失败,正在重试 (${retryCount + 1}/${maxRetries}): ${filename}`);
170
- setTimeout(() => {
171
- upload(url, filename, retryCount + 1, maxRetries)
172
- .then(resolve)
173
- .catch(reject);
174
- }, 1000 * (retryCount + 1)); // 递增延迟
175
- } else {
176
- console.error(` ❌ 上传失败(已重试 ${maxRetries} 次): ${filename}`, err.message);
177
- reject(err);
178
- }
179
- } else {
180
- resolve(data);
181
- }
182
- },
183
- );
184
- });
185
- }
186
-
187
- function getAllFiles(directoryPath) {
188
- const files = fs.readdirSync(directoryPath, { withFileTypes: true });
189
- const fileNamesAndPaths = [];
190
-
191
- files.forEach((file) => {
192
- const filePath = path.join(directoryPath, file.name);
193
-
194
- if (file.isFile()) {
195
- fileNamesAndPaths.push({
196
- fileName: file.name,
197
- filePath: filePath,
198
- });
199
- } else if (file.isDirectory()) {
200
- const subDirectoryFiles = getAllFiles(filePath);
201
- fileNamesAndPaths.push(...subDirectoryFiles);
202
- }
203
- });
204
-
205
- return fileNamesAndPaths;
206
- }
207
-
208
- /**
209
- * 删除远程项目目录
210
- * 注意:deleteObject 只能删除单个文件,不能删除目录
211
- * 如需删除整个目录,需要先列出所有文件再逐个删除
212
- */
213
- function deleteProject() {
214
- return new Promise((resolve, reject) => {
215
- // 先获取目录下的所有文件
216
- cos.getBucket(
217
- {
218
- Bucket: bucketConfig.name,
219
- Region: region,
220
- Prefix: projectRemoteUrl,
221
- },
222
- function (err, data) {
223
- if (err) {
224
- console.log('⚠️ 获取远程文件列表失败(可能目录不存在,继续上传)');
225
- resolve([]); // 目录不存在时继续执行
226
- return;
227
- }
228
-
229
- const files = data.Contents || [];
230
- if (files.length === 0) {
231
- console.log('📁 远程目录为空,无需删除');
232
- resolve([]);
233
- return;
234
- }
235
-
236
- console.log(`🗑️ 正在删除 ${files.length} 个旧文件...`);
237
-
238
- // 批量删除文件
239
- cos.deleteMultipleObject(
240
- {
241
- Bucket: bucketConfig.name,
242
- Region: region,
243
- Objects: files.map((file) => ({ Key: file.Key })),
244
- },
245
- function (err, data) {
246
- if (err) {
247
- console.error('❌ 删除失败:', err.message);
248
- reject(err);
249
- } else {
250
- console.log(`✅ 成功删除 ${files.length} 个旧文件`);
251
- resolve(data);
252
- }
253
- },
254
- );
255
- },
256
- );
257
- });
258
- }
259
-
260
- /**
261
- * 主函数:上传静态资源到 COS
262
- */
263
- async function staticUploadToCos() {
264
- const startTime = Date.now();
265
- console.log('\n' + '='.repeat(60));
266
- console.log('📦 开始上传静态资源到 COS');
267
- console.log('='.repeat(60));
268
- console.log(`📂 项目名称: ${packageProjectName}`);
269
- console.log(`🌍 环境模式: ${mode}`);
270
- console.log(`🪣 存储桶: ${bucketConfig.name} (${region})`);
271
- if (projectName) {
272
- console.log(`🎯 项目标识: ${projectName}`);
273
- }
274
- console.log(`📍 远程路径: ${projectRemoteUrl}`);
275
- console.log(`📁 本地目录: ${distDirUrl}`);
276
- console.log('='.repeat(60) + '\n');
277
-
278
- try {
279
- // 1. 初始化 COS
280
- await initCOS();
281
-
282
- // 2. 检查本地文件
283
- if (!fs.existsSync(distDirUrl)) {
284
- throw new Error(`本地目录不存在: ${distDirUrl}`);
285
- }
286
-
287
- const files = getAllFiles(distDirUrl);
288
- if (files.length === 0) {
289
- console.log('⚠️ 警告:没有找到需要上传的文件');
290
- return;
291
- }
292
-
293
- console.log(`📋 找到 ${files.length} 个文件待上传\n`);
294
-
295
- // 3. 删除远程旧文件
296
- await deleteProject();
297
-
298
- // 4. 上传所有文件
299
- console.log('\n📤 开始上传文件...\n');
300
- const uploadPromises = files.map((file) => {
301
- const filename = file.filePath.replace(distDirUrl, '');
302
- return upload(file.filePath, filename);
303
- });
304
-
305
- // 等待所有文件上传完成
306
- const results = await Promise.all(uploadPromises);
307
-
308
- // 5. 输出结果
309
- const endTime = Date.now();
310
- const duration = ((endTime - startTime) / 1000).toFixed(2);
311
-
312
- console.log('\n' + '='.repeat(60));
313
- console.log('🎉 上传完成!');
314
- console.log('='.repeat(60));
315
- console.log(`✅ 成功上传: ${results.length} 个文件`);
316
- console.log(`⏱️ 耗时: ${duration} 秒`);
317
- console.log(`🔗 访问地址: https://${bucketConfig.host}/${projectRemoteUrl}`);
318
- console.log('='.repeat(60) + '\n');
319
-
320
- process.exit(0);
321
- } catch (err) {
322
- console.error('\n' + '='.repeat(60));
323
- console.error('💥 上传失败!');
324
- console.error('='.repeat(60));
325
- console.error('❌ 错误信息:', err.message);
326
- console.error('='.repeat(60) + '\n');
327
- process.exit(1);
328
- }
329
- }
330
-
331
- module.exports = {
332
- staticUploadToCos,
333
- };
@@ -1,169 +0,0 @@
1
- import { type EnvMode } from './config';
2
- import type { InitConfig, UploadConfig, UploadResult } from './types';
3
- /**
4
- * BeLinkCOS 类 - 腾讯云 COS 文件上传工具
5
- *
6
- * 功能:文件上传、MD5 计算、临时密钥授权
7
- *
8
- * @example
9
- * import { BeLinkCOS } from '@be-link/cos';
10
- *
11
- * // 方式一:构造函数传入配置,立即初始化
12
- * const uploader = new BeLinkCOS({ mode: 'production' });
13
- * await uploader.uploadFile(file);
14
- *
15
- * // 方式二:先创建实例,稍后初始化(支持异步配置)
16
- * const uploader = new BeLinkCOS();
17
- * const config = await fetchConfig(); // 从服务器获取配置
18
- * uploader.init({ mode: 'production' });
19
- * await uploader.uploadFile(file);
20
- */
21
- export declare class BeLinkCOS {
22
- /** COS SDK 实例 */
23
- private cos;
24
- /** COS 存储的基础路径 */
25
- private readonly basePath;
26
- /** 自定义请求头 */
27
- headers: Record<string, any>;
28
- /** 当前环境模式 */
29
- mode: EnvMode | null;
30
- /** 项目名称 */
31
- projectName: string | undefined;
32
- /** 是否限制临时密钥的使用范围 */
33
- private scopeLimit;
34
- /** 生命周期状态 */
35
- protected isInitialized: boolean;
36
- protected isDestroyed: boolean;
37
- /** 调试模式 */
38
- private debug;
39
- /**
40
- * 构造函数
41
- *
42
- * 支持两种使用方式:
43
- * 1. 立即初始化:传入配置对象,构造函数中自动调用 init()
44
- * 2. 延迟初始化:不传配置,稍后调用 init() 方法(支持异步配置)
45
- *
46
- * @param config - 可选的初始化配置
47
- * @param config.mode - **必填** 环境模式:'development' | 'test' | 'production'
48
- * @param config.headers - 可选,自定义请求头
49
- * @param config.ScopeLimit - 可选,是否限制临时密钥的使用范围(默认 false)
50
- * @param config.debug - 可选,是否开启调试模式(默认 false)
51
- *
52
- * @example
53
- * // 立即初始化
54
- * const uploader = new BeLinkCOS({ mode: 'production' });
55
- *
56
- * // 延迟初始化
57
- * const uploader = new BeLinkCOS();
58
- * // ... 稍后调用 uploader.init(config);
59
- */
60
- constructor(config?: InitConfig);
61
- /**
62
- * 初始化 COS 实例
63
- * @param config 配置对象
64
- * @description 可以在创建实例时通过构造函数传入配置,也可以稍后调用此方法初始化
65
- */
66
- init(config: InitConfig): void;
67
- /**
68
- * 初始化 COS SDK 实例
69
- *
70
- * 内部方法,通过云函数获取临时密钥
71
- * 首次上传时会自动调用
72
- *
73
- * @returns Promise<void>
74
- */
75
- private initCOS;
76
- /**
77
- * 检查实例状态
78
- */
79
- protected checkState(methodName: string): boolean;
80
- /**
81
- * 内部日志方法
82
- */
83
- protected log(...args: unknown[]): void;
84
- protected warn(...args: unknown[]): void;
85
- protected error(...args: unknown[]): void;
86
- /**
87
- * 验证配置
88
- */
89
- protected validateConfig(config: InitConfig): boolean;
90
- /**
91
- * 获取当前使用的存储桶配置
92
- */
93
- private getCurrentBucketConfig;
94
- /**
95
- * 获取配置
96
- */
97
- getConfig(): {
98
- mode: EnvMode | null;
99
- projectName: string | undefined;
100
- headers: Record<string, any>;
101
- scopeLimit: boolean;
102
- } | null;
103
- /**
104
- * 计算文件的 MD5 哈希值
105
- *
106
- * 性能优化:
107
- * - 小文件(< 10MB):一次性读取,速度更快
108
- * - 大文件:分片读取,避免内存溢出
109
- *
110
- * @param file - 要计算 MD5 的文件对象
111
- * @param chunkSize - 分片大小(字节),默认 2MB
112
- * @returns Promise<string> 文件的 MD5 哈希值
113
- *
114
- * @example
115
- * const md5 = await beLinkCOS.createFileMd5(file);
116
- * console.log('文件 MD5:', md5);
117
- */
118
- createFileMd5(file: File, chunkSize?: number): Promise<string>;
119
- /**
120
- * 生成文件在 COS 中的存储路径
121
- *
122
- * 路径规则:/beLinkAllSource/static/{文件类型}/{文件名}_{时间戳}.{扩展名}
123
- * 例如:/beLinkAllSource/static/image/avatar_1699999999999.png
124
- *
125
- * @param file - 文件对象
126
- * @returns string COS 存储路径
127
- */
128
- private getFilePath;
129
- /**
130
- * 获取文件上传后的访问 URL(不执行实际上传)
131
- *
132
- * 用于在上传前预览文件的最终 URL
133
- *
134
- * @param file - 文件对象
135
- * @returns Promise<string | null> 文件的完整访问 URL,如果实例未初始化则返回 null
136
- *
137
- * @example
138
- * const url = await beLinkCOS.getSourceUrl(file);
139
- * console.log('文件将上传到:', url);
140
- */
141
- getSourceUrl(file: File): Promise<string | null>;
142
- /**
143
- * 上传文件到腾讯云 COS
144
- *
145
- * 核心功能:将文件上传到对应环境的 COS 存储桶
146
- * 支持上传进度回调、自定义请求头等配置
147
- *
148
- * @param file - 要上传的文件对象
149
- * @param config - 上传配置(可选)
150
- * @param config.Headers - 自定义请求头
151
- * @param config.onProgressCallback - 上传进度回调函数
152
- * @returns Promise<UploadResult> 上传结果,包含文件 URL、ETag 等信息
153
- *
154
- * @example
155
- * const uploader = new BeLinkCOS({ mode: 'production' });
156
- * const result = await uploader.uploadFile(file, {
157
- * onProgressCallback: (progressData) => {
158
- * console.log('进度:', progressData.percent * 100 + '%');
159
- * }
160
- * });
161
- * console.log('文件 URL:', result.url);
162
- */
163
- uploadFile(file: File, config?: UploadConfig): Promise<UploadResult>;
164
- /**
165
- * 销毁实例
166
- */
167
- destroy(): void;
168
- }
169
- //# sourceMappingURL=beLinkCos.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"beLinkCos.d.ts","sourceRoot":"","sources":["../src/beLinkCos.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,OAAO,EAA8B,MAAM,UAAU,CAAC;AACpE,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEtE;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,SAAS;IACpB,iBAAiB;IACjB,OAAO,CAAC,GAAG,CAAa;IACxB,kBAAkB;IAClB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAsC;IAC/D,aAAa;IACN,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAM;IACzC,aAAa;IACN,IAAI,EAAE,OAAO,GAAG,IAAI,CAAQ;IACnC,WAAW;IACJ,WAAW,EAAE,MAAM,GAAG,SAAS,CAAa;IACnD,oBAAoB;IACpB,OAAO,CAAC,UAAU,CAAkB;IACpC,aAAa;IACb,SAAS,CAAC,aAAa,EAAE,OAAO,CAAS;IACzC,SAAS,CAAC,WAAW,EAAE,OAAO,CAAS;IACvC,WAAW;IACX,OAAO,CAAC,KAAK,CAAkB;IAE/B;;;;;;;;;;;;;;;;;;;;OAoBG;gBACS,MAAM,CAAC,EAAE,UAAU;IAO/B;;;;OAIG;IACH,IAAI,CAAC,MAAM,EAAE,UAAU,GAAG,IAAI;I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