@joplo-app/core 0.2.10 → 0.2.13

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/dist/schema.js CHANGED
@@ -137,6 +137,8 @@ export const CALLOUT_SIDES = ['top', 'right', 'bottom', 'left'];
137
137
  export const Callout = z.strictObject({ target: z.string().min(1), text: z.string().min(1), side: z.enum(CALLOUT_SIDES).optional() });
138
138
  export const Step = z.strictObject({
139
139
  id: Qid,
140
+ /** Author identity, unique within a scenario. id remains the legacy playback address. */
141
+ key: Id.optional(),
140
142
  kind: z.enum(['user', 'system', 'card']),
141
143
  action: Action,
142
144
  caption: z.string().min(1),
@@ -0,0 +1,50 @@
1
+ import type { Project, Step } from './schema.js';
2
+ /** 作者要分享的范围:场景 id 与功能 id(功能 = 这个功能选定方案的全部场景;评审版是全部方案的场景)。 */
3
+ export type ScopeRequest = {
4
+ scenarios?: readonly string[];
5
+ features?: readonly string[];
6
+ };
7
+ /** publish = 只发布选定方案;review = 评审版(全部方案)。 */
8
+ export type ScopeMode = 'publish' | 'review';
9
+ /** 因为被范围内步骤引用而带上的别的功能的内容(只给作者看:终端输出、看板浮层,不进分享)。 */
10
+ export type ScopeBorrowed = {
11
+ kind: 'element';
12
+ featureId: string;
13
+ featureName: string;
14
+ optionId: string;
15
+ elementId: string;
16
+ route: string;
17
+ refs: string[];
18
+ scenarios: string[];
19
+ } | {
20
+ kind: 'page';
21
+ featureId: string;
22
+ featureName: string;
23
+ optionId: string;
24
+ route: string;
25
+ scenarios: string[];
26
+ };
27
+ export type ScopeInfo = {
28
+ /** `.joplo/cloud.json` 里这个范围的键:排序后的场景 id,用逗号连接;评审版前缀 `review:`。 */
29
+ key: string;
30
+ scenarios: string[];
31
+ features: string[];
32
+ borrowed: ScopeBorrowed[];
33
+ };
34
+ export declare const hasScope: (r: ScopeRequest | undefined) => r is ScopeRequest;
35
+ export declare const scopeKey: (scenarios: readonly string[], mode: ScopeMode) => string;
36
+ /**
37
+ * 把作者写的范围解析成场景 id(保持 IR 里的顺序)。写错的场景或功能、没有选定方案、范围为空时报错,调用方不应发布任何东西。
38
+ */
39
+ export declare function resolveScope(project: Project, request: ScopeRequest, mode: ScopeMode): string[];
40
+ /** 一步里引用到的元素 id:操作目标、镜头、标注、焦点提示、标注气泡、trace。 */
41
+ export declare function stepRefs(st: Step): string[];
42
+ /**
43
+ * 裁剪到给定场景(先用 resolveScope 解析)。返回新的 IR(输入不变)和范围说明。
44
+ */
45
+ export declare function scopeProject(project: Project, scenarioIds: readonly string[], mode?: ScopeMode): {
46
+ project: Project;
47
+ info: ScopeInfo;
48
+ };
49
+ /** 一条借用的说明(英文,CLI 与看板共用)。 */
50
+ export declare function borrowedLine(b: ScopeBorrowed): string;
package/dist/scope.js ADDED
@@ -0,0 +1,238 @@
1
+ /**
2
+ * 按场景保密分享(D75):把编译好的 IR 裁剪到若干场景。
3
+ *
4
+ * 不变量:裁剪后的 IR 里不出现范围外功能、方案、场景的 id、名字、目标、角色、说明和步骤文字。
5
+ * - 保留:范围内的场景;它们的方案和功能;场景用得到的画面(起始画面、navigate 能到的画面、方案的层级画面);这些画面的路径。
6
+ * - 堆叠元素:`from` 是范围外方案的贡献子树默认去掉(when 隐藏的也一样);范围内步骤引用到子树里的元素时整条子树保留(借用),
7
+ * 并去掉子树里所有指向范围外方案的 `from`。范围内场景跳到别的功能新增的路径时,这个页面也按借用保留,去掉 `addedBy`。
8
+ * - 范围外的分叉去掉;规则、情况、问题只留范围内功能(规则、问题再按方案过滤);项目说明去掉(常常概述所有功能),项目名保留。
9
+ * dev、publish、review 三种 IR 都能裁剪:share 用它裁剪发布 IR(上传的文件)和 dev IR(评审清单、预览图)。
10
+ */
11
+ import { orderedFeatures } from "./features.js";
12
+ import { JoploError } from "./result.js";
13
+ export const hasScope = (r) => !!r && ((r.scenarios?.length ?? 0) > 0 || (r.features?.length ?? 0) > 0);
14
+ export const scopeKey = (scenarios, mode) => `${mode === 'review' ? 'review:' : ''}${[...scenarios].sort().join(',')}`;
15
+ /** 演示顺序:按功能顺序(featureIds),同一功能里按 IR 顺序。 */
16
+ function demoOrder(project) {
17
+ const rank = new Map(orderedFeatures(project).map((f, i) => [f.id, i]));
18
+ const all = Object.values(project.scenarios);
19
+ const r = (optionId) => rank.get(project.options[optionId]?.featureId ?? '') ?? rank.size;
20
+ return all.map((s, i) => ({ s, i })).sort((a, b) => r(a.s.optionId) - r(b.s.optionId) || a.i - b.i).map(({ s }) => s.id);
21
+ }
22
+ /** 在给定模式下可分享的场景:publish 只有各功能选定方案的场景。 */
23
+ function shareable(project, mode) {
24
+ const picked = new Set(orderedFeatures(project).map((f) => f.pick).filter((p) => !!p));
25
+ return Object.values(project.scenarios).filter((s) => mode === 'review' || picked.has(s.optionId)).map((s) => s.id);
26
+ }
27
+ function listLines(project, ids) {
28
+ const shown = ids.slice(0, 20).map((id) => ` ${id} ${project.scenarios[id]?.name ?? ''}`);
29
+ return shown.length ? `\n${shown.join('\n')}${ids.length > shown.length ? `\n … ${ids.length - shown.length} more` : ''}` : ' (none)';
30
+ }
31
+ /**
32
+ * 把作者写的范围解析成场景 id(保持 IR 里的顺序)。写错的场景或功能、没有选定方案、范围为空时报错,调用方不应发布任何东西。
33
+ */
34
+ export function resolveScope(project, request, mode) {
35
+ const ok = new Set(shareable(project, mode));
36
+ const out = new Set();
37
+ for (const fid of request.features ?? []) {
38
+ const f = project.features[fid];
39
+ if (!f) {
40
+ const known = orderedFeatures(project).map((x) => x.id).join(', ') || 'none';
41
+ throw new JoploError('NOT_FOUND', `Unknown feature "${fid}"${mode === 'publish' ? ', or it has no picked option' : ''}. Features: ${known}`, { details: { scope: 'feature', id: fid } });
42
+ }
43
+ const opts = mode === 'review' ? f.optionIds : f.pick ? [f.pick] : [];
44
+ if (!opts.length)
45
+ throw new JoploError('USAGE', `Feature "${fid}" has no picked option, so nothing of it is published. Pick an option (feature.pick), or share the review version (--review)`, { details: { scope: 'feature', id: fid } });
46
+ for (const s of Object.values(project.scenarios))
47
+ if (opts.includes(s.optionId))
48
+ out.add(s.id);
49
+ }
50
+ for (const sid of request.scenarios ?? []) {
51
+ const s = project.scenarios[sid];
52
+ if (s && ok.has(sid)) {
53
+ out.add(sid);
54
+ continue;
55
+ }
56
+ if (s) {
57
+ const o = project.options[s.optionId];
58
+ throw new JoploError('USAGE', `Scenario ${sid} belongs to option ${s.optionId}, which is not the picked option of feature "${o?.featureId ?? '?'}"; only picked options are published. Pick it, or share the review version (--review)`, { details: { scope: 'scenario', id: sid } });
59
+ }
60
+ const tail = sid.split('.').pop() ?? sid;
61
+ const head = sid.split('.')[0] ?? sid;
62
+ const all = [...ok];
63
+ const near = all.filter((id) => id.endsWith(`.${tail}`) || id.startsWith(`${head}.`));
64
+ const hint = near.length ? `Did you mean:${listLines(project, near)}` : `Scenarios you can share:${listLines(project, all)}`;
65
+ throw new JoploError('NOT_FOUND', `Unknown scenario ${sid}. ${hint}\nNothing was built or uploaded`, { details: { scope: 'scenario', id: sid } });
66
+ }
67
+ const ids = demoOrder(project).filter((id) => out.has(id));
68
+ if (!ids.length)
69
+ throw new JoploError('USAGE', 'The scope has no scenarios; nothing to share');
70
+ return ids;
71
+ }
72
+ /** 一步里引用到的元素 id:操作目标、镜头、标注、焦点提示、标注气泡、trace。 */
73
+ export function stepRefs(st) {
74
+ const out = [];
75
+ if ('target' in st.action)
76
+ out.push(st.action.target);
77
+ for (const s of st.shots)
78
+ out.push(...s.targets);
79
+ for (const m of st.marks)
80
+ out.push(m.target);
81
+ for (const c of st.cues ?? [])
82
+ out.push(...c.targets);
83
+ for (const c of st.callouts ?? [])
84
+ out.push(c.target);
85
+ for (const t of st.traces)
86
+ out.push(...t.nodes, ...t.edges.map((e) => e.id), ...(t.groups ?? []), ...(t.errorGroups ?? []), ...(t.targets ?? []));
87
+ return out;
88
+ }
89
+ function idsIn(n, out = []) {
90
+ out.push(n.id);
91
+ for (const c of n.children ?? [])
92
+ idsIn(c, out);
93
+ return out;
94
+ }
95
+ /**
96
+ * 裁剪到给定场景(先用 resolveScope 解析)。返回新的 IR(输入不变)和范围说明。
97
+ */
98
+ export function scopeProject(project, scenarioIds, mode = project.mode === 'review' ? 'review' : 'publish') {
99
+ const S = new Set(scenarioIds.filter((id) => project.scenarios[id]));
100
+ if (!S.size)
101
+ throw new JoploError('USAGE', 'The scope has no scenarios; nothing to share');
102
+ const O = new Set([...S].map((id) => project.scenarios[id].optionId));
103
+ const F = new Set([...O].map((id) => project.options[id]?.featureId).filter((f) => !!f));
104
+ // 引用:元素 id → 引用它的场景
105
+ const refBy = new Map();
106
+ for (const sid of S)
107
+ for (const st of project.scenarios[sid].steps)
108
+ for (const id of stepRefs(st)) {
109
+ const set = refBy.get(id) ?? new Set();
110
+ set.add(sid);
111
+ refBy.set(id, set);
112
+ }
113
+ // 用得到的画面 → 用到它的场景
114
+ const sceneBy = new Map();
115
+ const useScene = (id, sid) => {
116
+ if (!project.scenes[id])
117
+ return;
118
+ const set = sceneBy.get(id) ?? new Set();
119
+ set.add(sid);
120
+ sceneBy.set(id, set);
121
+ };
122
+ for (const sid of S) {
123
+ const s = project.scenarios[sid];
124
+ useScene(s.initial.sceneId, sid);
125
+ for (const st of s.steps)
126
+ for (const e of st.effects)
127
+ if (e.type === 'navigate')
128
+ useScene(e.sceneId, sid);
129
+ for (const l of Object.values(project.options[s.optionId]?.layers ?? {}))
130
+ useScene(l.sceneId, sid);
131
+ }
132
+ const borrowed = [];
133
+ const featureOf = (optionId) => {
134
+ const fid = project.options[optionId]?.featureId ?? optionId.split('.')[0] ?? optionId;
135
+ return { featureId: fid, featureName: project.features[fid]?.name ?? fid };
136
+ };
137
+ /** 借用的子树:整条保留,去掉所有指向范围外方案的 from。 */
138
+ const strip = (n) => {
139
+ const { from, children, ...rest } = n;
140
+ return { ...rest, ...(from !== undefined && O.has(from) ? { from } : {}), ...(children ? { children: children.map(strip) } : {}) };
141
+ };
142
+ const prune = (n, scene, users) => {
143
+ if (n.from !== undefined && !O.has(n.from)) {
144
+ const ids = idsIn(n);
145
+ const refs = ids.filter((id) => refBy.has(id));
146
+ if (!refs.length)
147
+ return null;
148
+ const who = new Set(refs.flatMap((id) => [...refBy.get(id)]).filter((sid) => users.has(sid)));
149
+ borrowed.push({ kind: 'element', ...featureOf(n.from), optionId: n.from, elementId: n.id, route: scene.route, refs, scenarios: [...(who.size ? who : users)] });
150
+ return strip(n);
151
+ }
152
+ if (!n.children)
153
+ return n;
154
+ return { ...n, children: n.children.map((c) => prune(c, scene, users)).filter((c) => c !== null) };
155
+ };
156
+ const scenes = {};
157
+ for (const [id, scene] of Object.entries(project.scenes)) {
158
+ const users = sceneBy.get(id);
159
+ if (!users)
160
+ continue;
161
+ scenes[id] = { ...scene, root: prune(scene.root, scene, users) ?? scene.root };
162
+ }
163
+ // 路径:只留用得到的画面的路径;别的功能新增的页面按借用保留
164
+ const routes = {};
165
+ const paths = new Set(Object.values(scenes).map((s) => s.route));
166
+ for (const [p, r] of Object.entries(project.routes)) {
167
+ if (!paths.has(p))
168
+ continue;
169
+ if (r.addedBy && !O.has(r.addedBy)) {
170
+ const users = new Set(Object.entries(scenes).filter(([, s]) => s.route === p).flatMap(([id]) => [...(sceneBy.get(id) ?? [])]));
171
+ borrowed.push({ kind: 'page', ...featureOf(r.addedBy), optionId: r.addedBy, route: p, scenarios: [...users] });
172
+ const { addedBy: _a, ...rest } = r;
173
+ routes[p] = rest;
174
+ }
175
+ else
176
+ routes[p] = r;
177
+ }
178
+ // 画面之间不会互相借用页面以外的东西;同一元素在多个画面被借用时合并成一条
179
+ const seen = new Set();
180
+ const merged = borrowed.filter((b) => {
181
+ const k = b.kind === 'element' ? `e|${b.optionId}|${b.elementId}|${b.route}` : `p|${b.route}`;
182
+ if (seen.has(k))
183
+ return false;
184
+ seen.add(k);
185
+ return true;
186
+ });
187
+ const scenarios = {};
188
+ for (const sid of Object.keys(project.scenarios)) {
189
+ if (!S.has(sid))
190
+ continue;
191
+ const s = project.scenarios[sid];
192
+ scenarios[sid] = { ...s, steps: s.steps.map((st) => (st.forks.some((f) => !S.has(f.scenarioId)) ? { ...st, forks: st.forks.filter((f) => S.has(f.scenarioId)) } : st)) };
193
+ }
194
+ const options = {};
195
+ for (const [id, o] of Object.entries(project.options)) {
196
+ if (!O.has(id))
197
+ continue;
198
+ const coverage = Object.fromEntries(Object.entries(o.coverage)
199
+ .filter(([cid]) => F.has(project.cases[cid]?.featureId ?? cid.split('.')[0] ?? ''))
200
+ .map(([cid, c]) => [cid, { ...c, scenarioIds: c.scenarioIds.filter((x) => S.has(x)) }]));
201
+ options[id] = { ...o, coverage };
202
+ }
203
+ const features = {};
204
+ for (const f of orderedFeatures(project)) {
205
+ if (!F.has(f.id))
206
+ continue;
207
+ const optionIds = f.optionIds.filter((x) => O.has(x));
208
+ features[f.id] = { ...f, optionIds, pick: f.pick && O.has(f.pick) ? f.pick : null };
209
+ }
210
+ const featureIds = project.featureIds?.filter((id) => F.has(id));
211
+ const inF = (x) => F.has(x.featureId) && (x.optionId === undefined || O.has(x.optionId));
212
+ const roleIds = new Set(Object.values(features).flatMap((f) => f.roles.map((r) => r.id).filter((r) => !!r)));
213
+ const keepRoles = (v) => v && v.roles ? { ...v, roles: Object.fromEntries(Object.entries(v.roles).filter(([k]) => roleIds.has(k))) } : v;
214
+ const out = {
215
+ ...project,
216
+ // 项目说明常常概述所有功能:范围分享里不带;项目名保留(分享标题与页面标题要用,作者自己决定怎么起)
217
+ description: '',
218
+ routes,
219
+ features,
220
+ ...(featureIds ? { featureIds } : {}),
221
+ cases: Object.fromEntries(Object.entries(project.cases).filter(([, c]) => F.has(c.featureId))),
222
+ options,
223
+ rules: Object.fromEntries(Object.entries(project.rules).filter(([, r]) => inF(r))),
224
+ scenes,
225
+ scenarios,
226
+ issues: Object.fromEntries(Object.entries(project.issues).filter(([, i]) => inF(i))),
227
+ ...(project.voiceConfig ? { voiceConfig: keepRoles(project.voiceConfig) } : {}),
228
+ ...(project.voiceIndex ? { voiceIndex: keepRoles(project.voiceIndex) } : {}),
229
+ };
230
+ const ids = Object.keys(scenarios);
231
+ return { project: out, info: { key: scopeKey(ids, mode), scenarios: ids, features: Object.keys(features), borrowed: merged } };
232
+ }
233
+ /** 一条借用的说明(英文,CLI 与看板共用)。 */
234
+ export function borrowedLine(b) {
235
+ return b.kind === 'element'
236
+ ? `${b.featureName} › element "${b.elementId}" on ${b.route} (referenced by ${b.refs.join(', ')})`
237
+ : `${b.featureName} › page ${b.route} (the scenario navigates there)`;
238
+ }
@@ -0,0 +1,14 @@
1
+ /** Stable author identities are separate from public playback IR for strict legacy readers. */
2
+ import { z } from 'zod';
3
+ import { Project } from './schema.js';
4
+ export declare const StepIdentity: z.ZodObject<{
5
+ formatVersion: z.ZodLiteral<1>;
6
+ scenarios: z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodString>>;
7
+ }, z.core.$strict>;
8
+ export type StepIdentity = z.infer<typeof StepIdentity>;
9
+ /** Only stable keys and existing public playback addresses; no authoring metadata. */
10
+ export declare function stepIdentity(project: Project): StepIdentity | undefined;
11
+ /** Validate references and uniqueness before enriching an in-memory IR. Never mutate the serialized public IR. */
12
+ export declare function applyStepIdentity(value: unknown, metadata: unknown): Project;
13
+ /** Read inert JSON only; never execute either build. Unknown IR versions remain explicit incompatible inputs. */
14
+ export declare function readFeatureDiffBuild(html: string): unknown;
@@ -0,0 +1,70 @@
1
+ /** Stable author identities are separate from public playback IR for strict legacy readers. */
2
+ import { z } from 'zod';
3
+ import { Id, Project, Qid, SCHEMA_VERSION } from "./schema.js";
4
+ import { JoploError } from "./result.js";
5
+ export const StepIdentity = z.strictObject({
6
+ formatVersion: z.literal(1),
7
+ scenarios: z.record(Qid, z.record(Qid, Id)),
8
+ });
9
+ /** Only stable keys and existing public playback addresses; no authoring metadata. */
10
+ export function stepIdentity(project) {
11
+ const scenarios = Object.fromEntries(Object.values(project.scenarios).flatMap(s => {
12
+ const entries = s.steps.filter(st => st.key !== undefined).map(st => [st.id, st.key]);
13
+ return entries.length ? [[s.id, Object.fromEntries(entries)]] : [];
14
+ }));
15
+ if (!Object.keys(scenarios).length)
16
+ return undefined;
17
+ const identity = StepIdentity.parse({ formatVersion: 1, scenarios });
18
+ applyStepIdentity(project, identity);
19
+ return identity;
20
+ }
21
+ /** Validate references and uniqueness before enriching an in-memory IR. Never mutate the serialized public IR. */
22
+ export function applyStepIdentity(value, metadata) {
23
+ const parsed = Project.safeParse(value), parsedIdentity = StepIdentity.safeParse(metadata);
24
+ if (!parsed.success || !parsedIdentity.success)
25
+ throw new JoploError('INVALID_SCHEMA', 'Invalid or unsupported public step identity; rebuild both versions with a compatible CLI');
26
+ const project = parsed.data, identity = parsedIdentity.data;
27
+ for (const [id, keys] of Object.entries(identity.scenarios)) {
28
+ const scenario = project.scenarios[id];
29
+ if (!scenario || scenario.id !== id)
30
+ throw new JoploError('INVALID_REFERENCE', 'Step identity refers to a missing scenario');
31
+ if (new Set(scenario.steps.map(st => st.id)).size !== scenario.steps.length)
32
+ throw new JoploError('INVALID_REFERENCE', 'Step identity has ambiguous playback addresses');
33
+ for (const [stepId, key] of Object.entries(keys)) {
34
+ const step = scenario.steps.find(st => st.id === stepId);
35
+ if (!step)
36
+ throw new JoploError('INVALID_REFERENCE', 'Step identity refers to a missing step');
37
+ if (step.key !== undefined && step.key !== key)
38
+ throw new JoploError('INVALID_REFERENCE', 'Conflicting step identities');
39
+ step.key = key;
40
+ }
41
+ const all = scenario.steps.flatMap(st => st.key === undefined ? [] : [st.key]);
42
+ if (new Set(all).size !== all.length)
43
+ throw new JoploError('INVALID_REFERENCE', 'Stable step keys must be unique within each scenario');
44
+ }
45
+ return project;
46
+ }
47
+ /** Read inert JSON only; never execute either build. Unknown IR versions remain explicit incompatible inputs. */
48
+ export function readFeatureDiffBuild(html) {
49
+ const read = (id, required) => {
50
+ const matches = [...html.matchAll(new RegExp(`<script type="application/json" id="${id}">([\\s\\S]*?)<\\/script>`, 'g'))];
51
+ if (matches.length > 1 || required && matches.length !== 1)
52
+ throw new JoploError('INVALID_SCHEMA', `Expected one ${id} payload. Rebuild both versions; a missing baseline is not a new feature`);
53
+ if (!matches.length)
54
+ return undefined;
55
+ try {
56
+ return JSON.parse(matches[0][1]);
57
+ }
58
+ catch {
59
+ throw new JoploError('INVALID_SCHEMA', `Invalid ${id} JSON`);
60
+ }
61
+ };
62
+ const payload = read('joplo-ir', true);
63
+ if (!payload || typeof payload !== 'object' || !payload.project)
64
+ throw new JoploError('INVALID_SCHEMA', 'Missing public playback project');
65
+ // Future IR must reach featureDiff's explicit incompatible result, never be parsed as today's Project.
66
+ if (payload.project.schemaVersion !== SCHEMA_VERSION)
67
+ return payload.project;
68
+ const identity = read('joplo-step-keys', false);
69
+ return identity === undefined ? payload.project : applyStepIdentity(payload.project, identity);
70
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/core",
3
- "version": "0.2.10",
3
+ "version": "0.2.13",
4
4
  "description": "Joplo 编译器、校验器与播放器(IR v2)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -19,7 +19,7 @@
19
19
  "dist"
20
20
  ],
21
21
  "dependencies": {
22
- "@joplo-app/kit": "0.2.10",
22
+ "@joplo-app/kit": "0.2.13",
23
23
  "elkjs": "0.12.1",
24
24
  "zod": "4.6.7"
25
25
  },