jvs-ppt-ui 0.0.32 → 0.0.33

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.
@@ -729,8 +729,8 @@ function convertPitchBlockToElement(
729
729
  }
730
730
  }
731
731
 
732
- // 2. 图片块 (含 SVG 装饰图与版式占位图)
733
- if (blockType === 'image') {
732
+ // 2. 图片块 (含 SVG 装饰图、贴纸、GIF 与版式占位图)
733
+ if (blockType === 'image' || blockType === 'sticker' || blockType === 'gif') {
734
734
  const url = block.url || ''
735
735
  if (!url) return null
736
736
 
@@ -1016,20 +1016,58 @@ function convertPitchBlockToElement(
1016
1016
  return convertPitchChartBlock(block, recipe, boxCoords)
1017
1017
  }
1018
1018
 
1019
+ const PITCH_S3_BASE = 'https://pitch-assets-ccb95893-de3f-4266-973c-20049231b248.s3.eu-west-1.amazonaws.com'
1020
+
1019
1021
  // 6. 视频块
1020
1022
  if (blockType === 'video') {
1021
1023
  const sources: any[] = Array.isArray(block.sources) ? block.sources : []
1022
1024
  const playlistSource = sources.find(s => s && s['media-id'])
1025
+ const assetSource = sources.find(s => s && s['asset-id'])
1023
1026
  const mediaId = playlistSource?.['media-id']
1027
+ const rawMediaAssetIds: any[] = Array.isArray(block['media-asset-ids']) ? block['media-asset-ids'] : []
1028
+ const mediaAssetIds = rawMediaAssetIds.filter(
1029
+ id => typeof id === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)
1030
+ )
1024
1031
  const thumbTime = Number(block['thumbnail-time']) || 0
1025
- const posterUrl = mediaId ? `https://image.mux.com/${mediaId}/thumbnail.jpg?time=${thumbTime}` : ''
1026
- const videoUrl = block.url || (mediaId ? `https://stream.mux.com/${mediaId}/high.mp4` : '')
1032
+ const posterUrl =
1033
+ block['poster-url'] ||
1034
+ block.poster ||
1035
+ (mediaId ? `https://image.mux.com/${mediaId}/thumbnail.jpg?time=${thumbTime}` : '')
1036
+
1037
+ const candidateUrls: string[] = []
1038
+ const addCandidate = (u?: string) => {
1039
+ if (u && typeof u === 'string' && /^https?:\/\//i.test(u.trim()) && !candidateUrls.includes(u.trim())) {
1040
+ candidateUrls.push(u.trim())
1041
+ }
1042
+ }
1043
+ addCandidate(block.url)
1044
+ for (const s of sources) {
1045
+ addCandidate(s?.url)
1046
+ }
1047
+ for (const id of mediaAssetIds) {
1048
+ addCandidate(`${PITCH_S3_BASE}/${id}`)
1049
+ }
1050
+ if (assetSource?.['asset-id'] && /^[0-9a-f-]{36}$/i.test(String(assetSource['asset-id']))) {
1051
+ addCandidate(`${PITCH_S3_BASE}/${assetSource['asset-id']}`)
1052
+ }
1053
+ if (mediaId) {
1054
+ // Mux 默认关闭静态 MP4 直链 (返回 403),优先通过代理拉取 HLS (.m3u8) 并无损重封装为标准 MP4
1055
+ addCandidate(`https://stream.mux.com/${mediaId}.m3u8`)
1056
+ addCandidate(`https://stream.mux.com/${mediaId}/high.mp4`)
1057
+ addCandidate(`https://stream.mux.com/${mediaId}/capped-1080p.mp4`)
1058
+ addCandidate(`https://stream.mux.com/${mediaId}/medium.mp4`)
1059
+ addCandidate(`https://stream.mux.com/${mediaId}/low.mp4`)
1060
+ }
1061
+
1062
+ const videoUrl = candidateUrls[0] || ''
1027
1063
 
1028
1064
  return {
1029
1065
  id: block.id || `pitch-video-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
1030
1066
  type: 'video',
1031
1067
  content: videoUrl,
1068
+ src: videoUrl,
1032
1069
  ...(posterUrl ? { poster: posterUrl } : {}),
1070
+ ...(candidateUrls.length > 0 ? { __candidateUrls: candidateUrls } : {}),
1033
1071
  autoplay: Boolean(block.autoplay),
1034
1072
  left,
1035
1073
  top,
@@ -1046,6 +1084,53 @@ function convertPitchBlockToElement(
1046
1084
  } as any
1047
1085
  }
1048
1086
 
1087
+ // 7. 音频块
1088
+ if (blockType === 'audio') {
1089
+ const sources: any[] = Array.isArray(block.sources) ? block.sources : []
1090
+ const rawMediaAssetIds: any[] = Array.isArray(block['media-asset-ids']) ? block['media-asset-ids'] : []
1091
+ const mediaAssetIds = rawMediaAssetIds.filter(
1092
+ id => typeof id === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)
1093
+ )
1094
+ const candidateUrls: string[] = []
1095
+ const addCandidate = (u?: string) => {
1096
+ if (u && typeof u === 'string' && /^https?:\/\//i.test(u.trim()) && !candidateUrls.includes(u.trim())) {
1097
+ candidateUrls.push(u.trim())
1098
+ }
1099
+ }
1100
+ addCandidate(block.url)
1101
+ for (const s of sources) {
1102
+ addCandidate(s?.url)
1103
+ if (s?.['asset-id'] && /^[0-9a-f-]{36}$/i.test(String(s['asset-id']))) {
1104
+ addCandidate(`${PITCH_S3_BASE}/${s['asset-id']}`)
1105
+ }
1106
+ }
1107
+ for (const id of mediaAssetIds) {
1108
+ addCandidate(`${PITCH_S3_BASE}/${id}`)
1109
+ }
1110
+
1111
+ const audioUrl = candidateUrls[0] || ''
1112
+ if (!audioUrl) return null
1113
+
1114
+ return {
1115
+ id: block.id || `pitch-audio-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
1116
+ type: 'audio',
1117
+ content: audioUrl,
1118
+ src: audioUrl,
1119
+ ...(candidateUrls.length > 0 ? { __candidateUrls: candidateUrls } : {}),
1120
+ left,
1121
+ top,
1122
+ width: Math.max(60, width),
1123
+ height: Math.max(60, height),
1124
+ style: {
1125
+ left: `${left}px`,
1126
+ top: `${top}px`,
1127
+ width: `${Math.max(60, width)}px`,
1128
+ height: `${Math.max(60, height)}px`,
1129
+ opacity
1130
+ }
1131
+ } as any
1132
+ }
1133
+
1049
1134
  return null
1050
1135
  }
1051
1136
 
@@ -1126,6 +1211,7 @@ export function convertPitchTemplateToDeck(
1126
1211
  background = {
1127
1212
  type: 'image',
1128
1213
  color: slideBgColor,
1214
+ value: bgImgUrl,
1129
1215
  image: {
1130
1216
  src: bgImgUrl,
1131
1217
  size: 'cover',
@@ -1181,26 +1267,416 @@ export function convertPitchTemplateToDeck(
1181
1267
  }
1182
1268
  }
1183
1269
 
1270
+ function inferMimeFromUrl(urlStr: string, fallbackType: 'image' | 'video' | 'audio' = 'image'): string {
1271
+ try {
1272
+ const u = new URL(urlStr)
1273
+ const pitchCt = u.searchParams.get('pitch-content-type')
1274
+ if (pitchCt && !pitchCt.includes('octet-stream')) {
1275
+ return pitchCt.split(';')[0].trim()
1276
+ }
1277
+ } catch {
1278
+ // ignore
1279
+ }
1280
+ const lower = urlStr.split('?')[0].toLowerCase()
1281
+ if (lower.endsWith('.svg')) return 'image/svg+xml'
1282
+ if (lower.endsWith('.png')) return 'image/png'
1283
+ if (lower.endsWith('.jpg') || lower.endsWith('.jpeg')) return 'image/jpeg'
1284
+ if (lower.endsWith('.webp')) return 'image/webp'
1285
+ if (lower.endsWith('.gif')) return 'image/gif'
1286
+ if (lower.endsWith('.mp4')) return 'video/mp4'
1287
+ if (lower.endsWith('.webm')) return 'video/webm'
1288
+ if (lower.endsWith('.mp3')) return 'audio/mpeg'
1289
+ if (lower.endsWith('.wav')) return 'audio/wav'
1290
+ if (lower.endsWith('.ogg')) return 'audio/ogg'
1291
+ if (lower.endsWith('.m4a')) return 'audio/mp4'
1292
+ if (fallbackType === 'video') return 'video/mp4'
1293
+ if (fallbackType === 'audio') return 'audio/mpeg'
1294
+ return 'image/png'
1295
+ }
1296
+
1297
+ function arrayBufferToBase64DataUrl(buffer: ArrayBuffer, mime: string): string {
1298
+ const bytes = new Uint8Array(buffer)
1299
+ const chunkSize = 0x8000
1300
+ let binary = ''
1301
+ for (let i = 0; i < bytes.length; i += chunkSize) {
1302
+ const chunk = bytes.subarray(i, Math.min(i + chunkSize, bytes.length))
1303
+ binary += String.fromCharCode.apply(null, chunk as unknown as number[])
1304
+ }
1305
+ return `data:${mime};base64,${btoa(binary)}`
1306
+ }
1307
+
1308
+ async function fetchMediaAsBase64(
1309
+ primaryUrl: string,
1310
+ mediaType: 'image' | 'video' | 'audio' = 'image',
1311
+ candidates?: string[]
1312
+ ): Promise<string> {
1313
+ const trimmed = (primaryUrl || '').trim()
1314
+ if (!trimmed || trimmed.startsWith('data:')) return trimmed
1315
+
1316
+ const allCandidates: string[] = []
1317
+ if (/^https?:\/\//i.test(trimmed)) {
1318
+ allCandidates.push(trimmed)
1319
+ }
1320
+ if (Array.isArray(candidates)) {
1321
+ for (const c of candidates) {
1322
+ if (typeof c === 'string' && /^https?:\/\//i.test(c.trim()) && !allCandidates.includes(c.trim())) {
1323
+ allCandidates.push(c.trim())
1324
+ }
1325
+ }
1326
+ }
1327
+ if (allCandidates.length === 0) return trimmed
1328
+
1329
+ // 1. 优先通过本地 Vite 媒体代理拉取并转为 Base64(规避 S3 / Mux / Unsplash 跨域限制,并支持 HLS .m3u8 转 MP4)
1330
+ let proxyHandled = false
1331
+ if (import.meta.env.DEV) {
1332
+ try {
1333
+ const qs = new URLSearchParams({
1334
+ url: allCandidates[0],
1335
+ type: mediaType
1336
+ })
1337
+ if (allCandidates.length > 1) {
1338
+ qs.set('candidates', JSON.stringify(allCandidates))
1339
+ }
1340
+ const proxyRes = await fetch(`/__pitch_media_proxy?${qs.toString()}`)
1341
+ const ct = proxyRes.headers.get('content-type') || ''
1342
+ if (ct.includes('application/json')) {
1343
+ proxyHandled = true
1344
+ if (proxyRes.ok) {
1345
+ const payload = await proxyRes.json()
1346
+ if (payload?.dataUrl && typeof payload.dataUrl === 'string' && payload.dataUrl.startsWith('data:')) {
1347
+ return payload.dataUrl
1348
+ }
1349
+ }
1350
+ }
1351
+ } catch {
1352
+ // fallback to browser fetch if proxy not reachable
1353
+ }
1354
+ }
1355
+
1356
+ // 如果本地代理已尝试全部候选地址仍未成功,不再在浏览器端重复请求以避免控制台报 403/CORS 红字
1357
+ if (proxyHandled) {
1358
+ return trimmed
1359
+ }
1360
+
1361
+ // 2. 浏览器端直连回退(跳过 .m3u8 流及已知会 403 的 stream.mux.com 静态 mp4)
1362
+ for (const candidateUrl of allCandidates) {
1363
+ if (
1364
+ candidateUrl.split('?')[0].toLowerCase().endsWith('.m3u8') ||
1365
+ candidateUrl.includes('stream.mux.com/')
1366
+ ) {
1367
+ continue
1368
+ }
1369
+ try {
1370
+ const res = await fetch(candidateUrl, { mode: 'cors' })
1371
+ if (!res.ok) continue
1372
+ const contentType = (res.headers.get('content-type') || '').split(';')[0].trim().toLowerCase()
1373
+ if (contentType.includes('text/html')) continue
1374
+ const buf = await res.arrayBuffer()
1375
+ if (!buf || buf.byteLength === 0) continue
1376
+ const resolvedMime =
1377
+ contentType && contentType !== 'application/octet-stream' && contentType !== 'binary/octet-stream'
1378
+ ? contentType
1379
+ : inferMimeFromUrl(candidateUrl, mediaType)
1380
+ return arrayBufferToBase64DataUrl(buf, resolvedMime)
1381
+ } catch {
1382
+ // try next candidate
1383
+ }
1384
+ }
1385
+
1386
+ return trimmed
1387
+ }
1388
+
1389
+ // 会话级 Base64 Promise 缓存:同一资源无论出现在多少页幻灯片、或多次点击导入/下载,均只拉取并编码一次
1390
+ const sessionMediaBase64Cache = new Map<string, Promise<string>>()
1391
+
1392
+ /**
1393
+ * 将转换后的 DeckData 中所有图片、视频、音频及背景图外链资源批量拉取并内联为 Base64 DataURL
1394
+ */
1395
+ export async function convertDeckMediaToBase64(
1396
+ deck: DeckData & { styleRecipes: StyleRecipe[] },
1397
+ onProgress?: (completed: number, total: number) => void
1398
+ ): Promise<DeckData & { styleRecipes: StyleRecipe[] }> {
1399
+ if (!deck || !Array.isArray(deck.slides)) return deck
1400
+
1401
+ const getCachedBase64 = (
1402
+ url: string,
1403
+ mediaType: 'image' | 'video' | 'audio',
1404
+ candidates?: string[]
1405
+ ): Promise<string> => {
1406
+ const key = `${mediaType}:${url}:${candidates ? candidates.join('|') : ''}`
1407
+ const existing = sessionMediaBase64Cache.get(key)
1408
+ if (existing) return existing
1409
+
1410
+ const promise = fetchMediaAsBase64(url, mediaType, candidates).then(res => {
1411
+ // 如果拉取失败仍返回原始 http 地址,则从缓存移除以便后续可重试
1412
+ if (!res.startsWith('data:')) {
1413
+ sessionMediaBase64Cache.delete(key)
1414
+ }
1415
+ return res
1416
+ })
1417
+ sessionMediaBase64Cache.set(key, promise)
1418
+ return promise
1419
+ }
1420
+
1421
+ // 按唯一资源 Key 聚合所有引用点,保证相同资源只作为一个并发任务拉取一次,转换完成后一次性回填到所有引用元素
1422
+ const resourceTaskMap = new Map<
1423
+ string,
1424
+ {
1425
+ fetch: () => Promise<string>
1426
+ appliers: Array<(dataUrl: string) => void>
1427
+ }
1428
+ >()
1429
+
1430
+ const registerResource = (
1431
+ url: string,
1432
+ mediaType: 'image' | 'video' | 'audio',
1433
+ candidates: string[] | undefined,
1434
+ apply: (dataUrl: string) => void
1435
+ ) => {
1436
+ const key = `${mediaType}:${url}:${candidates ? candidates.join('|') : ''}`
1437
+ let entry = resourceTaskMap.get(key)
1438
+ if (!entry) {
1439
+ entry = {
1440
+ fetch: () => getCachedBase64(url, mediaType, candidates),
1441
+ appliers: []
1442
+ }
1443
+ resourceTaskMap.set(key, entry)
1444
+ }
1445
+ entry.appliers.push(apply)
1446
+ }
1447
+
1448
+ const collectElementTasks = (el: any) => {
1449
+ if (!el || typeof el !== 'object') return
1450
+
1451
+ if (el.type === 'image') {
1452
+ const targetUrl = (el.src || el.content || '').trim()
1453
+ if (/^https?:\/\//i.test(targetUrl)) {
1454
+ registerResource(targetUrl, 'image', undefined, dataUrl => {
1455
+ el.content = dataUrl
1456
+ delete el.src
1457
+ delete el.base64
1458
+ })
1459
+ }
1460
+ } else if (el.type === 'video') {
1461
+ const targetUrl = (el.src || el.content || '').trim()
1462
+ const candidateUrls: string[] | undefined = Array.isArray(el.__candidateUrls) ? el.__candidateUrls : undefined
1463
+ delete el.__candidateUrls
1464
+ if (/^https?:\/\//i.test(targetUrl) || (candidateUrls && candidateUrls.length > 0)) {
1465
+ const primary = targetUrl || candidateUrls![0]
1466
+ registerResource(primary, 'video', candidateUrls, dataUrl => {
1467
+ el.content = dataUrl
1468
+ delete el.src
1469
+ delete el.base64
1470
+ })
1471
+ }
1472
+ if (el.poster && typeof el.poster === 'string' && /^https?:\/\//i.test(el.poster.trim())) {
1473
+ const posterUrl = el.poster.trim()
1474
+ registerResource(posterUrl, 'image', undefined, dataUrl => {
1475
+ el.poster = dataUrl
1476
+ })
1477
+ }
1478
+ } else if (el.type === 'audio') {
1479
+ const targetUrl = (el.src || el.content || '').trim()
1480
+ const candidateUrls: string[] | undefined = Array.isArray(el.__candidateUrls) ? el.__candidateUrls : undefined
1481
+ delete el.__candidateUrls
1482
+ if (/^https?:\/\//i.test(targetUrl) || (candidateUrls && candidateUrls.length > 0)) {
1483
+ const primary = targetUrl || candidateUrls![0]
1484
+ registerResource(primary, 'audio', candidateUrls, dataUrl => {
1485
+ el.content = dataUrl
1486
+ delete el.src
1487
+ delete el.base64
1488
+ })
1489
+ }
1490
+ } else if (el.type === 'shape') {
1491
+ const patUrl = (el.pattern || el.style?.pattern || '').trim()
1492
+ if (/^https?:\/\//i.test(patUrl)) {
1493
+ registerResource(patUrl, 'image', undefined, dataUrl => {
1494
+ el.pattern = dataUrl
1495
+ if (el.style) el.style.pattern = dataUrl
1496
+ })
1497
+ }
1498
+ }
1499
+
1500
+ if (Array.isArray(el.elements)) {
1501
+ for (const child of el.elements) {
1502
+ collectElementTasks(child)
1503
+ }
1504
+ }
1505
+ }
1506
+
1507
+ for (const slide of deck.slides) {
1508
+ if (!slide) continue
1509
+ const bg: any = slide.background
1510
+ if (bg && typeof bg === 'object') {
1511
+ const bgSrc = (bg.image?.src || bg.value || '').trim()
1512
+ if (/^https?:\/\//i.test(bgSrc)) {
1513
+ registerResource(bgSrc, 'image', undefined, dataUrl => {
1514
+ delete bg.value
1515
+ if (bg.image && typeof bg.image === 'object') {
1516
+ bg.image.src = dataUrl
1517
+ delete bg.image.base64
1518
+ }
1519
+ })
1520
+ }
1521
+ } else if (typeof bg === 'string') {
1522
+ const urlMatch = bg.match(/url\(['"]?(https?:\/\/[^)'"]+)['"]?\)/i)
1523
+ if (urlMatch && urlMatch[1]) {
1524
+ const rawBgUrl = urlMatch[1]
1525
+ registerResource(rawBgUrl, 'image', undefined, dataUrl => {
1526
+ slide.background = bg.replace(rawBgUrl, dataUrl)
1527
+ })
1528
+ }
1529
+ }
1530
+
1531
+ if (Array.isArray(slide.elements)) {
1532
+ for (const el of slide.elements) {
1533
+ collectElementTasks(el)
1534
+ }
1535
+ }
1536
+ }
1537
+
1538
+ const uniqueEntries = Array.from(resourceTaskMap.values())
1539
+ const total = uniqueEntries.length
1540
+ if (total === 0) return deck
1541
+
1542
+ let completed = 0
1543
+ onProgress?.(0, total)
1544
+
1545
+ const CONCURRENCY = 6
1546
+ let cursor = 0
1547
+ const workers = Array.from({ length: Math.min(CONCURRENCY, total) }, async () => {
1548
+ while (cursor < total) {
1549
+ const currentIdx = cursor++
1550
+ const entry = uniqueEntries[currentIdx]
1551
+ if (entry) {
1552
+ const dataUrl = await entry.fetch()
1553
+ for (const apply of entry.appliers) {
1554
+ apply(dataUrl)
1555
+ }
1556
+ completed++
1557
+ onProgress?.(completed, total)
1558
+ }
1559
+ }
1560
+ })
1561
+
1562
+ await Promise.all(workers)
1563
+ return deck
1564
+ }
1565
+
1566
+ function stripRedundantElementBase64(el: any): any {
1567
+ if (!el || typeof el !== 'object') return el
1568
+ const cloned: any = { ...el }
1569
+ if (typeof cloned.content === 'string' && cloned.content.startsWith('data:')) {
1570
+ if (cloned.src === cloned.content) delete cloned.src
1571
+ if (cloned.base64 === cloned.content) delete cloned.base64
1572
+ } else if (typeof cloned.src === 'string' && cloned.src.startsWith('data:')) {
1573
+ if (cloned.base64 === cloned.src) delete cloned.base64
1574
+ }
1575
+ if (Array.isArray(cloned.elements)) {
1576
+ cloned.elements = cloned.elements.map(stripRedundantElementBase64)
1577
+ }
1578
+ return cloned
1579
+ }
1580
+
1581
+ function pushPageBlobParts(page: any, parts: BlobPart[], indent = ' ') {
1582
+ if (!page || typeof page !== 'object') {
1583
+ parts.push(indent + JSON.stringify(page))
1584
+ return
1585
+ }
1586
+ const keys = Object.keys(page).filter(k => page[k] !== undefined)
1587
+ parts.push(`${indent}{\n`)
1588
+ keys.forEach((k, idx) => {
1589
+ const isLast = idx === keys.length - 1
1590
+ const val = page[k]
1591
+ const propIndent = indent + ' '
1592
+ if (k === 'elements' && Array.isArray(val)) {
1593
+ if (val.length === 0) {
1594
+ parts.push(`${propIndent}"elements": []${isLast ? '\n' : ',\n'}`)
1595
+ } else {
1596
+ parts.push(`${propIndent}"elements": [\n`)
1597
+ val.forEach((el, elIdx) => {
1598
+ const elComma = elIdx < val.length - 1 ? ',\n' : '\n'
1599
+ parts.push(propIndent + ' ' + JSON.stringify(stripRedundantElementBase64(el)) + elComma)
1600
+ })
1601
+ parts.push(`${propIndent}]${isLast ? '\n' : ',\n'}`)
1602
+ }
1603
+ } else if (k === 'layouts' && Array.isArray(val)) {
1604
+ if (val.length === 0) {
1605
+ parts.push(`${propIndent}"layouts": []${isLast ? '\n' : ',\n'}`)
1606
+ } else {
1607
+ parts.push(`${propIndent}"layouts": [\n`)
1608
+ val.forEach((layout, lIdx) => {
1609
+ pushPageBlobParts(layout, parts, propIndent + ' ')
1610
+ parts.push(lIdx < val.length - 1 ? ',\n' : '\n')
1611
+ })
1612
+ parts.push(`${propIndent}]${isLast ? '\n' : ',\n'}`)
1613
+ }
1614
+ } else {
1615
+ parts.push(`${propIndent}${JSON.stringify(k)}: ${JSON.stringify(val)}${isLast ? '\n' : ',\n'}`)
1616
+ }
1617
+ })
1618
+ parts.push(`${indent}}`)
1619
+ }
1620
+
1621
+ /**
1622
+ * 分块流式构建包含大型 Base64 媒体的 Deck JSON Blob
1623
+ * 按单页/单元素粒度调用 JSON.stringify 并交由浏览器原生 Blob 拼接,彻底规避 V8 单字符串 512MB 长度上限 (RangeError: Invalid string length)
1624
+ */
1625
+ export function stringifyDeckToBlob(deckObj: Record<string, any>): Blob {
1626
+ const parts: BlobPart[] = ['{\n']
1627
+ const keys = Object.keys(deckObj).filter(k => deckObj[k] !== undefined)
1628
+ keys.forEach((key, keyIdx) => {
1629
+ const isLastKey = keyIdx === keys.length - 1
1630
+ const val = deckObj[key]
1631
+ if ((key === 'slides' || key === 'masters' || key === 'slideMasters') && Array.isArray(val)) {
1632
+ if (val.length === 0) {
1633
+ parts.push(` ${JSON.stringify(key)}: []${isLastKey ? '\n' : ',\n'}`)
1634
+ } else {
1635
+ parts.push(` ${JSON.stringify(key)}: [\n`)
1636
+ val.forEach((item, itemIdx) => {
1637
+ pushPageBlobParts(item, parts, ' ')
1638
+ parts.push(itemIdx < val.length - 1 ? ',\n' : '\n')
1639
+ })
1640
+ parts.push(` ]${isLastKey ? '\n' : ',\n'}`)
1641
+ }
1642
+ } else {
1643
+ const formatted = JSON.stringify(val, null, 2)
1644
+ const indented = formatted ? formatted.replace(/\n/g, '\n ') : 'null'
1645
+ parts.push(` ${JSON.stringify(key)}: ${indented}${isLastKey ? '\n' : ',\n'}`)
1646
+ }
1647
+ })
1648
+ parts.push('}\n')
1649
+ return new Blob(parts, { type: 'application/json;charset=utf-8' })
1650
+ }
1651
+
1184
1652
  /**
1185
- * 通过本地开发代理或直接 fetch 拉取 Pitch 模板/版式库并转换为 DeckData
1653
+ * 通过本地开发代理或直接 fetch 拉取 Pitch 模板/版式库并转换为 DeckData(自动将图片/视频/音频资源转换为 Base64)
1186
1654
  */
1187
1655
  export async function fetchAndConvertPitchTemplate(
1188
1656
  urlOrInput: string,
1189
- options?: { categoryFilter?: string }
1657
+ options?: {
1658
+ categoryFilter?: string
1659
+ convertMediaToBase64?: boolean
1660
+ onProgress?: (completed: number, total: number) => void
1661
+ }
1190
1662
  ): Promise<DeckData & { styleRecipes: StyleRecipe[] }> {
1191
1663
  const trimmed = (urlOrInput || '').trim()
1192
1664
  if (!trimmed) {
1193
1665
  throw new Error('请输入 Pitch 模板地址或 JSON 数据')
1194
1666
  }
1195
1667
 
1668
+ const shouldConvertMedia = options?.convertMediaToBase64 !== false
1669
+
1196
1670
  // 如果直接粘贴了 JSON 数组或对象文本
1197
1671
  if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
1198
1672
  const parsed = JSON.parse(trimmed)
1199
- return convertPitchTemplateToDeck(parsed, options)
1673
+ const deck = convertPitchTemplateToDeck(parsed, options)
1674
+ return shouldConvertMedia ? await convertDeckMediaToBase64(deck, options?.onProgress) : deck
1200
1675
  }
1201
1676
 
1202
1677
  const targetUrl = normalizePitchTemplateUrl(trimmed)
1203
1678
  let rawData: any = null
1679
+ let proxyErrorMsg = ''
1204
1680
 
1205
1681
  // 优先走本地 Vite 开发中间件代理 (规避浏览器 CORS 限制)
1206
1682
  if (import.meta.env.DEV) {
@@ -1208,19 +1684,42 @@ export async function fetchAndConvertPitchTemplate(
1208
1684
  const proxyRes = await fetch(`/__pitch_proxy?url=${encodeURIComponent(targetUrl)}`)
1209
1685
  if (proxyRes.ok) {
1210
1686
  rawData = await proxyRes.json()
1687
+ } else {
1688
+ const errBody = await proxyRes.json().catch(() => null)
1689
+ proxyErrorMsg = errBody?.error || `代理请求返回 HTTP ${proxyRes.status}`
1690
+ }
1691
+ } catch (e: any) {
1692
+ proxyErrorMsg = e?.message || ''
1693
+ }
1694
+ }
1695
+
1696
+ // 若请求的是官方版式库 key-layouts.transit 且远程代理失败,自动回退到本地静态缓存备份
1697
+ if (!rawData && targetUrl.includes('key-layouts.transit')) {
1698
+ try {
1699
+ const localRes = await fetch('/templates/key-layouts.transit')
1700
+ if (localRes.ok) {
1701
+ rawData = await localRes.json()
1211
1702
  }
1212
1703
  } catch {
1213
- // fallback to direct fetch
1704
+ // ignore local fallback failure
1214
1705
  }
1215
1706
  }
1216
1707
 
1217
1708
  if (!rawData) {
1218
- const res = await fetch(targetUrl)
1219
- if (!res.ok) {
1220
- throw new Error(`拉取 Pitch 数据失败 (HTTP ${res.status})`)
1709
+ try {
1710
+ const res = await fetch(targetUrl)
1711
+ if (!res.ok) {
1712
+ throw new Error(`拉取 Pitch 数据失败 (HTTP ${res.status})`)
1713
+ }
1714
+ rawData = await res.json()
1715
+ } catch (err: any) {
1716
+ if (proxyErrorMsg) {
1717
+ throw new Error(`拉取失败:${proxyErrorMsg}(浏览器直连因跨域 CORS 被拦截)`)
1718
+ }
1719
+ throw err
1221
1720
  }
1222
- rawData = await res.json()
1223
1721
  }
1224
1722
 
1225
- return convertPitchTemplateToDeck(rawData, options)
1723
+ const deck = convertPitchTemplateToDeck(rawData, options)
1724
+ return shouldConvertMedia ? await convertDeckMediaToBase64(deck, options?.onProgress) : deck
1226
1725
  }
@@ -1,5 +0,0 @@
1
- {
2
- "code": 0,
3
- "msg": "success",
4
- "templates": []
5
- }