刘光辉
12 小时以前 0dfe84494048ce27ba8449831782128412d3eb13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
export const PLUGIN_GUID = 'asc.{2D6D6CB6-F6FC-45B7-8EC7-0CC1940F1A6F}';
export const PLUGIN_VERSION = '0.1.0';
export const PLUGIN_BIZ_MODULE = 'eln.template';
export const PLUGIN_BIZ_SCENE = 'eln.template.annotate';
 
export interface PluginContext {
  apiBaseUrl: string;
  bizDataId: string;
  bizModule: typeof PLUGIN_BIZ_MODULE;
  bizScene: typeof PLUGIN_BIZ_SCENE;
  canAnnotate: boolean;
  documentId: string;
  pluginVersion: typeof PLUGIN_VERSION;
}
 
function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}
 
function isNonEmptyString(value: unknown): value is string {
  return typeof value === 'string' && value.trim().length > 0;
}
 
function isHttpUrl(value: unknown): value is string {
  if (!isNonEmptyString(value)) return false;
  try {
    const parsed = new URL(value);
    return ['http:', 'https:'].includes(parsed.protocol) && !parsed.username && !parsed.password && !parsed.search && !parsed.hash;
  } catch {
    return false;
  }
}
 
export function parsePluginContext(options: unknown): PluginContext {
  if (!isRecord(options)) {
    throw new Error('插件运行上下文无效');
  }
 
  const value = options;
  if (
    !isNonEmptyString(value.documentId) ||
    !isHttpUrl(value.apiBaseUrl) ||
    !isNonEmptyString(value.bizDataId) ||
    value.bizModule !== PLUGIN_BIZ_MODULE ||
    value.bizScene !== PLUGIN_BIZ_SCENE ||
    value.pluginVersion !== PLUGIN_VERSION ||
    typeof value.canAnnotate !== 'boolean'
  ) {
    throw new Error('插件运行上下文无效');
  }
 
  return {
    apiBaseUrl: value.apiBaseUrl.replace(/\/+$/u, ''),
    documentId: value.documentId,
    bizDataId: value.bizDataId,
    bizModule: value.bizModule,
    bizScene: value.bizScene,
    pluginVersion: value.pluginVersion,
    canAnnotate: value.canAnnotate,
  };
}