@joplo-app/core 0.6.2 → 0.7.2

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.
@@ -9,13 +9,13 @@
9
9
  /** `npx joplo skill <主题>` 的主题与一句话用途(guide.ts 生成正文;技能里按这份清单列出主题)。 */
10
10
  export declare const SKILL_TOPICS: readonly [{
11
11
  readonly name: "authoring";
12
- readonly description: "Works → slices → steps; feature review, chapters, drafts, files, explicit plugins, named local reactions, composable effects, state and conditions";
12
+ readonly description: "Works → slices → steps; feature review, chapters, drafts, files, explicit plugins, named local reactions, composable effects, state and conditions; read-only asset usage reports";
13
13
  }, {
14
14
  readonly name: "story";
15
15
  readonly description: "Plan a show before coding; for feature review start from needs, roles, goals and cases; for explainers and histories plan openings, continuity and captions";
16
16
  }, {
17
17
  readonly name: "demo";
18
- readonly description: "Scripted playback and local exploration, drag / hover / scroll / plugin actions, confirmed action entries, themes, layers, captions, deep links and screenshots";
18
+ readonly description: "Scripted playback and local exploration, drag / hover / scroll / plugin actions, confirmed action entries, themes, layers, captions, deep links and screenshots; real-browser layout audits and evidence";
19
19
  }, {
20
20
  readonly name: "focus";
21
21
  readonly description: "Guide attention: one focus per step, defaults, spotlight / highlight / callout / numbered / hold / redact";
@@ -46,7 +46,7 @@ export declare const MENTAL_MODEL: readonly ["Joplo shows are playable, interact
46
46
  /** 推荐的起步顺序(X2:先做最小的一条正常流程 + 一条错误恢复流程,在看板里确认交互模型后再扩展)。 */
47
47
  export declare const START_ORDER: readonly ["Choose the starting template: compare feature options with npx joplo init <dir> (or --template starter); make one show people can play, pause and try with npx joplo init <dir> --template work. Bare names select built-ins, never a same-named local directory; use --template ./work for a local folder. Names matching [a-z0-9][a-z0-9-]* select directories in the template repository default branch, without version tags. Init installs engine skills and AGENTS.md, preserving any bundled plugin guides; after installing dependencies run skill install.", "Read npx joplo skill authoring and choose the capabilities; for feature review read cases before asking the user about edge cases; demo and installed plugin skills as needed.", "Plan before coding (npx joplo skill story): audience, one to three points, one line per scenario (Given → When → Then, how it opens and ends; a case's expected is its Then); show the plan to the user. A demo is a story, not a feature tour.", "With minimal code, write one chapter for a standalone work, or one happy path and one error-and-recovery scenario for feature review.", "Run npx joplo check, then npx joplo dev; confirm typing, clicks, and layers really behave as intended in the board.", "Extend to every option and every case agreed with the user for feature review, or to the agreed chapters for a standalone work; run check until 0 errors.", "Required after every round of development: before handing off, read npx joplo skill review and start npx joplo feedback watch [dir] --local --follow --json in its own shell (joplo dev prints this exact command); only then give the user the board URL dev printed. Never hand off with only a URL, and never end your response without a running watcher (use --once below). While they test, read its output with short waits (about 1–5s) and acknowledge each feedback right away; do not wait for approval or process exit. If you end your response while they test, add --once so the watcher exits (and wakes a host that resumes on background exit) on the first event, then resume with --since. Receive and apply review results with the joplo-feedback skill."];
48
48
  /** 最常见的坑:一句话 + 详细主题。 */
49
- export declare const PITFALLS: readonly [readonly ["Finishing development is not the end: always start npx joplo feedback watch [dir] --local --follow --json (add --once if you will end your response) before you give the user the board URL, and keep receiving their feedback", "review"], readonly ["when takes a condition, not a boolean: when={eq($.ui.mode, 'code')}, never when={mode === 'code'}; for values known while writing use {flag && <X/>}", "authoring"], readonly ["Every interactive element needs a flow step, disabled={true} with disabledReason, or unmodeled; otherwise check warns UNBOUND_INTERACTIVE", "check"], readonly ["No onClick or other function props: behavior lives in flow steps (.click/.type/.select) and effects (set, push, go, done)", "authoring"], readonly ["Full-height layouts squeeze tables and forms: rows exist in the DOM but are cut off on screen; show 5–8 rows or move the table to its own layer", "demo"], readonly ["Deep links use short params ?o=&c=&s=&step=&l= (l is the layer key and pins that layer, so later steps stop switching layers; layer= is ignored); wait for rendering before screenshots", "demo"], readonly ["Rules you assume stay origin ai_assumption, status pending; never mark them confirmed for the user", "cases"], readonly ["CHOICE_REQUIRED (exit 2): ask both publishing questions; never fix it by silently adding --private --no-review, and do not reuse the previous invocation", "publish"], readonly ["Public portfolio work and the always-private review version are two separate links: give reviewers data.review.url, the audience data.url", "publish"], readonly ["Required: before every share, ask the user public or private AND whether to also publish a review version. Never choose for them or reuse a previous choice; CI must pin both flags in its workflow", "publish"], readonly ["Public shares enter the portfolio and search engines: write the project name, description, and feature goals and work summaries as search-result content; exclude unpublished information", "publish"], readonly ["Never invent or set an access password for the user: ask them to type it in their own terminal or set JOPLO_SHARE_PASSWORD; never put passwords in command history, files, or conversation summaries. Private Pro shares accept --password; omit both password flags to preserve protection", "publish"], readonly ["Never share or deploy without the user's go-ahead. Free links no longer expire, but every live share counts toward the account storage; if share fails with QUOTA_EXCEEDED (exit 6), tell the user the numbers and the two links from error.details, never delete their shares yourself", "publish"], readonly ["Joplo Cloud narration spends the user's characters: run npx joplo voice --dry-run and tell them the estimate before a large batch; on TTS_QUOTA_EXCEEDED (exit 7) keep what was made, pass on error.details.usageUrl, and never retry in a loop or buy for them", "publish"], readonly ["AiHubMix, OpenAI-compatible gateways and custom HTTP voice providers are gone: VOICE_UNSUPPORTED means ask the user to switch to Joplo Cloud narration, OpenAI or ElevenLabs (old audio still plays and ships); never hand-edit ~/.joplo/voice/profiles.json", "publish"], readonly ["Playing a demo never generates Joplo Cloud narration (it would spend characters): steps without audio use the browser voice until the user clicks Generate missing audio or you run npx joplo voice with their go-ahead", "publish"], readonly ["Re-sharing with the default voice keeps valid local clips plus reusable published clips, even when their voices differ (automatic captions must still match current text in the clip language; stale audio is excluded); an old custom provider named cloud stays unsupported until the user explicitly chooses official Joplo Cloud (use voice.profile: 'Joplo Cloud' when config owns the selection)", "publish"], readonly ["HAPPY_PATH_ONLY applies only to feature review: for a standalone explainer use work() + chapter(), with no cases or uses(); do not invent failure scenarios", "check"], readonly ["Required for short films and explainers: static storyboards cannot show hard cuts or frozen pictures. Run npx joplo render <dir> --scenario-id <first chapter> --film --chain, fix every CUT and STILL it reports, and watch --video once before handing over (render --video takes --width/--height, --voice, --clean and --srt for publishing; see joplo skill demo)", "demo"], readonly ["For multimodal stories, list assets and licenses first, prove one real asset in a playable chapter, then extend the batch within the agreed spending limit. Keep source claims separate from interpretations", "story"], readonly ["For generated binary assets, first look for CC0/public-domain material; use an enabled generation plugin for gaps. Run resources --dry-run before spending; check/build/render never generate paid artifacts. Commit outputs and metadata, keep keys local", "plugins"], readonly ["For background audio use a media plugin: enable it explicitly, read its skill, place play/stop in steps, and verify sound after a viewer gesture; local resource failures are warnings", "plugins"], readonly ["Collect reusable assets before drawing complex visuals; keep source URLs, authors, licenses and changes in assets/SOURCES.md, and verify bundled fonts and samples separately", "story"], readonly ["For audience exploration, use native UI controls or work.free; keep deterministic results in flow steps. Read demo before using drag, hover, scroll or plugin actions", "demo"], readonly ["Components outside the catalog may exist as plugins: install the npm package, add it to config({ plugins }), then read npx joplo skill <plugin id> before writing its components", "plugins"]];
49
+ export declare const PITFALLS: readonly [readonly ["Finishing development is not the end: always start npx joplo feedback watch [dir] --local --follow --json (add --once if you will end your response) before you give the user the board URL, and keep receiving their feedback", "review"], readonly ["when takes a condition, not a boolean: when={eq($.ui.mode, 'code')}, never when={mode === 'code'}; for values known while writing use {flag && <X/>}", "authoring"], readonly ["Every interactive element needs a flow step, disabled={true} with disabledReason, or unmodeled; otherwise check warns UNBOUND_INTERACTIVE", "check"], readonly ["No onClick or other function props: behavior lives in flow steps (.click/.type/.select) and effects (set, push, go, done)", "authoring"], readonly ["Full-height layouts squeeze tables and forms: rows exist in the DOM but are cut off on screen; show 5–8 rows or move the table to its own layer", "demo"], readonly ["Deep links use short params ?o=&c=&s=&step=&l= (l is the layer key and pins that layer, so later steps stop switching layers; layer= is ignored); wait for rendering before screenshots", "demo"], readonly ["Rules you assume stay origin ai_assumption, status pending; never mark them confirmed for the user", "cases"], readonly ["CHOICE_REQUIRED (exit 2): ask both publishing questions; never fix it by silently adding --private --no-review, and do not reuse the previous invocation", "publish"], readonly ["Public portfolio work and the always-private review version are two separate links: give reviewers data.review.url, the audience data.url", "publish"], readonly ["Required: before every share, ask the user public or private AND whether to also publish a review version. Never choose for them or reuse a previous choice; CI must pin both flags in its workflow", "publish"], readonly ["Public shares enter the portfolio and search engines: write the project name, description, and feature goals and work summaries as search-result content; exclude unpublished information", "publish"], readonly ["Never invent or set an access password for the user: ask them to type it in their own terminal or set JOPLO_SHARE_PASSWORD; never put passwords in command history, files, or conversation summaries. Private Pro shares accept --password; omit both password flags to preserve protection", "publish"], readonly ["Never share or deploy without the user's go-ahead. Free links no longer expire, but every live share counts toward the account storage; if share fails with QUOTA_EXCEEDED (exit 6), tell the user the numbers and the two links from error.details, never delete their shares yourself", "publish"], readonly ["Prepared narration/dialogue uses narrate(text, { audio: asset(...) }) or say(text, { role, audio: localResource(...) }); explicit audio never calls TTS or counts generation characters. Use hold('voice', { pad: 0.4 }) / hold('audio', ref) for measured-or-estimated audio dwell; check and outline identify the source; see demo before lining up tracks", "demo"], readonly ["Joplo Cloud narration spends the user's characters: run npx joplo voice --work <work-id> --dry-run (omit --work for all; --scenario follows continuing predecessors), inspect per-step details, use narrate(false) for silent steps, and tell them the estimate before a large batch; on TTS_QUOTA_EXCEEDED (exit 7) keep what was made, pass on error.details.usageUrl, and never retry in a loop or buy for them", "publish"], readonly ["AiHubMix, OpenAI-compatible gateways and custom HTTP voice providers are gone: VOICE_UNSUPPORTED means ask the user to switch to Joplo Cloud narration, OpenAI or ElevenLabs (old audio still plays and ships); never hand-edit ~/.joplo/voice/profiles.json", "publish"], readonly ["Playing a demo never generates Joplo Cloud narration (it would spend characters): steps without audio use the browser voice until the user clicks Generate missing audio or you run npx joplo voice with their go-ahead", "publish"], readonly ["Re-sharing with the default voice keeps valid local clips plus reusable published clips, even when their voices differ (automatic captions must still match current text in the clip language; stale audio is excluded); an old custom provider named cloud stays unsupported until the user explicitly chooses official Joplo Cloud (use voice.profile: 'Joplo Cloud' when config owns the selection)", "publish"], readonly ["HAPPY_PATH_ONLY applies only to feature review: for a standalone explainer use work() + chapter(), with no cases or uses(); do not invent failure scenarios", "check"], readonly ["Required for short films and explainers: static storyboards cannot show hard cuts or frozen pictures. Run npx joplo render <dir> --scenario-id <first chapter> --film --chain, fix every CUT and STILL it reports, and watch --video once before handing over (render supports --viewport/--no-frame, --crop and public --frames-out/--timeline; --video takes --width/--height, --voice, --clean and --srt for publishing; see joplo skill demo)", "demo"], readonly ["For multimodal stories, list assets and licenses first, prove one real asset in a playable chapter, then extend the batch within the agreed spending limit. Keep source claims separate from interpretations", "story"], readonly ["For generated binary assets, first look for CC0/public-domain material; use an enabled generation plugin for gaps. Run resources --dry-run before spending; check/build/render never generate paid artifacts. Commit outputs and metadata, keep keys local", "plugins"], readonly ["For background audio use a media plugin: enable it explicitly, read its skill, place play/stop in steps, and verify sound after a viewer gesture; local resource failures are warnings", "plugins"], readonly ["Collect reusable assets before drawing complex visuals; keep source URLs, authors, licenses and changes in assets/SOURCES.md, and verify bundled fonts and samples separately", "story"], readonly ["For audience exploration, use native UI controls or work.free; keep deterministic results in flow steps. Read demo before using drag, hover, scroll or plugin actions", "demo"], readonly ["Components outside the catalog may exist as plugins: install the npm package, add it to config({ plugins }), then read npx joplo skill <plugin id> before writing its components", "plugins"]];
50
50
  export type AgentSkill = {
51
51
  name: string;
52
52
  description: string;
@@ -8,9 +8,9 @@
8
8
  */
9
9
  /** `npx joplo skill <主题>` 的主题与一句话用途(guide.ts 生成正文;技能里按这份清单列出主题)。 */
10
10
  export const SKILL_TOPICS = [
11
- { name: 'authoring', description: 'Works → slices → steps; feature review, chapters, drafts, files, explicit plugins, named local reactions, composable effects, state and conditions' },
11
+ { name: 'authoring', description: 'Works → slices → steps; feature review, chapters, drafts, files, explicit plugins, named local reactions, composable effects, state and conditions; read-only asset usage reports' },
12
12
  { name: 'story', description: 'Plan a show before coding; for feature review start from needs, roles, goals and cases; for explainers and histories plan openings, continuity and captions' },
13
- { name: 'demo', description: 'Scripted playback and local exploration, drag / hover / scroll / plugin actions, confirmed action entries, themes, layers, captions, deep links and screenshots' },
13
+ { name: 'demo', description: 'Scripted playback and local exploration, drag / hover / scroll / plugin actions, confirmed action entries, themes, layers, captions, deep links and screenshots; real-browser layout audits and evidence' },
14
14
  { name: 'focus', description: 'Guide attention: one focus per step, defaults, spotlight / highlight / callout / numbered / hold / redact' },
15
15
  { name: 'cases', description: 'Feature-attached works only: cases and coverage; ask the user before starting' },
16
16
  { name: 'check', description: 'Read diagnostics, music duration/markers and timing warnings, UNBOUND_INTERACTIVE, and fix the indicated file and line' },
@@ -53,12 +53,13 @@ export const PITFALLS = [
53
53
  ["Public shares enter the portfolio and search engines: write the project name, description, and feature goals and work summaries as search-result content; exclude unpublished information", "publish"],
54
54
  ["Never invent or set an access password for the user: ask them to type it in their own terminal or set JOPLO_SHARE_PASSWORD; never put passwords in command history, files, or conversation summaries. Private Pro shares accept --password; omit both password flags to preserve protection", "publish"],
55
55
  ["Never share or deploy without the user's go-ahead. Free links no longer expire, but every live share counts toward the account storage; if share fails with QUOTA_EXCEEDED (exit 6), tell the user the numbers and the two links from error.details, never delete their shares yourself", "publish"],
56
- ["Joplo Cloud narration spends the user's characters: run npx joplo voice --dry-run and tell them the estimate before a large batch; on TTS_QUOTA_EXCEEDED (exit 7) keep what was made, pass on error.details.usageUrl, and never retry in a loop or buy for them", "publish"],
56
+ ["Prepared narration/dialogue uses narrate(text, { audio: asset(...) }) or say(text, { role, audio: localResource(...) }); explicit audio never calls TTS or counts generation characters. Use hold('voice', { pad: 0.4 }) / hold('audio', ref) for measured-or-estimated audio dwell; check and outline identify the source; see demo before lining up tracks", "demo"],
57
+ ["Joplo Cloud narration spends the user's characters: run npx joplo voice --work <work-id> --dry-run (omit --work for all; --scenario follows continuing predecessors), inspect per-step details, use narrate(false) for silent steps, and tell them the estimate before a large batch; on TTS_QUOTA_EXCEEDED (exit 7) keep what was made, pass on error.details.usageUrl, and never retry in a loop or buy for them", "publish"],
57
58
  ["AiHubMix, OpenAI-compatible gateways and custom HTTP voice providers are gone: VOICE_UNSUPPORTED means ask the user to switch to Joplo Cloud narration, OpenAI or ElevenLabs (old audio still plays and ships); never hand-edit ~/.joplo/voice/profiles.json", "publish"],
58
59
  ["Playing a demo never generates Joplo Cloud narration (it would spend characters): steps without audio use the browser voice until the user clicks Generate missing audio or you run npx joplo voice with their go-ahead", "publish"],
59
60
  ["Re-sharing with the default voice keeps valid local clips plus reusable published clips, even when their voices differ (automatic captions must still match current text in the clip language; stale audio is excluded); an old custom provider named cloud stays unsupported until the user explicitly chooses official Joplo Cloud (use voice.profile: 'Joplo Cloud' when config owns the selection)", "publish"],
60
61
  ["HAPPY_PATH_ONLY applies only to feature review: for a standalone explainer use work() + chapter(), with no cases or uses(); do not invent failure scenarios", "check"],
61
- ["Required for short films and explainers: static storyboards cannot show hard cuts or frozen pictures. Run npx joplo render <dir> --scenario-id <first chapter> --film --chain, fix every CUT and STILL it reports, and watch --video once before handing over (render --video takes --width/--height, --voice, --clean and --srt for publishing; see joplo skill demo)", "demo"],
62
+ ["Required for short films and explainers: static storyboards cannot show hard cuts or frozen pictures. Run npx joplo render <dir> --scenario-id <first chapter> --film --chain, fix every CUT and STILL it reports, and watch --video once before handing over (render supports --viewport/--no-frame, --crop and public --frames-out/--timeline; --video takes --width/--height, --voice, --clean and --srt for publishing; see joplo skill demo)", "demo"],
62
63
  ["For multimodal stories, list assets and licenses first, prove one real asset in a playable chapter, then extend the batch within the agreed spending limit. Keep source claims separate from interpretations", "story"],
63
64
  ["For generated binary assets, first look for CC0/public-domain material; use an enabled generation plugin for gaps. Run resources --dry-run before spending; check/build/render never generate paid artifacts. Commit outputs and metadata, keep keys local", "plugins"],
64
65
  ["For background audio use a media plugin: enable it explicitly, read its skill, place play/stop in steps, and verify sound after a viewer gesture; local resource failures are warnings", "plugins"],
@@ -118,6 +119,7 @@ function joploBody() {
118
119
  'Required: whenever you finish a round of development the user will look at, start the follower below before handing off, even for small changes and even if the user did not ask for a review. A hand-off without a running watcher loses their feedback.',
119
120
  'The user reviews in the board: they click through scenarios, write comments with the board\'s native feedback icon, and may confirm (approve) an option. You receive each event the moment it is saved.',
120
121
  '1. Start npx joplo feedback watch <dir> --local --follow --json in its own long-running shell (joplo dev prints this exact command; the board\'s feedback panel can copy it too). One follower covers every option of the project and attaches by itself to the new round each source edit opens.',
122
+ ' Successful dev startup/join registers review rounds before printing the ready link; no browser visit is required. Fix compile errors before starting watch. There is no idle expiry: inspect feedback list --local --all --json for closing reasons. A joined project depends on the original board process; keep its terminal running, or restart dev and watch after it stops.',
121
123
  '2. Then give the user the board URL that dev printed (do not assume port 4790) and point them to the native feedback icon. If they want to drive the UI themselves, only give the link.',
122
124
  '3. While they test, read the follower\'s output with short waits (about 1–5 seconds). Each stdout line is one JSON event (feedback, approved, closed) carrying eventId, workId, sessionId and context (route, scenario, step, source); deduplicate by eventId. A background shell alone does not wake an idle agent: stay in a receive loop, and do not claim you are still listening after ending your response unless the host can resume you.',
123
125
  ' - If you will end your response while the user tests, and your host wakes you when a background command finishes (a host configured to resume on process exit does): run the follower in the background with --once added. It exits 0 on the first feedback or approval, which wakes you. Handle the events, then start it again with --since <createdAt of the last event> (the exit message prints this exact command) so nothing is replayed or lost. Without such a host, tell the user to message you after they confirm.',
package/dist/compile.js CHANGED
@@ -116,6 +116,8 @@ export function compile(src, mode, opts = {}) {
116
116
  const definitions = f ? sortedEntries(f.works) : [[id, works.get(id)]];
117
117
  for (const [key, raw] of definitions) {
118
118
  const qid = f ? `${id}.${key}` : key;
119
+ if (raw.pace !== undefined && (!raw.pace || typeof raw.pace !== 'object' || Array.isArray(raw.pace) || Object.keys(raw.pace).some(k => k !== 'systemLead') || (raw.pace.systemLead !== undefined && (typeof raw.pace.systemLead !== 'number' || !Number.isFinite(raw.pace.systemLead) || raw.pace.systemLead < 0 || raw.pace.systemLead > 30))))
120
+ err('PACE_INVALID', 'work pace.systemLead must be a finite number of seconds from 0 to 30; omit it for the default 0.9 seconds', raw.source);
119
121
  const slices = resolveSlices(raw.scenarios, `Work ${qid}`, err);
120
122
  if (slices.linear)
121
123
  linearWorks.add(qid);
@@ -230,6 +232,8 @@ export function compile(src, mode, opts = {}) {
230
232
  list.push(ctx);
231
233
  return list;
232
234
  };
235
+ /** 每个画面的元素事件(写法 v2),编译剧本与本地反应时读取。 */
236
+ const sceneEvents = new Map();
233
237
  const composeScene = (route, ctx) => {
234
238
  const sceneId = ctx ? `${ctx.qid}@${route.path}` : `@${route.path}`;
235
239
  const page = route.page;
@@ -268,7 +272,9 @@ export function compile(src, mode, opts = {}) {
268
272
  const base = tree;
269
273
  const rootJ = { ...base, type: base.type, children: [...base.children, ...overlays] };
270
274
  const ids = new Map();
271
- const root = toSceneNode(rootJ, 'root', ids, nodeCtx, null);
275
+ const events = new Map();
276
+ const root = toSceneNode(rootJ, 'root', ids, { ...nodeCtx, events }, null);
277
+ sceneEvents.set(sceneId, events);
272
278
  const scene = { id: sceneId, workId: ctx?.qid ?? null, route: route.path, name: `${page.title}${ctx ? ` · ${ctx.def.title}` : ''}`, viewport: page.viewport ?? 'desktop', root };
273
279
  if (!diags.some(d => d.severity === 'error'))
274
280
  host.derive(scene);
@@ -347,8 +353,10 @@ export function compile(src, mode, opts = {}) {
347
353
  }
348
354
  const rootJ = nodes.length === 1 ? nodes[0] : { ...nodes[0], type: '#fragment', props: {}, children: nodes };
349
355
  const ids = new Map();
350
- const root = toSceneNode(rootJ, `layer_${lk}`, ids, nodeCtx, null);
351
356
  const sceneId = `${qid}~${lk}`;
357
+ const events = new Map();
358
+ const root = toSceneNode(rootJ, `layer_${lk}`, ids, { ...nodeCtx, events }, null);
359
+ sceneEvents.set(sceneId, events);
352
360
  const scene = { id: sceneId, workId: qid, route: layerRoute, name: `${ld.title} · ${def.title}`, viewport: ld.viewport ?? 'desktop', root, layer: lk };
353
361
  if (!diags.some(d => d.severity === 'error'))
354
362
  host.derive(scene);
@@ -367,6 +375,10 @@ export function compile(src, mode, opts = {}) {
367
375
  const layersWith = (id) => layerScenes.filter((l) => findIn(l.scene.root, id)).map((l) => l.key);
368
376
  const layerSceneWith = (id) => layerScenes.find((l) => findIn(l.scene.root, id))?.scene;
369
377
  const effectRoots = [...layerScenes.map(l => l.scene), ...[...sceneFor.values()].filter(x => x.workId === qid || !isIsolated && x.workId == null)];
378
+ /** 这件作品的观众会看到的画面:有层级时是各层,否则是每个路径在这件作品里的画面。 */
379
+ const viewScenes = hasLayers ? layerScenes.map(l => l.scene) : [...ctxRoutes].map(path => sceneFor.get(sceneOf(path))).filter((x) => !!x);
380
+ /** 某一步(所在路径 route)点到的元素自带的 onClick。 */
381
+ const eventOf = (route, target) => hasLayers ? sceneEvents.get(layerSceneWith(target)?.id ?? '')?.get(target) : sceneEvents.get(sceneOf(route))?.get(target);
370
382
  const scenarioIds = {};
371
383
  // flow({ from }) 接力:按依赖顺序编译,被接的场景先编译,记下它结尾的路径与导演层;
372
384
  // 接力场景的逐步校验(页面里找目标、焦点提示、镜头、自动字幕)都从那里开始,而不是默认起点
@@ -390,16 +402,18 @@ export function compile(src, mode, opts = {}) {
390
402
  /** 每个场景编译完之后的结尾:路径(按 go / back 推算)与导演层。 */
391
403
  const scenarioEnd = new Map();
392
404
  for (const skey of orderedKeys) {
393
- const fl = scenarioDefs[skey];
405
+ const authored = scenarioDefs[skey];
394
406
  const sid = `${qid}.${skey}`;
395
- const fromEnd = fl.opts.from !== undefined && fl.opts.from !== skey ? scenarioEnd.get(fl.opts.from) : undefined;
396
- if (fl.opts.from !== undefined && fl.opts.start !== undefined)
397
- err('FROM_WITH_START', `flow({ from: ${JSON.stringify(fl.opts.from)}, start: ${JSON.stringify(fl.opts.start)} }): a scenario that continues another starts where that one ended; remove start (or remove from to start fresh)`, fl.source);
398
- const start = fromEnd?.route ?? fl.opts.start ?? (isIsolated ? '/' : touched[0] ?? src.config.home ?? [...ctxRoutes][0]);
407
+ const fromEnd = authored.opts.from !== undefined && authored.opts.from !== skey ? scenarioEnd.get(authored.opts.from) : undefined;
408
+ if (authored.opts.from !== undefined && authored.opts.start !== undefined)
409
+ err('FROM_WITH_START', `flow({ from: ${JSON.stringify(authored.opts.from)}, start: ${JSON.stringify(authored.opts.start)} }): a scenario that continues another starts where that one ended; remove start (or remove from to start fresh)`, authored.source);
410
+ const start = fromEnd?.route ?? authored.opts.start ?? (isIsolated ? '/' : touched[0] ?? src.config.home ?? [...ctxRoutes][0]);
399
411
  if (!start || !ctxRoutes.has(start)) {
400
- err('UNKNOWN_ROUTE', `Scenario ${sid} starts at unknown route ${start ?? '(none)'}`, fl.source);
412
+ err('UNKNOWN_ROUTE', `Scenario ${sid} starts at unknown route ${start ?? '(none)'}`, authored.source);
401
413
  continue;
402
414
  }
415
+ // 写法 v2:点击步骤先执行被点元素的 onClick,再执行步骤自己写的效果。页面跟踪(go / back)看得到合并后的效果。
416
+ const fl = Object.assign(Object.create(Object.getPrototypeOf(authored)), authored, { steps: withElementEvents(authored.steps, start, eventOf, warn) });
403
417
  for (const c of fl.opts.cases ?? []) {
404
418
  if (!fdef?.cases?.[c])
405
419
  err('UNKNOWN_CASE', `Scenario ${sid} covers case "${c}", which is not in feature.cases`, fl.source);
@@ -520,6 +534,49 @@ export function compile(src, mode, opts = {}) {
520
534
  }
521
535
  free[key] = { action: a.data, effects, ...(reaction.source ? { source: rel(reaction.source) } : {}) };
522
536
  }
537
+ // 元素事件生成本地反应:观众接管后点它,效果和剧本里那一步相同(uses 只是规则关联,不进本地层)
538
+ {
539
+ const seen = new Map();
540
+ for (const scene of viewScenes)
541
+ for (const [target, ev] of sceneEvents.get(scene.id) ?? []) {
542
+ const effects = [];
543
+ for (const e of ev.effects) {
544
+ if (e.type === 'go') {
545
+ if (!ctxRoutes.has(e.route)) {
546
+ err('UNKNOWN_ROUTE', `onClick go("${e.route}") on ${target} navigates to an unknown route`, ev.at);
547
+ continue;
548
+ }
549
+ effects.push({ type: 'navigate', sceneId: sceneOf(e.route) });
550
+ }
551
+ else if (e.type === 'set' || e.type === 'append')
552
+ effects.push({ type: e.type, path: e.path, value: e.value });
553
+ else if (e.type === 'toast')
554
+ effects.push({ type: 'toast', text: e.text, tone: e.tone });
555
+ }
556
+ const parsed = effects.map(e => Effect.safeParse(e));
557
+ if (parsed.some(r => !r.success)) {
558
+ err('EVENT_EFFECT_INVALID', `onClick on ${target} writes an invalid state path or value`, ev.at);
559
+ continue;
560
+ }
561
+ const json = JSON.stringify(effects);
562
+ const prev = seen.get(target);
563
+ if (prev) {
564
+ if (prev.json !== json)
565
+ err('EVENT_CONFLICT', `${target} has a different onClick on two stages of work ${qid} (other location: ${rel(prev.at) ?? 'unknown'}); one id has one behavior, so give the elements different ids`, ev.at);
566
+ continue;
567
+ }
568
+ seen.set(target, { json, ...(ev.at ? { at: ev.at } : {}) });
569
+ if (!effects.length)
570
+ continue;
571
+ const handWritten = Object.entries(free).find(([, r]) => r.action.type === 'click' && 'target' in r.action && r.action.target === target);
572
+ if (handWritten) {
573
+ err('FREE_EVENT_CONFLICT', `Free reaction ${handWritten[0]} also handles clicks on ${target}, which has onClick; keep one: move its effects into onClick and delete the free reaction`, ev.at);
574
+ continue;
575
+ }
576
+ const key = eventFreeKey(target, free);
577
+ free[key] = { action: { type: 'click', target }, effects: parsed.map(r => r.data), ...(ev.at && rel(ev.at) ? { source: rel(ev.at) } : {}) };
578
+ }
579
+ }
523
580
  if (fdef)
524
581
  out.features[fid].alternatives[qid] = { decisionFocus: strip ? '' : def.focus ?? '', tradeoffs: strip ? [] : def.tradeoffs ?? [], coverage };
525
582
  out.works[qid] = {
@@ -609,6 +666,8 @@ export function compile(src, mode, opts = {}) {
609
666
  }
610
667
  if (diags.some((d) => d.severity === 'error'))
611
668
  return { project: null, diagnostics: diags };
669
+ if (Object.keys(host.embeddedAudio).length)
670
+ out.mediaAssets = host.embeddedAudio;
612
671
  const parsed = Project.safeParse(out);
613
672
  if (!parsed.success) {
614
673
  // 同一根因(共享的 JSX)在多个画面展开时合并成一条,定位到作者元素(schema-issues.ts)
@@ -715,6 +774,9 @@ function lowerStep(c, st, i) {
715
774
  const says = [];
716
775
  let sayRole = null;
717
776
  const narrates = [];
777
+ let mute = false;
778
+ const sayAudio = [], narrateAudio = [];
779
+ let holdFor;
718
780
  /** 插件效果声明的最短停留(D98):同一步取最大值。 */
719
781
  let effectHoldMs = 0;
720
782
  const ext = {};
@@ -750,6 +812,8 @@ function lowerStep(c, st, i) {
750
812
  else if (e.type === 'shot' || e.type === 'mark' || e.type === 'fork' || e.type === 'cue' || e.type === 'callout' || e.type === 'hold')
751
813
  continue; // 镜头与焦点提示不是状态变化,下面单独归类
752
814
  else if (e.type === 'say') {
815
+ if (e.audio !== undefined)
816
+ sayAudio.push(e.audio);
753
817
  if (e.role !== undefined) {
754
818
  if (typeof e.role !== 'string' || !roleKeys.has(e.role))
755
819
  err('ROLE_UNKNOWN', `say() role "${String(e.role)}" is not in ${roleScope}${roleKeys.size ? ` (available: ${[...roleKeys].join(', ')})` : ` (${roleScope} must use { key: role('Name') })`}`, st.source);
@@ -764,7 +828,11 @@ function lowerStep(c, st, i) {
764
828
  err('SAY_EMPTY', 'say() needs the line the character speaks, for example say(\'I can make it!\'). Remove it to read the caption instead', st.source);
765
829
  }
766
830
  else if (e.type === 'narrate') {
767
- if (typeof e.text === 'string' && e.text.trim())
831
+ if (e.audio !== undefined)
832
+ narrateAudio.push(e.audio);
833
+ if (e.text === false)
834
+ mute = true;
835
+ else if (typeof e.text === 'string' && e.text.trim())
768
836
  narrates.push(e.text.trim());
769
837
  else
770
838
  err('NARRATE_EMPTY', 'narrate() needs the narrator\'s words, for example narrate(\'She sends Ajie the plan as a link, so he needs no app.\'). Remove it to read say() or the caption instead', st.source);
@@ -860,6 +928,18 @@ function lowerStep(c, st, i) {
860
928
  }
861
929
  }
862
930
  else if (e.type === 'hold') {
931
+ if ('timing' in e) {
932
+ const pad = e.pad ?? 0.45;
933
+ if (!['voice', 'audio'].includes(e.timing) || typeof pad !== 'number' || !Number.isFinite(pad) || pad < 0 || pad > 30)
934
+ err('HOLD_AUDIO_INVALID', 'Audio-derived hold pad must be finite seconds from 0 to 30', st.source);
935
+ else if (holdFor)
936
+ err('HOLD_AUDIO_CONFLICT', 'A step can have only one audio-derived hold declaration', st.source);
937
+ else {
938
+ const audio = e.timing === 'audio' ? host.audioSource(e.audio, st.source) : undefined;
939
+ holdFor = { kind: e.timing, padMs: Math.round(pad * 1000), ...(audio ? { audio } : {}) };
940
+ }
941
+ continue;
942
+ }
863
943
  const sec = e.seconds;
864
944
  if (typeof sec !== 'number' || !Number.isFinite(sec) || sec < HOLD_MIN_SECONDS || sec > HOLD_MAX_SECONDS)
865
945
  err('HOLD_INVALID', `hold(${String(sec)}) must be between ${HOLD_MIN_SECONDS} and ${HOLD_MAX_SECONDS} seconds`, st.source);
@@ -937,6 +1017,18 @@ function lowerStep(c, st, i) {
937
1017
  for (const s of shots)
938
1018
  frame.set(s.layer === DIRECTOR_LAYER ? director : s.layer, [...s.targets]);
939
1019
  const generated = st.caption === undefined ? autoCaption(st, (hasLayers && actionTarget ? layerSceneWith(actionTarget) : undefined) ?? sceneBefore, out) : null;
1020
+ const selectedAudio = narrates.length ? narrateAudio : sayAudio;
1021
+ const selectedLines = narrates.length ? narrates : says;
1022
+ if (!mute && selectedAudio.length && (selectedAudio.length !== 1 || selectedLines.length !== 1))
1023
+ err('SPEECH_AUDIO_CONFLICT', 'An explicit audio clip must accompany exactly one selected narrate() or say() line per step', st.source);
1024
+ const audio = !mute && selectedAudio.length === 1 ? host.audioSource(selectedAudio[0], st.source) : undefined;
1025
+ if (holdFor) {
1026
+ const cached = holdFor.kind === 'voice' && !audio && !mute ? host.voiceDuration(`${sid}#${i + 1}`) : undefined;
1027
+ const duration = holdFor.kind === 'audio' ? (holdFor.audio ? host.audioDuration(holdFor.audio) : undefined)
1028
+ : mute ? undefined : audio ? host.audioDuration(audio) : cached?.durationMs;
1029
+ if (typeof duration === 'number' && Number.isFinite(duration) && duration > 0)
1030
+ holdFor = { ...holdFor, durationMs: duration, durationKey: cached?.key ?? (holdFor.kind === 'audio' ? holdFor.audio : audio) };
1031
+ }
940
1032
  c.director = director;
941
1033
  return {
942
1034
  id: `${sid}#${i + 1}`,
@@ -957,11 +1049,15 @@ function lowerStep(c, st, i) {
957
1049
  marks,
958
1050
  ...(cues.length ? { cues } : {}),
959
1051
  ...(callouts.length ? { callouts } : {}),
1052
+ ...(audio ? { audio } : {}),
1053
+ ...(holdFor ? { holdFor } : {}),
960
1054
  ...(holdMs !== undefined ? { hold: holdMs } : {}),
961
1055
  ...(effectHoldMs > 0 ? { effectHold: effectHoldMs } : {}),
962
1056
  ...(says.length ? { say: says.join(' ') } : {}),
963
1057
  ...(says.length && sayRole ? { sayRole } : {}),
964
1058
  ...(narrates.length ? { narrate: narrates.join(' ') } : {}),
1059
+ ...(mute ? { mute: true } : {}),
1060
+ ...(st.kind === 'system' && typeof def.pace?.systemLead === 'number' && Number.isFinite(def.pace.systemLead) && def.pace.systemLead >= 0 && def.pace.systemLead <= 30 ? { systemLead: Math.round(def.pace.systemLead * 1000) } : {}),
965
1061
  ...(st.source ? { source: rel(st.source) } : {}),
966
1062
  };
967
1063
  }
@@ -1030,6 +1126,22 @@ function expandSlots(n, fill, outlet) {
1030
1126
  function tagFrom(n, from) {
1031
1127
  return { ...n, props: { ...n.props, __from: from } };
1032
1128
  }
1129
+ /** 元素事件里允许的效果:会改变画面状态的本地效果,加上规则关联。完成、镜头、朗读、插件效果属于剧本步骤。 */
1130
+ const EVENT_EFFECTS = new Set(['set', 'append', 'toast', 'go', 'uses']);
1131
+ /** onClick={effect} 或 onClick={[effect, [effect]]};不是效果时返回 null。 */
1132
+ function eventEffects(v) {
1133
+ const out = [];
1134
+ const rec = (x) => {
1135
+ if (Array.isArray(x))
1136
+ return x.every(rec);
1137
+ if (x && typeof x === 'object' && x.kind === 'effect') {
1138
+ out.push(x);
1139
+ return true;
1140
+ }
1141
+ return false;
1142
+ };
1143
+ return rec(v) && out.length ? out : null;
1144
+ }
1033
1145
  function toSceneNode(n, fallbackId, ids, nc, parentType) {
1034
1146
  const { report: err, rel } = nc;
1035
1147
  n = { ...n, props: n.props ?? {}, children: n.children ?? [] };
@@ -1058,6 +1170,38 @@ function toSceneNode(n, fallbackId, ids, nc, parentType) {
1058
1170
  if (spec?.needsId && typeof rawId !== 'string' && !interactive)
1059
1171
  err('MISSING_ID', `<${n.type}> "${labelOf(n)}" requires an id`, at);
1060
1172
  const id = typeof rawId === 'string' ? rawId : `_${fallbackId}`;
1173
+ for (const k of Object.keys(rest)) {
1174
+ if (!/^on[A-Z]/.test(k))
1175
+ continue;
1176
+ const v = rest[k];
1177
+ delete rest[k];
1178
+ if (v === undefined)
1179
+ continue;
1180
+ if (typeof v === 'function' && !isBind(v)) {
1181
+ err('FUNCTION_PROP', `<${n.type}> prop ${k} is a function, and callbacks never run. Give a button its behavior as effects, for example onClick={set($.ui.open, true)}, or put it in the flow steps`, at);
1182
+ continue;
1183
+ }
1184
+ if (k !== 'onClick') {
1185
+ err('EVENT_UNSUPPORTED', `<${n.type}> ${k} is not supported yet; only onClick takes effects. Bind inputs with value={$.ui.name} and put other reactions in the steps`, at);
1186
+ continue;
1187
+ }
1188
+ const effects = eventEffects(v);
1189
+ if (!effects) {
1190
+ err('EVENT_EFFECT_INVALID', `<${n.type}> onClick must be effects, for example onClick={set($.ui.open, true)} or onClick={[set($.ui.open, true), go('/next')]}; got ${JSON.stringify(v)}`, at);
1191
+ continue;
1192
+ }
1193
+ const bad = effects.find(e => !EVENT_EFFECTS.has(e.type));
1194
+ if (bad) {
1195
+ err('EVENT_EFFECT_INVALID', `<${n.type}> onClick: ${bad.type === 'complete' ? 'done()' : `${bad.type}()`} cannot run when the viewer clicks. onClick takes set, push, toast, go and uses; put completion, camera, narration and plugin effects in the step that clicks it`, at);
1196
+ continue;
1197
+ }
1198
+ if (!interactive) {
1199
+ err('EVENT_NOT_INTERACTIVE', `<${n.type}> "${labelOf(n)}" cannot be clicked, so onClick would never run; put it on a button, link or other interactive element`, at);
1200
+ continue;
1201
+ }
1202
+ if (typeof rawId === 'string')
1203
+ nc.events?.set(rawId, { effects, ...(at ? { at } : {}) });
1204
+ }
1061
1205
  if (ids.has(id))
1062
1206
  err('DUPLICATE_ID', `Duplicate id "${id}" in the same stage (other location: ${rel(ids.get(id)) ?? 'unknown'})`, at);
1063
1207
  ids.set(id, at);
@@ -1066,7 +1210,7 @@ function toSceneNode(n, fallbackId, ids, nc, parentType) {
1066
1210
  if (v === undefined)
1067
1211
  continue; // 写了属性但值是 undefined(如 description={cond ? '…' : undefined})= 没写
1068
1212
  if (typeof v === 'function' && !isBind(v)) {
1069
- err('FUNCTION_PROP', `<${n.type}> prop ${k} is a function. Put behavior in the work's flow steps instead of event callbacks`, at);
1213
+ err('FUNCTION_PROP', `<${n.type}> prop ${k} is a function, and callbacks never run. Give a button its behavior as effects, for example onClick={set($.ui.open, true)}, or put it in the flow steps`, at);
1070
1214
  continue;
1071
1215
  }
1072
1216
  if (isNode(v)) {
@@ -1191,6 +1335,42 @@ function stepRouteBefore(steps, i, start) {
1191
1335
  }
1192
1336
  return route;
1193
1337
  }
1338
+ /**
1339
+ * 写法 v2:把被点元素的 onClick 合并进点击步骤(元素效果在前,步骤自己的效果在后)。
1340
+ * 按与 stepRouteBefore 相同的顺序跟踪路径,并且看得到合并进来的 go(),所以元素跳页之后的步骤在新页面上找目标。
1341
+ */
1342
+ function withElementEvents(steps, start, eventOf, warn) {
1343
+ let route = start;
1344
+ const stack = [];
1345
+ return steps.map((st) => {
1346
+ if (st.action.type === 'back')
1347
+ route = stack.pop() ?? route;
1348
+ let next = st;
1349
+ const target = st.action.type === 'click' ? st.action.target : null;
1350
+ const ev = target ? eventOf(route, target) : undefined;
1351
+ if (target && ev) {
1352
+ const writes = new Set(ev.effects.flatMap(e => e.type === 'set' || e.type === 'append' ? [e.path] : []));
1353
+ const repeated = st.effects.find((e) => (e.type === 'set' || e.type === 'append') && writes.has(e.path));
1354
+ if (repeated)
1355
+ warn('STEP_REPEATS_EVENT', `This click on ${target} writes ${repeated.path}, which its onClick already writes; delete the write from the step (onClick runs first, then the step's own effects)`, st.source);
1356
+ next = { ...st, effects: [...ev.effects, ...st.effects] };
1357
+ }
1358
+ for (const e of next.effects)
1359
+ if (e.type === 'go') {
1360
+ stack.push(route);
1361
+ route = e.route;
1362
+ }
1363
+ return next;
1364
+ });
1365
+ }
1366
+ /** 元素事件生成的本地反应用 on-<id> 作键;与作者写的 free 键重名时加序号。 */
1367
+ function eventFreeKey(target, taken) {
1368
+ const base = `on-${target}`.slice(0, 64);
1369
+ let key = base;
1370
+ for (let n = 2; Object.hasOwn(taken, key); n++)
1371
+ key = `${base.slice(0, 60)}-${n}`;
1372
+ return key;
1373
+ }
1194
1374
  /** id 是 frameId 本身或它的子孙(在同一棵树里)。 */
1195
1375
  function findIn(node, id) {
1196
1376
  if (node.id === id)