@dajiaoai/algeo-sdk 2.16.0 → 2.16.2

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  大角几何内嵌画板 SDK,支持在任意网页中嵌入几何画板,通过 postMessage 与内嵌页通信。
4
4
 
5
- 当前版本:**2.16.0**。版本变更与升级注意事项见 [GitHub Release](https://github.com/dajiaoai/algeo-sdk/releases/tag/2.16.0)。
5
+ 当前版本:**2.16.2**。版本变更与升级注意事项见 [GitHub Release](https://github.com/dajiaoai/algeo-sdk/releases/tag/2.16.2)。
6
6
 
7
7
  ## 交流与支持
8
8
 
@@ -35,6 +35,15 @@ npm install @dajiaoai/algeo-sdk
35
35
 
36
36
  ## 使用方式
37
37
 
38
+ ### 本地使用
39
+
40
+ 通过 `file://` 直接打开本地文件,或通过 `localhost`、`127.0.0.1` 访问本地服务时,演示和编辑模式都可以省略 `auth`。本地联调应用授权时,请使用本地 HTTP 服务并配置 `auth.appId` 和域名白名单。详见 [SDK 鉴权说明](https://open.dajiaoai.com/sdk/2/auth)。
41
+
42
+ ```javascript
43
+ const presentation = await createPresentation(container, { shareId: '33TA3484' });
44
+ const editor = await createEditor(container);
45
+ ```
46
+
38
47
  ### 方式一:演示模式
39
48
 
40
49
  ```javascript
@@ -292,7 +301,7 @@ create(container, {
292
301
 
293
302
  演示模式快捷入口。该函数负责真正创建并初始化 `EmbeddedPresentation`。
294
303
 
295
- 创建成功后,SDK 会额外调用 `https://open.dajiaoai.com/console/api/whitelist/check`,使用 `options.auth.appId` 与当前页面 `hostname` 做白名单校验。若未命中白名单,iframe 仍会完成初始化并呈现页面,`createPresentation` 仍会成功返回实例,但后续 `loadShareById`、`loadFile`、`switchSlide`、`getSlideCount`、`repl` 等演示模式 API 会被拒绝,并在控制台输出包含方法名的错误,便于接入方感知并处理。
304
+ `createPresentation` 初始化时会加载画板。首次调用 `switchSlide` 等需要授权的方法时,SDK 才校验应用和宿主主机名。校验失败时,该方法返回错误。
296
305
 
297
306
  ```javascript
298
307
  create(container, {
@@ -1,5 +1,33 @@
1
1
  'use strict';
2
2
 
3
+ const SDK_LOGO = `<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" fill="none" viewBox="0 0 36 36">
4
+ <g clip-path="url(#a)">
5
+ <path stroke="#A668B8" stroke-width="3.819" d="m30.261 29.85-5.368-23.9c-.163-.723-1.126-.875-1.503-.237l-9.082 15.349a.818.818 0 0 0 .288 1.12l14.45 8.551a.818.818 0 0 0 1.215-.884Z"/>
6
+ <path stroke="#01B88B" stroke-width="3.819" d="M5.335 11.746V30.12c6.605.315 14.644.647 15.468-8.963.165-1.922-.34-4.035-.824-5.9-.851-3.276-3.854-5.913-12.59-5.913"/>
7
+ <path fill="#A668B8" d="m16.483 13.62 2.182-3.682 3.273 1.91-3.682 6.137-1.773-4.364Z"/>
8
+ </g>
9
+ <defs>
10
+ <clipPath id="a">
11
+ <path fill="#fff" d="M0 0h36v36H0z"/>
12
+ </clipPath>
13
+ </defs>
14
+ </svg>`;
15
+ const BADGE_STYLE = 'background-color: #f1faf7; background-position: 9px center;' +
16
+ 'background-repeat: no-repeat; background-size: 24px 24px;' +
17
+ 'border: 1px solid #9cd4c5; border-radius: 4px; padding: 6px 12px 6px 42px;' +
18
+ 'color: #123e35; font-size: 14px; font-weight: bold;';
19
+ const TITLE_STYLE = 'background-color: #174e42; color: #fff; font-weight: bold; padding: 2px 8px;';
20
+ const DIVIDER = '+------------------------------------------------------+';
21
+ function logSdk(...entry) {
22
+ if (entry[0] === 'debug') {
23
+ const [, message, ...details] = entry;
24
+ console.debug('[Algeo SDK]', message, ...details);
25
+ return;
26
+ }
27
+ const [, { title, lines }] = entry;
28
+ console.info(`%cALGEO SDK / 大角几何%c\n\n${DIVIDER}\n| %c%s%c\n%s\n${DIVIDER}`, `background-image: url(data:image/svg+xml;base64,${btoa(SDK_LOGO)});${BADGE_STYLE}`, '', TITLE_STYLE, title, '', ['|', ...lines.map((line) => (line ? `| ${line}` : '|'))].join('\n'));
29
+ }
30
+
3
31
  var util;
4
32
  (function (util) {
5
33
  util.assertEqual = (_) => { };
@@ -4011,11 +4039,42 @@ function convertToLatest(content) {
4011
4039
  }
4012
4040
 
4013
4041
  /** SDK 版本号,构建时由 rollup 注入 */
4014
- const VERSION = '2.16.0';
4042
+ const VERSION = '2.16.2';
4015
4043
  const DEFAULT_EMBED_BASE = 'https://dajiaoai.com';
4016
4044
  const DEFAULT_PRESENTATION_PATH = '/embed/present';
4017
4045
  const DEFAULT_EDITOR_PATH = '/embed/edit';
4018
4046
  const EMBED_TIMEOUT_MS = 30000;
4047
+ function isLocalFileHost() {
4048
+ return typeof window !== 'undefined' && window.location.protocol === 'file:';
4049
+ }
4050
+ function isLocalLoopbackHost() {
4051
+ if (typeof window === 'undefined')
4052
+ return false;
4053
+ const { protocol, hostname } = window.location;
4054
+ return ((protocol === 'http:' || protocol === 'https:') &&
4055
+ ['localhost', '127.0.0.1'].includes(hostname));
4056
+ }
4057
+ function readEmbedAppId(auth) {
4058
+ const appId = auth?.appId?.trim() ?? '';
4059
+ if (!appId) {
4060
+ logSdk('notice', {
4061
+ title: '未配置应用 ID(auth.appId)',
4062
+ lines: [
4063
+ '注册应用 > 配置域名白名单 > 填写 auth.appId',
4064
+ '开放平台 https://open.dajiaoai.com/console',
4065
+ '使用许可 https://open.dajiaoai.com/sdk/2/auth',
4066
+ '',
4067
+ '版权 © 大角几何',
4068
+ ],
4069
+ });
4070
+ }
4071
+ return appId;
4072
+ }
4073
+ function requireHttpHostForAppId(appId) {
4074
+ if (appId && isLocalFileHost()) {
4075
+ throw new AlgeoError('file:// 没有可校验的宿主域名。请通过本地 HTTP 服务打开页面,将该主机加入应用白名单后重试。', EMBED_ERROR_CODES.BAD_REQUEST);
4076
+ }
4077
+ }
4019
4078
  let requestIdCounter = 0;
4020
4079
  function generateRequestId() {
4021
4080
  return `req-${Date.now()}-${++requestIdCounter}`;
@@ -4130,12 +4189,24 @@ function buildEmbedSrc(options) {
4130
4189
  const baseUrl = normalizeBaseUrl(options.baseUrl ?? DEFAULT_EMBED_BASE);
4131
4190
  const mode = normalizeMode(options.mode);
4132
4191
  const path = getEmbedPath(mode);
4133
- const appId = options.auth?.appId?.trim() ?? '';
4192
+ const appId = options.auth?.appId?.trim();
4193
+ const localFile = !appId && isLocalFileHost();
4194
+ const localLoopback = !appId && isLocalLoopbackHost();
4134
4195
  const initialId = options.initialId?.trim();
4135
- const src = `${baseUrl}${path}/${encodeURIComponent(appId)}${initialId ? `/${encodeURIComponent(initialId)}` : ''}`;
4136
- return mode === 'editor' && options.cameraMode
4137
- ? `${src}?cameraMode=${encodeURIComponent(options.cameraMode)}`
4138
- : src;
4196
+ const initialPath = initialId ? `/${encodeURIComponent(initialId)}` : '';
4197
+ const routeAppId = appId || (localFile || localLoopback ? 'local' : 'public');
4198
+ const src = `${baseUrl}${path}/${encodeURIComponent(routeAppId)}${initialPath}`;
4199
+ const params = new URLSearchParams();
4200
+ if (mode === 'editor' && options.cameraMode) {
4201
+ params.set('cameraMode', options.cameraMode);
4202
+ }
4203
+ if (mode === 'editor' && localFile) {
4204
+ params.set('localFile', '1');
4205
+ }
4206
+ if (mode === 'editor' && localLoopback) {
4207
+ params.set('localLoopback', '1');
4208
+ }
4209
+ return params.size ? `${src}?${params}` : src;
4139
4210
  }
4140
4211
  const MASTER_TEMPLATE_OPERATIONS = [
4141
4212
  'listSystem',
@@ -4234,6 +4305,7 @@ class EmbeddedTarget {
4234
4305
  ...options,
4235
4306
  mode: this.embedMode,
4236
4307
  });
4308
+ const iframeOrigin = new URL(src, window.location.href).origin;
4237
4309
  let settled = false;
4238
4310
  let initTimeoutId;
4239
4311
  const finalizeFailure = (error) => {
@@ -4280,6 +4352,25 @@ class EmbeddedTarget {
4280
4352
  return;
4281
4353
  }
4282
4354
  const { data } = e;
4355
+ if (data?.type === 'localFileHostCheck' &&
4356
+ typeof data.requestId === 'string' &&
4357
+ isLocalFileHost()) {
4358
+ iframe.contentWindow?.postMessage({ type: 'localFileHostConfirmed', requestId: data.requestId }, '*');
4359
+ return;
4360
+ }
4361
+ if (data?.type === 'localLoopbackHostCheck' &&
4362
+ typeof data.requestId === 'string' &&
4363
+ !options.auth?.appId?.trim() &&
4364
+ isLocalLoopbackHost()) {
4365
+ iframe.contentWindow?.postMessage({ type: 'localLoopbackHostConfirmed', requestId: data.requestId }, iframeOrigin);
4366
+ return;
4367
+ }
4368
+ if (this.embedMode === 'editor' &&
4369
+ e.origin === iframeOrigin &&
4370
+ data?.type === 'embedEditAuthorizationFailed') {
4371
+ finalizeFailure(new AlgeoError('白名单校验未通过。请在开放平台将当前主机加入应用白名单后重试。', EMBED_ERROR_CODES.BAD_REQUEST));
4372
+ return;
4373
+ }
4283
4374
  if (isReadyMessage(data)) {
4284
4375
  if (this._ready) {
4285
4376
  return;
@@ -4412,6 +4503,7 @@ class EmbeddedPresentation extends EmbeddedTarget {
4412
4503
  super(container, 'presentation');
4413
4504
  this.currentSlideIndex = 0;
4414
4505
  this.slideCount = 0;
4506
+ this.appId = '';
4415
4507
  this.uiConfig = {
4416
4508
  logo: true,
4417
4509
  slidePanel: true,
@@ -4421,19 +4513,30 @@ class EmbeddedPresentation extends EmbeddedTarget {
4421
4513
  this.mode = {
4422
4514
  getUiConfig: () => ({ ...this.uiConfig }),
4423
4515
  setUiConfig: async (config) => {
4516
+ await this.ensureWhitelistAccess('setUiConfig');
4424
4517
  await this.post('setUiConfig', { config });
4425
4518
  this.uiConfig = {
4426
4519
  ...this.uiConfig,
4427
4520
  ...config,
4428
4521
  };
4429
4522
  },
4430
- setMasterTemplate: (template) => {
4431
- this.ensureWhitelistAccess('setMasterTemplate');
4523
+ setMasterTemplate: async (template) => {
4524
+ await this.ensureWhitelistAccess('setMasterTemplate');
4432
4525
  return this.post('setMasterTemplate', { template });
4433
4526
  },
4434
4527
  };
4435
4528
  }
4436
4529
  async initialize(options = {}, baseUrl) {
4530
+ const appId = readEmbedAppId(options.auth);
4531
+ if (!this.iframe) {
4532
+ this.appId = appId;
4533
+ this.whitelistCheck = undefined;
4534
+ }
4535
+ // 未配置应用的部署页面按默认样式展示公开分享。
4536
+ if (!appId && !isLocalFileHost() && !isLocalLoopbackHost()) {
4537
+ await this.init({ baseUrl, initialId: options.shareId });
4538
+ return;
4539
+ }
4437
4540
  this.uiConfig = {
4438
4541
  logo: true,
4439
4542
  slidePanel: true,
@@ -4452,7 +4555,7 @@ class EmbeddedPresentation extends EmbeddedTarget {
4452
4555
  if (options.fonts) {
4453
4556
  await this.post('setFontConfig', { config: options.fonts });
4454
4557
  }
4455
- await this.mode.setUiConfig(this.uiConfig);
4558
+ await this.post('setUiConfig', { config: this.uiConfig });
4456
4559
  }
4457
4560
  acceptsEventMessage() {
4458
4561
  return false;
@@ -4460,16 +4563,44 @@ class EmbeddedPresentation extends EmbeddedTarget {
4460
4563
  setWhitelistError(error) {
4461
4564
  this.whitelistError = error;
4462
4565
  }
4463
- ensureWhitelistAccess(methodName) {
4464
- if (!this.whitelistError) {
4465
- return;
4566
+ async checkWhitelist(appId) {
4567
+ if (!appId) {
4568
+ if (isLocalFileHost() || isLocalLoopbackHost())
4569
+ return;
4570
+ throw new AlgeoError('正式接入演示模式需要提供 auth.appId。', EMBED_ERROR_CODES.MISSING_APP_ID);
4571
+ }
4572
+ requireHttpHostForAppId(appId);
4573
+ const host = window.location.hostname;
4574
+ const url = new URL('https://open.dajiaoai.com/console/api/whitelist/check');
4575
+ url.searchParams.set('appId', appId);
4576
+ url.searchParams.set('host', host);
4577
+ try {
4578
+ const response = await fetch(url.toString(), { cache: 'no-store' });
4579
+ if (response.ok && (await response.json()).matched === true)
4580
+ return;
4581
+ }
4582
+ catch {
4583
+ // 网络或响应解析失败时按鉴权失败处理。
4584
+ }
4585
+ throw new AlgeoError(`白名单校验未通过,appId="${appId}",host="${host}"。请在开放平台将该主机加入应用白名单后重试。`, EMBED_ERROR_CODES.BAD_REQUEST);
4586
+ }
4587
+ async ensureWhitelistAccess(methodName) {
4588
+ try {
4589
+ if (this.whitelistError)
4590
+ throw this.whitelistError;
4591
+ this.whitelistCheck ?? (this.whitelistCheck = this.checkWhitelist(this.appId));
4592
+ await this.whitelistCheck;
4593
+ }
4594
+ catch (cause) {
4595
+ if (!(cause instanceof AlgeoError))
4596
+ throw cause;
4597
+ const error = new AlgeoError(`演示模式调用 ${methodName} 被白名单限制。${cause.message}`, cause.code, cause.details);
4598
+ console.error(error);
4599
+ throw error;
4466
4600
  }
4467
- const error = new AlgeoError(`演示模式调用 ${methodName} 被白名单限制。${this.whitelistError.message}`, this.whitelistError.code, this.whitelistError.details);
4468
- console.error(error);
4469
- throw error;
4470
4601
  }
4471
4602
  async loadShareById(id) {
4472
- this.ensureWhitelistAccess('loadShareById');
4603
+ await this.ensureWhitelistAccess('loadShareById');
4473
4604
  const result = await this.post('loadShareById', {
4474
4605
  id,
4475
4606
  });
@@ -4479,7 +4610,7 @@ class EmbeddedPresentation extends EmbeddedTarget {
4479
4610
  return result;
4480
4611
  }
4481
4612
  async loadFile(content) {
4482
- this.ensureWhitelistAccess('loadFile');
4613
+ await this.ensureWhitelistAccess('loadFile');
4483
4614
  const latestContent = convertToLatest(content);
4484
4615
  const result = await this.post('loadContent', {
4485
4616
  content: latestContent,
@@ -4490,19 +4621,19 @@ class EmbeddedPresentation extends EmbeddedTarget {
4490
4621
  return result;
4491
4622
  }
4492
4623
  async switchSlide(index) {
4493
- this.ensureWhitelistAccess('switchSlide');
4624
+ await this.ensureWhitelistAccess('switchSlide');
4494
4625
  const result = await this.post('switchSlide', { index });
4495
4626
  this.currentSlideIndex = index;
4496
4627
  return result;
4497
4628
  }
4498
4629
  async getSlideCount() {
4499
- this.ensureWhitelistAccess('getSlideCount');
4630
+ await this.ensureWhitelistAccess('getSlideCount');
4500
4631
  const result = await this.post('getSlideCount', {});
4501
4632
  this.slideCount = result.count;
4502
4633
  return result;
4503
4634
  }
4504
4635
  async repl(command) {
4505
- this.ensureWhitelistAccess('repl');
4636
+ await this.ensureWhitelistAccess('repl');
4506
4637
  return this.post('repl', { command });
4507
4638
  }
4508
4639
  }
@@ -4690,7 +4821,9 @@ class EmbeddedEditor extends EmbeddedTarget {
4690
4821
  this.historyCurrentIndex = state.historyCurrentIndex;
4691
4822
  }
4692
4823
  async initialize(options = {}, baseUrl) {
4693
- if (!options.auth?.appId?.trim()) {
4824
+ const appId = readEmbedAppId(options.auth);
4825
+ requireHttpHostForAppId(appId);
4826
+ if (!appId && !isLocalFileHost() && !isLocalLoopbackHost()) {
4694
4827
  throw new AlgeoError('编辑模式需要提供 auth.appId。', EMBED_ERROR_CODES.MISSING_APP_ID);
4695
4828
  }
4696
4829
  this.uiConfig = options.ui ? { ...options.ui } : {};
@@ -5200,33 +5333,6 @@ class EmbeddedEditor extends EmbeddedTarget {
5200
5333
  }
5201
5334
  }
5202
5335
 
5203
- const WHITELIST_CHECK_BASE_URL = 'https://open.dajiaoai.com/console';
5204
- const WHITELIST_CHECK_PATH = '/api/whitelist/check';
5205
- async function checkPresentationWhitelist(options) {
5206
- const appId = options.auth?.appId?.trim() ?? '';
5207
- const host = window.location.hostname.trim();
5208
- const url = new URL(`${normalizeBaseUrl(WHITELIST_CHECK_BASE_URL)}${WHITELIST_CHECK_PATH}`);
5209
- url.searchParams.set('appId', appId);
5210
- url.searchParams.set('host', host);
5211
- let matched = false;
5212
- try {
5213
- const response = await fetch(url.toString(), {
5214
- method: 'GET',
5215
- cache: 'no-store',
5216
- });
5217
- if (response.ok) {
5218
- const payload = (await response.json());
5219
- matched = payload.matched === true;
5220
- }
5221
- }
5222
- catch {
5223
- matched = false;
5224
- }
5225
- if (matched) {
5226
- return null;
5227
- }
5228
- return new AlgeoError(`白名单校验未通过,appId="${appId || '(empty)'}",host="${host || '(empty)'}"。`, EMBED_ERROR_CODES.BAD_REQUEST);
5229
- }
5230
5336
  async function createEditorInstance(container, options = {}, baseUrl) {
5231
5337
  const editor = new EmbeddedEditor(container);
5232
5338
  await editor.initialize(options, baseUrl);
@@ -5235,10 +5341,6 @@ async function createEditorInstance(container, options = {}, baseUrl) {
5235
5341
  async function createPresentationInstance(container, options = {}, baseUrl) {
5236
5342
  const presentation = new EmbeddedPresentation(container);
5237
5343
  await presentation.initialize(options, baseUrl);
5238
- const whitelistError = await checkPresentationWhitelist(options);
5239
- if (whitelistError) {
5240
- presentation.setWhitelistError(whitelistError);
5241
- }
5242
5344
  return presentation;
5243
5345
  }
5244
5346
  function createEmbeddedInstance(container, options) {