@schema-element-editor/host-sdk 2.1.0 → 2.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.
@@ -0,0 +1,492 @@
1
+ // src/constants.ts
2
+ var DEFAULT_SOURCE_CONFIG = {
3
+ contentSource: "schema-element-editor-content",
4
+ hostSource: "schema-element-editor-host"
5
+ };
6
+ var SDK_COORDINATOR_SOURCE = "schema-element-editor-sdk-coordinator";
7
+ var DEFAULT_MESSAGE_TYPES = {
8
+ getSchema: "GET_SCHEMA",
9
+ updateSchema: "UPDATE_SCHEMA",
10
+ checkPreview: "CHECK_PREVIEW",
11
+ renderPreview: "RENDER_PREVIEW",
12
+ cleanupPreview: "CLEANUP_PREVIEW",
13
+ // 录制模式相关
14
+ startRecording: "START_RECORDING",
15
+ stopRecording: "STOP_RECORDING",
16
+ schemaPush: "SCHEMA_PUSH"
17
+ };
18
+ var SDK_COORDINATION_MESSAGE_TYPES = {
19
+ register: "SDK_REGISTER",
20
+ unregister: "SDK_UNREGISTER",
21
+ query: "SDK_QUERY"
22
+ };
23
+
24
+ // src/coordinator.ts
25
+ function generateSdkId() {
26
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
27
+ return crypto.randomUUID();
28
+ }
29
+ return `sdk-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
30
+ }
31
+ var SdkCoordinator = class {
32
+ constructor(config) {
33
+ /**
34
+ * SDK 销毁标志
35
+ *
36
+ * 作用:防止在 cleanup() 执行期间,监听器移除前仍然响应请求
37
+ *
38
+ * 场景:cleanup() 中先调用 destroy()(设置 isDestroyed = true),
39
+ * 然后才移除 handleMessage 监听器。在这个微小的时间窗口内,
40
+ * 如果插件请求到达,没有 isDestroyed 检查会导致已销毁的 SDK 仍然响应。
41
+ */
42
+ this.isDestroyed = false;
43
+ /**
44
+ * 存储比当前 SDK 优先级更高的其他 SDK ID
45
+ * 按方法分类:如果某个方法的集合不为空,说明有更高优先级的 SDK 应该处理该方法
46
+ *
47
+ * 优化:只为当前 SDK 实现了的方法维护优先级集合
48
+ */
49
+ this.higherLevelSDKs = {};
50
+ /**
51
+ * 存储与当前 SDK 优先级相同的其他 SDK ID
52
+ * 按方法分类:用于判断是否需要在执行失败时跳过响应
53
+ *
54
+ * 当有同级竞争者时,SDK在执行失败/无数据时会跳过响应,让其他SDK有机会响应
55
+ */
56
+ this.sameLevelSDKs = {};
57
+ /**
58
+ * 处理 SDK 协调消息
59
+ */
60
+ this.handleCoordinationMessage = (event) => {
61
+ const isFromSelf = event.source === window;
62
+ const isFromParent = window !== window.top && event.source === window.parent;
63
+ if (!isFromSelf && !isFromParent) return;
64
+ const data = event.data;
65
+ if (!data || data.source !== SDK_COORDINATOR_SOURCE) return;
66
+ switch (data.type) {
67
+ case SDK_COORDINATION_MESSAGE_TYPES.query:
68
+ this.sendRegister();
69
+ break;
70
+ case SDK_COORDINATION_MESSAGE_TYPES.register:
71
+ this.handleSdkRegister(data.payload);
72
+ break;
73
+ case SDK_COORDINATION_MESSAGE_TYPES.unregister:
74
+ this.handleSdkUnregister(data.payload.sdkId);
75
+ break;
76
+ }
77
+ };
78
+ this.sdkId = config.sdkId || generateSdkId();
79
+ this.messageSource = config.messageSource;
80
+ this.level = config.level ?? 0;
81
+ this.methodLevels = config.methodLevels ?? {};
82
+ this.implementedMethods = config.implementedMethods;
83
+ this.implementedMethods.forEach((method) => {
84
+ this.higherLevelSDKs[method] = /* @__PURE__ */ new Set();
85
+ this.sameLevelSDKs[method] = /* @__PURE__ */ new Set();
86
+ });
87
+ }
88
+ /**
89
+ * 初始化协调器
90
+ */
91
+ init() {
92
+ window.addEventListener("message", this.handleCoordinationMessage);
93
+ this.sendQuery();
94
+ console.log("[SDK Coordinator] \u521D\u59CB\u5316\u5E76\u5E7F\u64AD\u6CE8\u518C\u4FE1\u606F:", {
95
+ sdkId: this.sdkId,
96
+ level: this.level,
97
+ methodLevels: this.methodLevels,
98
+ implementedMethods: this.implementedMethods
99
+ });
100
+ this.sendRegister();
101
+ }
102
+ /**
103
+ * 销毁协调器
104
+ */
105
+ destroy() {
106
+ this.isDestroyed = true;
107
+ this.sendUnregister();
108
+ window.removeEventListener("message", this.handleCoordinationMessage);
109
+ Object.values(this.higherLevelSDKs).forEach((set) => set.clear());
110
+ Object.values(this.sameLevelSDKs).forEach((set) => set.clear());
111
+ }
112
+ /**
113
+ * 判断是否应该响应某个方法的请求
114
+ * @param method - 方法名
115
+ * @returns 是否应该响应
116
+ */
117
+ shouldRespond(method) {
118
+ if (this.isDestroyed) return false;
119
+ if (!this.implementedMethods.includes(method)) {
120
+ return false;
121
+ }
122
+ const higherSDKs = this.higherLevelSDKs[method];
123
+ return !higherSDKs || higherSDKs.size === 0;
124
+ }
125
+ /**
126
+ * 判断某个方法是否有相同优先级的竞争者
127
+ * @param method - 方法名
128
+ * @returns 是否存在同级竞争者
129
+ */
130
+ hasSameLevelCompetitors(method) {
131
+ const sameSDKs = this.sameLevelSDKs[method];
132
+ return sameSDKs ? sameSDKs.size > 0 : false;
133
+ }
134
+ /**
135
+ * 获取方法的优先级
136
+ */
137
+ getMethodLevel(method) {
138
+ return this.methodLevels[method] ?? this.level;
139
+ }
140
+ /**
141
+ * 处理其他 SDK 的注册
142
+ */
143
+ handleSdkRegister(info) {
144
+ if (info.sdkId === this.sdkId) return;
145
+ if (info.messageSource !== this.messageSource) return;
146
+ console.log("[SDK Coordinator] \u68C0\u6D4B\u5230\u5176\u4ED6 SDK \u6CE8\u518C:", {
147
+ otherSdkId: info.sdkId,
148
+ otherLevel: info.level,
149
+ otherImplementedMethods: info.implementedMethods,
150
+ mySdkId: this.sdkId,
151
+ myLevel: this.level,
152
+ myImplementedMethods: this.implementedMethods
153
+ });
154
+ this.implementedMethods.forEach((method) => {
155
+ if (!info.implementedMethods.includes(method)) {
156
+ return;
157
+ }
158
+ const myLevel = this.getMethodLevel(method);
159
+ const otherLevel = info.methodLevels[method] ?? info.level;
160
+ console.log(`[SDK Coordinator] \u65B9\u6CD5 ${method} \u4F18\u5148\u7EA7\u5BF9\u6BD4:`, {
161
+ myLevel,
162
+ otherLevel,
163
+ result: otherLevel > myLevel ? "\u5BF9\u65B9\u66F4\u9AD8" : otherLevel === myLevel ? "\u540C\u7EA7" : "\u6211\u65B9\u66F4\u9AD8"
164
+ });
165
+ if (otherLevel > myLevel) {
166
+ this.higherLevelSDKs[method].add(info.sdkId);
167
+ this.sameLevelSDKs[method].delete(info.sdkId);
168
+ } else if (otherLevel === myLevel) {
169
+ this.sameLevelSDKs[method].add(info.sdkId);
170
+ this.higherLevelSDKs[method].delete(info.sdkId);
171
+ } else {
172
+ this.higherLevelSDKs[method].delete(info.sdkId);
173
+ this.sameLevelSDKs[method].delete(info.sdkId);
174
+ }
175
+ });
176
+ }
177
+ /**
178
+ * 处理其他 SDK 的注销
179
+ */
180
+ handleSdkUnregister(sdkId) {
181
+ Object.values(this.higherLevelSDKs).forEach((set) => {
182
+ set.delete(sdkId);
183
+ });
184
+ Object.values(this.sameLevelSDKs).forEach((set) => {
185
+ set.delete(sdkId);
186
+ });
187
+ }
188
+ /**
189
+ * 发送查询消息
190
+ */
191
+ sendQuery() {
192
+ const message = {
193
+ source: SDK_COORDINATOR_SOURCE,
194
+ type: SDK_COORDINATION_MESSAGE_TYPES.query,
195
+ payload: { sdkId: this.sdkId }
196
+ };
197
+ this.postCoordinationMessage(message);
198
+ }
199
+ /**
200
+ * 发送注册消息
201
+ */
202
+ sendRegister() {
203
+ const message = {
204
+ source: SDK_COORDINATOR_SOURCE,
205
+ type: SDK_COORDINATION_MESSAGE_TYPES.register,
206
+ payload: {
207
+ sdkId: this.sdkId,
208
+ messageSource: this.messageSource,
209
+ level: this.level,
210
+ methodLevels: this.methodLevels,
211
+ implementedMethods: this.implementedMethods
212
+ }
213
+ };
214
+ this.postCoordinationMessage(message);
215
+ }
216
+ /**
217
+ * 发送注销消息
218
+ */
219
+ sendUnregister() {
220
+ const message = {
221
+ source: SDK_COORDINATOR_SOURCE,
222
+ type: SDK_COORDINATION_MESSAGE_TYPES.unregister,
223
+ payload: { sdkId: this.sdkId }
224
+ };
225
+ this.postCoordinationMessage(message);
226
+ }
227
+ /**
228
+ * 发送协调消息
229
+ */
230
+ postCoordinationMessage(message) {
231
+ window.postMessage(message, "*");
232
+ if (window.top && window.top !== window) {
233
+ window.top.postMessage(message, "*");
234
+ }
235
+ }
236
+ };
237
+
238
+ // src/bridge.ts
239
+ var METHOD_NAMES = {
240
+ GET_SCHEMA: "getSchema",
241
+ UPDATE_SCHEMA: "updateSchema",
242
+ CHECK_PREVIEW: "checkPreview",
243
+ RENDER_PREVIEW: "renderPreview",
244
+ CLEANUP_PREVIEW: "cleanupPreview",
245
+ START_RECORDING: "startRecording",
246
+ STOP_RECORDING: "stopRecording"
247
+ };
248
+ function shouldSkipFailedResponse(method, result) {
249
+ switch (method) {
250
+ case METHOD_NAMES.GET_SCHEMA:
251
+ return result.success === true && result.data === void 0;
252
+ case METHOD_NAMES.UPDATE_SCHEMA:
253
+ return result.success === false;
254
+ case METHOD_NAMES.RENDER_PREVIEW:
255
+ case METHOD_NAMES.CLEANUP_PREVIEW:
256
+ return result.success === false;
257
+ case METHOD_NAMES.CHECK_PREVIEW:
258
+ case METHOD_NAMES.START_RECORDING:
259
+ case METHOD_NAMES.STOP_RECORDING:
260
+ return false;
261
+ default:
262
+ return false;
263
+ }
264
+ }
265
+ function createSchemaElementEditorBridge(config) {
266
+ const {
267
+ getSchema,
268
+ updateSchema,
269
+ renderPreview,
270
+ sourceConfig,
271
+ messageTypes,
272
+ sdkId,
273
+ level,
274
+ methodLevels
275
+ } = config;
276
+ const mergedSourceConfig = {
277
+ ...DEFAULT_SOURCE_CONFIG,
278
+ ...sourceConfig
279
+ };
280
+ const mergedMessageTypes = {
281
+ ...DEFAULT_MESSAGE_TYPES,
282
+ ...messageTypes
283
+ };
284
+ const implementedMethods = [];
285
+ if (typeof getSchema === "function") implementedMethods.push(METHOD_NAMES.GET_SCHEMA);
286
+ if (typeof updateSchema === "function") implementedMethods.push(METHOD_NAMES.UPDATE_SCHEMA);
287
+ if (renderPreview !== void 0) {
288
+ console.log("[SDK] renderPreview \u4E0D\u662F undefined\uFF0C\u5C06\u53C2\u4E0E\u9884\u89C8\u65B9\u6CD5\u7ADE\u4E89:", {
289
+ renderPreview,
290
+ isNull: renderPreview === null,
291
+ isFunction: typeof renderPreview === "function",
292
+ level
293
+ });
294
+ implementedMethods.push(
295
+ METHOD_NAMES.CHECK_PREVIEW,
296
+ METHOD_NAMES.RENDER_PREVIEW,
297
+ METHOD_NAMES.CLEANUP_PREVIEW
298
+ );
299
+ } else {
300
+ console.log("[SDK] renderPreview \u662F undefined\uFF0C\u4E0D\u53C2\u4E0E\u9884\u89C8\u65B9\u6CD5\u7ADE\u4E89");
301
+ }
302
+ implementedMethods.push(METHOD_NAMES.START_RECORDING, METHOD_NAMES.STOP_RECORDING);
303
+ const coordinator = new SdkCoordinator({
304
+ sdkId,
305
+ messageSource: mergedSourceConfig.contentSource,
306
+ level,
307
+ methodLevels,
308
+ implementedMethods
309
+ });
310
+ coordinator.init();
311
+ let previewCleanupFn = null;
312
+ const recordingParams = /* @__PURE__ */ new Set();
313
+ const currentConfig = { getSchema, updateSchema, renderPreview };
314
+ const methodTypeToName = {
315
+ [mergedMessageTypes.getSchema]: METHOD_NAMES.GET_SCHEMA,
316
+ [mergedMessageTypes.updateSchema]: METHOD_NAMES.UPDATE_SCHEMA,
317
+ [mergedMessageTypes.checkPreview]: METHOD_NAMES.CHECK_PREVIEW,
318
+ [mergedMessageTypes.renderPreview]: METHOD_NAMES.RENDER_PREVIEW,
319
+ [mergedMessageTypes.cleanupPreview]: METHOD_NAMES.CLEANUP_PREVIEW,
320
+ [mergedMessageTypes.startRecording]: METHOD_NAMES.START_RECORDING,
321
+ [mergedMessageTypes.stopRecording]: METHOD_NAMES.STOP_RECORDING
322
+ };
323
+ const getMethodNameByType = (type) => {
324
+ return methodTypeToName[type] ?? null;
325
+ };
326
+ const sendResponse = (requestId, result) => {
327
+ const message = {
328
+ source: mergedSourceConfig.hostSource,
329
+ requestId,
330
+ ...result
331
+ };
332
+ const targetWindow = window.top ?? window;
333
+ targetWindow.postMessage(message, "*");
334
+ };
335
+ const pushSchema = (params, data) => {
336
+ if (!recordingParams.has(params)) {
337
+ return;
338
+ }
339
+ const message = {
340
+ source: mergedSourceConfig.hostSource,
341
+ type: mergedMessageTypes.schemaPush,
342
+ payload: {
343
+ success: true,
344
+ data,
345
+ params
346
+ }
347
+ };
348
+ const targetWindow = window.top ?? window;
349
+ targetWindow.postMessage(message, "*");
350
+ };
351
+ const handleMessage = (event) => {
352
+ const isFromSelf = event.source === window;
353
+ const isFromParent = window !== window.top && event.source === window.parent;
354
+ if (!isFromSelf && !isFromParent) return;
355
+ if (!event.data || event.data.source !== mergedSourceConfig.contentSource) return;
356
+ const { type, payload, requestId } = event.data;
357
+ if (!requestId) return;
358
+ const methodName = getMethodNameByType(type);
359
+ if (!methodName) return;
360
+ if (!coordinator.shouldRespond(methodName)) {
361
+ return;
362
+ }
363
+ const { getSchema: getSchema2, updateSchema: updateSchema2, renderPreview: renderPreview2 } = currentConfig;
364
+ let result;
365
+ switch (type) {
366
+ case mergedMessageTypes.getSchema: {
367
+ if (typeof getSchema2 !== "function") {
368
+ return;
369
+ }
370
+ const params = String(payload?.params ?? "");
371
+ try {
372
+ const data = getSchema2(params);
373
+ result = { success: true, data };
374
+ } catch (error) {
375
+ result = {
376
+ success: false,
377
+ error: error instanceof Error ? error.message : "\u83B7\u53D6 Schema \u5931\u8D25"
378
+ };
379
+ }
380
+ break;
381
+ }
382
+ case mergedMessageTypes.updateSchema: {
383
+ if (typeof updateSchema2 !== "function") {
384
+ return;
385
+ }
386
+ const schema = payload?.schema;
387
+ const params = String(payload?.params ?? "");
388
+ try {
389
+ const success = updateSchema2(schema, params);
390
+ result = { success };
391
+ } catch (error) {
392
+ result = {
393
+ success: false,
394
+ error: error instanceof Error ? error.message : "\u66F4\u65B0 Schema \u5931\u8D25"
395
+ };
396
+ }
397
+ break;
398
+ }
399
+ case mergedMessageTypes.checkPreview: {
400
+ const exists = typeof renderPreview2 === "function";
401
+ console.log("[SDK] CHECK_PREVIEW \u54CD\u5E94:", {
402
+ renderPreview: renderPreview2,
403
+ isNull: renderPreview2 === null,
404
+ isFunction: typeof renderPreview2 === "function",
405
+ exists,
406
+ level,
407
+ sdkId
408
+ });
409
+ result = { exists };
410
+ break;
411
+ }
412
+ case mergedMessageTypes.renderPreview: {
413
+ if (typeof renderPreview2 !== "function") {
414
+ result = { success: false, error: "\u9884\u89C8\u529F\u80FD\u672A\u914D\u7F6E" };
415
+ break;
416
+ }
417
+ const schema = payload?.schema;
418
+ const containerId = String(payload?.containerId ?? "");
419
+ try {
420
+ if (previewCleanupFn) {
421
+ previewCleanupFn();
422
+ previewCleanupFn = null;
423
+ }
424
+ const cleanup = renderPreview2(schema, containerId);
425
+ if (typeof cleanup === "function") {
426
+ previewCleanupFn = cleanup;
427
+ }
428
+ result = { success: true };
429
+ } catch (error) {
430
+ result = {
431
+ success: false,
432
+ error: error instanceof Error ? error.message : "\u6E32\u67D3\u9884\u89C8\u5931\u8D25"
433
+ };
434
+ }
435
+ break;
436
+ }
437
+ case mergedMessageTypes.cleanupPreview: {
438
+ try {
439
+ if (previewCleanupFn) {
440
+ previewCleanupFn();
441
+ previewCleanupFn = null;
442
+ }
443
+ result = { success: true };
444
+ } catch (error) {
445
+ result = {
446
+ success: false,
447
+ error: error instanceof Error ? error.message : "\u6E05\u7406\u9884\u89C8\u5931\u8D25"
448
+ };
449
+ }
450
+ break;
451
+ }
452
+ case mergedMessageTypes.startRecording: {
453
+ const params = String(payload?.params ?? "");
454
+ recordingParams.add(params);
455
+ result = { success: true };
456
+ break;
457
+ }
458
+ case mergedMessageTypes.stopRecording: {
459
+ const params = String(payload?.params ?? "");
460
+ recordingParams.delete(params);
461
+ result = { success: true };
462
+ break;
463
+ }
464
+ default:
465
+ return;
466
+ }
467
+ const hasSameLevelSdks = coordinator.hasSameLevelCompetitors(methodName);
468
+ if (hasSameLevelSdks && shouldSkipFailedResponse(methodName, result)) {
469
+ return;
470
+ }
471
+ sendResponse(requestId, result);
472
+ };
473
+ window.addEventListener("message", handleMessage);
474
+ return {
475
+ cleanup: () => {
476
+ coordinator.destroy();
477
+ window.removeEventListener("message", handleMessage);
478
+ if (previewCleanupFn) {
479
+ previewCleanupFn();
480
+ previewCleanupFn = null;
481
+ }
482
+ recordingParams.clear();
483
+ },
484
+ recording: {
485
+ push: pushSchema
486
+ }
487
+ };
488
+ }
489
+
490
+ export {
491
+ createSchemaElementEditorBridge
492
+ };