@kimposoft/plugin-sdk 0.0.0-stage → 1.1.0-tp.20
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/LICENSE +202 -0
- package/NOTICE +9 -0
- package/README.md +48 -2
- package/package.json +141 -4
- package/src/action-designer.ts +250 -0
- package/src/attachment-url.ts +195 -0
- package/src/auth/index.ts +6 -0
- package/src/auth/qrcode.ts +519 -0
- package/src/auth/types.ts +261 -0
- package/src/display-style.ts +250 -0
- package/src/editor-frame.ts +623 -0
- package/src/editor-session.ts +1214 -0
- package/src/editor-testing.ts +838 -0
- package/src/editor.ts +1641 -0
- package/src/frame-transport.ts +491 -0
- package/src/frontend-routes.ts +99 -0
- package/src/hooks.ts +48 -0
- package/src/host-caps.ts +93 -0
- package/src/i18n.ts +238 -0
- package/src/im-panel.ts +132 -0
- package/src/image-tools.ts +91 -0
- package/src/index.ts +118 -0
- package/src/interactive-session.ts +94 -0
- package/src/nahida-im.ts +391 -0
- package/src/nahida-ws.ts +23 -0
- package/src/org-directory.ts +78 -0
- package/src/oz-realtime.ts +144 -0
- package/src/page.ts +404 -0
- package/src/print.ts +393 -0
- package/src/surface.ts +281 -0
- package/src/theme-mocks.ts +140 -0
- package/src/theme.ts +125 -0
- package/src/ui-fixtures/confirm.ts +16 -0
- package/src/ui-fixtures/entity-picker.ts +24 -0
- package/src/ui-fixtures/expression-editor.ts +52 -0
- package/src/ui-fixtures/image-cropper.ts +23 -0
- package/src/ui-fixtures/index.ts +16 -0
- package/src/ui-fixtures/org-tri-picker.ts +19 -0
- package/src/ui-fixtures/prompt.ts +19 -0
- package/src/ui-fixtures/record-picker.ts +17 -0
- package/src/ui-fixtures/template-picker.ts +13 -0
- package/src/ui-mocks.ts +250 -0
- package/src/ui.ts +479 -0
- package/src/workflow-designer.ts +475 -0
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
// iframe 沙箱挂载档的框架侧传输层。
|
|
2
|
+
//
|
|
3
|
+
// 第三方插件前端一律在宿主的沙箱框架里运行:框架是不透明源(不带用户会话 Cookie、读不到宿主页面),CSP 禁止一切
|
|
4
|
+
// 网络请求,宿主能力只能经 MessageChannel 桥由宿主代执行。本文件让插件代码在两种挂载档下写法完全一样:
|
|
5
|
+
// - 插件照常 `export const createSurface = definePluginSurface(input => ({ component, props }))`;
|
|
6
|
+
// - 在沙箱框架里,definePluginSurface 会自动启动本运行时:等宿主握手 → 把宿主桥还原成同形对象(方法变成
|
|
7
|
+
// 返回 Promise 的远程调用)→ 调用 createSurface → 用框架里的 window.Vue 挂载组件 → 同步宿主 props 更新;
|
|
8
|
+
// - 同源档(官方插件)里本运行时不启动,definePluginSurface 仍是纯类型辅助。
|
|
9
|
+
//
|
|
10
|
+
// 与同源档的行为差异(插件作者需要知道的只有这些):
|
|
11
|
+
// - 宿主桥上的方法一律异步(返回 Promise);同步取值的能力已由宿主做成快照:`permission.templatePermission()`、
|
|
12
|
+
// `template-settings.get()` 同步返回挂载时的值,`timezone.value` / `theme` 为挂载时快照;
|
|
13
|
+
// - `i18n`:`locale.value` 与 `onLocaleChange` 跟随宿主实时切换;`t()` 只查宿主为本框架裁出的只读词条快照
|
|
14
|
+
// (1.1.0-tp.18 起,需支持的宿主:冻结公共词表 COMMON_VOCABULARY、`err.plugin.*` 族、本插件命名空间下管理员补的
|
|
15
|
+
// locale;其他插件与宿主私有键一律不下发),未命中返回空串,createPluginI18n 随即回落插件自带语言包;
|
|
16
|
+
// 老宿主不下发快照时 `t()` 恒返回空串(行为同 tp.17);
|
|
17
|
+
// - 结果里的函数与类实例被宿主剥离,只拿到纯数据;
|
|
18
|
+
// - 框架内 fetch / XHR / WebSocket / <img src="/api/…"> 均不可用;访问宿主接口用 `hostBridge.request`
|
|
19
|
+
// (须在 manifest `capabilities.frontend.routes` 声明并获授予),图片等资源经桥取成 blob 后用 blob: URL 显示。
|
|
20
|
+
//
|
|
21
|
+
// 协议 v1(端口上的消息,与宿主沙箱框架宿主侧实现同口径):
|
|
22
|
+
// 宿主 → 框架:init / props / result / cb / event / expose / destroy
|
|
23
|
+
// 框架 → 宿主:call / mounted / mount-error / expose-result / resize / log
|
|
24
|
+
// 编码标记:{__kimpoFn:id, snap?}(宿主函数句柄 / 同步快照)、{__kimpoI18n:{…}}(宿主语言能力,可带 messages 词条快照)、
|
|
25
|
+
// {__kimpoCb:id}(框架回调,作为调用参数传给宿主)。
|
|
26
|
+
// 事件:{t:'event', kind:'i18n.locale', locale, messages?}(切语言,附新语言的词条快照)、
|
|
27
|
+
// {t:'event', kind:'i18n.messages', messages}(同一语言下宿主补载运行时语言包后刷新快照)。
|
|
28
|
+
// 握手:宿主在框架首次 load 后向框架 window 投递一次 {kimpoFrame:'init', v} 并转移 port2;框架只接受来自
|
|
29
|
+
// window.parent 的第一次握手,此后只在端口上通信(window 层消息宿主一律丢弃)。
|
|
30
|
+
|
|
31
|
+
import type { SurfaceCreateInput, SurfaceMountResult } from './surface';
|
|
32
|
+
|
|
33
|
+
/** 协议版本。 */
|
|
34
|
+
export const FRAME_PROTOCOL_VERSION = 1;
|
|
35
|
+
|
|
36
|
+
/** 框架文档 <meta name="kimpo-frame"> 携带的引导信息(宿主 frame 端点写入)。 */
|
|
37
|
+
export interface KimpoFrameMeta {
|
|
38
|
+
v: number;
|
|
39
|
+
plugin_id: string;
|
|
40
|
+
/** surface 标识 type[:slot|bind]。 */
|
|
41
|
+
surface: string;
|
|
42
|
+
/** manifest capabilities.frontend.global_name。 */
|
|
43
|
+
global_name: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 桥调用失败时抛出的错误。宿主回包 `{t:'result', id, ok:false, error:{code, message, params?}}`:
|
|
48
|
+
* - code:宿主后端错误码原样(如 REQUIRED_FIELD_MISSING、VERSION_CONFLICT、EDITOR_SESSION_READONLY),
|
|
49
|
+
* 没有时为宿主具名码,都没有才是 PLUGIN_BRIDGE_CALL_FAILED(老宿主一律是它);
|
|
50
|
+
* - message:宿主按请求语言渲染的文案(可直接展示);
|
|
51
|
+
* - params:可选的纯数据参数(如必填缺失 `{field_ids: [...]}`、删字段被挡 `{field_id, affected_rows}`)。
|
|
52
|
+
*/
|
|
53
|
+
export class HostBridgeCallError extends Error {
|
|
54
|
+
code: string;
|
|
55
|
+
params?: Record<string, unknown>;
|
|
56
|
+
constructor(code: string, message: string, params?: Record<string, unknown>) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = 'HostBridgeCallError';
|
|
59
|
+
this.code = code;
|
|
60
|
+
if (params) this.params = params;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 默认桥错误码(宿主没给码,或老宿主)。 */
|
|
65
|
+
export const PLUGIN_BRIDGE_CALL_FAILED = 'PLUGIN_BRIDGE_CALL_FAILED';
|
|
66
|
+
|
|
67
|
+
/** 把宿主回包里的 error 还原为 HostBridgeCallError(code / message 缺失或不是字符串时回落默认值)。 */
|
|
68
|
+
export function hostBridgeErrorFrom(error: unknown): HostBridgeCallError {
|
|
69
|
+
const err = isRecord(error) ? error : {};
|
|
70
|
+
const code = typeof err.code === 'string' && err.code.trim() ? err.code.trim() : PLUGIN_BRIDGE_CALL_FAILED;
|
|
71
|
+
const message = typeof err.message === 'string' && err.message ? err.message : 'host bridge call failed';
|
|
72
|
+
const params = isRecord(err.params) ? (err.params as Record<string, unknown>) : undefined;
|
|
73
|
+
return new HostBridgeCallError(code, message, params);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 本运行时依赖的最小 Vue 运行时面(框架里由宿主提供的 window.Vue)。 */
|
|
77
|
+
export interface FrameVueRuntime {
|
|
78
|
+
createApp(root: unknown): { mount(el: unknown): unknown; unmount(): void; config: { errorHandler?: unknown } };
|
|
79
|
+
h(type: unknown, props?: unknown): unknown;
|
|
80
|
+
ref<T>(value: T): { value: T };
|
|
81
|
+
shallowReactive<T extends object>(value: T): T;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
type AnyFn = (...args: unknown[]) => unknown;
|
|
85
|
+
|
|
86
|
+
/** 读取框架引导 meta;不在沙箱框架里返回 null。 */
|
|
87
|
+
export function readKimpoFrameMeta(doc: Document | undefined = typeof document === 'undefined' ? undefined : document): KimpoFrameMeta | null {
|
|
88
|
+
try {
|
|
89
|
+
const el = doc?.querySelector('meta[name="kimpo-frame"]');
|
|
90
|
+
const raw = el?.getAttribute('content');
|
|
91
|
+
if (!raw) return null;
|
|
92
|
+
const meta = JSON.parse(raw) as KimpoFrameMeta;
|
|
93
|
+
return meta && typeof meta.global_name === 'string' ? meta : null;
|
|
94
|
+
} catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 当前是否运行在宿主沙箱框架里(有引导 meta 且是子框架)。 */
|
|
100
|
+
export function isKimpoFrameContext(): boolean {
|
|
101
|
+
if (typeof window === 'undefined') return false;
|
|
102
|
+
let framed = false;
|
|
103
|
+
try {
|
|
104
|
+
framed = window.parent !== window;
|
|
105
|
+
} catch {
|
|
106
|
+
framed = true;
|
|
107
|
+
}
|
|
108
|
+
return framed && readKimpoFrameMeta() !== null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
112
|
+
return value !== null && typeof value === 'object';
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function isCloneablePrimitiveObject(value: object): boolean {
|
|
116
|
+
return (
|
|
117
|
+
value instanceof Date ||
|
|
118
|
+
value instanceof RegExp ||
|
|
119
|
+
value instanceof ArrayBuffer ||
|
|
120
|
+
ArrayBuffer.isView(value) ||
|
|
121
|
+
(typeof Blob !== 'undefined' && value instanceof Blob)
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 宿主 LocalizedText 取当前语言(与宿主 resolve 同口径:精确 → 下划线形态 → 语言前缀 → zh-CN → 第一个值)。 */
|
|
126
|
+
function resolveLocalized(value: unknown, locale: string): string {
|
|
127
|
+
if (typeof value === 'string') return value;
|
|
128
|
+
if (!isRecord(value)) return '';
|
|
129
|
+
const table = value as Record<string, unknown>;
|
|
130
|
+
const candidates = [locale, locale.replace('-', '_'), locale.split('-')[0], 'zh-CN', 'zh_CN'];
|
|
131
|
+
for (const key of candidates) {
|
|
132
|
+
if (typeof table[key] === 'string' && table[key]) return table[key] as string;
|
|
133
|
+
}
|
|
134
|
+
const first = Object.values(table).find(v => typeof v === 'string');
|
|
135
|
+
return typeof first === 'string' ? first : '';
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** 单份框架词条快照的上限(条数 / 单条长度):防宿主异常时把超大对象灌进框架。 */
|
|
139
|
+
const FRAME_I18N_MAX_ENTRIES = 5000;
|
|
140
|
+
const FRAME_I18N_MAX_TEXT = 4000;
|
|
141
|
+
|
|
142
|
+
/** 把宿主下发的词条快照收敛为 `{string: string}`(丢弃非字符串值与超限条目)。 */
|
|
143
|
+
function sanitizeFrameI18nMessages(value: unknown): Record<string, string> {
|
|
144
|
+
const out: Record<string, string> = {};
|
|
145
|
+
if (!isRecord(value) || Array.isArray(value)) return out;
|
|
146
|
+
let count = 0;
|
|
147
|
+
for (const [key, text] of Object.entries(value)) {
|
|
148
|
+
if (count >= FRAME_I18N_MAX_ENTRIES) break;
|
|
149
|
+
if (typeof text !== 'string' || !text || text.length > FRAME_I18N_MAX_TEXT) continue;
|
|
150
|
+
out[key] = text;
|
|
151
|
+
count += 1;
|
|
152
|
+
}
|
|
153
|
+
return out;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** {name} 占位插值(与 i18n.ts createPluginI18n 的插值同口径:缺参保留占位)。 */
|
|
157
|
+
function interpolateFrameText(text: string, params?: Record<string, unknown>): string {
|
|
158
|
+
if (!params) return text;
|
|
159
|
+
return text.replace(/\{(\w+)\}/g, (m, name: string) => {
|
|
160
|
+
const v = params[name];
|
|
161
|
+
return v === undefined || v === null ? m : String(v);
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 框架侧桥客户端:在端口上发起调用、登记回调、把宿主编码还原成同形对象。
|
|
167
|
+
* 与 DOM 无关,可在任意持有 MessagePort 的环境使用(也是单测入口)。
|
|
168
|
+
*/
|
|
169
|
+
export function createFrameClient(port: MessagePort) {
|
|
170
|
+
let seq = 0;
|
|
171
|
+
let cbSeq = 0;
|
|
172
|
+
const pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: unknown) => void }>();
|
|
173
|
+
const callbacks = new Map<number, AnyFn>();
|
|
174
|
+
const callbackIds = new WeakMap<AnyFn, number>();
|
|
175
|
+
const localeListeners = new Set<(locale: string) => void>();
|
|
176
|
+
const handlers = new Map<string, (msg: Record<string, unknown>) => void>();
|
|
177
|
+
let currentLocale = '';
|
|
178
|
+
// 宿主为本框架裁出的只读词条快照(宿主中央包 key → 文案,只含当前 locale);老宿主不下发时为空表。
|
|
179
|
+
let hostMessages: Record<string, string> = {};
|
|
180
|
+
const applyHostMessages = (value: unknown) => {
|
|
181
|
+
hostMessages = sanitizeFrameI18nMessages(value);
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
/** 框架 → 宿主参数编码:函数登记为回调;其余深拷贝为纯数据(Proxy / 响应式对象按自身键展开)。 */
|
|
185
|
+
const encodeArg = (value: unknown, depth = 0, seen = new WeakSet<object>()): unknown => {
|
|
186
|
+
if (typeof value === 'function') {
|
|
187
|
+
const fn = value as AnyFn;
|
|
188
|
+
let id = callbackIds.get(fn);
|
|
189
|
+
if (id === undefined) {
|
|
190
|
+
cbSeq += 1;
|
|
191
|
+
id = cbSeq;
|
|
192
|
+
callbacks.set(id, fn);
|
|
193
|
+
callbackIds.set(fn, id);
|
|
194
|
+
}
|
|
195
|
+
return { __kimpoCb: id };
|
|
196
|
+
}
|
|
197
|
+
if (!isRecord(value) || depth > 24) return value;
|
|
198
|
+
if (isCloneablePrimitiveObject(value)) return value;
|
|
199
|
+
if (seen.has(value)) return undefined;
|
|
200
|
+
seen.add(value);
|
|
201
|
+
if (Array.isArray(value)) return value.map(item => encodeArg(item, depth + 1, seen));
|
|
202
|
+
const out: Record<string, unknown> = {};
|
|
203
|
+
for (const key of Object.keys(value)) out[key] = encodeArg(value[key], depth + 1, seen);
|
|
204
|
+
return out;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const call = (fn: number, args: unknown[]) =>
|
|
208
|
+
new Promise<unknown>((resolve, reject) => {
|
|
209
|
+
seq += 1;
|
|
210
|
+
const id = seq;
|
|
211
|
+
pending.set(id, { resolve, reject });
|
|
212
|
+
port.postMessage({ t: 'call', id, fn, args: args.map(arg => encodeArg(arg)) });
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
/** 宿主 → 框架解码:句柄还原为函数,宿主语言能力还原为 HostI18n 同形对象。 */
|
|
216
|
+
const decode = (value: unknown, depth = 0): unknown => {
|
|
217
|
+
if (!isRecord(value) || depth > 24 || isCloneablePrimitiveObject(value)) return value;
|
|
218
|
+
if (Array.isArray(value)) return value.map(item => decode(item, depth + 1));
|
|
219
|
+
if (typeof value.__kimpoFn === 'number') {
|
|
220
|
+
const id = value.__kimpoFn;
|
|
221
|
+
if ('snap' in value) {
|
|
222
|
+
const snap = decode(value.snap, depth + 1);
|
|
223
|
+
return () => snap;
|
|
224
|
+
}
|
|
225
|
+
return (...args: unknown[]) => call(id, args).then(result => decode(result));
|
|
226
|
+
}
|
|
227
|
+
if (isRecord(value.__kimpoI18n)) {
|
|
228
|
+
const spec = value.__kimpoI18n;
|
|
229
|
+
currentLocale = typeof spec.locale === 'string' ? spec.locale : '';
|
|
230
|
+
applyHostMessages(spec.messages);
|
|
231
|
+
const switchLocale = spec.switchLocale ? (decode(spec.switchLocale, depth + 1) as AnyFn) : undefined;
|
|
232
|
+
return {
|
|
233
|
+
locale: {
|
|
234
|
+
get value() {
|
|
235
|
+
return currentLocale;
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
// 只查宿主下发的裁剪快照;未命中按 HostI18n 契约返回空串,createPluginI18n 会回落插件自带语言包。
|
|
239
|
+
t: (key: string, params?: Record<string, unknown>) => {
|
|
240
|
+
const text = typeof key === 'string' ? hostMessages[key] : undefined;
|
|
241
|
+
return text ? interpolateFrameText(text, params) : '';
|
|
242
|
+
},
|
|
243
|
+
resolve: (text: unknown) => resolveLocalized(text, currentLocale),
|
|
244
|
+
onLocaleChange: (cb: (locale: string) => void) => {
|
|
245
|
+
localeListeners.add(cb);
|
|
246
|
+
return () => localeListeners.delete(cb);
|
|
247
|
+
},
|
|
248
|
+
availableLocales: spec.availableLocales,
|
|
249
|
+
switchLocale
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
const out: Record<string, unknown> = {};
|
|
253
|
+
for (const key of Object.keys(value)) out[key] = decode(value[key], depth + 1);
|
|
254
|
+
return out;
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
port.onmessage = event => {
|
|
258
|
+
const msg = event.data as Record<string, unknown>;
|
|
259
|
+
if (!isRecord(msg)) return;
|
|
260
|
+
switch (msg.t) {
|
|
261
|
+
case 'result': {
|
|
262
|
+
const p = pending.get(msg.id as number);
|
|
263
|
+
if (!p) return;
|
|
264
|
+
pending.delete(msg.id as number);
|
|
265
|
+
if (msg.ok) p.resolve(msg.value);
|
|
266
|
+
else {
|
|
267
|
+
p.reject(hostBridgeErrorFrom(msg.error));
|
|
268
|
+
}
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
case 'cb': {
|
|
272
|
+
const fn = callbacks.get(msg.cb as number);
|
|
273
|
+
if (fn) {
|
|
274
|
+
try {
|
|
275
|
+
fn(...((Array.isArray(msg.args) ? msg.args : []).map(arg => decode(arg))));
|
|
276
|
+
} catch (error) {
|
|
277
|
+
port.postMessage({ t: 'log', level: 'error', message: `callback failed: ${String(error)}` });
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
case 'event':
|
|
283
|
+
if (msg.kind === 'i18n.locale' && typeof msg.locale === 'string') {
|
|
284
|
+
currentLocale = msg.locale;
|
|
285
|
+
// 新宿主随切语言事件附上新语言的词条快照;老宿主不带时清空,避免拿旧语言文案冒充新语言。
|
|
286
|
+
applyHostMessages(msg.messages);
|
|
287
|
+
localeListeners.forEach(cb => cb(currentLocale));
|
|
288
|
+
} else if (msg.kind === 'i18n.messages') {
|
|
289
|
+
// 同一语言下宿主补载了运行时语言包(如管理员刚上传补充 locale):只刷新快照,不触发语言切换回调。
|
|
290
|
+
applyHostMessages(msg.messages);
|
|
291
|
+
}
|
|
292
|
+
return;
|
|
293
|
+
default: {
|
|
294
|
+
const handler = handlers.get(String(msg.t));
|
|
295
|
+
handler?.(msg);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
return {
|
|
301
|
+
call,
|
|
302
|
+
decode,
|
|
303
|
+
encodeArg,
|
|
304
|
+
post: (msg: Record<string, unknown>) => port.postMessage(msg),
|
|
305
|
+
/** 订阅其它宿主消息(init / props / expose / destroy)。 */
|
|
306
|
+
on: (type: string, handler: (msg: Record<string, unknown>) => void) => handlers.set(type, handler),
|
|
307
|
+
get locale() {
|
|
308
|
+
return currentLocale;
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* 把「订阅 / 监听」类宿主方法的返回值统一成同步退订函数(1.1.0-tp.5 起)。
|
|
315
|
+
*
|
|
316
|
+
* 同源档里 `ws.subscribe(kind, handler)`、`interactiveSession.onChange(cb)` 等直接返回 `() => void`;
|
|
317
|
+
* 沙箱档里宿主方法都是远程调用,返回的是 `Promise<() => void>`。插件统一写
|
|
318
|
+
* `const off = disposerOf(ws.subscribe('im.message', onFrame))`,两种挂载档都能在卸载时同步调用 `off()`:
|
|
319
|
+
* Promise 尚未兑现时先记下「已退订」,兑现后立即补调真正的退订函数,不会漏退订。
|
|
320
|
+
* 其它返回值(undefined、非函数)得到空操作函数。
|
|
321
|
+
*/
|
|
322
|
+
export function disposerOf(value: unknown): () => void {
|
|
323
|
+
if (typeof value === 'function') return value as () => void;
|
|
324
|
+
if (value && typeof (value as PromiseLike<unknown>).then === 'function') {
|
|
325
|
+
let disposed = false;
|
|
326
|
+
let real: (() => void) | undefined;
|
|
327
|
+
(value as PromiseLike<unknown>).then(
|
|
328
|
+
resolved => {
|
|
329
|
+
if (typeof resolved !== 'function') return;
|
|
330
|
+
real = resolved as () => void;
|
|
331
|
+
if (disposed) {
|
|
332
|
+
try {
|
|
333
|
+
real();
|
|
334
|
+
} catch {
|
|
335
|
+
// 宿主侧退订失败不影响插件卸载。
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
},
|
|
339
|
+
() => undefined
|
|
340
|
+
);
|
|
341
|
+
return () => {
|
|
342
|
+
if (disposed) return;
|
|
343
|
+
disposed = true;
|
|
344
|
+
try {
|
|
345
|
+
real?.();
|
|
346
|
+
} catch {
|
|
347
|
+
// 同上。
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
return () => undefined;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** 合并宿主 props 与插件 createSurface 返回的 props(与同源档容器的合并顺序一致)。 */
|
|
355
|
+
export function mergeSurfaceProps(
|
|
356
|
+
hostProps: Record<string, unknown>,
|
|
357
|
+
pluginProps: Record<string, unknown> | undefined,
|
|
358
|
+
precedence: 'host' | 'plugin'
|
|
359
|
+
): Record<string, unknown> {
|
|
360
|
+
return precedence === 'host' ? { ...(pluginProps ?? {}), ...hostProps } : { ...hostProps, ...(pluginProps ?? {}) };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** startKimpoFrameRuntime 的可注入依赖(默认取浏览器全局,单测可替换)。 */
|
|
364
|
+
export interface FrameRuntimeOptions {
|
|
365
|
+
/** createSurface 工厂;缺省取 window[global_name].createSurface,再缺省取最近一次 definePluginSurface 登记的工厂。 */
|
|
366
|
+
factory?: (input: SurfaceCreateInput) => SurfaceMountResult;
|
|
367
|
+
win?: Window;
|
|
368
|
+
doc?: Document;
|
|
369
|
+
vue?: FrameVueRuntime;
|
|
370
|
+
/** 挂载根元素;缺省 #kimpo-frame-root。 */
|
|
371
|
+
root?: unknown;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const RUNTIME_STARTED = Symbol.for('kimpo.frame.runtime.started');
|
|
375
|
+
let registeredFactory: ((input: SurfaceCreateInput) => SurfaceMountResult) | undefined;
|
|
376
|
+
|
|
377
|
+
/** definePluginSurface 在沙箱框架里调用:登记工厂并(首次)启动运行时。 */
|
|
378
|
+
export function registerFrameSurfaceFactory(factory: (input: SurfaceCreateInput) => SurfaceMountResult): void {
|
|
379
|
+
registeredFactory = factory;
|
|
380
|
+
startKimpoFrameRuntime();
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function readGlobal(win: Window, path: string): unknown {
|
|
384
|
+
return path
|
|
385
|
+
.split('.')
|
|
386
|
+
.filter(Boolean)
|
|
387
|
+
.reduce<unknown>((cur, key) => (isRecord(cur) ? cur[key] : undefined), win as unknown);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* 启动框架运行时(幂等):等待宿主握手,挂载插件组件。不在沙箱框架里时直接返回 false。
|
|
392
|
+
* 插件一般不必直接调用——definePluginSurface 在框架里会自动调用;不使用 definePluginSurface 的 bundle 可手动调用。
|
|
393
|
+
*/
|
|
394
|
+
export function startKimpoFrameRuntime(options: FrameRuntimeOptions = {}): boolean {
|
|
395
|
+
const win = options.win ?? (typeof window === 'undefined' ? undefined : window);
|
|
396
|
+
const doc = options.doc ?? (typeof document === 'undefined' ? undefined : document);
|
|
397
|
+
if (!win || !doc) return false;
|
|
398
|
+
const meta = readKimpoFrameMeta(doc);
|
|
399
|
+
if (!meta) return false;
|
|
400
|
+
const flagHost = win as unknown as Record<symbol, boolean>;
|
|
401
|
+
if (flagHost[RUNTIME_STARTED]) return true;
|
|
402
|
+
flagHost[RUNTIME_STARTED] = true;
|
|
403
|
+
|
|
404
|
+
const onInit = (event: MessageEvent) => {
|
|
405
|
+
// 只认父窗口的第一次握手;其余 window 层消息一律忽略。
|
|
406
|
+
if (event.source !== win.parent) return;
|
|
407
|
+
const data = event.data as Record<string, unknown> | null;
|
|
408
|
+
if (!isRecord(data) || data.kimpoFrame !== 'init' || !event.ports?.[0]) return;
|
|
409
|
+
win.removeEventListener('message', onInit);
|
|
410
|
+
bootOnPort(event.ports[0], meta, options, win, doc);
|
|
411
|
+
};
|
|
412
|
+
win.addEventListener('message', onInit);
|
|
413
|
+
return true;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function bootOnPort(port: MessagePort, meta: KimpoFrameMeta, options: FrameRuntimeOptions, win: Window, doc: Document): void {
|
|
417
|
+
const client = createFrameClient(port);
|
|
418
|
+
const log = (level: 'info' | 'warn' | 'error', message: string) => client.post({ t: 'log', level, message });
|
|
419
|
+
win.addEventListener('error', event => log('error', String((event as ErrorEvent).message ?? event)));
|
|
420
|
+
win.addEventListener('unhandledrejection', event => log('error', `unhandled rejection: ${String((event as PromiseRejectionEvent).reason)}`));
|
|
421
|
+
|
|
422
|
+
let app: ReturnType<FrameVueRuntime['createApp']> | undefined;
|
|
423
|
+
let hostPropsState: { value: Record<string, unknown> } | undefined;
|
|
424
|
+
let instance: { value: unknown } | undefined;
|
|
425
|
+
|
|
426
|
+
client.on('init', msg => {
|
|
427
|
+
try {
|
|
428
|
+
if (msg.v !== FRAME_PROTOCOL_VERSION) throw new Error(`unsupported frame protocol version ${String(msg.v)}`);
|
|
429
|
+
const vue = options.vue ?? (readGlobal(win, 'Vue') as FrameVueRuntime | undefined);
|
|
430
|
+
if (!vue || typeof vue.createApp !== 'function') throw new Error('Vue runtime is not available in the sandbox frame');
|
|
431
|
+
const exported = readGlobal(win, `${meta.global_name}.createSurface`);
|
|
432
|
+
const factory = options.factory ?? (typeof exported === 'function' ? (exported as typeof registeredFactory) : registeredFactory);
|
|
433
|
+
if (!factory) throw new Error(`no createSurface found for ${meta.global_name}`);
|
|
434
|
+
const baseInput = (client.decode(msg.input) ?? {}) as Record<string, unknown>;
|
|
435
|
+
const input = { ...baseInput, hostBridge: client.decode(msg.bridge) ?? {} } as unknown as SurfaceCreateInput;
|
|
436
|
+
const mounted = factory(input);
|
|
437
|
+
if (!mounted?.component) throw new Error('createSurface returned no component');
|
|
438
|
+
const precedence = msg.propsPrecedence === 'host' ? 'host' : 'plugin';
|
|
439
|
+
const state = vue.shallowReactive({ value: (client.decode(msg.hostProps) ?? {}) as Record<string, unknown> });
|
|
440
|
+
hostPropsState = state;
|
|
441
|
+
const Root = {
|
|
442
|
+
name: 'KimpoFrameRoot',
|
|
443
|
+
setup() {
|
|
444
|
+
const inst = vue.ref<unknown>(null);
|
|
445
|
+
instance = inst;
|
|
446
|
+
return () => vue.h(mounted.component, { ...mergeSurfaceProps(state.value, mounted.props, precedence), ref: inst });
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
app = vue.createApp(Root);
|
|
450
|
+
app.config.errorHandler = (error: unknown) => log('error', `render error: ${String(error)}`);
|
|
451
|
+
app.mount(options.root ?? doc.getElementById('kimpo-frame-root') ?? doc.body);
|
|
452
|
+
client.post({ t: 'mounted' });
|
|
453
|
+
observeHeight(doc, win, height => client.post({ t: 'resize', height }));
|
|
454
|
+
} catch (error) {
|
|
455
|
+
client.post({ t: 'mount-error', message: error instanceof Error ? error.message : String(error) });
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
|
|
459
|
+
client.on('props', msg => {
|
|
460
|
+
if (hostPropsState) hostPropsState.value = (client.decode(msg.hostProps) ?? {}) as Record<string, unknown>;
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
client.on('expose', async msg => {
|
|
464
|
+
try {
|
|
465
|
+
const target = instance?.value as Record<string, unknown> | null | undefined;
|
|
466
|
+
const method = target?.[String(msg.method)];
|
|
467
|
+
const args = (Array.isArray(msg.args) ? msg.args : []).map(arg => client.decode(arg));
|
|
468
|
+
const value = typeof method === 'function' ? await (method as AnyFn).apply(target, args) : undefined;
|
|
469
|
+
client.post({ t: 'expose-result', id: msg.id, ok: true, value: client.encodeArg(value) });
|
|
470
|
+
} catch (error) {
|
|
471
|
+
client.post({ t: 'expose-result', id: msg.id, ok: false, error: { message: String(error) } });
|
|
472
|
+
}
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
client.on('destroy', () => {
|
|
476
|
+
try {
|
|
477
|
+
app?.unmount();
|
|
478
|
+
} catch {
|
|
479
|
+
// 宿主即将移除框架,卸载失败无需处理。
|
|
480
|
+
}
|
|
481
|
+
app = undefined;
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** 内容高度变化时上报(动作配置面板等需要按内容撑高的挂载点用)。 */
|
|
486
|
+
function observeHeight(doc: Document, win: Window, report: (height: number) => void): void {
|
|
487
|
+
const measure = () => report(Math.ceil(doc.documentElement?.scrollHeight ?? doc.body?.scrollHeight ?? 0));
|
|
488
|
+
measure();
|
|
489
|
+
const RO = (win as unknown as { ResizeObserver?: typeof ResizeObserver }).ResizeObserver;
|
|
490
|
+
if (RO && doc.body) new RO(measure).observe(doc.body);
|
|
491
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// manifest capabilities.frontend.routes 的前端类型与自检。
|
|
2
|
+
//
|
|
3
|
+
// 插件前端会调用的宿主 HTTP 接口须在 manifest 里逐条声明;宿主前端经 hostBridge.request 发出的请求会自动
|
|
4
|
+
// 带上插件身份头 X-Kimpo-Plugin,后端路由闸按「声明 ∩ 管理员授予」匹配:观察模式只记日志,强制模式未命中
|
|
5
|
+
// 返回 403 PLUGIN_ROUTE_NOT_DECLARED。规则与 Go 侧 plugin/frontend_routes.go、宿主准入同口径:
|
|
6
|
+
// - method:大写 GET / POST / PUT / PATCH / DELETE;WebSocket 握手记为 GET;
|
|
7
|
+
// - path:以 /api/ 或 /ws/ 开头,段不得为空、不得为 . / ..,不得含 ? # % \ 与空白;
|
|
8
|
+
// - `*` 整段匹配恰好一段,`**` 整段匹配零或多段且只能是最后一段;
|
|
9
|
+
// - 通配前至少固定 /api/<版本>/<资源>(/ws/ 下至少 /ws/<通道>);同 manifest 内不得重复,最多 256 条。
|
|
10
|
+
|
|
11
|
+
/** 允许声明的 HTTP 方法。 */
|
|
12
|
+
export type FrontendRouteMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
13
|
+
|
|
14
|
+
/** 单条前端路由声明。 */
|
|
15
|
+
export interface FrontendRouteDecl {
|
|
16
|
+
method: FrontendRouteMethod;
|
|
17
|
+
/** 路径模板,如 `/api/v1/sheet/sessions/*\/export/xlsx`、`/api/v1/sheet/**`。 */
|
|
18
|
+
path: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const METHODS = new Set<string>(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);
|
|
22
|
+
const MAX_ROUTES = 256;
|
|
23
|
+
const MAX_PATH_LEN = 512;
|
|
24
|
+
|
|
25
|
+
/** 校验单条声明,非法时返回错误说明,合法返回 null。 */
|
|
26
|
+
export function validateFrontendRoute(route: { method: string; path: string }): string | null {
|
|
27
|
+
if (!METHODS.has(route.method)) {
|
|
28
|
+
return `method "${route.method}" must be one of GET/POST/PUT/PATCH/DELETE (uppercase; WebSocket handshakes are GET)`;
|
|
29
|
+
}
|
|
30
|
+
const path = route.path;
|
|
31
|
+
if (typeof path !== 'string') return 'path must be a string';
|
|
32
|
+
if (path.length > MAX_PATH_LEN) return `path exceeds ${MAX_PATH_LEN} characters`;
|
|
33
|
+
let minLiteral: number;
|
|
34
|
+
if (path.startsWith('/api/')) minLiteral = 3;
|
|
35
|
+
else if (path.startsWith('/ws/')) minLiteral = 2;
|
|
36
|
+
else return `path "${path}" must start with /api/ or /ws/`;
|
|
37
|
+
if (/[?#%\\\s]/.test(path)) {
|
|
38
|
+
return `path "${path}" must not contain query, fragment, percent-encoding, backslash or whitespace`;
|
|
39
|
+
}
|
|
40
|
+
const segments = path.slice(1).split('/');
|
|
41
|
+
let literalPrefix = 0;
|
|
42
|
+
let wildcardSeen = false;
|
|
43
|
+
for (let i = 0; i < segments.length; i += 1) {
|
|
44
|
+
const seg = segments[i];
|
|
45
|
+
if (seg === '') return `path "${path}" must not contain empty segments or a trailing slash`;
|
|
46
|
+
if (seg === '.' || seg === '..') return `path "${path}" must not contain dot segments`;
|
|
47
|
+
if (seg === '**') {
|
|
48
|
+
if (i !== segments.length - 1) return `path "${path}": ** is only allowed as the last segment`;
|
|
49
|
+
wildcardSeen = true;
|
|
50
|
+
} else if (seg === '*') {
|
|
51
|
+
wildcardSeen = true;
|
|
52
|
+
} else if (seg.includes('*')) {
|
|
53
|
+
return `path "${path}": wildcard must be a whole segment (* or **)`;
|
|
54
|
+
} else if (!wildcardSeen) {
|
|
55
|
+
literalPrefix += 1;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (wildcardSeen && literalPrefix < minLiteral) {
|
|
59
|
+
return `path "${path}": wildcards need at least ${minLiteral} fixed leading segments`;
|
|
60
|
+
}
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 校验一组声明(数量、重复、逐条),返回全部错误(空数组即通过)。 */
|
|
65
|
+
export function validateFrontendRoutes(routes: ReadonlyArray<{ method: string; path: string }>): string[] {
|
|
66
|
+
const errors: string[] = [];
|
|
67
|
+
if (routes.length > MAX_ROUTES) errors.push(`at most ${MAX_ROUTES} routes allowed, got ${routes.length}`);
|
|
68
|
+
const seen = new Set<string>();
|
|
69
|
+
routes.forEach((route, i) => {
|
|
70
|
+
const err = validateFrontendRoute(route);
|
|
71
|
+
if (err) errors.push(`routes[${i}]: ${err}`);
|
|
72
|
+
const key = `${route.method} ${route.path}`;
|
|
73
|
+
if (seen.has(key)) errors.push(`routes[${i}]: duplicate route "${key}"`);
|
|
74
|
+
seen.add(key);
|
|
75
|
+
});
|
|
76
|
+
return errors;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 判断请求是否命中某条声明(插件自测用;宿主后端是权威实现)。
|
|
81
|
+
* HEAD 按 GET 匹配;请求路径末尾单个 "/" 忽略;含空段或点段的路径不命中。
|
|
82
|
+
*/
|
|
83
|
+
export function matchFrontendRoute(route: FrontendRouteDecl, method: string, requestPath: string): boolean {
|
|
84
|
+
let m = method.trim().toUpperCase();
|
|
85
|
+
if (m === 'HEAD') m = 'GET';
|
|
86
|
+
if (route.method !== m || !requestPath.startsWith('/')) return false;
|
|
87
|
+
let p = requestPath.slice(1);
|
|
88
|
+
if (p.length > 0 && p.endsWith('/')) p = p.slice(0, -1);
|
|
89
|
+
if (p === '') return false;
|
|
90
|
+
const req = p.split('/');
|
|
91
|
+
if (req.some(s => s === '' || s === '.' || s === '..')) return false;
|
|
92
|
+
const pat = route.path.slice(1).split('/');
|
|
93
|
+
for (let i = 0; i < pat.length; i += 1) {
|
|
94
|
+
if (pat[i] === '**') return true;
|
|
95
|
+
if (i >= req.length) return false;
|
|
96
|
+
if (pat[i] !== '*' && pat[i] !== req[i]) return false;
|
|
97
|
+
}
|
|
98
|
+
return pat.length === req.length;
|
|
99
|
+
}
|
package/src/hooks.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// 前端扩展槽(slot)注册表的类型契约。
|
|
2
|
+
//
|
|
3
|
+
// 🔴 定位(1.1.0-tp.18 起如实标注,已知限制 KL-52):**插件内部自用契约,宿主不注入**。
|
|
4
|
+
// - 宿主没有向任何插件(同源档或沙箱档)注入注册表实例,任何宿主桥上都没有这样的键;
|
|
5
|
+
// 插件不能借它往宿主页面的扩展点挂组件——宿主页面能挂插件的位置只有 manifest
|
|
6
|
+
// `capabilities.frontend.surfaces` 声明的挂载点(见 surface.ts)。
|
|
7
|
+
// - 它与 Go 侧 direction/hooks(后端钩子点:record.before_save 等)无关,名字相近仅是历史原因。
|
|
8
|
+
// - 用途:插件在自己的前端里组织「可插拔面板 / 子模块」时,可按本接口自行实现一个注册表
|
|
9
|
+
// (replace 槽取最高 priority、append 槽按 priority 排序等语义),便于与其他插件共用同一套心智模型。
|
|
10
|
+
// 这里只有接口与数据类型,不含实现。
|
|
11
|
+
|
|
12
|
+
// 槽位类型:替换 / 追加 / 前插 / 注入
|
|
13
|
+
export type SlotType = 'replace' | 'append' | 'prepend' | 'inject';
|
|
14
|
+
|
|
15
|
+
// 槽位定义:由 host 声明一个可被插件填充的扩展点
|
|
16
|
+
export interface SlotDefinition {
|
|
17
|
+
id: string;
|
|
18
|
+
title: string; // 可读名称
|
|
19
|
+
description?: string; // 可选描述
|
|
20
|
+
type: SlotType; // replace/append/prepend/inject
|
|
21
|
+
maxPlugins?: number; // 最大插件数(0 = 不限)
|
|
22
|
+
requiredPermissions?: string[]; // 所需权限
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// 槽位注册:插件把自身挂到某个槽位
|
|
26
|
+
export interface SlotRegistration {
|
|
27
|
+
id: string;
|
|
28
|
+
slotId: string;
|
|
29
|
+
pluginId: string;
|
|
30
|
+
instanceName: string;
|
|
31
|
+
type: SlotType;
|
|
32
|
+
priority: number; // 越大越靠前(replace 时取最高优先级)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 前端扩展注册表契约(插件内部自用,宿主不注入,见文件头)。
|
|
37
|
+
* 插件自行实现本接口来管理自己前端里的扩展槽;不要在宿主桥上找 registry。
|
|
38
|
+
*/
|
|
39
|
+
export interface FrontendExtensionRegistry {
|
|
40
|
+
registerSlot(slotId: string, def: SlotDefinition): boolean;
|
|
41
|
+
registerSlotRegistration(reg: SlotRegistration): boolean;
|
|
42
|
+
unregisterSlotRegistration(slotId: string, pluginId: string): boolean;
|
|
43
|
+
getRegistrations(slotId: string): SlotRegistration[];
|
|
44
|
+
getSlot(slotId: string): SlotDefinition | undefined;
|
|
45
|
+
getSlots(): SlotDefinition[];
|
|
46
|
+
getPluginSlots(pluginId: string): SlotRegistration[];
|
|
47
|
+
clear(): void;
|
|
48
|
+
}
|