@sublane/core 0.1.2 → 0.2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sublane/core",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "exports": {
package/src/contract.ts CHANGED
@@ -28,6 +28,9 @@ export interface VideoSubtitleCapabilities {
28
28
  bilingualDownload: boolean
29
29
  sidebar: boolean
30
30
  manualTimingOffset: boolean
31
+ /** 本版支持 detached 渲染(0.2.0,F-27);宿主 feature-detect 的首选旗标(§7-4),
32
+ * 方法存在性探测仅作兜底。供应商实现 createDetachedInstance 后置位。 */
33
+ detachedRender?: boolean
31
34
  }
32
35
 
33
36
  export type SettingsField =
@@ -83,6 +86,17 @@ export interface VideoSubtitlePlugin {
83
86
  matches: string[]
84
87
  }>
85
88
  createInstance(ctx: PluginMountContext): VideoSubtitlePluginInstance
89
+ /** 0.2.0 可选(F-27/P1):在宿主提供的任意 video 元素上创建**独立的**渲染实例。
90
+ * 语义要求:与 live mount 并存(R1,状态零共享);共享 settings 解析/样式注入/布局
91
+ * 代码路径(R2,禁止 detached 专用样式常量);注入轨视为 untrusted(R4,超限拒载);
92
+ * live 行为零变化(N2)。不支持时缺席于 session.handles(宿主按 A8 降级)。
93
+ * ctx.emitConfigPatch 已被编排器中立化(M1)——detached 的 settings 权威在框架键。 */
94
+ createDetachedInstance?(
95
+ ctx: DetachedInstanceContext,
96
+ video: HTMLVideoElement,
97
+ source: TrackSource,
98
+ options?: DetachedMountOptions,
99
+ ): Promise<VideoSubtitlePluginInstance & { detach(): DetachedHandle }>
86
100
  }
87
101
 
88
102
  /** background 侧:一个扩展只有一个 service worker,供应商在此登记私产后端 */
@@ -102,3 +116,54 @@ export interface FrameworkStoragePort {
102
116
  * 等对端 onDisconnect 未必到来)。框架在重试前调用。 */
103
117
  reset?(): void
104
118
  }
119
+
120
+ // ── detached 渲染会话契约(0.2.0,F-27,ReplayChannel P0)──────────────────
121
+ // 设计文档:docs/integrations/2026-11-17-replaychannel-proposal.md;裁决回函:
122
+ // docs/integrations/2026-11-18-replaychannel-adjudication.md(Q1-Q8 裁决 + M1/M2 修订 + Q9)。
123
+
124
+ /** 注入轨的标准 cue 形状(P0)。时间语义:活跃区间 = [tsMs, tsMs + durationMs);
125
+ * durationMs 缺省按下一条 tsMs 推断,末条视为播到轨终点。与 fluent
126
+ * VideoSubtitleCue{startMs,durationMs,text} 和 read-frog
127
+ * SubtitlesFragment{text,start,end,translation?} 可无损互转(契约测试夹具义务)。 */
128
+ export interface SubtitleCue {
129
+ tsMs: number
130
+ durationMs?: number
131
+ original: string
132
+ /** 按 SupplierId 的译文;缺项/null = 该家未译(detached 渲染降级为原文行,无 pending 态,R5) */
133
+ translations?: Partial<Record<SupplierId, string | null>>
134
+ }
135
+
136
+ /** 数据注入源(P0)。宿主实现;vendor 消费。getTrack 可返回 null(暂无轨 = 空渲染);
137
+ * onUpdate 用于流式补译/追加(返回取消监听函数)。 */
138
+ export interface TrackSource {
139
+ getTrack(): Promise<{ cues: SubtitleCue[] } | null>
140
+ onUpdate?(cb: (track: { cues: SubtitleCue[] }) => void): () => void
141
+ /** 默认 false:注入轨自带译文即渲染,不触发 vendor 翻译请求(N4,防隐性调用量) */
142
+ allowVendorTranslation?: boolean
143
+ }
144
+
145
+ export interface DetachedMountOptions {
146
+ /** injected-only(默认):纯注入数据渲染;hybrid 远期(P2 后另议,Q7 裁决不入 0.2.0) */
147
+ dataMode?: 'injected-only'
148
+ /** 宿主侧取消信号(如 Modal 关闭);abort 即全量卸载 */
149
+ signal?: AbortSignal
150
+ }
151
+
152
+ /** detached 会话对宿主暴露的生命周期句柄;unmount 与 setSource 均不重挂 DOM 之外的对象 */
153
+ export interface DetachedHandle {
154
+ unmount(): void | Promise<void>
155
+ /** 替换数据源(如切换 Clip 区间);不重挂 DOM */
156
+ setSource(source: TrackSource): void
157
+ }
158
+
159
+ /** detached 会话上下文:与 live PluginMountContext 同形,但编排器已将 emitConfigPatch
160
+ * 中立化为空实现(M1)——detached 的 settings 权威在框架键,实例不得回写(防污染 live)。 */
161
+ export interface DetachedInstanceContext extends PluginMountContext {}
162
+
163
+ /** 信任边界上限(R4):契约默认沿用 fluent 页面注入既有上限(≤20,000 cues / ≤4MB / ≤4096 字符每 cue);
164
+ * per-supplier 覆盖经 createDetachedSession 的 limits 选项(M3/Q9) */
165
+ export interface TrackLimits {
166
+ maxCues: number
167
+ maxTotalBytes: number
168
+ maxCharsPerCue: number
169
+ }
package/src/runtime.ts CHANGED
@@ -6,8 +6,9 @@
6
6
  * 模块边界:零 DOM、零字幕业务逻辑(宪法 NO-3);只编排实例生命周期,渲染/翻译/抓取全部归供应商。
7
7
  */
8
8
  import type {
9
- FrameworkStoragePort, PluginMountContext, SupplierRuntimeConfig,
9
+ FrameworkStoragePort, PluginMountContext, SupplierRuntimeConfig, LaneAssignment,
10
10
  VideoSubtitlePlugin, VideoSubtitlePluginInstance,
11
+ SubtitleCue, TrackSource, DetachedMountOptions, DetachedHandle, DetachedInstanceContext, TrackLimits,
11
12
  } from './contract.ts'
12
13
 
13
14
  export const FRAMEWORK_STORAGE_KEY = 'sublane:plugins.videoSubtitle'
@@ -43,6 +44,46 @@ export function unionMatches(plugins: Array<Pick<VideoSubtitlePlugin, 'capabilit
43
44
  return [...matches]
44
45
  }
45
46
 
47
+ /** 诊断标记:仅浏览器环境写 dataset(框架零 DOM 约束;node:test 无 document)。
48
+ * 作用域在模块层:live 框架与 detached 会话(F-27)共用;曾定义在 readConfig 体内,
49
+ * 降级自愈越作用域引用即 ReferenceError 崩死(0.1.3 修复 F-25)——提升至此杜绝复发。 */
50
+ function makeBootMarker(): (name: string) => void {
51
+ return (name: string) => {
52
+ if (typeof document === 'undefined') return
53
+ const el = document.documentElement
54
+ el.dataset.sublaneBoot = `${el.dataset.sublaneBoot ?? ''}|rc:${name}`.slice(-400)
55
+ }
56
+ }
57
+
58
+ /** 框架配置读取:重试/降级逻辑(live 框架与 detached 会话共用,F-27/0.2.0)。 */
59
+ async function readFrameworkConfig(storage: FrameworkStoragePort, mark: (name: string) => void): Promise<{ config: FrameworkConfig; degraded: boolean }> {
60
+ mark('get-begin')
61
+ // 存储端口是可靠性单点(中继 Port 可能因 SW 冷启动/休眠变僵尸:请求无应答且不触发
62
+ // onDisconnect;或 SW 断线瞬间请求在途被 reject)。单次读取限时 1.5s,超时或拒绝均
63
+ // reset() 立即重建通道再重试,共 3 次——拒绝若逃逸会经 onChange→applyConfig 路径变
64
+ // uncaught(真机 Errors 页实证),此处按可重试吸收;最坏 ~4.5s 内拿到配置或判空继续,
65
+ // storagePort.onChange 在端口恢复后仍会触发 applyConfig 补挂载(鲁棒:不信任任何未验证假设)。
66
+ for (let attempt = 1; attempt <= 3; attempt += 1) {
67
+ const saved = (await Promise.race([
68
+ storage.get(FRAMEWORK_STORAGE_KEY).catch((error: Error) => {
69
+ mark(`get-rejected:${attempt}:${error?.message?.slice(0, 24) ?? 'unknown'}`)
70
+ return 'REJECTED' as const
71
+ }),
72
+ new Promise<'TIMEOUT'>((resolve) => setTimeout(() => resolve('TIMEOUT'), 1500)),
73
+ ])) as FrameworkConfig | 'TIMEOUT' | 'REJECTED' | undefined
74
+ if (saved === 'TIMEOUT' || saved === 'REJECTED') {
75
+ if (saved === 'TIMEOUT') mark(`get-timeout:${attempt}`)
76
+ storage.reset?.()
77
+ continue
78
+ }
79
+ mark(`get-done:${saved ? Object.keys(saved.suppliers ?? {}).join('+') || 'empty' : 'null'}`)
80
+ if (!saved || typeof saved !== 'object') return { config: { version: 1, suppliers: {} }, degraded: false }
81
+ return { config: saved, degraded: false }
82
+ }
83
+ mark('get-exhausted')
84
+ return { config: { version: 1, suppliers: {} }, degraded: true }
85
+ }
86
+
46
87
  export interface CreateFrameworkOptions {
47
88
  ctx: { onInvalidated(cb: () => void): void }
48
89
  plugins: VideoSubtitlePlugin[]
@@ -57,41 +98,12 @@ export function createVideoSubtitleFramework({ ctx, plugins, storage: storagePor
57
98
  * 只能靠存储变更事件才恢复——而卡死场景恰恰没有事件。降阶后有限退避重读,SW 恢复
58
99
  * 即自动点亮,无需用户刷新)。 */
59
100
  let readDegraded = false
101
+ const mark = makeBootMarker()
60
102
 
61
103
  async function readConfig(): Promise<FrameworkConfig> {
62
- // 诊断标记:仅浏览器环境写 dataset(框架零 DOM 约束;node:test 无 document)
63
- const mark = (name: string) => {
64
- if (typeof document === 'undefined') return
65
- const el = document.documentElement
66
- el.dataset.sublaneBoot = `${el.dataset.sublaneBoot ?? ''}|rc:${name}`.slice(-400)
67
- }
68
- mark('get-begin')
69
- // 存储端口是可靠性单点(中继 Port 可能因 SW 冷启动/休眠变僵尸:请求无应答且不触发
70
- // onDisconnect;或 SW 断线瞬间请求在途被 reject)。单次读取限时 1.5s,超时或拒绝均
71
- // reset() 立即重建通道再重试,共 3 次——拒绝若逃逸会经 onChange→applyConfig 路径变
72
- // uncaught(真机 Errors 页实证),此处按可重试吸收;最坏 ~4.5s 内拿到配置或判空继续,
73
- // storagePort.onChange 在端口恢复后仍会触发 applyConfig 补挂载(鲁棒:不信任任何未验证假设)。
74
- for (let attempt = 1; attempt <= 3; attempt += 1) {
75
- const saved = (await Promise.race([
76
- storagePort.get(FRAMEWORK_STORAGE_KEY).catch((error: Error) => {
77
- mark(`get-rejected:${attempt}:${error?.message?.slice(0, 24) ?? 'unknown'}`)
78
- return 'REJECTED' as const
79
- }),
80
- new Promise<'TIMEOUT'>((resolve) => setTimeout(() => resolve('TIMEOUT'), 1500)),
81
- ])) as FrameworkConfig | 'TIMEOUT' | 'REJECTED' | undefined
82
- if (saved === 'TIMEOUT' || saved === 'REJECTED') {
83
- if (saved === 'TIMEOUT') mark(`get-timeout:${attempt}`)
84
- storagePort.reset?.()
85
- continue
86
- }
87
- mark(`get-done:${saved ? Object.keys(saved.suppliers ?? {}).join('+') || 'empty' : 'null'}`)
88
- readDegraded = false
89
- if (!saved || typeof saved !== 'object') return { version: 1, suppliers: {} }
90
- return saved
91
- }
92
- mark('get-exhausted')
93
- readDegraded = true
94
- return { version: 1, suppliers: {} }
104
+ const { config, degraded } = await readFrameworkConfig(storagePort, mark)
105
+ readDegraded = degraded
106
+ return config
95
107
  }
96
108
 
97
109
  function mountInstance(plugin: VideoSubtitlePlugin, config: SupplierRuntimeConfig) {
@@ -146,7 +158,7 @@ export function createVideoSubtitleFramework({ ctx, plugins, storage: storagePor
146
158
  const settingsChanged = JSON.stringify(run.config.settings) !== JSON.stringify(next.settings)
147
159
  if (laneChanged || settingsChanged) {
148
160
  run.config = next
149
- try { run.instance.setConfig(next) } catch (error) { log(`[${plugin.id}] setConfig 失败:${error?.message ?? error}`) }
161
+ try { run.instance.setConfig(next) } catch (error: unknown) { log(`[${plugin.id}] setConfig 失败:${error instanceof Error ? error.message : error}`) }
150
162
  }
151
163
  })
152
164
  }
@@ -180,3 +192,137 @@ export function createVideoSubtitleFramework({ ctx, plugins, storage: storagePor
180
192
  },
181
193
  }
182
194
  }
195
+
196
+ // ── detached 渲染会话(0.2.0,F-27,ReplayChannel P0)─────────────────────────
197
+ // 裁决回函:docs/integrations/2026-11-18-replaychannel-adjudication.md(Q1-Q8 裁决 + M1/M2 修订 + Q9)。
198
+ // 宪法边界:本节零 DOM(video 元素由宿主传入)、零字幕业务逻辑;编排=配置读取+车道分配+实例装配+生命周期。
199
+
200
+ /** 契约默认信任边界(R4,沿用 fluent 页面注入既有上限);per-supplier 覆盖经 limits 选项(M3/Q9) */
201
+ export const TRACK_LIMITS: TrackLimits = { maxCues: 20_000, maxTotalBytes: 4 * 1024 * 1024, maxCharsPerCue: 4096 }
202
+
203
+ /** 超限错误:code 恒为 'REPLAY_TRACK_LIMIT',消费方按 code 判别(勿依赖类型链)。
204
+ * 注意:本仓测试走 node --experimental-strip-types(strip-only),禁用参数属性等不可擦除语法。 */
205
+ export class ReplayTrackLimitError extends Error {
206
+ override name = 'ReplayTrackLimitError'
207
+ readonly code = 'REPLAY_TRACK_LIMIT' as const
208
+ readonly axis: keyof TrackLimits
209
+ readonly limit: number
210
+ readonly actual: number
211
+ constructor(axis: keyof TrackLimits, limit: number, actual: number) {
212
+ super(`REPLAY_TRACK_LIMIT: ${axis} 实际 ${actual} 超限 ${limit}`)
213
+ this.axis = axis
214
+ this.limit = limit
215
+ this.actual = actual
216
+ }
217
+ }
218
+
219
+ /** 信任边界校验(R4):注入 cue 视为 untrusted,三轴判超限,超限抛 ReplayTrackLimitError */
220
+ export function validateTrackCues(cues: SubtitleCue[], limits: Partial<TrackLimits> = {}): void {
221
+ const lim: TrackLimits = { ...TRACK_LIMITS, ...limits }
222
+ if (cues.length > lim.maxCues) throw new ReplayTrackLimitError('maxCues', lim.maxCues, cues.length)
223
+ const enc = new TextEncoder()
224
+ let totalBytes = 0
225
+ for (const cue of cues) {
226
+ if (cue.original.length > lim.maxCharsPerCue) throw new ReplayTrackLimitError('maxCharsPerCue', lim.maxCharsPerCue, cue.original.length)
227
+ totalBytes += enc.encode(cue.original).length
228
+ if (cue.translations) for (const t of Object.values(cue.translations)) if (t != null) totalBytes += enc.encode(t).length
229
+ if (totalBytes > lim.maxTotalBytes) throw new ReplayTrackLimitError('maxTotalBytes', lim.maxTotalBytes, totalBytes)
230
+ }
231
+ }
232
+
233
+ export interface CreateDetachedSessionOptions {
234
+ ctx: { onInvalidated(cb: () => void): void }
235
+ plugins: VideoSubtitlePlugin[]
236
+ storage: FrameworkStoragePort
237
+ video: HTMLVideoElement
238
+ source: TrackSource
239
+ options?: DetachedMountOptions
240
+ /** true = 挂载时快照 settings 并冻结;false/缺省 = 实时跟随框架键(onChange→setConfig,与 live 一致) */
241
+ freezeConfig?: boolean
242
+ /** per-supplier 信任边界覆盖(M3/Q9):缺省用 TRACK_LIMITS;超限者拒载(缺席 handles),他者不受影响 */
243
+ limits?: Partial<Record<string, Partial<TrackLimits>>>
244
+ log?: (msg: string) => void
245
+ }
246
+
247
+ export interface DetachedSession {
248
+ /** 仅含 enabled 且支持 createDetachedInstance 且信任边界通过者的句柄;其余如实缺席(A8/R7) */
249
+ handles: Map<string, DetachedHandle>
250
+ dispose(): Promise<void>
251
+ }
252
+
253
+ /** detached 渲染会话编排器(F-27/P0):「配置读取+车道分配+实例装配+生命周期」在宿主注入场景的重放。
254
+ * 零 DOM(video 由宿主传入);settings 权威在框架键(Q2);车道按 detached 参与者分配(G4),热更不重排(M2/Q3)。 */
255
+ export async function createDetachedSession(opts: CreateDetachedSessionOptions): Promise<DetachedSession> {
256
+ const { ctx, plugins, storage, video, source, options, freezeConfig = false, limits = {}, log = () => {} } = opts
257
+ const mark = makeBootMarker()
258
+ const records: Array<{ id: string; instance: VideoSubtitlePluginInstance; handle: DetachedHandle; lane: LaneAssignment }> = []
259
+ const handles = new Map<string, DetachedHandle>()
260
+ let offChange: (() => void) | null = null
261
+ let disposed = false
262
+ const dispose = async (): Promise<void> => {
263
+ if (disposed) return
264
+ disposed = true
265
+ offChange?.()
266
+ for (const r of records) {
267
+ await Promise.resolve(r.handle.unmount()).catch((error: unknown) => log(`[${r.id}] detached unmount 失败:${error instanceof Error ? error.message : error}`))
268
+ }
269
+ records.length = 0
270
+ handles.clear()
271
+ }
272
+
273
+ // 配置读取:复用 live 同款重试/降级逻辑。降级 → suppliers 空 → handles 空(如实上报宿主,
274
+ // 宿主可重建会话重试);detached 会话生命周期短(如 Modal),不挂 live 的自愈循环。
275
+ const { config: frameworkConfig, degraded } = await readFrameworkConfig(storage, mark)
276
+ if (degraded) log('detached 会话:框架配置读取降级——handles 为空,请重建会话重试')
277
+ const enabledIds = new Set(Object.entries(frameworkConfig.suppliers ?? {}).filter(([, e]) => e.enabled).map(([id]) => id))
278
+ // feature-detect(A8):enabled 且实现 createDetachedInstance 者参与;其余如实缺席不抛
279
+ const capable = plugins.filter((p): p is VideoSubtitlePlugin & { createDetachedInstance: NonNullable<VideoSubtitlePlugin['createDetachedInstance']> } => enabledIds.has(p.id) && typeof p.createDetachedInstance === 'function')
280
+
281
+ // pass 1 信任边界预检(R4/M3):per-supplier 限额,超限者拒载(缺席+日志),他者不受影响(R7/A7)
282
+ const admitted: typeof capable = []
283
+ for (const plugin of capable) {
284
+ try {
285
+ const track = await source.getTrack()
286
+ if (track) validateTrackCues(track.cues, limits[plugin.id])
287
+ admitted.push(plugin)
288
+ } catch (error) {
289
+ const code = error instanceof ReplayTrackLimitError ? 'REPLAY_TRACK_LIMIT' : 'GET_TRACK_FAILED'
290
+ log(`[${plugin.id}] detached 预检失败(${code}):${error instanceof Error ? error.message : error}——该家拒载,其余不受影响`)
291
+ }
292
+ }
293
+
294
+ // pass 2 车道分配(算法同 applyConfig:133-139)+ 实例创建
295
+ for (const [index, plugin] of admitted.entries()) {
296
+ const lane = { index, count: admitted.length }
297
+ const ctxForDetached: DetachedInstanceContext = {
298
+ contentScript: ctx,
299
+ config: { enabled: true, lane, settings: frameworkConfig.suppliers[plugin.id]?.settings ?? {} },
300
+ emitConfigPatch: () => {}, // M1:中立化——detached 的 settings 权威在框架键,实例不得回写
301
+ }
302
+ const instance = await plugin.createDetachedInstance(ctxForDetached, video, source, options)
303
+ await Promise.resolve(instance.mount()).catch((error: unknown) => log(`[${plugin.id}] detached mount 失败:${error instanceof Error ? error.message : error}`))
304
+ const handle = instance.detach()
305
+ records.push({ id: plugin.id, instance, handle, lane })
306
+ handles.set(plugin.id, handle)
307
+ }
308
+
309
+ // 热更(Q2 默认跟随 + M2 lane 保留):onChange → 仅替换 settings,lane 以 detached 分配为准(Q3:重排靠重建会话)
310
+ if (!freezeConfig && admitted.length > 0) {
311
+ offChange = storage.onChange((key) => {
312
+ if (key !== FRAMEWORK_STORAGE_KEY || disposed) return
313
+ void (async () => {
314
+ const { config: next } = await readFrameworkConfig(storage, mark)
315
+ for (const r of records) {
316
+ const entry = next.suppliers[r.id]
317
+ if (!entry?.enabled) { log(`[${r.id}] detached 会话内 disabled——忽略(变更参与集请重建会话,Q3)`); continue }
318
+ r.instance.setConfig({ enabled: true, lane: r.lane, settings: entry.settings ?? {} })
319
+ }
320
+ })().catch((error: unknown) => log(`detached 热更失败:${error instanceof Error ? error.message : error}`))
321
+ })
322
+ }
323
+
324
+ ctx.onInvalidated(() => { void dispose() })
325
+ options?.signal?.addEventListener('abort', () => { void dispose() }, { once: true })
326
+ if (options?.signal?.aborted) void dispose()
327
+ return { handles, dispose }
328
+ }