jvs-ppt-ui 0.0.17 → 0.0.19

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.
@@ -0,0 +1,445 @@
1
+ import { ref, computed, onMounted, onUnmounted } from 'vue'
2
+ import { useSlides } from '../../composables/useSlides'
3
+
4
+ /**
5
+ * 读取指定名称的 Cookie
6
+ */
7
+ export function getCookieValue(cname: string): string {
8
+ if (typeof document === 'undefined' || !document.cookie) return ''
9
+ const name = cname + '='
10
+ const parts = document.cookie.split(';')
11
+ for (let i = 0; i < parts.length; i++) {
12
+ const item = parts[i]?.trim()
13
+ if (item && item.indexOf(name) === 0) {
14
+ try {
15
+ return decodeURIComponent(item.substring(name.length))
16
+ } catch {
17
+ return item.substring(name.length)
18
+ }
19
+ }
20
+ }
21
+ return ''
22
+ }
23
+
24
+ /**
25
+ * 从 Storage 中读取指定 key(兼容 jvs- 前缀包装格式与原始字符串格式)
26
+ */
27
+ function readStorageKey(storage: Storage | undefined, key: string): string {
28
+ if (!storage) return ''
29
+ try {
30
+ const raw = storage.getItem(key)
31
+ if (!raw) return ''
32
+ try {
33
+ const parsed = JSON.parse(raw)
34
+ if (parsed && typeof parsed === 'object' && 'content' in parsed) {
35
+ return typeof parsed.content === 'string' ? parsed.content.trim() : ''
36
+ }
37
+ if (typeof parsed === 'string') return parsed.trim()
38
+ } catch {
39
+ return raw.trim()
40
+ }
41
+ } catch {
42
+ return ''
43
+ }
44
+ return ''
45
+ }
46
+
47
+ /**
48
+ * 向 Storage 写入 jvs- 标准包装格式数据(对齐 jvs-material-ui / jvs-narrivo-ai-ui 的 setStore 规范)
49
+ */
50
+ function writeJvsStore(name: string, content: string): void {
51
+ if (typeof window === 'undefined' || !window.localStorage || !name) return
52
+ try {
53
+ const payload = JSON.stringify({
54
+ dataType: typeof content,
55
+ content,
56
+ datetime: Date.now()
57
+ })
58
+ window.localStorage.setItem(`jvs-${name}`, payload)
59
+ if (window.sessionStorage) {
60
+ window.sessionStorage.setItem(`jvs-${name}`, payload)
61
+ }
62
+ } catch {
63
+ // 忽略隐私模式或配额异常
64
+ }
65
+ }
66
+
67
+ function removeJvsStore(name: string): void {
68
+ if (typeof window === 'undefined') return
69
+ try {
70
+ window.localStorage?.removeItem(`jvs-${name}`)
71
+ window.localStorage?.removeItem(name)
72
+ window.sessionStorage?.removeItem(`jvs-${name}`)
73
+ window.sessionStorage?.removeItem(name)
74
+ } catch {
75
+ // ignore
76
+ }
77
+ }
78
+
79
+ /**
80
+ * 提取 jvs_session_v3 登录凭证
81
+ * 判定顺序:
82
+ * 1. document.cookie 中的 jvs_session_v3 或 Set-Cookie(非 HttpOnly 场景)
83
+ * 2. localStorage / sessionStorage 中的 jvs_session_v3、jvs-jvs_session_v3、jvs-sessionV3、sessionV3、jvs-access_token
84
+ * 3. materialHeaders 中显式传入的 jvs_session_v3 或 Authorization
85
+ */
86
+ export function resolveJvsSessionV3(extraHeaders?: Record<string, string>): string {
87
+ if (typeof window === 'undefined') return ''
88
+
89
+ // 1. Cookie: jvs_session_v3(若未开启 HttpOnly 可直接读取)
90
+ const fromCookie = getCookieValue('jvs_session_v3') || getCookieValue('Set-Cookie')
91
+ if (fromCookie && fromCookie.trim()) {
92
+ return fromCookie.trim()
93
+ }
94
+
95
+ // 2. LocalStorage / SessionStorage
96
+ const candidateKeys = [
97
+ 'jvs_session_v3',
98
+ 'jvs-jvs_session_v3',
99
+ 'jvs-sessionV3',
100
+ 'sessionV3',
101
+ 'jvs-access_token',
102
+ 'access_token'
103
+ ]
104
+ for (const key of candidateKeys) {
105
+ const localVal = readStorageKey(window.localStorage, key)
106
+ if (localVal) return localVal
107
+ const sessionVal = readStorageKey(window.sessionStorage, key)
108
+ if (sessionVal) return sessionVal
109
+ }
110
+
111
+ // 3. 外部注入的 Headers
112
+ if (extraHeaders) {
113
+ const headerVal =
114
+ extraHeaders['jvs_session_v3'] ||
115
+ extraHeaders['JVS_SESSION_V3'] ||
116
+ (extraHeaders['Authorization'] ? extraHeaders['Authorization'].replace(/^Bearer\s+/i, '') : '') ||
117
+ (extraHeaders['authorization'] ? extraHeaders['authorization'].replace(/^Bearer\s+/i, '') : '')
118
+ if (typeof headerVal === 'string' && headerVal.trim()) {
119
+ return headerVal.trim()
120
+ }
121
+ }
122
+
123
+ return ''
124
+ }
125
+
126
+ /**
127
+ * 提取服务网关 Origin 前缀(如配置了完整域名则复用该域名,否则使用当前站点相对路径 '')
128
+ */
129
+ export function resolveGatewayOrigin(configuredUrl?: string): string {
130
+ if (configuredUrl && /^https?:\/\//i.test(configuredUrl.trim())) {
131
+ try {
132
+ const u = new URL(configuredUrl.trim())
133
+ return u.origin
134
+ } catch {
135
+ return ''
136
+ }
137
+ }
138
+ return ''
139
+ }
140
+
141
+ /**
142
+ * 提取 DAM 服务基础路径(默认 /jvs-dam)
143
+ */
144
+ export function resolveDamBaseUrl(configuredUrl?: string): string {
145
+ if (configuredUrl && configuredUrl.trim()) {
146
+ const clean = configuredUrl.trim()
147
+ const damIdx = clean.indexOf('/jvs-dam')
148
+ if (damIdx >= 0) {
149
+ return clean.slice(0, damIdx + '/jvs-dam'.length)
150
+ }
151
+ }
152
+ return '/jvs-dam'
153
+ }
154
+
155
+ export type DamMainTab = 'search' | 'mine' | 'create'
156
+
157
+ /**
158
+ * 跨组件共享的素材库顶层 Tab 状态(支持画布占位符「AI生成」直接跳转至「创建素材」)
159
+ */
160
+ const sharedMaterialMainTab = ref<DamMainTab>('search')
161
+
162
+ /**
163
+ * 针对主域 .bctools.cn 下 HttpOnly Cookie (jvs_session_v3) 的服务端换取/探测状态
164
+ * 说明:当 jvs_session_v3 设置了 HttpOnly=true 时,前端 document.cookie 无法直接读取,
165
+ * 需通过同域/跨子域携带 Cookie 请求 /jvs-system/login/token(对齐 jvs-material-ui / jvs-narrivo-ai-ui)换取 sessionV3。
166
+ */
167
+ const remoteSessionToken = ref<string>('')
168
+ const remoteCookieSessionVerified = ref<boolean>(false)
169
+ let inFlightSessionProbe: Promise<boolean> | null = null
170
+ let hasInitialProbed = false
171
+
172
+ export function setSharedMaterialMainTab(tab: DamMainTab) {
173
+ sharedMaterialMainTab.value = tab
174
+ }
175
+
176
+ /**
177
+ * DAM 登录态与通用请求工具 Composable
178
+ */
179
+ export function useDamAuth() {
180
+ const { materialApiUrl, materialHeaders } = useSlides()
181
+ const sessionTick = ref(0)
182
+ let pollTimer: ReturnType<typeof setInterval> | null = null
183
+
184
+ const damBaseUrl = computed(() => resolveDamBaseUrl(materialApiUrl.value))
185
+ const gatewayOrigin = computed(() => resolveGatewayOrigin(materialApiUrl.value))
186
+
187
+ /**
188
+ * 通过服务端接口换取/校验主域 (.bctools.cn) 下的 HttpOnly jvs_session_v3 Cookie
189
+ */
190
+ async function probeRemoteSessionV3(force = false): Promise<boolean> {
191
+ if (typeof window === 'undefined') return false
192
+
193
+ const localToken = resolveJvsSessionV3(materialHeaders.value) || remoteSessionToken.value
194
+ if (localToken && !force && hasInitialProbed) {
195
+ return true
196
+ }
197
+
198
+ if (inFlightSessionProbe) {
199
+ return inFlightSessionProbe
200
+ }
201
+
202
+ inFlightSessionProbe = (async () => {
203
+ hasInitialProbed = true
204
+ const origin = gatewayOrigin.value
205
+
206
+ // 1. 标准 JVS 换取方式:请求 /jvs-system/login/token(浏览器自动携带 .bctools.cn 下的 HttpOnly jvs_session_v3)
207
+ try {
208
+ const tokenResp = await fetch(`${origin}/jvs-system/login/token`, {
209
+ method: 'GET',
210
+ credentials: 'include',
211
+ headers: {
212
+ 'jvs-rule-ua': encodeURI('2.4'),
213
+ ...(materialHeaders.value || {})
214
+ }
215
+ })
216
+
217
+ if (tokenResp.ok) {
218
+ const text = (await tokenResp.text()).trim()
219
+ if (text && !text.startsWith('<')) {
220
+ const parsed = JSON.parse(text)
221
+ const code = parsed?.code ?? parsed?.data?.code
222
+ const tokenData = parsed?.data?.data !== undefined ? parsed.data.data : parsed?.data
223
+
224
+ if (code === 0) {
225
+ const tokenStr =
226
+ typeof tokenData === 'string'
227
+ ? tokenData.trim()
228
+ : typeof tokenData?.access_token === 'string'
229
+ ? tokenData.access_token.trim()
230
+ : ''
231
+
232
+ if (tokenStr) {
233
+ remoteSessionToken.value = tokenStr
234
+ remoteCookieSessionVerified.value = true
235
+ writeJvsStore('sessionV3', tokenStr)
236
+ writeJvsStore('access_token', tokenStr)
237
+ sessionTick.value++
238
+
239
+ // 若本地尚无 tenantId,顺带拉取当前租户 ID
240
+ if (!readStorageKey(window.localStorage, 'jvs-tenantId')) {
241
+ fetch(`${origin}/jvs-system/index/this/tenant`, {
242
+ method: 'GET',
243
+ credentials: 'include',
244
+ headers: {
245
+ 'jvs-rule-ua': encodeURI('2.4'),
246
+ Authorization: `Bearer ${tokenStr}`
247
+ }
248
+ })
249
+ .then(r => r.json())
250
+ .then(tRes => {
251
+ const tData = tRes?.data?.data || tRes?.data
252
+ if (tData?.id) {
253
+ writeJvsStore('tenantId', String(tData.id))
254
+ }
255
+ })
256
+ .catch(() => {})
257
+ }
258
+
259
+ return true
260
+ } else {
261
+ // /jvs-system/login/token 明确返回 code=0 但无 token,说明主域未登录或已退出
262
+ remoteSessionToken.value = ''
263
+ remoteCookieSessionVerified.value = false
264
+ removeJvsStore('sessionV3')
265
+ removeJvsStore('access_token')
266
+ sessionTick.value++
267
+ return false
268
+ }
269
+ }
270
+ }
271
+ }
272
+ } catch {
273
+ // 忽略 /jvs-system/login/token 网络或未代理异常,继续尝试步骤 2
274
+ }
275
+
276
+ // 2. 兜底探测:若当前站点未代理 /jvs-system,但代理了 /jvs-dam 且网关直接透传 .bctools.cn 的 HttpOnly Cookie
277
+ try {
278
+ const probeResp = await fetch(`${damBaseUrl.value}/project/my`, {
279
+ method: 'GET',
280
+ credentials: 'include',
281
+ headers: buildDamHeaders(false)
282
+ })
283
+ if (probeResp.ok) {
284
+ const text = (await probeResp.text()).trim()
285
+ if (text && !text.startsWith('<')) {
286
+ const parsed = JSON.parse(text)
287
+ const code = parsed?.code ?? parsed?.data?.code
288
+ if (code === 0 || code === 200) {
289
+ remoteCookieSessionVerified.value = true
290
+ sessionTick.value++
291
+ return true
292
+ }
293
+ }
294
+ }
295
+ } catch {
296
+ // ignore
297
+ }
298
+
299
+ return Boolean(resolveJvsSessionV3(materialHeaders.value))
300
+ })()
301
+
302
+ try {
303
+ return await inFlightSessionProbe
304
+ } finally {
305
+ inFlightSessionProbe = null
306
+ }
307
+ }
308
+
309
+ const refreshSessionState = () => {
310
+ sessionTick.value++
311
+ if (!resolveJvsSessionV3(materialHeaders.value) && !remoteSessionToken.value && !remoteCookieSessionVerified.value) {
312
+ void probeRemoteSessionV3(false)
313
+ }
314
+ }
315
+
316
+ const handleWindowFocus = () => {
317
+ sessionTick.value++
318
+ if (!resolveJvsSessionV3(materialHeaders.value) && !remoteSessionToken.value && !remoteCookieSessionVerified.value) {
319
+ void probeRemoteSessionV3(false)
320
+ }
321
+ }
322
+
323
+ onMounted(() => {
324
+ window.addEventListener('storage', refreshSessionState)
325
+ window.addEventListener('focus', handleWindowFocus)
326
+ // 立即探测一次主域 (.bctools.cn) HttpOnly jvs_session_v3 登录态
327
+ void probeRemoteSessionV3(false)
328
+ // 定期轻量同步状态变化
329
+ pollTimer = setInterval(refreshSessionState, 3000)
330
+ })
331
+
332
+ onUnmounted(() => {
333
+ window.removeEventListener('storage', refreshSessionState)
334
+ window.removeEventListener('focus', handleWindowFocus)
335
+ if (pollTimer) {
336
+ clearInterval(pollTimer)
337
+ pollTimer = null
338
+ }
339
+ })
340
+
341
+ const sessionV3 = computed(() => {
342
+ void sessionTick.value
343
+ return remoteSessionToken.value || resolveJvsSessionV3(materialHeaders.value)
344
+ })
345
+
346
+ /** 是否已登录(jvs_session_v3 存在有效内容,或通过主域 HttpOnly Cookie 换取/验证通过) */
347
+ const isDamLoggedIn = computed(() => {
348
+ void sessionTick.value
349
+ return Boolean(sessionV3.value || remoteCookieSessionVerified.value)
350
+ })
351
+
352
+ /**
353
+ * 构造携带鉴权信息的 Headers
354
+ */
355
+ function buildDamHeaders(isJson = true): Record<string, string> {
356
+ const headers: Record<string, string> = {
357
+ 'jvs-rule-ua': encodeURI('2.4'),
358
+ ...(materialHeaders.value || {})
359
+ }
360
+ if (isJson) {
361
+ headers['Content-Type'] = 'application/json;charset=utf-8'
362
+ }
363
+ const token = sessionV3.value || readStorageKey(window?.localStorage, 'jvs-access_token')
364
+ if (token && !headers['Authorization'] && !headers['authorization']) {
365
+ headers['Authorization'] = `Bearer ${token}`
366
+ }
367
+ const tenantId = readStorageKey(window?.localStorage, 'jvs-tenantId')
368
+ if (tenantId && !headers['tenant-id']) {
369
+ headers['tenant-id'] = tenantId
370
+ }
371
+ return headers
372
+ }
373
+
374
+ /**
375
+ * 统一安全的 JSON 请求封装
376
+ */
377
+ async function damFetchJson<T = any>(
378
+ pathOrUrl: string,
379
+ options: RequestInit & { params?: Record<string, any> } = {}
380
+ ): Promise<T> {
381
+ const base = damBaseUrl.value
382
+ let fullUrl = pathOrUrl.startsWith('http') || pathOrUrl.startsWith('/jvs-')
383
+ ? pathOrUrl
384
+ : `${base}${pathOrUrl.startsWith('/') ? '' : '/'}${pathOrUrl}`
385
+
386
+ if (options.params) {
387
+ const searchParams = new URLSearchParams()
388
+ Object.entries(options.params).forEach(([k, v]) => {
389
+ if (v !== undefined && v !== null && v !== '') {
390
+ if (Array.isArray(v)) {
391
+ if (v.length > 0) searchParams.append(k, v.join(','))
392
+ } else {
393
+ searchParams.append(k, String(v))
394
+ }
395
+ }
396
+ })
397
+ const qs = searchParams.toString()
398
+ if (qs) {
399
+ fullUrl += (fullUrl.includes('?') ? '&' : '?') + qs
400
+ }
401
+ }
402
+
403
+ const isFormData = typeof FormData !== 'undefined' && options.body instanceof FormData
404
+ const mergedHeaders = {
405
+ ...buildDamHeaders(!isFormData),
406
+ ...((options.headers as Record<string, string>) || {})
407
+ }
408
+ if (isFormData) {
409
+ delete mergedHeaders['Content-Type']
410
+ delete mergedHeaders['content-type']
411
+ }
412
+
413
+ const response = await fetch(fullUrl, {
414
+ ...options,
415
+ credentials: 'include',
416
+ headers: mergedHeaders
417
+ })
418
+
419
+ const rawText = await response.text()
420
+ if (!response.ok) {
421
+ throw new Error(`请求异常 (${response.status})`)
422
+ }
423
+ const trimmed = rawText.trim()
424
+ if (trimmed.startsWith('<') || trimmed.toLowerCase().startsWith('<!doctype')) {
425
+ throw new Error('接口返回了非 JSON 格式响应')
426
+ }
427
+ try {
428
+ return JSON.parse(rawText) as T
429
+ } catch (err: any) {
430
+ throw new Error(`数据解析失败: ${err.message}`)
431
+ }
432
+ }
433
+
434
+ return {
435
+ sessionV3,
436
+ isDamLoggedIn,
437
+ damBaseUrl,
438
+ sharedMaterialMainTab,
439
+ setSharedMaterialMainTab,
440
+ refreshSessionState,
441
+ probeRemoteSessionV3,
442
+ buildDamHeaders,
443
+ damFetchJson
444
+ }
445
+ }