@lark-apaas/coding-template-nestjs-react-fullstack 0.1.72-alpha.20261123002135 → 0.1.72-alpha.20261124145149
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/package.json
CHANGED
|
@@ -16,7 +16,6 @@ export enum ResponseCode {
|
|
|
16
16
|
VALIDATION_ERROR = 'VALIDATION_ERROR',
|
|
17
17
|
CONFLICT = 'CONFLICT',
|
|
18
18
|
TOO_MANY_REQUESTS = 'TOO_MANY_REQUESTS',
|
|
19
|
-
PAYLOAD_TOO_LARGE = 'PAYLOAD_TOO_LARGE',
|
|
20
19
|
|
|
21
20
|
// 服务端错误
|
|
22
21
|
INTERNAL_ERROR = 'INTERNAL_ERROR',
|
|
@@ -41,7 +40,6 @@ export const RESPONSE_CODE_TO_HTTP_STATUS_MAP: Record<ResponseCode, number> = {
|
|
|
41
40
|
[ResponseCode.VALIDATION_ERROR]: HttpStatus.UNPROCESSABLE_ENTITY,
|
|
42
41
|
[ResponseCode.CONFLICT]: HttpStatus.CONFLICT,
|
|
43
42
|
[ResponseCode.TOO_MANY_REQUESTS]: HttpStatus.TOO_MANY_REQUESTS,
|
|
44
|
-
[ResponseCode.PAYLOAD_TOO_LARGE]: HttpStatus.PAYLOAD_TOO_LARGE,
|
|
45
43
|
|
|
46
44
|
[ResponseCode.INTERNAL_ERROR]: HttpStatus.INTERNAL_SERVER_ERROR,
|
|
47
45
|
[ResponseCode.BAD_GATEWAY]: HttpStatus.BAD_GATEWAY,
|
|
@@ -44,23 +44,6 @@ export class GlobalExceptionFilter implements ExceptionFilter {
|
|
|
44
44
|
timestamp: Date.now(),
|
|
45
45
|
},
|
|
46
46
|
};
|
|
47
|
-
} else if (
|
|
48
|
-
typeof exception === 'object' &&
|
|
49
|
-
exception !== null &&
|
|
50
|
-
((exception as { status?: unknown }).status === HttpStatus.PAYLOAD_TOO_LARGE ||
|
|
51
|
-
(exception as { statusCode?: unknown }).statusCode === HttpStatus.PAYLOAD_TOO_LARGE ||
|
|
52
|
-
(exception as { type?: unknown }).type === 'entity.too.large')
|
|
53
|
-
) {
|
|
54
|
-
// body-parser 请求体超限(PayloadTooLargeError):status/statusCode 为 413 或 type 为 entity.too.large
|
|
55
|
-
// 错误发生在 Nest 路由之前,按异常自带语义状态码响应,避免被兜成 500
|
|
56
|
-
httpStatus = HttpStatus.PAYLOAD_TOO_LARGE;
|
|
57
|
-
errorResponse = {
|
|
58
|
-
error: {
|
|
59
|
-
code: ResponseCode.PAYLOAD_TOO_LARGE,
|
|
60
|
-
message: '请求体过大',
|
|
61
|
-
timestamp: Date.now(),
|
|
62
|
-
},
|
|
63
|
-
};
|
|
64
47
|
} else if (
|
|
65
48
|
typeof exception === 'object' &&
|
|
66
49
|
exception !== null &&
|
|
@@ -0,0 +1,577 @@
|
|
|
1
|
+
import { HttpStatus, Logger } from '@nestjs/common';
|
|
2
|
+
import * as lark from '@larksuiteoapi/node-sdk';
|
|
3
|
+
import { Buffer } from 'node:buffer';
|
|
4
|
+
import { createWriteStream } from 'node:fs';
|
|
5
|
+
import { Readable } from 'node:stream';
|
|
6
|
+
import { pipeline } from 'node:stream/promises';
|
|
7
|
+
import { ResponseCode } from './constants/api_response_code';
|
|
8
|
+
import { BusinessException } from './interfaces/exception.interface';
|
|
9
|
+
|
|
10
|
+
export interface LarkCallContext {
|
|
11
|
+
/** Use the actual SDK operation, e.g. minutes.v1.minuteTranscript.get. */
|
|
12
|
+
operation: string;
|
|
13
|
+
/** Original document/Wiki/Minutes URL, not a temporary download URL. */
|
|
14
|
+
resourceUrl?: string;
|
|
15
|
+
/** Necessary scopes for this operation, when already known. */
|
|
16
|
+
requiredScopes?: readonly string[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface LarkJsonResult {
|
|
20
|
+
code?: number;
|
|
21
|
+
msg?: string;
|
|
22
|
+
request_id?: string;
|
|
23
|
+
error?: { log_id?: string; permission_violations?: unknown };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface LarkFileResult {
|
|
27
|
+
headers: unknown;
|
|
28
|
+
writeFile(filePath: string): Promise<unknown>;
|
|
29
|
+
getReadableStream(): Readable;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type LarkFailureKind =
|
|
33
|
+
| 'scope_missing'
|
|
34
|
+
| 'resource_permission'
|
|
35
|
+
| 'not_found'
|
|
36
|
+
| 'deleted'
|
|
37
|
+
| 'not_ready'
|
|
38
|
+
| 'rate_limited'
|
|
39
|
+
| 'configuration'
|
|
40
|
+
| 'invalid_request'
|
|
41
|
+
| 'upstream'
|
|
42
|
+
| 'file_processing';
|
|
43
|
+
|
|
44
|
+
interface FailureDetails {
|
|
45
|
+
provider: 'lark_openapi';
|
|
46
|
+
operation: string;
|
|
47
|
+
kind: LarkFailureKind;
|
|
48
|
+
larkCode?: number;
|
|
49
|
+
larkHttpStatus?: number;
|
|
50
|
+
nativeMessage?: string;
|
|
51
|
+
requestId?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Preserves the template's error.code / error.message / error.details contract. */
|
|
55
|
+
export class LarkOpenApiException extends BusinessException {
|
|
56
|
+
public readonly kind: LarkFailureKind;
|
|
57
|
+
public readonly larkCode?: number;
|
|
58
|
+
public readonly larkHttpStatus?: number;
|
|
59
|
+
public readonly requestId?: string;
|
|
60
|
+
|
|
61
|
+
constructor(
|
|
62
|
+
code: ResponseCode,
|
|
63
|
+
message: string,
|
|
64
|
+
httpStatus: HttpStatus,
|
|
65
|
+
details: FailureDetails,
|
|
66
|
+
) {
|
|
67
|
+
super(code, message, httpStatus, JSON.stringify(details));
|
|
68
|
+
this.name = 'LarkOpenApiException';
|
|
69
|
+
this.kind = details.kind;
|
|
70
|
+
this.larkCode = details.larkCode;
|
|
71
|
+
this.larkHttpStatus = details.larkHttpStatus;
|
|
72
|
+
this.requestId = details.requestId;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let cachedClient:
|
|
77
|
+
| {
|
|
78
|
+
appId: string;
|
|
79
|
+
appSecret: string;
|
|
80
|
+
domain: lark.Domain | string;
|
|
81
|
+
client: lark.Client;
|
|
82
|
+
}
|
|
83
|
+
| undefined;
|
|
84
|
+
|
|
85
|
+
const logger = new Logger('LarkOpenAPI');
|
|
86
|
+
|
|
87
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
88
|
+
return typeof value === 'object' && value !== null
|
|
89
|
+
? (value as Record<string, unknown>)
|
|
90
|
+
: undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function configurationError(message: string): LarkOpenApiException {
|
|
94
|
+
return new LarkOpenApiException(
|
|
95
|
+
ResponseCode.SERVICE_UNAVAILABLE,
|
|
96
|
+
message,
|
|
97
|
+
HttpStatus.SERVICE_UNAVAILABLE,
|
|
98
|
+
{
|
|
99
|
+
provider: 'lark_openapi',
|
|
100
|
+
operation: 'client.initialize',
|
|
101
|
+
kind: 'configuration',
|
|
102
|
+
},
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function getLarkSdkDomain(): lark.Domain | string {
|
|
107
|
+
const environment =
|
|
108
|
+
process.env.FORCE_FRAMEWORK_ENVIRONMENT?.trim().toLowerCase();
|
|
109
|
+
if (environment === 'boe') return 'https://open.feishu-boe.cn';
|
|
110
|
+
if (environment === 'pre' || environment === 'online')
|
|
111
|
+
return lark.Domain.Feishu;
|
|
112
|
+
throw configurationError(
|
|
113
|
+
'飞书集成部署环境尚未就绪,请应用开发者核对平台环境配置。',
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Call inside a business method. Importing this file never initializes credentials. */
|
|
118
|
+
export function getLarkClient(): lark.Client {
|
|
119
|
+
const domain = getLarkSdkDomain();
|
|
120
|
+
const appId = process.env.LARK_APP_ID;
|
|
121
|
+
const appSecret = process.env.LARK_APP_SECRET;
|
|
122
|
+
if (!appId || !appSecret) {
|
|
123
|
+
throw configurationError(
|
|
124
|
+
'飞书集成配置尚未就绪,请核对应用绑定与环境同步。',
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
if (
|
|
128
|
+
cachedClient?.appId === appId &&
|
|
129
|
+
cachedClient.appSecret === appSecret &&
|
|
130
|
+
cachedClient.domain === domain
|
|
131
|
+
) {
|
|
132
|
+
return cachedClient.client;
|
|
133
|
+
}
|
|
134
|
+
const client = new lark.Client({
|
|
135
|
+
appId,
|
|
136
|
+
appSecret,
|
|
137
|
+
appType: lark.AppType.SelfBuild,
|
|
138
|
+
domain,
|
|
139
|
+
// SDK error formatting can include request configuration. Emit safe diagnostics below.
|
|
140
|
+
logger: { trace() {}, debug() {}, info() {}, warn() {}, error() {} },
|
|
141
|
+
});
|
|
142
|
+
cachedClient = { appId, appSecret, domain, client };
|
|
143
|
+
return client;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function header(headers: unknown, key: string): string | undefined {
|
|
147
|
+
const value = record(headers)?.[key];
|
|
148
|
+
return typeof value === 'string' && value.length <= 200 ? value : undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function nativeCode(body: unknown): number | undefined {
|
|
152
|
+
const value = record(body)?.code;
|
|
153
|
+
if (typeof value === 'number' && Number.isSafeInteger(value)) return value;
|
|
154
|
+
if (typeof value === 'string' && /^\d{1,10}$/.test(value))
|
|
155
|
+
return Number(value);
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function nativeMessage(body: unknown): string | undefined {
|
|
160
|
+
const value = record(body)?.msg;
|
|
161
|
+
if (typeof value !== 'string' || value.length > 64 * 1024) return undefined;
|
|
162
|
+
let text = value;
|
|
163
|
+
const secret = process.env.LARK_APP_SECRET;
|
|
164
|
+
if (secret) text = text.split(secret).join('[redacted]');
|
|
165
|
+
text = text
|
|
166
|
+
.replace(/Bearer\s+[A-Za-z0-9._~+\/-]+/gi, 'Bearer [redacted]')
|
|
167
|
+
.replace(
|
|
168
|
+
/\b(app_secret|access_token|tenant_access_token|user_access_token)\b(["']?\s*[:=]\s*["']?)[^"',\s}]+/gi,
|
|
169
|
+
'$1$2[redacted]',
|
|
170
|
+
)
|
|
171
|
+
.replace(/[\u0000-\u001f\u007f]/g, ' ')
|
|
172
|
+
.trim();
|
|
173
|
+
return text ? text.slice(0, 500) : undefined;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Emits one bounded completion record, without SDK objects or business content. */
|
|
177
|
+
function logCall(params: {
|
|
178
|
+
context: LarkCallContext;
|
|
179
|
+
startedAt: number;
|
|
180
|
+
resultType: 'json' | 'file';
|
|
181
|
+
phase: 'request' | 'consume';
|
|
182
|
+
outcome: 'success' | 'failure';
|
|
183
|
+
error?: unknown;
|
|
184
|
+
cause?: unknown;
|
|
185
|
+
requestId?: string;
|
|
186
|
+
}): void {
|
|
187
|
+
const error = params.error;
|
|
188
|
+
const failure = error instanceof LarkOpenApiException ? error : undefined;
|
|
189
|
+
const transportCode = record(params.cause ?? error)?.code;
|
|
190
|
+
const details = {
|
|
191
|
+
provider: 'lark_openapi',
|
|
192
|
+
operation: /^[a-zA-Z][a-zA-Z0-9_.]{0,159}$/.test(params.context.operation)
|
|
193
|
+
? params.context.operation
|
|
194
|
+
: 'unknown',
|
|
195
|
+
resultType: params.resultType,
|
|
196
|
+
phase: params.phase,
|
|
197
|
+
outcome: params.outcome,
|
|
198
|
+
durationMs: Math.max(0, Date.now() - params.startedAt),
|
|
199
|
+
kind: failure?.kind,
|
|
200
|
+
larkCode:
|
|
201
|
+
failure?.larkCode ??
|
|
202
|
+
(params.outcome === 'success' && params.resultType === 'json'
|
|
203
|
+
? 0
|
|
204
|
+
: undefined),
|
|
205
|
+
larkHttpStatus: failure?.larkHttpStatus,
|
|
206
|
+
requestId: failure?.requestId ?? params.requestId,
|
|
207
|
+
transportCode:
|
|
208
|
+
typeof transportCode === 'string' &&
|
|
209
|
+
/^(ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ECONNABORTED|ERR_CANCELED)$/.test(
|
|
210
|
+
transportCode,
|
|
211
|
+
)
|
|
212
|
+
? transportCode
|
|
213
|
+
: undefined,
|
|
214
|
+
};
|
|
215
|
+
// Logging must not turn a completed call into a failure or replace its error.
|
|
216
|
+
try {
|
|
217
|
+
const message = JSON.stringify(details);
|
|
218
|
+
if (params.outcome === 'success') logger.log(message);
|
|
219
|
+
else logger.warn(message);
|
|
220
|
+
} catch {
|
|
221
|
+
// The caller's result remains authoritative when a log sink is unavailable.
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function parseJson(text: string): unknown {
|
|
226
|
+
try {
|
|
227
|
+
return JSON.parse(text);
|
|
228
|
+
} catch {
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Limits apply only to error bodies; successful transcript streams are not truncated. */
|
|
234
|
+
async function errorBody(value: unknown): Promise<unknown> {
|
|
235
|
+
const limit = 64 * 1024;
|
|
236
|
+
if (typeof value === 'string') {
|
|
237
|
+
return Buffer.byteLength(value) <= limit ? parseJson(value) : undefined;
|
|
238
|
+
}
|
|
239
|
+
if (Buffer.isBuffer(value)) {
|
|
240
|
+
return value.length <= limit
|
|
241
|
+
? parseJson(value.toString('utf8'))
|
|
242
|
+
: undefined;
|
|
243
|
+
}
|
|
244
|
+
if (!(value instanceof Readable)) return record(value);
|
|
245
|
+
return new Promise((resolve) => {
|
|
246
|
+
const chunks: Buffer[] = [];
|
|
247
|
+
let bytes = 0;
|
|
248
|
+
let finished = false;
|
|
249
|
+
const finish = (body: unknown, destroy = false): void => {
|
|
250
|
+
if (finished) return;
|
|
251
|
+
finished = true;
|
|
252
|
+
clearTimeout(timer);
|
|
253
|
+
value.removeListener('data', onData);
|
|
254
|
+
value.removeListener('end', onEnd);
|
|
255
|
+
value.removeListener('error', onError);
|
|
256
|
+
value.removeListener('close', onClose);
|
|
257
|
+
if (destroy) value.destroy();
|
|
258
|
+
resolve(body);
|
|
259
|
+
};
|
|
260
|
+
const onData = (chunk: unknown): void => {
|
|
261
|
+
if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string')
|
|
262
|
+
return finish(undefined, true);
|
|
263
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
264
|
+
bytes += buffer.length;
|
|
265
|
+
if (bytes > limit) return finish(undefined, true);
|
|
266
|
+
chunks.push(buffer);
|
|
267
|
+
};
|
|
268
|
+
const onEnd = (): void =>
|
|
269
|
+
finish(parseJson(Buffer.concat(chunks).toString('utf8')));
|
|
270
|
+
const onError = (): void => finish(undefined, true);
|
|
271
|
+
const onClose = (): void => finish(undefined);
|
|
272
|
+
const timer = setTimeout(() => finish(undefined, true), 5000);
|
|
273
|
+
value.on('data', onData);
|
|
274
|
+
value.once('end', onEnd);
|
|
275
|
+
value.once('error', onError);
|
|
276
|
+
value.once('close', onClose);
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function resourceLink(context: LarkCallContext): string {
|
|
281
|
+
if (!context.resourceUrl) return '';
|
|
282
|
+
try {
|
|
283
|
+
const url = new URL(context.resourceUrl);
|
|
284
|
+
if (
|
|
285
|
+
!['https:', 'http:'].includes(url.protocol) ||
|
|
286
|
+
url.username ||
|
|
287
|
+
url.password
|
|
288
|
+
)
|
|
289
|
+
return '';
|
|
290
|
+
const href = url.href.replace(/[()<>]/g, (character: string) =>
|
|
291
|
+
encodeURIComponent(character),
|
|
292
|
+
);
|
|
293
|
+
const label = context.operation.startsWith('minutes.')
|
|
294
|
+
? '打开妙记'
|
|
295
|
+
: context.operation.startsWith('wiki.')
|
|
296
|
+
? '打开知识库节点'
|
|
297
|
+
: '打开文档';
|
|
298
|
+
return ` [${label}](${href})`;
|
|
299
|
+
} catch {
|
|
300
|
+
return '';
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function scopeLink(body: unknown, context: LarkCallContext): string {
|
|
305
|
+
const violations = record(record(body)?.error)?.permission_violations;
|
|
306
|
+
if (!Array.isArray(violations)) return '';
|
|
307
|
+
const scopes = [
|
|
308
|
+
...new Set(
|
|
309
|
+
violations.flatMap((item: unknown): string[] => {
|
|
310
|
+
const violation = record(item);
|
|
311
|
+
return violation?.type === 'action_scope_required' &&
|
|
312
|
+
typeof violation.subject === 'string' &&
|
|
313
|
+
/^[a-zA-Z0-9_:.-]+$/.test(violation.subject)
|
|
314
|
+
? [violation.subject]
|
|
315
|
+
: [];
|
|
316
|
+
}),
|
|
317
|
+
),
|
|
318
|
+
];
|
|
319
|
+
if (!scopes.length) return '';
|
|
320
|
+
const message = record(body)?.msg;
|
|
321
|
+
const anyOf = typeof message === 'string' && /one of|任一/i.test(message);
|
|
322
|
+
const known = context.requiredScopes?.filter((scope: string) =>
|
|
323
|
+
scopes.includes(scope),
|
|
324
|
+
);
|
|
325
|
+
const preferred =
|
|
326
|
+
context.operation === 'minutes.v1.minuteTranscript.get'
|
|
327
|
+
? 'minutes:minutes.transcript:export'
|
|
328
|
+
: context.operation === 'minutes.v1.minute.get'
|
|
329
|
+
? 'minutes:minutes.basic:read'
|
|
330
|
+
: context.operation.startsWith('docx.')
|
|
331
|
+
? 'docx:document:readonly'
|
|
332
|
+
: context.operation === 'wiki.v2.space.getNode'
|
|
333
|
+
? 'wiki:wiki:readonly'
|
|
334
|
+
: undefined;
|
|
335
|
+
const selected = anyOf
|
|
336
|
+
? [
|
|
337
|
+
(preferred && scopes.includes(preferred) ? preferred : undefined) ??
|
|
338
|
+
known?.[0] ??
|
|
339
|
+
scopes.find((scope: string) =>
|
|
340
|
+
/:readonly$|\.basic:read$/.test(scope),
|
|
341
|
+
) ??
|
|
342
|
+
scopes[0],
|
|
343
|
+
]
|
|
344
|
+
: scopes;
|
|
345
|
+
const appId = process.env.LARK_APP_ID;
|
|
346
|
+
if (!appId || !/^cli_[a-zA-Z0-9]+$/.test(appId)) return '';
|
|
347
|
+
const domain = getLarkSdkDomain();
|
|
348
|
+
const base = typeof domain === 'string' ? domain : 'https://open.feishu.cn';
|
|
349
|
+
return ` 请[申请飞书应用权限](${base}/app/${appId}/auth?q=${encodeURIComponent(selected.join(','))}&op_from=openapi),权限审批及发布生效后重试。`;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function failure(
|
|
353
|
+
context: LarkCallContext,
|
|
354
|
+
body?: unknown,
|
|
355
|
+
httpStatus?: number,
|
|
356
|
+
headers?: unknown,
|
|
357
|
+
kindOverride?: LarkFailureKind,
|
|
358
|
+
): LarkOpenApiException {
|
|
359
|
+
const code = nativeCode(body);
|
|
360
|
+
const originalMessage = nativeMessage(body);
|
|
361
|
+
const error = record(record(body)?.error);
|
|
362
|
+
const id =
|
|
363
|
+
record(body)?.request_id ?? error?.log_id ?? header(headers, 'x-tt-logid');
|
|
364
|
+
const requestId = typeof id === 'string' && id.length <= 200 ? id : undefined;
|
|
365
|
+
let kind: LarkFailureKind = kindOverride ?? 'upstream';
|
|
366
|
+
let responseCode = ResponseCode.BAD_GATEWAY;
|
|
367
|
+
let status = HttpStatus.BAD_GATEWAY;
|
|
368
|
+
let message = '飞书调用失败,请应用开发者根据诊断信息排查。';
|
|
369
|
+
if (kindOverride === 'file_processing') {
|
|
370
|
+
responseCode = ResponseCode.INTERNAL_ERROR;
|
|
371
|
+
status = HttpStatus.INTERNAL_SERVER_ERROR;
|
|
372
|
+
message = '飞书文件读取或保存失败,请应用开发者排查文件处理过程。';
|
|
373
|
+
} else if (code === 99991672) {
|
|
374
|
+
kind = 'scope_missing';
|
|
375
|
+
responseCode = ResponseCode.FORBIDDEN;
|
|
376
|
+
status = HttpStatus.FORBIDDEN;
|
|
377
|
+
message =
|
|
378
|
+
'当前绑定飞书应用缺少本次调用所需的 API 权限。请该应用管理员处理权限配置。' +
|
|
379
|
+
scopeLink(body, context);
|
|
380
|
+
} else if (code === 1770032 || code === 131006 || code === 2091005) {
|
|
381
|
+
kind = 'resource_permission';
|
|
382
|
+
responseCode = ResponseCode.FORBIDDEN;
|
|
383
|
+
status = HttpStatus.FORBIDDEN;
|
|
384
|
+
if (code === 1770032) {
|
|
385
|
+
message =
|
|
386
|
+
'当前绑定飞书应用没有这份文档的阅读权限。请文档拥有者或管理者通过右上角“…”→“…更多”→“添加文档应用”为该应用授权。';
|
|
387
|
+
} else if (code === 131006) {
|
|
388
|
+
message =
|
|
389
|
+
'当前绑定飞书应用没有该知识库节点或空间的访问权限。请知识库管理员或节点管理者为该应用授权所需节点范围。';
|
|
390
|
+
} else if (context.operation === 'minutes.v1.minuteTranscript.get') {
|
|
391
|
+
message =
|
|
392
|
+
'当前绑定飞书应用无法导出这篇妙记的文字记录。请妙记拥有者或管理者确认资源访问范围与导出权限。';
|
|
393
|
+
} else if (context.operation === 'minutes.v1.minute.get') {
|
|
394
|
+
message =
|
|
395
|
+
'当前绑定飞书应用无法读取这篇妙记的基本信息。请妙记拥有者或管理者确认资源阅读权限。';
|
|
396
|
+
} else {
|
|
397
|
+
message =
|
|
398
|
+
'当前绑定飞书应用无权执行本次妙记操作。请妙记拥有者或管理者确认资源与操作权限。';
|
|
399
|
+
}
|
|
400
|
+
message += resourceLink(context);
|
|
401
|
+
} else if ([1770002, 131005, 2091002].includes(code ?? -1)) {
|
|
402
|
+
kind = 'not_found';
|
|
403
|
+
responseCode = ResponseCode.NOT_FOUND;
|
|
404
|
+
status = HttpStatus.NOT_FOUND;
|
|
405
|
+
message =
|
|
406
|
+
'无法找到指定飞书资源,请检查原始链接、资源标识及实际访问范围。' +
|
|
407
|
+
resourceLink(context);
|
|
408
|
+
} else if (code === 1770003 || code === 2091004) {
|
|
409
|
+
kind = 'deleted';
|
|
410
|
+
responseCode = ResponseCode.NOT_FOUND;
|
|
411
|
+
status = HttpStatus.NOT_FOUND;
|
|
412
|
+
message = '指定飞书资源已被删除,请确认原始资源。' + resourceLink(context);
|
|
413
|
+
} else if (code === 2091003) {
|
|
414
|
+
kind = 'not_ready';
|
|
415
|
+
responseCode = ResponseCode.CONFLICT;
|
|
416
|
+
status = HttpStatus.CONFLICT;
|
|
417
|
+
message =
|
|
418
|
+
'妙记文字记录尚未就绪,请等待转写完成后重试。' + resourceLink(context);
|
|
419
|
+
} else if (code === 99991400 || httpStatus === 429) {
|
|
420
|
+
kind = 'rate_limited';
|
|
421
|
+
responseCode = ResponseCode.TOO_MANY_REQUESTS;
|
|
422
|
+
status = HttpStatus.TOO_MANY_REQUESTS;
|
|
423
|
+
message = '飞书请求达到频率限制,请稍后重试。';
|
|
424
|
+
} else if (code === 10014 || code === 99991671) {
|
|
425
|
+
kind = 'configuration';
|
|
426
|
+
responseCode = ResponseCode.SERVICE_UNAVAILABLE;
|
|
427
|
+
status = HttpStatus.SERVICE_UNAVAILABLE;
|
|
428
|
+
message = '飞书调用身份配置未生效,请应用开发者核对绑定与平台环境。';
|
|
429
|
+
} else if (code === 2091001) {
|
|
430
|
+
kind = 'invalid_request';
|
|
431
|
+
responseCode = ResponseCode.BAD_REQUEST;
|
|
432
|
+
status = HttpStatus.BAD_REQUEST;
|
|
433
|
+
message = '飞书请求参数有误,请应用开发者核对资源标识与本次操作的参数。';
|
|
434
|
+
} else if (httpStatus === 400) {
|
|
435
|
+
responseCode = ResponseCode.BAD_REQUEST;
|
|
436
|
+
status = HttpStatus.BAD_REQUEST;
|
|
437
|
+
message = '飞书拒绝本次请求,请根据返回原因处理。';
|
|
438
|
+
}
|
|
439
|
+
if (originalMessage) {
|
|
440
|
+
const plainMessage = originalMessage.replace(/[\\`*_\[\]()<>]/g, '\\$&');
|
|
441
|
+
message += ` 飞书返回:${plainMessage}`;
|
|
442
|
+
}
|
|
443
|
+
const details: FailureDetails = {
|
|
444
|
+
provider: 'lark_openapi',
|
|
445
|
+
operation: context.operation,
|
|
446
|
+
kind,
|
|
447
|
+
larkCode: code,
|
|
448
|
+
larkHttpStatus: httpStatus,
|
|
449
|
+
nativeMessage: originalMessage,
|
|
450
|
+
requestId,
|
|
451
|
+
};
|
|
452
|
+
// Never serialize the original SDK error, credentials, request config or transcript.
|
|
453
|
+
return new LarkOpenApiException(responseCode, message, status, details);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
async function requestFailure(
|
|
457
|
+
error: unknown,
|
|
458
|
+
context: LarkCallContext,
|
|
459
|
+
): Promise<LarkOpenApiException> {
|
|
460
|
+
const response = record(record(error)?.response);
|
|
461
|
+
const body = await errorBody(response?.data ?? error);
|
|
462
|
+
const status =
|
|
463
|
+
typeof response?.status === 'number' ? response.status : undefined;
|
|
464
|
+
return failure(context, body, status, response?.headers);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Checks the JSON business code as well as rejected HTTP requests; never retries writes. */
|
|
468
|
+
export async function callLarkJson<T extends LarkJsonResult>(
|
|
469
|
+
context: LarkCallContext,
|
|
470
|
+
request: (client: lark.Client) => Promise<T>,
|
|
471
|
+
): Promise<T> {
|
|
472
|
+
const startedAt = Date.now();
|
|
473
|
+
try {
|
|
474
|
+
const result = await request(getLarkClient());
|
|
475
|
+
if (result?.code !== 0) throw failure(context, result);
|
|
476
|
+
const requestId =
|
|
477
|
+
header(result, 'request_id') ?? header(result.error, 'log_id');
|
|
478
|
+
logCall({
|
|
479
|
+
context,
|
|
480
|
+
startedAt,
|
|
481
|
+
resultType: 'json',
|
|
482
|
+
phase: 'request',
|
|
483
|
+
outcome: 'success',
|
|
484
|
+
requestId,
|
|
485
|
+
});
|
|
486
|
+
return result;
|
|
487
|
+
} catch (error: unknown) {
|
|
488
|
+
const normalized =
|
|
489
|
+
error instanceof BusinessException
|
|
490
|
+
? error
|
|
491
|
+
: await requestFailure(error, context);
|
|
492
|
+
logCall({
|
|
493
|
+
context,
|
|
494
|
+
startedAt,
|
|
495
|
+
resultType: 'json',
|
|
496
|
+
phase: 'request',
|
|
497
|
+
outcome: 'failure',
|
|
498
|
+
error: normalized,
|
|
499
|
+
cause: error,
|
|
500
|
+
});
|
|
501
|
+
throw normalized;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** Consume the successful download once; local consumption errors are not resource permissions. */
|
|
506
|
+
export async function callLarkFile<T>(
|
|
507
|
+
context: LarkCallContext,
|
|
508
|
+
request: (client: lark.Client) => Promise<LarkFileResult>,
|
|
509
|
+
consume: (file: LarkFileResult) => Promise<T>,
|
|
510
|
+
): Promise<T> {
|
|
511
|
+
const startedAt = Date.now();
|
|
512
|
+
let phase: 'request' | 'consume' = 'request';
|
|
513
|
+
let file: LarkFileResult;
|
|
514
|
+
try {
|
|
515
|
+
file = await request(getLarkClient());
|
|
516
|
+
if (
|
|
517
|
+
typeof file?.getReadableStream !== 'function' ||
|
|
518
|
+
typeof file.writeFile !== 'function'
|
|
519
|
+
) {
|
|
520
|
+
throw failure(context, file);
|
|
521
|
+
}
|
|
522
|
+
if (header(file.headers, 'content-type')?.includes('application/json')) {
|
|
523
|
+
throw failure(
|
|
524
|
+
context,
|
|
525
|
+
await errorBody(file.getReadableStream()),
|
|
526
|
+
200,
|
|
527
|
+
file.headers,
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
phase = 'consume';
|
|
531
|
+
// Application validation/database errors retain their contract in this phase.
|
|
532
|
+
const result = await consume({
|
|
533
|
+
headers: file.headers,
|
|
534
|
+
getReadableStream: () => file.getReadableStream(),
|
|
535
|
+
// Only this file I/O boundary converts source-stream and destination-file failures.
|
|
536
|
+
writeFile: async (filePath: string) => {
|
|
537
|
+
try {
|
|
538
|
+
await pipeline(file.getReadableStream(), createWriteStream(filePath));
|
|
539
|
+
return filePath;
|
|
540
|
+
} catch (error: unknown) {
|
|
541
|
+
if (error instanceof BusinessException) throw error;
|
|
542
|
+
throw failure(
|
|
543
|
+
context,
|
|
544
|
+
undefined,
|
|
545
|
+
undefined,
|
|
546
|
+
file.headers,
|
|
547
|
+
'file_processing',
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
},
|
|
551
|
+
});
|
|
552
|
+
logCall({
|
|
553
|
+
context,
|
|
554
|
+
startedAt,
|
|
555
|
+
resultType: 'file',
|
|
556
|
+
phase,
|
|
557
|
+
outcome: 'success',
|
|
558
|
+
requestId: header(file.headers, 'x-tt-logid'),
|
|
559
|
+
});
|
|
560
|
+
return result;
|
|
561
|
+
} catch (error: unknown) {
|
|
562
|
+
const normalized =
|
|
563
|
+
phase === 'request' && !(error instanceof BusinessException)
|
|
564
|
+
? await requestFailure(error, context)
|
|
565
|
+
: error;
|
|
566
|
+
logCall({
|
|
567
|
+
context,
|
|
568
|
+
startedAt,
|
|
569
|
+
resultType: 'file',
|
|
570
|
+
phase,
|
|
571
|
+
outcome: 'failure',
|
|
572
|
+
error: normalized,
|
|
573
|
+
cause: error,
|
|
574
|
+
});
|
|
575
|
+
throw normalized;
|
|
576
|
+
}
|
|
577
|
+
}
|