@zhin.js/command 1.1.7 → 1.1.9
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 +54 -1
- package/lib/command-index.d.ts +21 -2
- package/lib/command-index.js +115 -29
- package/lib/command-menu.d.ts +31 -0
- package/lib/command-menu.js +81 -0
- package/lib/definition.d.ts +18 -1
- package/lib/definition.js +30 -5
- package/lib/execution-policy.d.ts +18 -0
- package/lib/execution-policy.js +27 -0
- package/lib/execution-runtime.d.ts +65 -0
- package/lib/execution-runtime.js +167 -0
- package/lib/index.d.ts +3 -2
- package/lib/index.js +3 -2
- package/lib/permission-explanation.d.ts +22 -0
- package/lib/permission-explanation.js +54 -0
- package/lib/permit.d.ts +8 -0
- package/lib/permit.js +11 -0
- package/lib/provider.d.ts +15 -0
- package/lib/provider.js +88 -4
- package/package.json +8 -4
- package/src/command-index.ts +132 -36
- package/src/command-menu.ts +112 -0
- package/src/definition.ts +52 -6
- package/src/execution-policy.ts +39 -0
- package/src/execution-runtime.ts +202 -0
- package/src/index.ts +5 -0
- package/src/permission-explanation.ts +58 -0
- package/src/permit.ts +14 -0
- package/src/provider.ts +124 -4
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/** Internal composition contract. Not part of the command authoring facade. */
|
|
2
|
+
import { createToken, type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
|
|
3
|
+
import type { CommandExecutionLimit, CommandExecutionPolicy } from './execution-policy.js';
|
|
4
|
+
|
|
5
|
+
interface ConversationIdentity {
|
|
6
|
+
readonly endpoint: { readonly adapter: string; readonly id: string };
|
|
7
|
+
readonly kind: string;
|
|
8
|
+
readonly id: string;
|
|
9
|
+
readonly parent?: { readonly kind: string; readonly id: string };
|
|
10
|
+
readonly threadId?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface AdmissionReader {
|
|
14
|
+
admit(source: unknown, capability: string, owner: PluginId, policy: CommandExecutionPolicy, snapshot: RuntimeSnapshot): CommandExecutionLimit | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* Programmatic call with no inbound source (e.g. `CommandIndex.execute`). The policy is keyed by command only:
|
|
17
|
+
* there is no sender or conversation to budget, and no reply channel for progress feedback.
|
|
18
|
+
* On success the caller must invoke `release` once the execution settles.
|
|
19
|
+
*/
|
|
20
|
+
admitDirect(capability: string, policy: CommandExecutionPolicy): DirectAdmission;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type DirectAdmission = { readonly limit: CommandExecutionLimit; readonly release?: undefined } | { readonly limit?: undefined; readonly release: () => void };
|
|
24
|
+
|
|
25
|
+
/** @internal Admission-only Root resource; no bind or finish authority is published. */
|
|
26
|
+
export const commandExecutionAdmissionToken = createToken<AdmissionReader>('zhin.command.execution-admission');
|
|
27
|
+
|
|
28
|
+
/** @internal Held only by Core's actual leased operation. */
|
|
29
|
+
export interface CommandOperationController {
|
|
30
|
+
bind(view: object, owner: PluginId): void;
|
|
31
|
+
/** Core registers actual started delivery promises, never a caller-supplied completion callback. */
|
|
32
|
+
trackSend(send: Promise<unknown>): void;
|
|
33
|
+
/** Stop pending feedback and drain already-started feedback before the final reply. */
|
|
34
|
+
stopProgress(): Promise<void>;
|
|
35
|
+
/** Called only by the real outer operation's finally, after all final sends settle. */
|
|
36
|
+
finish(): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface Entry { active: number; cooldownUntil: number }
|
|
40
|
+
interface Operation {
|
|
41
|
+
snapshot?: RuntimeSnapshot;
|
|
42
|
+
key?: readonly string[];
|
|
43
|
+
active: boolean;
|
|
44
|
+
progressStopped: boolean;
|
|
45
|
+
admitted: boolean;
|
|
46
|
+
signal: AbortSignal;
|
|
47
|
+
reply?: (owner: PluginId, text: string) => Promise<unknown>;
|
|
48
|
+
readonly releases: (() => void)[];
|
|
49
|
+
readonly timers: Set<ReturnType<typeof setTimeout>>;
|
|
50
|
+
readonly feedback: Promise<void>[];
|
|
51
|
+
readonly accepted: Set<string>;
|
|
52
|
+
readonly sends: Set<Promise<void>>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** @internal Root-instance-owned state shared by projections and draining retired generations. */
|
|
56
|
+
export class CommandExecutionBudget {
|
|
57
|
+
readonly #entries = new Map<string, Entry>();
|
|
58
|
+
readonly #views = new WeakMap<object, { operation: Operation; owner: PluginId }>();
|
|
59
|
+
readonly #clock: () => number;
|
|
60
|
+
readonly #capacity: number;
|
|
61
|
+
readonly admission: AdmissionReader;
|
|
62
|
+
|
|
63
|
+
constructor(options: { readonly clock?: () => number; readonly capacity?: number } = {}) {
|
|
64
|
+
this.#clock = options.clock ?? (() => performance.now());
|
|
65
|
+
this.#capacity = options.capacity ?? 10_000;
|
|
66
|
+
if (!Number.isSafeInteger(this.#capacity) || this.#capacity < 1) throw new TypeError('Invalid command budget capacity');
|
|
67
|
+
this.admission = Object.freeze<AdmissionReader>({ admit: (source, capability, owner, policy, snapshot) => this.#admit(source, capability, owner, policy, snapshot),
|
|
68
|
+
admitDirect: (capability, policy) => this.#admitDirect(capability, policy) });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
openOperation(input: {
|
|
72
|
+
readonly snapshot: RuntimeSnapshot;
|
|
73
|
+
readonly conversation: ConversationIdentity;
|
|
74
|
+
readonly senderId?: string;
|
|
75
|
+
readonly retirementSignal: AbortSignal;
|
|
76
|
+
readonly reply: (owner: PluginId, text: string) => Promise<unknown>;
|
|
77
|
+
}): CommandOperationController {
|
|
78
|
+
const c = input.conversation;
|
|
79
|
+
const values = [c.endpoint.adapter, c.endpoint.id, c.kind, c.id, c.parent?.kind ?? '', c.parent?.id ?? '', c.threadId ?? '', input.senderId ?? ''];
|
|
80
|
+
const valid = values.slice(0, 4).every(nonempty) && ['private', 'group', 'channel'].includes(c.kind) && nonempty(input.senderId)
|
|
81
|
+
&& (c.parent === undefined || (nonempty(c.parent.kind) && nonempty(c.parent.id)))
|
|
82
|
+
&& (c.threadId === undefined || nonempty(c.threadId)) && values.every(value => value.length <= 1024);
|
|
83
|
+
const operation: Operation = {
|
|
84
|
+
snapshot: input.snapshot, key: valid ? Object.freeze(values) : undefined,
|
|
85
|
+
active: true, progressStopped: false, admitted: false, signal: input.retirementSignal,
|
|
86
|
+
reply: input.reply, releases: [], timers: new Set(), feedback: [], accepted: new Set(), sends: new Set(),
|
|
87
|
+
};
|
|
88
|
+
const stop = () => {
|
|
89
|
+
operation.progressStopped = true;
|
|
90
|
+
for (const timer of operation.timers) clearTimeout(timer);
|
|
91
|
+
operation.timers.clear();
|
|
92
|
+
};
|
|
93
|
+
input.retirementSignal.addEventListener('abort', stop, { once: true });
|
|
94
|
+
return Object.freeze({
|
|
95
|
+
bind: (view: object, owner: PluginId) => { if (operation.active) this.#views.set(view, { operation, owner }); },
|
|
96
|
+
trackSend: (send: Promise<unknown>) => {
|
|
97
|
+
if (!operation.active) return;
|
|
98
|
+
const settled = send.then(() => { operation.sends.delete(settled); }, () => { operation.sends.delete(settled); });
|
|
99
|
+
operation.sends.add(settled);
|
|
100
|
+
},
|
|
101
|
+
stopProgress: async () => { stop(); await Promise.all(operation.feedback); },
|
|
102
|
+
finish: async () => {
|
|
103
|
+
stop();
|
|
104
|
+
await Promise.all(operation.feedback);
|
|
105
|
+
// New sends may start while an earlier send is draining. Do not release from an initial snapshot alone.
|
|
106
|
+
if (operation.admitted) while (operation.sends.size > 0) await Promise.all(operation.sends);
|
|
107
|
+
if (!operation.active) return;
|
|
108
|
+
operation.active = false;
|
|
109
|
+
operation.signal.removeEventListener('abort', stop);
|
|
110
|
+
for (const release of operation.releases) release();
|
|
111
|
+
operation.releases.length = 0;
|
|
112
|
+
operation.feedback.length = 0;
|
|
113
|
+
operation.accepted.clear();
|
|
114
|
+
operation.sends.clear();
|
|
115
|
+
operation.reply = undefined;
|
|
116
|
+
operation.snapshot = undefined;
|
|
117
|
+
operation.key = undefined;
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
#admitDirect(capability: string, policy: CommandExecutionPolicy): DirectAdmission {
|
|
123
|
+
return this.#acquire(JSON.stringify([capability, 'direct']), policy);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Shared entry accounting: concurrency, cooldown and capacity. Returns a one-shot release on success. */
|
|
127
|
+
#acquire(key: string, policy: CommandExecutionPolicy): DirectAdmission {
|
|
128
|
+
const now = this.#clock();
|
|
129
|
+
let entry = this.#entries.get(key);
|
|
130
|
+
if (entry && policy.maxConcurrent !== undefined && entry.active >= policy.maxConcurrent) return { limit: limited('busy') };
|
|
131
|
+
if (entry && entry.cooldownUntil > now) return { limit: Object.freeze({ reason: 'cooldown', retryAfterMs: Math.ceil(entry.cooldownUntil - now) }) };
|
|
132
|
+
if (!entry) {
|
|
133
|
+
if (this.#entries.size >= this.#capacity) {
|
|
134
|
+
for (const [oldKey, old] of this.#entries) if (old.active === 0 && old.cooldownUntil <= now) this.#entries.delete(oldKey);
|
|
135
|
+
if (this.#entries.size >= this.#capacity) {
|
|
136
|
+
// Still full of cooling identities: drop the oldest idle one. Forgetting a cooldown is acceptable;
|
|
137
|
+
// refusing every new identity is not. Only entries with running operations are never evicted.
|
|
138
|
+
for (const [oldKey, old] of this.#entries) if (old.active === 0) { this.#entries.delete(oldKey); break; }
|
|
139
|
+
}
|
|
140
|
+
if (this.#entries.size >= this.#capacity) return { limit: limited('capacity') };
|
|
141
|
+
}
|
|
142
|
+
entry = { active: 0, cooldownUntil: 0 };
|
|
143
|
+
this.#entries.set(key, entry);
|
|
144
|
+
}
|
|
145
|
+
entry.active++;
|
|
146
|
+
entry.cooldownUntil = now + (policy.cooldownMs ?? 0);
|
|
147
|
+
const acceptedEntry = entry;
|
|
148
|
+
let released = false;
|
|
149
|
+
return {
|
|
150
|
+
release: () => {
|
|
151
|
+
if (released) return;
|
|
152
|
+
released = true;
|
|
153
|
+
acceptedEntry.active--;
|
|
154
|
+
if (acceptedEntry.active === 0 && acceptedEntry.cooldownUntil <= this.#clock()) this.#entries.delete(key);
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
#admit(source: unknown, capability: string, owner: PluginId, policy: CommandExecutionPolicy, snapshot: RuntimeSnapshot): CommandExecutionLimit | undefined {
|
|
160
|
+
const binding = source !== null && typeof source === 'object' ? this.#views.get(source) : undefined;
|
|
161
|
+
const operation = binding?.operation;
|
|
162
|
+
if (!operation?.active || operation.snapshot !== snapshot || binding?.owner !== owner || operation.signal.aborted) return limited('operation_unavailable');
|
|
163
|
+
if (!operation.key) return limited('identity_unavailable');
|
|
164
|
+
const key = JSON.stringify([capability, ...operation.key]);
|
|
165
|
+
// Re-entering the same capability is a second attempt, rather than a second free execution.
|
|
166
|
+
const acquired = this.#acquire(key, policy);
|
|
167
|
+
if (acquired.limit) return acquired.limit;
|
|
168
|
+
operation.admitted = true;
|
|
169
|
+
operation.releases.push(acquired.release);
|
|
170
|
+
if (policy.progressAfterMs !== undefined && !operation.progressStopped && !operation.accepted.has(capability)) {
|
|
171
|
+
const timer = setTimeout(() => {
|
|
172
|
+
operation.timers.delete(timer);
|
|
173
|
+
if (!operation.active || operation.progressStopped || operation.signal.aborted || !operation.reply) return;
|
|
174
|
+
// Observe failure once. Never retry uncertain delivery and never expose the exception.
|
|
175
|
+
let send: Promise<void>;
|
|
176
|
+
try { send = Promise.resolve(operation.reply(owner, '正在处理中,请稍候。')).then(() => {}, () => {}); }
|
|
177
|
+
catch { send = Promise.resolve(); }
|
|
178
|
+
operation.feedback.push(send);
|
|
179
|
+
}, policy.progressAfterMs);
|
|
180
|
+
operation.timers.add(timer);
|
|
181
|
+
}
|
|
182
|
+
operation.accepted.add(capability);
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function nonempty(value: unknown): value is string { return typeof value === 'string' && value.length > 0; }
|
|
188
|
+
function limited(reason: CommandExecutionLimit['reason']): CommandExecutionLimit { return Object.freeze({ reason }); }
|
|
189
|
+
|
|
190
|
+
/** @internal Projection reads the Root resource; ordinary authoring values cannot bind an operation. */
|
|
191
|
+
export function admitCommandExecution(source: unknown, capability: string, owner: PluginId, policy: CommandExecutionPolicy | undefined, snapshot: RuntimeSnapshot): CommandExecutionLimit | undefined {
|
|
192
|
+
if (!policy) return undefined;
|
|
193
|
+
const reader = snapshot.resources.get(snapshot.root)?.get(commandExecutionAdmissionToken.id) as AdmissionReader | undefined;
|
|
194
|
+
return reader ? reader.admit(source, capability, owner, policy, snapshot) : limited('service_unavailable');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** @internal Programmatic (source-less) admission: keyed by command only, never refused for lacking a source. */
|
|
198
|
+
export function admitDirectCommandExecution(capability: string, policy: CommandExecutionPolicy | undefined, snapshot: RuntimeSnapshot): DirectAdmission {
|
|
199
|
+
if (!policy) return { release: () => {} };
|
|
200
|
+
const reader = snapshot.resources.get(snapshot.root)?.get(commandExecutionAdmissionToken.id) as AdmissionReader | undefined;
|
|
201
|
+
return reader ? reader.admitDirect(capability, policy) : { limit: limited('service_unavailable') };
|
|
202
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -6,7 +6,10 @@
|
|
|
6
6
|
export * from './command-index.js';
|
|
7
7
|
/** @public Command authoring contract and `defineCommand`. */
|
|
8
8
|
export * from './definition.js';
|
|
9
|
+
export * from './permission-explanation.js';
|
|
9
10
|
export {
|
|
11
|
+
CONVERSATION_MANAGER_PERMIT,
|
|
12
|
+
canManageConversation,
|
|
10
13
|
assertBuiltinPermits,
|
|
11
14
|
checkBuiltinPermit,
|
|
12
15
|
checkBuiltinPermitList,
|
|
@@ -17,8 +20,10 @@ export {
|
|
|
17
20
|
type PermitKind,
|
|
18
21
|
} from './permit.js';
|
|
19
22
|
export {
|
|
23
|
+
bindCommandSource,
|
|
20
24
|
CommandPathSyntaxError,
|
|
21
25
|
commandFeatureId,
|
|
26
|
+
type BoundCommandSource,
|
|
22
27
|
default as commandFeature,
|
|
23
28
|
} from './provider.js';
|
|
24
29
|
export { default } from './provider.js';
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { operationClientAdapter } from '@zhin.js/feature-kit';
|
|
2
|
+
import { explainPermitRules, toPermissionSubject, type PermissionSubject, type PermissionConditionExplanation } from '@zhin.js/permission';
|
|
3
|
+
import { resolveCommandSender, resolveCommandSession, type CommandMessage } from './definition.js';
|
|
4
|
+
import type { CommandDescriptor } from './command-index.js';
|
|
5
|
+
|
|
6
|
+
/** The exact subject projection used by the real command permit gate. No factories or checkers run. */
|
|
7
|
+
export function toCommandPermissionSubject(source: unknown): PermissionSubject {
|
|
8
|
+
const projected = toPermissionSubject(source);
|
|
9
|
+
const session = resolveCommandSession(source);
|
|
10
|
+
return { ...projected, ...session, ...(session.sender ? { sender: { ...projected.sender, ...session.sender } } : {}) };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Exact authoring adapter restriction, distinct from builtin adapter(...) matching. */
|
|
14
|
+
export function commandAdapterMatches(command: Readonly<{ adapter?: string }>, source: unknown): boolean {
|
|
15
|
+
return !command.adapter || operationClientAdapter(source) === command.adapter;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type CommandPermissionHostStatus = 'present' | 'missing' | 'unverified';
|
|
19
|
+
|
|
20
|
+
/** Read-only hypothetical conditions. A match is not permission to execute the command. */
|
|
21
|
+
export function explainCommandPermissions(
|
|
22
|
+
command: Pick<CommandDescriptor, 'adapter' | 'permit'>,
|
|
23
|
+
options: Readonly<{ source?: unknown; rolesKnown?: boolean; permissionHost: CommandPermissionHostStatus }>,
|
|
24
|
+
) {
|
|
25
|
+
const projected = toCommandPermissionSubject(options.source);
|
|
26
|
+
const inputSender = options.source && typeof options.source === 'object'
|
|
27
|
+
? (options.source as Pick<CommandMessage, 'sender'>).sender : undefined;
|
|
28
|
+
const structuredRoles = inputSender && typeof inputSender === 'object'
|
|
29
|
+
&& Array.isArray((inputSender as { readonly role?: unknown }).role);
|
|
30
|
+
// A sender-only assumption has no synthetic conversation. Apply the real canonical
|
|
31
|
+
// sender defaults without inventing an Endpoint or treating unknown roles as known.
|
|
32
|
+
const senderOnly = options.source && typeof options.source === 'object' && !('conversation' in options.source) && !structuredRoles
|
|
33
|
+
? resolveCommandSender(options.source as Pick<CommandMessage, 'sender'>, undefined) : undefined;
|
|
34
|
+
const subject = senderOnly ? { ...projected, sender: senderOnly } : projected;
|
|
35
|
+
const defaultedRoles = options.rolesKnown && Array.isArray(inputSender?.roles) && inputSender.roles.length === 0
|
|
36
|
+
&& subject.sender?.role.length === 1 && subject.sender.role[0] === 'user';
|
|
37
|
+
const actualAdapter = operationClientAdapter(options.source);
|
|
38
|
+
const adapter: PermissionConditionExplanation = !command.adapter
|
|
39
|
+
? { outcome: 'not_evaluated', reason: '命令未声明 adapter 约束' }
|
|
40
|
+
: !actualAdapter ? { outcome: 'unknown', reason: '未选择当前 Endpoint,无法判断命令的精确 adapter 约束' }
|
|
41
|
+
: { outcome: commandAdapterMatches(command, options.source) ? 'match' : 'mismatch', reason: '命令 adapter 与当前 Endpoint 声明的原生适配器精确比较;未探测在线状态' };
|
|
42
|
+
const rules = explainPermitRules(command.permit ?? [], subject, { rolesKnown: options.rolesKnown });
|
|
43
|
+
const conditions = [...(command.adapter ? [adapter] : []), ...rules];
|
|
44
|
+
let summary: PermissionConditionExplanation;
|
|
45
|
+
if (conditions.some(item => item.outcome === 'mismatch')) summary = { outcome: 'mismatch', reason: '至少一个声明条件与假设输入不符;这不是实际准入检查' };
|
|
46
|
+
else if ((rules.length > 0 && options.permissionHost !== 'present') || conditions.some(item => item.outcome === 'unknown')) {
|
|
47
|
+
summary = { outcome: 'unknown', reason: rules.length > 0 && options.permissionHost !== 'present'
|
|
48
|
+
? 'PermissionHost 缺失或无法确认;不能推断命令可执行' : '存在缺少依据的条件,不能推断命令可执行' };
|
|
49
|
+
} else if (rules.length === 0) summary = { outcome: 'not_evaluated', reason: '命令未声明 permit 限制;这不表示已获得执行权限' };
|
|
50
|
+
else if (conditions.some(item => item.outcome === 'not_evaluated')) summary = { outcome: 'not_evaluated', reason: '存在未执行的平台或自定义条件,不能推断命令可执行' };
|
|
51
|
+
else summary = { outcome: 'match', reason: '已解释的 builtin 条件与假设输入匹配;不代表真实授权或命令可执行' };
|
|
52
|
+
return Object.freeze({ permissionHost: options.permissionHost, adapter: Object.freeze(adapter), rules, summary: Object.freeze(summary),
|
|
53
|
+
unconstrained: Object.freeze(['已解释的 builtin 规则不检查具体 Endpoint、parent 或 thread;保留完整目标不等于这些维度受规则限制']),
|
|
54
|
+
assumptions: Object.freeze(['身份与角色仅用于模拟,未向平台核实', '未执行命令、动态默认值、平台或自定义 checker',
|
|
55
|
+
...(defaultedRoles
|
|
56
|
+
? ['canonical 输入未附角色时按命令运行时默认 user 解释;这不是已核验的平台角色'] : [])]),
|
|
57
|
+
});
|
|
58
|
+
}
|
package/src/permit.ts
CHANGED
|
@@ -2,6 +2,20 @@
|
|
|
2
2
|
* Re-export permit 解析/校验 from @zhin.js/permission (SSOT)。
|
|
3
3
|
* 保留 CommandSession 兼容签名供 command-index 过渡使用。
|
|
4
4
|
*/
|
|
5
|
+
import { checkBuiltinPermit, type PermissionSubject } from '@zhin.js/permission';
|
|
6
|
+
|
|
7
|
+
/** 会话管理者:群主 / 群管理员 / 机器人主人(适配器投影的规范角色名)。 */
|
|
8
|
+
export const CONVERSATION_MANAGER_PERMIT = 'role(owner,admin,master)';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 「私聊,或 owner / admin / master」。`permit` 列表只支持 AND,
|
|
12
|
+
* 订阅类命令需要这个 OR 规则时用它,并以命令会话的 `scene` / `sender.role` 为输入。
|
|
13
|
+
*/
|
|
14
|
+
export function canManageConversation(subject: PermissionSubject): boolean {
|
|
15
|
+
return checkBuiltinPermit('private()', subject)
|
|
16
|
+
|| checkBuiltinPermit(CONVERSATION_MANAGER_PERMIT, subject);
|
|
17
|
+
}
|
|
18
|
+
|
|
5
19
|
export {
|
|
6
20
|
type PermitKind,
|
|
7
21
|
type ParsedPermit,
|
package/src/provider.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { basename, dirname, join, sep } from 'node:path';
|
|
1
|
+
import { basename, dirname, join, relative, sep } from 'node:path';
|
|
2
2
|
import { featureId, isCapabilityLocalSegment } from '@zhin.js/plugin-runtime';
|
|
3
3
|
import {
|
|
4
4
|
defineFeatureProvider,
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
type DiscoveredSource,
|
|
7
7
|
type SourceConvention,
|
|
8
8
|
} from '@zhin.js/feature-kit';
|
|
9
|
-
import { CommandIndex } from './command-index.js';
|
|
9
|
+
import { CommandIndex, assertParameterSegment } from './command-index.js';
|
|
10
10
|
import {
|
|
11
11
|
bindCommandParameter,
|
|
12
12
|
parseCommandDefinition,
|
|
@@ -32,6 +32,8 @@ const commandFiles: SourceConvention = {
|
|
|
32
32
|
async load(source, context) {
|
|
33
33
|
const module = await context.host.loadModule<{ default?: unknown }>(source.source);
|
|
34
34
|
const definition = parseCommandDefinition(module.default);
|
|
35
|
+
const commandDirectories = commandDirectoriesOf(context.packageRoot, source.source);
|
|
36
|
+
assertSingleTrailingParameterDirectory(commandDirectories, source.source);
|
|
35
37
|
const file = parseCommandDirectory(basename(dirname(source.source)));
|
|
36
38
|
return bindCommandParameter(definition, resolveParameter(definition, file, source.source));
|
|
37
39
|
},
|
|
@@ -109,6 +111,76 @@ function parseCommandDirectory(value: string): ParsedCommandFile | undefined {
|
|
|
109
111
|
return undefined;
|
|
110
112
|
}
|
|
111
113
|
|
|
114
|
+
/** Directory segments between `commands/` and the command's `index.*` file. */
|
|
115
|
+
function commandDirectoriesOf(packageRoot: string, source: string): string[] {
|
|
116
|
+
const commandsRoot = join(packageRoot, 'commands');
|
|
117
|
+
const commandDirectory = dirname(source);
|
|
118
|
+
return relative(commandsRoot, commandDirectory)
|
|
119
|
+
.split(sep)
|
|
120
|
+
.filter((segment) => segment !== '');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
interface ParameterDirectory {
|
|
124
|
+
readonly position: number;
|
|
125
|
+
readonly directory: string;
|
|
126
|
+
readonly hint: CommandParameterHint;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* A command path may contain at most one parameter directory, and it must be the
|
|
131
|
+
* last directory before `index.*`. Further arguments belong in `defineCommand({ params })`.
|
|
132
|
+
*/
|
|
133
|
+
function assertSingleTrailingParameterDirectory(directories: readonly string[], source: string): void {
|
|
134
|
+
const parameterDirectories: ParameterDirectory[] = [];
|
|
135
|
+
directories.forEach((directory, position) => {
|
|
136
|
+
const hint = parseCommandDirectory(directory)?.parameter;
|
|
137
|
+
if (hint) parameterDirectories.push({ position, directory, hint });
|
|
138
|
+
});
|
|
139
|
+
const [keptDirectory, ...movedDirectories] = parameterDirectories;
|
|
140
|
+
if (!keptDirectory) return;
|
|
141
|
+
const lastPosition = directories.length - 1;
|
|
142
|
+
if (movedDirectories.length === 0 && keptDirectory.position === lastPosition) return;
|
|
143
|
+
throw new CommandPathSyntaxError(
|
|
144
|
+
source,
|
|
145
|
+
describeParameterDirectoryRule(directories, keptDirectory, movedDirectories),
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function describeParameterDirectoryRule(
|
|
150
|
+
directories: readonly string[],
|
|
151
|
+
keptDirectory: ParameterDirectory,
|
|
152
|
+
movedDirectories: readonly ParameterDirectory[],
|
|
153
|
+
): string {
|
|
154
|
+
const parameterDirectories = [keptDirectory, ...movedDirectories];
|
|
155
|
+
const currentPath = `commands/${directories.join('/')}/index.ts`;
|
|
156
|
+
const foundDirectories = parameterDirectories.map((entry) => entry.directory).join(', ');
|
|
157
|
+
const staticDirectories = directories.filter((_directory, position) =>
|
|
158
|
+
!parameterDirectories.some((entry) => entry.position === position));
|
|
159
|
+
const suggestedPath = `commands/${[...staticDirectories, keptDirectory.directory].join('/')}/index.ts`;
|
|
160
|
+
const suggestedParams = parameterDirectories
|
|
161
|
+
.map((entry) => describeParamDeclaration(entry.hint))
|
|
162
|
+
.join(', ');
|
|
163
|
+
const movedNote = movedDirectories.length > 0
|
|
164
|
+
? `move ${movedDirectories.map((entry) => entry.directory).join(', ')} into defineCommand({ params })`
|
|
165
|
+
: 'move the parameter directory to the end of the path';
|
|
166
|
+
return `only the last directory of a command path may be a parameter directory `
|
|
167
|
+
+ `([name], [[name]], [...name] or [[...name]]), and a command may have at most one; `
|
|
168
|
+
+ `found ${foundDirectories} in ${currentPath}. `
|
|
169
|
+
+ `Fix: ${movedNote}, e.g. ${suggestedPath} with `
|
|
170
|
+
+ `defineCommand({ params: { ${suggestedParams} } }) `
|
|
171
|
+
+ `(the directory parameter must be listed first). `
|
|
172
|
+
+ 'See https://zhin.js.org/authoring/commands#目录参数规则';
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function describeParamDeclaration(hint: CommandParameterHint): string {
|
|
176
|
+
const type = hint.rest ? 'text' : 'string';
|
|
177
|
+
const flags: string[] = [];
|
|
178
|
+
if (hint.optional) flags.push('optional: true');
|
|
179
|
+
if (hint.rest) flags.push('rest: true');
|
|
180
|
+
const flagText = flags.map((flag) => `, ${flag}`).join('');
|
|
181
|
+
return `${hint.name}: { type: '${type}'${flagText} }`;
|
|
182
|
+
}
|
|
183
|
+
|
|
112
184
|
/** 把文件名形态与 `definition.params` 合并成完整参数定义。 */
|
|
113
185
|
function resolveParameter(
|
|
114
186
|
definition: CommandDefinition,
|
|
@@ -124,8 +196,16 @@ function resolveParameter(
|
|
|
124
196
|
`missing params.${hint.name} declaration in defineCommand({ params })`,
|
|
125
197
|
);
|
|
126
198
|
}
|
|
127
|
-
|
|
128
|
-
|
|
199
|
+
const declaredNames = Object.keys(definition.params ?? {});
|
|
200
|
+
if (declaredNames[0] !== hint.name) {
|
|
201
|
+
const reorderedNames = [hint.name, ...declaredNames.filter((name) => name !== hint.name)];
|
|
202
|
+
throw new CommandPathSyntaxError(
|
|
203
|
+
source,
|
|
204
|
+
`params.${hint.name} must be the first parameter declaration: the parameter directory `
|
|
205
|
+
+ `binds the first argument after the command name, so it has to come first in `
|
|
206
|
+
+ `defineCommand({ params }). Current order: { ${declaredNames.join(', ')} }; `
|
|
207
|
+
+ `reorder to { ${reorderedNames.join(', ')} }`,
|
|
208
|
+
);
|
|
129
209
|
}
|
|
130
210
|
if (schema.rest !== undefined && schema.rest !== hint.rest
|
|
131
211
|
|| schema.optional !== undefined && schema.optional !== hint.optional) {
|
|
@@ -166,6 +246,46 @@ function preferredCommandIndex(
|
|
|
166
246
|
- commandFilePriority(right.name, preferJavaScript))[0]?.name;
|
|
167
247
|
}
|
|
168
248
|
|
|
249
|
+
export interface BoundCommandSource<TDefinition> {
|
|
250
|
+
/** Plugin-local name the runtime registers, e.g. `term/$word`. */
|
|
251
|
+
readonly localName: string;
|
|
252
|
+
/** The definition with `$parameter` bound from the directory shape, as the runtime loads it. */
|
|
253
|
+
readonly definition: TDefinition;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Apply the runtime's convention-path rules to one command module: directory syntax
|
|
258
|
+
* (`[name]`, `[[name]]`, `[...name]`, `[[...name]]`), the `params` declaration the directory
|
|
259
|
+
* implies, and the route shape (one dynamic segment, last). `source` is the command's `index`
|
|
260
|
+
* file or its directory; everything after the last `commands` directory is the command path.
|
|
261
|
+
* Throws the same errors discovery, loading and the command index throw.
|
|
262
|
+
*/
|
|
263
|
+
export function bindCommandSource<TDefinition extends CommandDefinition>(
|
|
264
|
+
value: TDefinition,
|
|
265
|
+
source: string,
|
|
266
|
+
): BoundCommandSource<TDefinition>;
|
|
267
|
+
export function bindCommandSource(value: unknown, source: string): BoundCommandSource<CommandDefinition>;
|
|
268
|
+
export function bindCommandSource(value: unknown, source: string): BoundCommandSource<CommandDefinition> {
|
|
269
|
+
const directory = /^index\.(?:tsx?|[cm]?js)$/u.test(basename(source)) ? dirname(source) : source;
|
|
270
|
+
const parts = directory.split(/[\\/]/u).filter(Boolean);
|
|
271
|
+
const commandsAt = parts.lastIndexOf('commands');
|
|
272
|
+
if (commandsAt < 0 || commandsAt === parts.length - 1) {
|
|
273
|
+
throw new CommandPathSyntaxError(source, 'expected a path under commands/, e.g. commands/foo/index.ts');
|
|
274
|
+
}
|
|
275
|
+
const segments = parts.slice(commandsAt + 1).map((name) => {
|
|
276
|
+
const segment = parseCommandDirectory(name);
|
|
277
|
+
if (!segment) {
|
|
278
|
+
throw new CommandPathSyntaxError(source, `"${name}" is not a command directory name, so the runtime does not discover it`);
|
|
279
|
+
}
|
|
280
|
+
return segment;
|
|
281
|
+
});
|
|
282
|
+
const definition = parseCommandDefinition(value);
|
|
283
|
+
const bound = bindCommandParameter(definition, resolveParameter(definition, segments.at(-1), source));
|
|
284
|
+
const localName = segments.map((segment) => segment.localSegment).join('/');
|
|
285
|
+
assertParameterSegment(localName.split('/'), bound.$parameter, source);
|
|
286
|
+
return Object.freeze({ localName, definition: bound });
|
|
287
|
+
}
|
|
288
|
+
|
|
169
289
|
export class CommandPathSyntaxError extends TypeError {
|
|
170
290
|
constructor(
|
|
171
291
|
file: string,
|