@neogis-auxiliary/adapters 0.0.0-stage → 0.2.0-next.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,4 @@
1
+ import type { CardBindingsPort } from '@neogis-auxiliary/core';
2
+ import type { AdapterOptions } from './types.js';
3
+ /** Compile platform rules independently of the host adapter. */
4
+ export declare function createCardBindings(options: AdapterOptions): CardBindingsPort;
@@ -0,0 +1,162 @@
1
+ import { isAlias, isScalar } from '@neogis-auxiliary/core';
2
+ import { RuleCompiler, compileSubscription } from './compiler.js';
3
+ import { builtinConverters } from './converters.js';
4
+ import { checkJson, keys, record } from './shared.js';
5
+ /** Compile platform rules independently of the host adapter. */
6
+ export function createCardBindings(options) {
7
+ checkJson(options.config, 'bindings');
8
+ const entries = Object.entries(record(options.config, 'bindings')).map(([name, raw]) => {
9
+ if (!isAlias(name))
10
+ throw new Error('无效绑定名称:' + name);
11
+ const rule = record(raw, name);
12
+ keys(rule, ['read', 'refreshOn', 'inputs'], name);
13
+ const inputs = [];
14
+ if (rule.inputs !== undefined) {
15
+ if (!Array.isArray(rule.inputs) || !rule.inputs.every(isAlias) || new Set(rule.inputs).size !== rule.inputs.length) {
16
+ throw new Error('inputs 需要唯一的参数名:' + name);
17
+ }
18
+ inputs.push(...rule.inputs);
19
+ }
20
+ const compiler = new RuleCompiler(options.targets, { ...builtinConverters, ...options.converters }, inputs, true);
21
+ const input = record(rule.read, name + '.read');
22
+ keys(input, ['call', 'read', 'compose', 'args', 'convert', 'extract'], name + '.read');
23
+ const { extract, ...mapping } = input;
24
+ if (extract !== undefined && (typeof extract !== 'string' || !extract))
25
+ throw new Error('extract 需要非空字段路径');
26
+ if (extract !== undefined && mapping.convert !== undefined)
27
+ throw new Error('extract 不可与 convert 同用');
28
+ mapping.convert ??= extract === undefined
29
+ ? { type: 'identity' }
30
+ : { type: 'getOptionalProperty', args: ['$result', extract.split('.')] };
31
+ const read = compiler.compile(mapping, name + '.read', true);
32
+ const subscribe = rule.refreshOn === undefined ? undefined
33
+ : compileSubscription(rule.refreshOn, name + '.refreshOn', options.targets);
34
+ return { name, inputs, read, subscribe };
35
+ });
36
+ const shared = new Map();
37
+ const instances = new Map();
38
+ let notify;
39
+ async function refresh(entry, readings, reading) {
40
+ const version = ++reading.version;
41
+ let value = null;
42
+ try {
43
+ const result = await entry.read(...reading.args);
44
+ if (isScalar(result))
45
+ value = result;
46
+ }
47
+ catch { /* The card renders its fallback for missing or failed values. */ }
48
+ if (!notify || readings.get(entry.name) !== reading || reading.version !== version || reading.value === value)
49
+ return;
50
+ reading.value = value;
51
+ notify();
52
+ }
53
+ function startReading(entry, readings, reading) {
54
+ reading.pending = refresh(entry, readings, reading);
55
+ return reading.pending;
56
+ }
57
+ function refreshEntry(entry) {
58
+ if (!notify)
59
+ return [];
60
+ const pending = [];
61
+ for (const readings of entry.inputs.length ? instances.values() : [shared]) {
62
+ const reading = readings.get(entry.name);
63
+ if (reading)
64
+ pending.push(startReading(entry, readings, reading));
65
+ }
66
+ return pending;
67
+ }
68
+ return {
69
+ async refreshBindings() {
70
+ await Promise.all(entries.flatMap(refreshEntry));
71
+ },
72
+ async whenBindingsReady(card) {
73
+ const instance = instances.get(card.id);
74
+ await Promise.all([...shared.values(), ...(instance?.values() ?? [])].map(reading => reading.pending));
75
+ },
76
+ getBindings(card) {
77
+ const values = Object.create(null);
78
+ for (const [name, reading] of shared)
79
+ if (reading.value !== undefined)
80
+ values[name] = reading.value;
81
+ for (const [name, reading] of instances.get(card?.id ?? '') ?? []) {
82
+ if (reading.value !== undefined)
83
+ values[name] = reading.value;
84
+ }
85
+ return Object.freeze(values);
86
+ },
87
+ syncCards(cards) {
88
+ if (!notify)
89
+ return;
90
+ const ids = new Set(cards.map(card => card.id));
91
+ for (const [id, readings] of instances) {
92
+ if (ids.has(id))
93
+ continue;
94
+ readings.clear();
95
+ instances.delete(id);
96
+ }
97
+ for (const card of cards) {
98
+ const readings = instances.get(card.id) ?? new Map();
99
+ for (const entry of entries) {
100
+ if (!entry.inputs.length)
101
+ continue;
102
+ const args = entry.inputs.map(name => card.params?.[name]);
103
+ if (!args.every(isScalar)) {
104
+ readings.delete(entry.name);
105
+ continue;
106
+ }
107
+ const existing = readings.get(entry.name);
108
+ if (existing && args.every((value, index) => value === existing.args[index]))
109
+ continue;
110
+ const reading = { args, version: 0 };
111
+ readings.set(entry.name, reading);
112
+ void startReading(entry, readings, reading);
113
+ }
114
+ instances.set(card.id, readings);
115
+ }
116
+ },
117
+ onBindingsChanged(listener) {
118
+ if (notify)
119
+ throw new Error('绑定实例已经连接');
120
+ notify = listener;
121
+ shared.clear();
122
+ let active = true;
123
+ const cleanups = [];
124
+ const stop = () => {
125
+ if (!active)
126
+ return;
127
+ active = false;
128
+ notify = undefined;
129
+ for (const readings of instances.values())
130
+ readings.clear();
131
+ instances.clear();
132
+ const errors = [];
133
+ for (const cleanup of cleanups.splice(0)) {
134
+ try {
135
+ cleanup();
136
+ }
137
+ catch (error) {
138
+ errors.push(error);
139
+ }
140
+ }
141
+ if (errors.length)
142
+ throw new AggregateError(errors, '绑定订阅清理失败');
143
+ };
144
+ try {
145
+ for (const entry of entries) {
146
+ if (!entry.inputs.length)
147
+ shared.set(entry.name, { args: [], version: 0 });
148
+ const refreshAll = () => { if (active)
149
+ void Promise.all(refreshEntry(entry)); };
150
+ if (entry.subscribe)
151
+ cleanups.push(entry.subscribe(refreshAll));
152
+ refreshAll();
153
+ }
154
+ }
155
+ catch (error) {
156
+ stop();
157
+ throw error;
158
+ }
159
+ return stop;
160
+ },
161
+ };
162
+ }
@@ -0,0 +1,9 @@
1
+ import { type CardActionsPort } from '@neogis-auxiliary/core';
2
+ import type { AdapterOptions } from './types.js';
3
+ export interface CardActionMapping {
4
+ readonly inputs?: readonly string[];
5
+ readonly call: string;
6
+ readonly args?: readonly unknown[];
7
+ }
8
+ /** Compile commands separately from the bindings refreshed by data and map events. */
9
+ export declare function createCardActions(options: AdapterOptions): CardActionsPort;
@@ -0,0 +1,39 @@
1
+ import { HostDataError, isAlias, isScalar } from '@neogis-auxiliary/core';
2
+ import { RuleCompiler } from './compiler.js';
3
+ import { builtinConverters } from './converters.js';
4
+ import { checkJson, keys, record } from './shared.js';
5
+ /** Compile commands separately from the bindings refreshed by data and map events. */
6
+ export function createCardActions(options) {
7
+ checkJson(options.config, 'actions');
8
+ const commands = new Map(Object.entries(record(options.config, 'actions')).map(([name, raw]) => {
9
+ const path = 'actions.' + name;
10
+ if (!isAlias(name))
11
+ throw new Error('无效动作名称:' + name);
12
+ const rule = record(raw, path);
13
+ keys(rule, ['inputs', 'call', 'args'], path);
14
+ const inputs = rule.inputs === undefined ? [] : rule.inputs;
15
+ if (!Array.isArray(inputs) || !inputs.every(isAlias) || inputs.includes('scope') || new Set(inputs).size !== inputs.length) {
16
+ throw new Error(path + '.inputs 需要唯一参数名,scope 由 SDK 提供');
17
+ }
18
+ const compiler = new RuleCompiler(options.targets, { ...builtinConverters, ...options.converters }, [...inputs, 'scope'], true, args => args[inputs.length].active, true);
19
+ const args = rule.args === undefined ? inputs.map(input => '$input.' + input) : rule.args;
20
+ const invoke = compiler.compile({ call: rule.call, args, convert: { type: 'identity' } }, path);
21
+ return [name, { inputs, invoke }];
22
+ }));
23
+ return {
24
+ async invoke(name, card, scope) {
25
+ const command = commands.get(name);
26
+ if (!command)
27
+ throw new HostDataError('unsupported', '平台未提供此动作:' + name, 'ACTION_UNSUPPORTED');
28
+ const values = command.inputs.map(input => card.params?.[input]);
29
+ const missing = values.findIndex(value => !isScalar(value) || value === null);
30
+ if (missing >= 0)
31
+ throw new HostDataError('error', '缺少动作参数:' + command.inputs[missing], 'ACTION_UNCONFIGURED');
32
+ if (!scope.active)
33
+ return;
34
+ const result = await command.invoke(...values, scope);
35
+ if (typeof result === 'function')
36
+ return () => { result(); };
37
+ },
38
+ };
39
+ }
@@ -0,0 +1,22 @@
1
+ import type { AdapterFunction, ConverterRegistry, TargetRegistry } from './types.js';
2
+ export declare class RuleCompiler {
3
+ private readonly targets;
4
+ private readonly converters;
5
+ private readonly inputNames;
6
+ private readonly asyncAllowed;
7
+ private readonly isActive?;
8
+ private readonly preserveLateResult;
9
+ private readonly active;
10
+ constructor(targets: TargetRegistry, converters: ConverterRegistry, inputNames: readonly string[], asyncAllowed: boolean, isActive?: ((sdkArgs: unknown[]) => boolean) | undefined, preserveLateResult?: boolean);
11
+ private visit;
12
+ /** Resolve dependencies in order, without adding a Promise to synchronous calls. */
13
+ private collect;
14
+ private value;
15
+ private arguments;
16
+ private conversion;
17
+ private target;
18
+ private result;
19
+ private rule;
20
+ compile(value: unknown, path: string, nullable?: boolean): AdapterFunction;
21
+ }
22
+ export declare function compileSubscription(value: unknown, path: string, targets: TargetRegistry): (listener: () => void) => () => void;
@@ -0,0 +1,293 @@
1
+ import { cloneData, fail, getPath, isPromise, keys, name, pathParts, record, requireDenseArray, safeKey, synchronous, withPath } from './shared.js';
2
+ /** Check ordinary properties without invoking getters or calling platform methods. */
3
+ const dynamicMember = Symbol('dynamic member');
4
+ function checkMember(value, parts, path) {
5
+ let current = value;
6
+ for (const part of parts) {
7
+ if ((typeof current !== 'object' && typeof current !== 'function') || current === null)
8
+ fail(path, '目标路径不可访问');
9
+ let owner = current;
10
+ let descriptor;
11
+ while (owner && !descriptor) {
12
+ descriptor = Object.getOwnPropertyDescriptor(owner, part);
13
+ owner = Object.getPrototypeOf(owner);
14
+ }
15
+ if (!descriptor)
16
+ fail(path, '目标字段不存在:' + part);
17
+ if (descriptor.get)
18
+ return dynamicMember;
19
+ current = descriptor.value;
20
+ }
21
+ return current;
22
+ }
23
+ function checkCallable(value, parts, path) {
24
+ const member = checkMember(value, parts, path);
25
+ if (member !== dynamicMember && typeof member !== 'function')
26
+ fail(path, '目标成员不是方法');
27
+ }
28
+ export class RuleCompiler {
29
+ targets;
30
+ converters;
31
+ inputNames;
32
+ asyncAllowed;
33
+ isActive;
34
+ preserveLateResult;
35
+ active = new Set();
36
+ constructor(targets, converters, inputNames, asyncAllowed, isActive, preserveLateResult = false) {
37
+ this.targets = targets;
38
+ this.converters = converters;
39
+ this.inputNames = inputNames;
40
+ this.asyncAllowed = asyncAllowed;
41
+ this.isActive = isActive;
42
+ this.preserveLateResult = preserveLateResult;
43
+ }
44
+ visit(value, path, compile) {
45
+ if (this.active.has(value))
46
+ fail(path, '配置包含循环引用');
47
+ this.active.add(value);
48
+ try {
49
+ return compile();
50
+ }
51
+ finally {
52
+ this.active.delete(value);
53
+ }
54
+ }
55
+ /** Resolve dependencies in order, without adding a Promise to synchronous calls. */
56
+ collect(entries, evaluate, pathFor) {
57
+ const values = [];
58
+ const advance = (start) => {
59
+ for (let index = start; index < entries.length; index++) {
60
+ const path = pathFor(index);
61
+ const value = withPath(path, () => evaluate(entries[index], index));
62
+ if (isPromise(value))
63
+ return this.result(value, path, resolved => {
64
+ values.push(resolved);
65
+ return advance(index + 1);
66
+ });
67
+ values.push(value);
68
+ }
69
+ return values;
70
+ };
71
+ return advance(0);
72
+ }
73
+ value(value, path, access) {
74
+ if (typeof value === 'string' && value.startsWith('$')) {
75
+ const [root, ...parts] = pathParts(value.slice(1), path);
76
+ if (!['input', 'result', 'item'].includes(root))
77
+ fail(path, '未知引用来源');
78
+ if (root === 'result' && !access.result)
79
+ fail(path, '调用前无法读取 $result');
80
+ if (root === 'item' && !access.item)
81
+ fail(path, '$item 只在 mapItems.item 中可用');
82
+ if (root === 'input' && parts.length && !this.inputNames.includes(parts[0]))
83
+ fail(path, '未知 SDK 参数:' + parts[0]);
84
+ return scope => getPath(scope[root], parts, path);
85
+ }
86
+ if (value === null || ['string', 'boolean', 'number'].includes(typeof value))
87
+ return () => value;
88
+ if (Array.isArray(value))
89
+ return this.visit(value, path, () => {
90
+ const children = value.map((child, index) => this.value(child, path + '[' + index + ']', access));
91
+ return scope => this.collect(children, child => child(scope), index => path + '[' + index + ']');
92
+ });
93
+ const object = record(value, path);
94
+ return this.visit(object, path, () => {
95
+ if (Object.hasOwn(object, 'literal')) {
96
+ keys(object, ['literal'], path);
97
+ const literal = cloneData(object.literal);
98
+ return () => cloneData(literal);
99
+ }
100
+ if (Object.hasOwn(object, 'convert')) {
101
+ keys(object, ['convert'], path);
102
+ return this.conversion(object.convert, path + '.convert', access);
103
+ }
104
+ const fields = Object.entries(object).map(([key, child]) => {
105
+ safeKey(key, path + '.' + key);
106
+ return [key, this.value(child, path + '.' + key, access)];
107
+ });
108
+ return scope => this.result(this.collect(fields, ([, evaluate]) => evaluate(scope), index => path + '.' + fields[index][0]), path, values => Object.fromEntries(fields.map(([key], index) => [key, values[index]])));
109
+ });
110
+ }
111
+ arguments(value, path, access) {
112
+ if (!Array.isArray(value))
113
+ fail(path, 'args 需要数组');
114
+ const compiled = value.map((item, index) => this.value(item, path + '[' + index + ']', access));
115
+ return scope => this.collect(compiled, evaluate => evaluate(scope), index => path + '[' + index + ']');
116
+ }
117
+ conversion(value, path, access) {
118
+ const rule = record(value, path);
119
+ return this.visit(rule, path, () => {
120
+ const type = name(rule.type, path + '.type');
121
+ keys(rule, type === 'mapItems' ? ['type', 'args', 'item'] : ['type', 'args'], path);
122
+ const args = this.arguments(Object.hasOwn(rule, 'args') ? rule.args : ['$result'], path + '.args', access);
123
+ if (type === 'mapItems') {
124
+ const item = this.conversion(rule.item, path + '.item', { ...access, item: true });
125
+ return scope => withPath(path, () => this.result(args(scope), path, resolved => {
126
+ const values = resolved;
127
+ if (values.length !== 1 || !Array.isArray(values[0]))
128
+ fail(path + '.args', 'mapItems 需要一个数组参数');
129
+ requireDenseArray(values[0], path + '.args[0]');
130
+ // Capture list membership for this invocation; each item retains its own scope.
131
+ return this.collect([...values[0]], value => item({ ...scope, item: value }), () => path + '.item');
132
+ }));
133
+ }
134
+ if (!Object.hasOwn(this.converters, type) || typeof this.converters[type] !== 'function')
135
+ fail(path + '.type', '转换器未注册:' + type);
136
+ const convert = this.converters[type];
137
+ return scope => withPath(path, () => this.result(args(scope), path, values => this.result(convert(...values), path, result => result)));
138
+ });
139
+ }
140
+ target(pathValue, path, callable) {
141
+ const parts = pathParts(name(pathValue, path), path);
142
+ const targetName = parts.shift();
143
+ if (!parts.length || !Object.hasOwn(this.targets, targetName))
144
+ fail(path, '目标未注册或缺少成员路径');
145
+ const target = this.targets[targetName];
146
+ if (callable)
147
+ checkCallable(target, parts, path);
148
+ else
149
+ checkMember(target, parts, path);
150
+ const member = parts.pop();
151
+ return () => {
152
+ const owner = getPath(target, parts, path);
153
+ const value = getPath(owner, [member], path);
154
+ if (callable && typeof value !== 'function')
155
+ fail(path, '目标成员不是方法');
156
+ return { owner, value };
157
+ };
158
+ }
159
+ result(value, path, complete) {
160
+ return withPath(path, () => {
161
+ if (!this.asyncAllowed)
162
+ return synchronous(complete(synchronous(value, path)), path);
163
+ const result = isPromise(value) ? Promise.resolve(value).then(complete) : complete(value);
164
+ return isPromise(result) ? Promise.resolve(result).catch(error => withPath(path, () => { throw error; })) : result;
165
+ });
166
+ }
167
+ rule(value, path, nullable) {
168
+ const rule = record(value, path);
169
+ return this.visit(rule, path, () => {
170
+ const sources = ['call', 'read', 'compose'].filter(key => Object.hasOwn(rule, key));
171
+ if (sources.length !== 1)
172
+ fail(path, '需要且只能提供 call/read/compose 之一');
173
+ const source = sources[0];
174
+ keys(rule, source === 'call' ? ['call', 'args', 'convert'] : [source, 'convert'], path);
175
+ const convert = this.conversion(rule.convert, path + '.convert', { result: true, item: false });
176
+ let read;
177
+ if (source === 'compose') {
178
+ const fields = Object.entries(record(rule.compose, path + '.compose')).map(([key, child]) => {
179
+ safeKey(key, path + '.compose.' + key);
180
+ return [key, this.rule(child, path + '.compose.' + key, false)];
181
+ });
182
+ read = scope => this.result(this.collect(fields, ([, evaluate]) => evaluate(scope), index => path + '.compose.' + fields[index][0]), path + '.compose', values => Object.fromEntries(fields.map(([key], index) => [key, values[index]])));
183
+ }
184
+ else {
185
+ const target = this.target(rule[source], path + '.' + source, source === 'call');
186
+ const args = source === 'call' && Object.hasOwn(rule, 'args') ? this.arguments(rule.args, path + '.args', { result: false, item: false }) : (scope) => scope.sdkArgs;
187
+ read = source === 'call'
188
+ ? scope => this.result(args(scope), path, values => {
189
+ // A conversion may have awaited while an action's live scope expired.
190
+ if (this.isActive && !this.isActive(scope.sdkArgs))
191
+ return undefined;
192
+ const { owner, value } = target();
193
+ return value.apply(owner, values);
194
+ })
195
+ : () => target().value;
196
+ }
197
+ return scope => withPath(path, () => this.result(read(scope), path, result => {
198
+ if (!this.preserveLateResult && this.isActive && !this.isActive(scope.sdkArgs))
199
+ return undefined;
200
+ if (nullable && result === null)
201
+ return null;
202
+ return convert({ ...scope, result });
203
+ }));
204
+ });
205
+ }
206
+ compile(value, path, nullable = false) {
207
+ const evaluate = this.rule(value, path, nullable);
208
+ return (...sdkArgs) => {
209
+ const input = Object.fromEntries(this.inputNames.map((key, index) => [key, sdkArgs[index]]));
210
+ return evaluate({ input, sdkArgs });
211
+ };
212
+ }
213
+ }
214
+ export function compileSubscription(value, path, targets) {
215
+ const rule = record(value, path);
216
+ const mode = rule.mode;
217
+ if (mode !== 'on-off' && mode !== 'returned-cleanup')
218
+ fail(path + '.mode', '未知订阅模式');
219
+ keys(rule, mode === 'on-off' ? ['mode', 'target', 'subscribe', 'unsubscribe', 'event'] : ['mode', 'target', 'subscribe'], path);
220
+ const targetName = name(rule.target, path + '.target');
221
+ if (!Object.hasOwn(targets, targetName))
222
+ fail(path, '订阅目标未注册');
223
+ const target = targets[targetName];
224
+ const subscribeName = name(rule.subscribe, path + '.subscribe');
225
+ safeKey(subscribeName, path + '.subscribe');
226
+ checkCallable(target, [subscribeName], path + '.subscribe');
227
+ const unsubscribeName = mode === 'on-off' ? name(rule.unsubscribe, path + '.unsubscribe') : '';
228
+ const eventName = mode === 'on-off' ? name(rule.event, path + '.event') : '';
229
+ if (mode === 'on-off') {
230
+ safeKey(unsubscribeName, path + '.unsubscribe');
231
+ checkCallable(target, [unsubscribeName], path + '.unsubscribe');
232
+ }
233
+ const invoke = (method, args) => {
234
+ const fn = getPath(target, [method], path);
235
+ if (typeof fn !== 'function')
236
+ fail(path, '事件成员不是方法');
237
+ return fn.apply(target, args);
238
+ };
239
+ function subscribe(listener) {
240
+ if (mode === 'returned-cleanup')
241
+ return invoke(subscribeName, [listener]);
242
+ try {
243
+ const returned = invoke(subscribeName, [eventName, listener]);
244
+ if (isPromise(returned)) {
245
+ // Invalid async subscriptions can register after the immediate rollback.
246
+ // Release again after either settlement, including register-then-reject.
247
+ const release = () => invoke(unsubscribeName, [eventName, listener]);
248
+ void Promise.resolve(returned).then(release, release).catch(() => { });
249
+ }
250
+ synchronous(returned, path);
251
+ }
252
+ catch (error) {
253
+ try {
254
+ synchronous(invoke(unsubscribeName, [eventName, listener]), path);
255
+ }
256
+ catch { /* Preserve the subscription failure. */ }
257
+ throw error;
258
+ }
259
+ return () => synchronous(invoke(unsubscribeName, [eventName, listener]), path);
260
+ }
261
+ return listener => withPath(path, () => {
262
+ let active = true;
263
+ const notify = () => { if (active)
264
+ listener(); };
265
+ let cleanup;
266
+ try {
267
+ const returned = subscribe(notify);
268
+ if (isPromise(returned)) {
269
+ // The caller still receives the synchronous contract error. Release any
270
+ // registration for which an invalid asynchronous API supplies cleanup later.
271
+ void Promise.resolve(returned).then(lateCleanup => {
272
+ if (typeof lateCleanup === 'function')
273
+ return lateCleanup();
274
+ }).catch(() => { });
275
+ }
276
+ cleanup = synchronous(returned, path);
277
+ }
278
+ catch (error) {
279
+ active = false;
280
+ throw error;
281
+ }
282
+ if (typeof cleanup !== 'function') {
283
+ active = false;
284
+ fail(path, '订阅必须返回清理函数');
285
+ }
286
+ return () => {
287
+ if (!active)
288
+ return;
289
+ active = false;
290
+ withPath(path, () => synchronous(cleanup(), path));
291
+ };
292
+ });
293
+ }
@@ -0,0 +1,11 @@
1
+ import { type FeatureSnapshot, type FieldDescriptor } from '@neogis-auxiliary/core';
2
+ import type { ConverterRegistry } from './types.js';
3
+ /** 可选路径缺失时返回默认值;仅显式开启时将空字符串视为缺失,保留 null、false 和 0。 */
4
+ export declare function getOptionalProperty(value: unknown, path: unknown, options?: unknown): unknown;
5
+ /**
6
+ * 通用字段类型表转换:按 fields 顺序生成 SDK 字段描述,未声明类型的字段不参与推断。
7
+ * typeMap 可把平台的文本/数值类型编码映射到 string、number、boolean,未知编码明确报错。
8
+ */
9
+ export declare function platformFieldTypesToFieldSchema(fields: unknown, fieldTypes: unknown, typeMap?: unknown): FieldDescriptor[] | undefined;
10
+ export declare function geoJsonFeatureToFeatureSnapshot(feature: unknown, layerId: string): FeatureSnapshot;
11
+ export declare const builtinConverters: ConverterRegistry;
@@ -0,0 +1,135 @@
1
+ import { isPosition, isRecord } from '@neogis-auxiliary/core';
2
+ import { cloneData, getPath, requireDenseArray, safeKey } from './shared.js';
3
+ function toString(value) {
4
+ if (typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value)))
5
+ return String(value);
6
+ throw new Error('toString 需要字符串或有限数字');
7
+ }
8
+ function toNumber(value) {
9
+ if ((typeof value !== 'string' && typeof value !== 'number') || (typeof value === 'string' && !value.trim()))
10
+ throw new Error('toNumber 需要非空数字文本或数字');
11
+ const result = Number(value);
12
+ if (!Number.isFinite(result))
13
+ throw new Error('toNumber 需要有限数字');
14
+ return result;
15
+ }
16
+ function getProperty(value, path) {
17
+ if (!Array.isArray(path) || !path.every(part => typeof part === 'string' || Number.isInteger(part)))
18
+ throw new Error('getProperty 需要路径数组');
19
+ try {
20
+ return getPath(value, path, 'getProperty');
21
+ }
22
+ catch (error) {
23
+ throw new Error(error instanceof Error ? error.message : String(error), { cause: error });
24
+ }
25
+ }
26
+ /** 可选路径缺失时返回默认值;仅显式开启时将空字符串视为缺失,保留 null、false 和 0。 */
27
+ export function getOptionalProperty(value, path, options = {}) {
28
+ requireDenseArray(path, 'getOptionalProperty.path');
29
+ if (!path.every(part => typeof part === 'string' || Number.isInteger(part)))
30
+ throw new Error('getOptionalProperty 需要路径数组');
31
+ // 先校验整个路径,不能因为前半段缺失就漏过后半段的不安全字段。
32
+ path.forEach(part => safeKey(String(part), 'getOptionalProperty.path'));
33
+ if (!isRecord(options) || Object.keys(options).some(key => !['defaultValue', 'emptyStringAsMissing'].includes(key))) {
34
+ throw new Error('getOptionalProperty 只支持 defaultValue 和 emptyStringAsMissing 选项');
35
+ }
36
+ if (options.emptyStringAsMissing !== undefined && typeof options.emptyStringAsMissing !== 'boolean') {
37
+ throw new Error('emptyStringAsMissing 需要布尔值');
38
+ }
39
+ let current = value;
40
+ for (const part of path) {
41
+ if (current === undefined || current === null)
42
+ return options.defaultValue;
43
+ if (typeof current !== 'object' && typeof current !== 'function')
44
+ throw new Error('getOptionalProperty 路径需要对象');
45
+ if (!(part in current))
46
+ return options.defaultValue;
47
+ // 不捕获 getter 或平台异常,读取失败不能被误认为可选字段缺失。
48
+ current = current[part];
49
+ }
50
+ return current === undefined || (options.emptyStringAsMissing && current === '') ? options.defaultValue : current;
51
+ }
52
+ /**
53
+ * 通用字段类型表转换:按 fields 顺序生成 SDK 字段描述,未声明类型的字段不参与推断。
54
+ * typeMap 可把平台的文本/数值类型编码映射到 string、number、boolean,未知编码明确报错。
55
+ */
56
+ export function platformFieldTypesToFieldSchema(fields, fieldTypes, typeMap = { string: 'string', number: 'number', boolean: 'boolean' }) {
57
+ requireDenseArray(fields, 'platformFieldTypesToFieldSchema.fields');
58
+ if (!fields.every(field => typeof field === 'string' && field.trim()) || new Set(fields).size !== fields.length) {
59
+ throw new Error('字段名称需要非空且不能重复');
60
+ }
61
+ if (!isRecord(typeMap) || Object.values(typeMap).some(type => !['string', 'number', 'boolean'].includes(type))) {
62
+ throw new Error('字段类型映射必须返回 string、number 或 boolean');
63
+ }
64
+ if (fieldTypes === undefined || fieldTypes === null)
65
+ return undefined;
66
+ if (!isRecord(fieldTypes))
67
+ throw new Error('字段类型表需要对象');
68
+ const result = [];
69
+ for (const field of fields) {
70
+ if (!Object.hasOwn(fieldTypes, field))
71
+ continue;
72
+ const rawType = fieldTypes[field];
73
+ if ((typeof rawType !== 'string' && !(typeof rawType === 'number' && Number.isFinite(rawType)))
74
+ || !Object.hasOwn(typeMap, String(rawType)))
75
+ throw new Error('字段类型没有对应映射:' + field);
76
+ result.push({ name: field, type: typeMap[String(rawType)] });
77
+ }
78
+ return result;
79
+ }
80
+ export function geoJsonFeatureToFeatureSnapshot(feature, layerId) {
81
+ if (!isRecord(feature) || feature.type !== 'Feature' || (feature.properties !== null && !isRecord(feature.properties)))
82
+ throw new Error('需要 GeoJSON Feature 和属性对象');
83
+ const featureId = toString(feature.id);
84
+ if (!featureId.trim() || !layerId.trim())
85
+ throw new Error('图层与要素需要稳定 ID');
86
+ let position;
87
+ if (isRecord(feature.geometry) && feature.geometry.type === 'Point') {
88
+ const coordinates = feature.geometry.coordinates;
89
+ if (!Array.isArray(coordinates) || !isPosition(coordinates.slice(0, 2)))
90
+ throw new Error('点坐标必须为有效 WGS 84 经纬度');
91
+ position = coordinates.slice(0, 2);
92
+ }
93
+ return { layerId, featureId, properties: cloneData(feature.properties ?? {}), ...(position ? { position } : {}) };
94
+ }
95
+ export const builtinConverters = Object.freeze({
96
+ identity: (value) => value,
97
+ toString,
98
+ toNumber,
99
+ createArray: (...values) => values,
100
+ createObject: (fields) => {
101
+ if (!isRecord(fields))
102
+ throw new Error('createObject 需要字段对象');
103
+ return { ...fields };
104
+ },
105
+ getProperty,
106
+ getOptionalProperty,
107
+ mapEnum: (value, table) => {
108
+ if (!isRecord(table) || !['string', 'number', 'boolean'].includes(typeof value) || !Object.hasOwn(table, String(value)))
109
+ throw new Error('枚举值没有对应映射');
110
+ return table[String(value)];
111
+ },
112
+ mapItems: (items, mapItem) => {
113
+ if (typeof mapItem !== 'function')
114
+ throw new Error('mapItems 需要逐项转换规则');
115
+ requireDenseArray(items, 'mapItems');
116
+ return items.map(item => mapItem(item));
117
+ },
118
+ findItem: (items, path, expectedValue) => {
119
+ requireDenseArray(items, 'findItem');
120
+ return items.find(item => getProperty(item, path) === expectedValue) ?? null;
121
+ },
122
+ parseJson: (text) => {
123
+ if (typeof text !== 'string')
124
+ throw new Error('parseJson 需要字符串');
125
+ return JSON.parse(text);
126
+ },
127
+ stringifyJson: (value) => {
128
+ const result = JSON.stringify(value);
129
+ if (result === undefined)
130
+ throw new Error('文档无法序列化');
131
+ return result;
132
+ },
133
+ geoJsonFeatureToFeatureSnapshot,
134
+ platformFieldTypesToFieldSchema,
135
+ });
@@ -0,0 +1,9 @@
1
+ import type { HostPort, MapEnginePort } from '@neogis-auxiliary/core';
2
+ import type { AdapterOptions } from './types.js';
3
+ export * from './types.js';
4
+ export { AdapterError } from './shared.js';
5
+ export { geoJsonFeatureToFeatureSnapshot, getOptionalProperty, platformFieldTypesToFieldSchema, builtinConverters } from './converters.js';
6
+ export declare function createMapEngineAdapter(options: AdapterOptions): MapEnginePort;
7
+ export declare function createPlatformHostAdapter(options: AdapterOptions): HostPort;
8
+ export { createCardBindings } from './bindings.js';
9
+ export { createCardActions, type CardActionMapping } from './card-actions.js';
package/dist/index.js ADDED
@@ -0,0 +1,127 @@
1
+ import { builtinConverters } from './converters.js';
2
+ import { compileSubscription, RuleCompiler } from './compiler.js';
3
+ import { checkJson, cloneData, dataProperty, fail, isPromise, keys, record, safeKey, synchronous, withPath } from './shared.js';
4
+ import { validateOutput } from './outputs.js';
5
+ export * from './types.js';
6
+ export { AdapterError } from './shared.js';
7
+ export { geoJsonFeatureToFeatureSnapshot, getOptionalProperty, platformFieldTypesToFieldSchema, builtinConverters } from './converters.js';
8
+ const engineInputs = {
9
+ getCamera: [], getBounds: [], getViewport: [], project: ['position'], unproject: ['point'],
10
+ };
11
+ const hostInputs = {
12
+ listLayers: [], getLayer: ['layerId'], getEnvironment: [], resolveFeature: ['layerId', 'featureId'],
13
+ queryPointFeatures: ['layerId'], querySpatialFeatures: ['layerId'],
14
+ readDocument: ['key'], writeDocument: ['key', 'value'], performAction: ['action', 'scope'], releaseActions: ['ownerId'],
15
+ };
16
+ const requiredHost = ['listLayers', 'getLayer', 'getEnvironment', 'resolveFeature', 'readDocument', 'writeDocument'];
17
+ const asynchronous = new Set(['getLayer', 'resolveFeature', 'queryPointFeatures', 'querySpatialFeatures', 'performAction']);
18
+ function mergeFunctions(destination, source, path) {
19
+ if (source === undefined)
20
+ return;
21
+ for (const [key, fn] of Object.entries(record(source, path))) {
22
+ safeKey(key, path + '.' + key);
23
+ if (typeof fn !== 'function')
24
+ fail(path + '.' + key, '注册项需要函数');
25
+ if (Object.hasOwn(destination, key))
26
+ fail(path + '.' + key, '注册名称冲突');
27
+ destination[key] = fn;
28
+ }
29
+ }
30
+ function prepare(options, role) {
31
+ const config = record(options.config, 'config');
32
+ checkJson(config, 'config');
33
+ keys(config, ['version', 'engine', 'host'], 'config');
34
+ if (config.version !== 1)
35
+ fail('config.version', '只支持配置版本 1');
36
+ const targets = record(options.targets, 'targets');
37
+ const section = typeof config[role] === 'string' ? { preset: config[role] } : record(config[role], role);
38
+ let preset;
39
+ let presetConfig = {};
40
+ if (Object.hasOwn(section, 'preset')) {
41
+ const presetName = section.preset;
42
+ if (typeof presetName !== 'string' || !options.presets || !Object.hasOwn(options.presets, presetName))
43
+ fail(role + '.preset', '预置未注册');
44
+ preset = options.presets[presetName];
45
+ if (!preset || preset.role !== role)
46
+ fail(role + '.preset', '预置角色不匹配');
47
+ presetConfig = record(dataProperty(preset, 'config', role + '.preset.config'), role + '.preset.config');
48
+ checkJson(presetConfig, role + '.preset.config');
49
+ if (Object.hasOwn(presetConfig, 'preset'))
50
+ fail(role + '.preset', '预置定义需要展开其继承配置');
51
+ }
52
+ const merged = { ...presetConfig, ...section };
53
+ delete merged.preset;
54
+ if (Object.hasOwn(section, 'events') || presetConfig.events !== undefined) {
55
+ const inherited = presetConfig.events === undefined ? {} : record(presetConfig.events, role + '.preset.events');
56
+ const overrides = section.events === undefined ? {} : record(section.events, role + '.events');
57
+ merged.events = { ...inherited, ...overrides };
58
+ }
59
+ const inputs = role === 'engine' ? engineInputs : hostInputs;
60
+ keys(merged, [...Object.keys(inputs), 'events'], role);
61
+ for (const method of role === 'engine' ? Object.keys(engineInputs) : requiredHost) {
62
+ if (merged[method] === undefined || merged[method] === null)
63
+ fail(role + '.' + method, '缺少必需能力');
64
+ }
65
+ const converters = { ...builtinConverters };
66
+ let bound;
67
+ if (preset?.bind)
68
+ bound = withPath(role + '.preset.bind', () => synchronous(preset.bind(targets), role + '.preset.bind'));
69
+ if (bound !== undefined) {
70
+ keys(record(bound, role + '.preset.bind'), ['converters'], role + '.preset.bind');
71
+ }
72
+ for (const [label, registry] of [['preset', preset], ['bound', bound], ['options', options]]) {
73
+ mergeFunctions(converters, registry?.converters, role + '.' + label + '.converters');
74
+ }
75
+ return { config: cloneData(merged), targets, converters, inputs };
76
+ }
77
+ function createMethods(options, role) {
78
+ const prepared = prepare(options, role);
79
+ const methods = {};
80
+ for (const [method, inputNames] of Object.entries(prepared.inputs)) {
81
+ const rule = prepared.config[method];
82
+ if (rule === null || rule === undefined)
83
+ continue;
84
+ const path = role + '.' + method;
85
+ // 参数转换可能异步完成;动作实际派发前仍需读取原会话的动态有效性。
86
+ const isActive = method === 'performAction' ? (args) => args[1].active : undefined;
87
+ const compiler = new RuleCompiler(prepared.targets, prepared.converters, inputNames, asynchronous.has(method), isActive);
88
+ const execute = compiler.compile(rule, path, ['getLayer', 'resolveFeature', 'readDocument'].includes(method));
89
+ methods[method] = (...args) => withPath(path, () => {
90
+ const result = execute(...args);
91
+ const validate = (value) => withPath(path, () => validateOutput(method, value, args, path));
92
+ return isPromise(result) ? Promise.resolve(result).then(validate) : validate(result);
93
+ });
94
+ }
95
+ const events = prepared.config.events === undefined ? {} : record(prepared.config.events, role + '.events');
96
+ keys(events, role === 'engine' ? ['camera', 'resize'] : ['dataChanged'], role + '.events');
97
+ const subscriptions = {};
98
+ for (const event of role === 'engine' ? ['camera', 'resize'] : ['dataChanged']) {
99
+ if (events[event] === null || events[event] === undefined) {
100
+ if (role === 'engine')
101
+ fail(role + '.events.' + event, '缺少必需事件');
102
+ continue;
103
+ }
104
+ subscriptions[event] = compileSubscription(events[event], role + '.events.' + event, prepared.targets);
105
+ }
106
+ return { methods, subscriptions };
107
+ }
108
+ export function createMapEngineAdapter(options) {
109
+ const { methods, subscriptions } = createMethods(options, 'engine');
110
+ return {
111
+ ...methods,
112
+ on(event, listener) {
113
+ if (!Object.hasOwn(subscriptions, event))
114
+ fail('engine.events', '未知地图事件');
115
+ return subscriptions[event](listener);
116
+ },
117
+ };
118
+ }
119
+ export function createPlatformHostAdapter(options) {
120
+ const { methods, subscriptions } = createMethods(options, 'host');
121
+ return {
122
+ ...methods,
123
+ ...(subscriptions.dataChanged ? { onDataChanged: subscriptions.dataChanged } : {}),
124
+ };
125
+ }
126
+ export { createCardBindings } from './bindings.js';
127
+ export { createCardActions } from './card-actions.js';
@@ -0,0 +1 @@
1
+ export declare function validateOutput(method: string, value: unknown, args: unknown[], path: string): unknown;
@@ -0,0 +1,117 @@
1
+ import { checkPointFeatures, checkSpatialFeatures, isPosition, isRecord } from '@neogis-auxiliary/core';
2
+ import { cloneData, fail, record, requireDenseArray } from './shared.js';
3
+ function finite(value) { return typeof value === 'number' && Number.isFinite(value); }
4
+ function pair(value) {
5
+ return Array.isArray(value) && value.length === 2 && Object.hasOwn(value, 0) && Object.hasOwn(value, 1) && value.every(finite);
6
+ }
7
+ function identifier(value) { return typeof value === 'string' && !!value.trim(); }
8
+ function enumValue(value, allowed) {
9
+ return typeof value === 'string' && allowed.includes(value);
10
+ }
11
+ function layer(value, path) {
12
+ // Read known protocol fields once. Class getters become own snapshot properties.
13
+ const { id, name, type, visible, fields: rawFields, displayField, fieldSchema: rawSchema } = record(value, path);
14
+ const fields = Array.isArray(rawFields) ? Array.from(rawFields) : rawFields;
15
+ if (!identifier(id) || typeof name !== 'string' || !enumValue(type, ['point', 'line', 'polygon'])
16
+ || typeof visible !== 'boolean' || !Array.isArray(fields) || !fields.every(identifier)
17
+ || new Set(fields).size !== fields.length)
18
+ fail(path, '图层 ID、名称、类型、显隐或字段列表无效');
19
+ if (displayField !== undefined && typeof displayField !== 'string')
20
+ fail(path, 'displayField 需要字符串');
21
+ let fieldSchema;
22
+ if (rawSchema !== undefined) {
23
+ if (!Array.isArray(rawSchema))
24
+ fail(path, 'fieldSchema 需要数组');
25
+ fieldSchema = Array.from(rawSchema).map((field, index) => {
26
+ const { name, type, label } = record(field, path + '.fieldSchema[' + index + ']');
27
+ if (!identifier(name) || !enumValue(type, ['string', 'number', 'boolean']) || (label !== undefined && typeof label !== 'string'))
28
+ fail(path, 'fieldSchema 无效');
29
+ return { name, type, ...(label !== undefined ? { label } : {}) };
30
+ });
31
+ }
32
+ return { id, name, type, visible, fields, ...(displayField !== undefined ? { displayField } : {}),
33
+ ...(fieldSchema !== undefined ? { fieldSchema } : {}) };
34
+ }
35
+ function feature(value, path) {
36
+ const { layerId, featureId, properties, position, revision, displayName } = record(value, path);
37
+ if (!identifier(layerId) || !identifier(featureId) || !isRecord(properties))
38
+ fail(path, '要素需要图层 ID、要素 ID 和属性对象');
39
+ if (position !== undefined && !isPosition(position))
40
+ fail(path, '要素位置需要 WGS 84 经纬度');
41
+ if (revision !== undefined && typeof revision !== 'string')
42
+ fail(path, 'revision 需要字符串');
43
+ if (displayName !== undefined && typeof displayName !== 'string')
44
+ fail(path, 'displayName 需要字符串');
45
+ return { layerId, featureId, properties, ...(position !== undefined ? { position } : {}),
46
+ ...(revision !== undefined ? { revision } : {}), ...(displayName !== undefined ? { displayName } : {}) };
47
+ }
48
+ export function validateOutput(method, value, args, path) {
49
+ if (['writeDocument', 'performAction', 'releaseActions'].includes(method))
50
+ return undefined;
51
+ if (value === null && ['getLayer', 'resolveFeature', 'readDocument'].includes(method))
52
+ return null;
53
+ if (value === undefined)
54
+ fail(path, '接口返回 undefined');
55
+ switch (method) {
56
+ case 'getCamera': {
57
+ const { center, zoom, bearing, pitch } = record(value, path);
58
+ if (!pair(center) || ![zoom, bearing, pitch].every(finite))
59
+ fail(path, '相机快照无效');
60
+ return cloneData({ center, zoom, bearing, pitch });
61
+ }
62
+ case 'getBounds': {
63
+ const { west, east, south, north, crossesAntimeridian } = record(value, path);
64
+ if (![west, east, south, north].every(finite) || typeof crossesAntimeridian !== 'boolean')
65
+ fail(path, '地图范围快照无效');
66
+ return { west, east, south, north, crossesAntimeridian };
67
+ }
68
+ case 'getViewport': {
69
+ const { width, height } = record(value, path);
70
+ if (!finite(width) || !finite(height) || width < 0 || height < 0)
71
+ fail(path, '视口需要非负 CSS 像素宽高');
72
+ return { width, height };
73
+ }
74
+ case 'project': {
75
+ const { x, y } = record(value, path);
76
+ if (typeof x !== 'number' || typeof y !== 'number')
77
+ fail(path, '投影需要数值 x/y');
78
+ return { x, y };
79
+ }
80
+ case 'unproject':
81
+ if (!pair(value))
82
+ fail(path, '反投影需要经纬度数值对');
83
+ return cloneData(value);
84
+ case 'listLayers': {
85
+ requireDenseArray(value, path);
86
+ const layers = value.map((item, index) => layer(item, path + '[' + index + ']'));
87
+ if (new Set(layers.map(item => item.id)).size !== layers.length)
88
+ fail(path, '图层 ID 重复');
89
+ return cloneData(layers);
90
+ }
91
+ case 'getLayer': {
92
+ const result = layer(value, path);
93
+ if (result.id !== args[0])
94
+ fail(path, '返回图层 ID 与查询不一致');
95
+ return cloneData(result);
96
+ }
97
+ case 'resolveFeature': {
98
+ const result = feature(value, path);
99
+ if (result.layerId !== args[0] || result.featureId !== args[1])
100
+ fail(path, '返回要素 ID 与查询不一致');
101
+ return cloneData(result);
102
+ }
103
+ case 'queryPointFeatures':
104
+ requireDenseArray(value, path);
105
+ return cloneData(checkPointFeatures(value, String(args[0])));
106
+ case 'querySpatialFeatures':
107
+ requireDenseArray(value, path);
108
+ return cloneData(checkSpatialFeatures(value, String(args[0])));
109
+ case 'getEnvironment': {
110
+ const { locale, theme } = record(value, path);
111
+ if (!identifier(locale) || !enumValue(theme, ['light', 'dark']))
112
+ fail(path, '环境需要 locale 和 light/dark theme');
113
+ return { locale, theme };
114
+ }
115
+ }
116
+ return cloneData(value);
117
+ }
@@ -0,0 +1,21 @@
1
+ import { HostDataError } from '@neogis-auxiliary/core';
2
+ export declare class AdapterError extends HostDataError {
3
+ readonly path: string;
4
+ readonly cause: unknown;
5
+ constructor(path: string, message: string, cause?: unknown, code?: string);
6
+ }
7
+ export declare function fail(path: string, message: string): never;
8
+ export declare function record(value: unknown, path: string): Record<string, unknown>;
9
+ export declare function keys(value: Record<string, unknown>, allowed: readonly string[], path: string): void;
10
+ export declare function name(value: unknown, path: string): string;
11
+ export declare function checkJson(value: unknown, path: string, ancestors?: Set<object>): void;
12
+ export declare function requireDenseArray(value: unknown, path: string): asserts value is unknown[];
13
+ export declare function dataProperty(value: object, key: string, path: string): unknown;
14
+ export declare function safeKey(key: string, path: string): void;
15
+ export declare function pathParts(value: string, path: string): string[];
16
+ export declare function getPath(value: unknown, parts: readonly (string | number)[], path: string): unknown;
17
+ export declare function isPromise(value: unknown): value is PromiseLike<unknown>;
18
+ export declare function synchronous(value: unknown, path: string): unknown;
19
+ export declare function withPath<T>(path: string, action: () => T): T;
20
+ /** Clone snapshots without freezing or mutating any platform-owned object. */
21
+ export declare function cloneData<T>(value: T, seen?: WeakMap<object, unknown>): T;
package/dist/shared.js ADDED
@@ -0,0 +1,131 @@
1
+ import { HostDataError, isRecord } from '@neogis-auxiliary/core';
2
+ export class AdapterError extends HostDataError {
3
+ path;
4
+ cause;
5
+ constructor(path, message, cause, code = 'ADAPTER_CONFIG') {
6
+ super(cause instanceof HostDataError ? cause.status : 'error', path + ': ' + message, cause instanceof HostDataError ? cause.code : code);
7
+ this.path = path;
8
+ this.name = 'AdapterError';
9
+ this.cause = cause;
10
+ }
11
+ }
12
+ export function fail(path, message) { throw new AdapterError(path, message); }
13
+ export function record(value, path) {
14
+ if (!isRecord(value))
15
+ return fail(path, '需要对象');
16
+ return value;
17
+ }
18
+ export function keys(value, allowed, path) {
19
+ for (const key of Object.keys(value))
20
+ if (!allowed.includes(key))
21
+ fail(path + '.' + key, '未知字段');
22
+ }
23
+ export function name(value, path) {
24
+ if (typeof value !== 'string' || !value.trim())
25
+ return fail(path, '需要非空名称');
26
+ return value;
27
+ }
28
+ export function checkJson(value, path, ancestors = new Set()) {
29
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
30
+ return;
31
+ if (typeof value === 'number' && Number.isFinite(value))
32
+ return;
33
+ if (typeof value !== 'object')
34
+ fail(path, '配置需要 JSON 可表达的值');
35
+ if (ancestors.has(value))
36
+ fail(path, '配置包含循环引用');
37
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
38
+ fail(path, '配置需要普通对象或数组');
39
+ if (Array.isArray(value))
40
+ requireDenseArray(value, path);
41
+ ancestors.add(value);
42
+ try {
43
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
44
+ if ('get' in descriptor || 'set' in descriptor)
45
+ fail(path + '.' + key, 'JSON 配置需要数据属性,不能包含 getter/setter');
46
+ if (descriptor.enumerable)
47
+ checkJson(descriptor.value, path + '.' + key, ancestors);
48
+ }
49
+ }
50
+ finally {
51
+ ancestors.delete(value);
52
+ }
53
+ }
54
+ export function requireDenseArray(value, path) {
55
+ if (!Array.isArray(value))
56
+ fail(path, '需要数组');
57
+ for (let index = 0; index < value.length; index++) {
58
+ if (!Object.hasOwn(value, index))
59
+ fail(path + '[' + index + ']', '数组存在缺失项');
60
+ }
61
+ }
62
+ export function dataProperty(value, key, path) {
63
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
64
+ if (descriptor && ('get' in descriptor || 'set' in descriptor))
65
+ fail(path, '配置需要直接声明的数据属性');
66
+ return descriptor?.value;
67
+ }
68
+ const reserved = new Set(['__proto__', 'prototype', 'constructor']);
69
+ export function safeKey(key, path) {
70
+ if (reserved.has(key))
71
+ fail(path, '保留字段不可作为路径或配置键');
72
+ }
73
+ export function pathParts(value, path) {
74
+ const parts = value.split('.');
75
+ if (parts.some(part => !part))
76
+ fail(path, '路径包含空字段');
77
+ parts.forEach(part => safeKey(part, path));
78
+ return parts;
79
+ }
80
+ export function getPath(value, parts, path) {
81
+ let current = value;
82
+ for (const part of parts) {
83
+ safeKey(String(part), path);
84
+ if ((typeof current !== 'object' && typeof current !== 'function') || current === null || !(part in current)) {
85
+ return fail(path, '字段不存在:' + parts.join('.'));
86
+ }
87
+ current = current[part];
88
+ }
89
+ return current;
90
+ }
91
+ export function isPromise(value) {
92
+ return value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function';
93
+ }
94
+ export function synchronous(value, path) {
95
+ if (isPromise(value)) {
96
+ void Promise.resolve(value).catch(() => { });
97
+ return fail(path, '同步能力或转换器返回了 Promise');
98
+ }
99
+ return value;
100
+ }
101
+ export function withPath(path, action) {
102
+ try {
103
+ return action();
104
+ }
105
+ catch (error) {
106
+ if (error instanceof AdapterError)
107
+ throw error;
108
+ throw new AdapterError(path, error instanceof Error ? error.message : String(error), error, 'ADAPTER_EXECUTION');
109
+ }
110
+ }
111
+ /** Clone snapshots without freezing or mutating any platform-owned object. */
112
+ export function cloneData(value, seen = new WeakMap()) {
113
+ if (value === null || typeof value !== 'object')
114
+ return value;
115
+ if (seen.has(value))
116
+ return seen.get(value);
117
+ if (value instanceof Date)
118
+ return new Date(value.getTime());
119
+ if (Array.isArray(value)) {
120
+ for (let index = 0; index < value.length; index++) {
121
+ if (!Object.hasOwn(value, index))
122
+ throw new Error('快照数组存在缺失项:' + index);
123
+ }
124
+ }
125
+ const result = Array.isArray(value) ? [] : {};
126
+ seen.set(value, result);
127
+ for (const [key, child] of Object.entries(value)) {
128
+ Object.defineProperty(result, key, { value: cloneData(child, seen), enumerable: true, writable: true, configurable: true });
129
+ }
130
+ return result;
131
+ }
@@ -0,0 +1,53 @@
1
+ /** Platform functions keep their own parameter types. Values are checked at the adapter boundary. */
2
+ export type AdapterFunction = (...args: any[]) => unknown;
3
+ export type ConverterRegistry = Readonly<Record<string, AdapterFunction>>;
4
+ export type TargetRegistry = Readonly<Record<string, unknown>>;
5
+ export interface ConversionRule {
6
+ readonly type: string;
7
+ readonly args?: readonly unknown[];
8
+ readonly item?: ConversionRule;
9
+ }
10
+ export type MethodRule = {
11
+ readonly call: string;
12
+ readonly args?: readonly unknown[];
13
+ readonly convert: ConversionRule;
14
+ } | {
15
+ readonly read: string;
16
+ readonly convert: ConversionRule;
17
+ } | {
18
+ readonly compose: Readonly<Record<string, MethodRule>>;
19
+ readonly convert: ConversionRule;
20
+ };
21
+ export type EventRule = {
22
+ readonly mode: 'on-off';
23
+ readonly target: string;
24
+ readonly subscribe: string;
25
+ readonly unsubscribe: string;
26
+ readonly event: string;
27
+ } | {
28
+ readonly mode: 'returned-cleanup';
29
+ readonly target: string;
30
+ readonly subscribe: string;
31
+ };
32
+ export type AdapterSection = string | Readonly<Record<string, unknown>>;
33
+ export type MapEngineConfig = AdapterSection;
34
+ export type PlatformHostConfig = AdapterSection;
35
+ export interface MapCardAdapterConfig {
36
+ readonly version: 1;
37
+ readonly engine?: MapEngineConfig;
38
+ readonly host?: PlatformHostConfig;
39
+ }
40
+ export interface BoundAdapterFunctions {
41
+ readonly converters?: ConverterRegistry;
42
+ }
43
+ export interface AdapterPreset extends BoundAdapterFunctions {
44
+ readonly role: 'engine' | 'host';
45
+ readonly config: Readonly<Record<string, unknown>>;
46
+ readonly bind?: (targets: TargetRegistry) => BoundAdapterFunctions;
47
+ }
48
+ export interface AdapterOptions extends BoundAdapterFunctions {
49
+ /** Accept JSON as unknown so file loading always passes through runtime validation. */
50
+ readonly config: unknown;
51
+ readonly targets: TargetRegistry;
52
+ readonly presets?: Readonly<Record<string, AdapterPreset>>;
53
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
- {
2
- "name": "@neogis-auxiliary/adapters",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@neogis-auxiliary/adapters",
3
+ "version": "0.2.0-next.0",
4
+ "publishConfig": {
5
+ "registry": "https://registry.npmjs.org/",
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "dependencies": {
19
+ "@neogis-auxiliary/core": "0.1.0"
20
+ }
21
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.