@lalalic/markcut 3.2.62 → 3.2.64

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 CHANGED
@@ -137,30 +137,26 @@ Two override mechanisms:
137
137
 
138
138
  ### Interactive NeoY Design Mode (before formal Review)
139
139
 
140
- Open the **existing Markcut Previewer** directly on NeoY with a mounted `video.md`:
141
-
142
- ```sh
143
- markcut preview /absolute/path/to/video.md --design
144
- # or only publish/watch the standalone viewer:
145
- markcut preview /absolute/path/to/video.md --design --no-split
146
- ```
147
-
148
- The command compiles the source, publishes the original Markcut player as
149
- `https://neoy.qili2.com/files/_neoy/markcut/design.html?path=/files/<mount>/.../video.md`
150
- (the actual URL is printed with its path encoded), and watches source/asset
151
- changes. The *same browser page* polls the current preview pointer; it retains
152
- the existing top **Original / named variants / Editor Decisions** selector and
153
- tries to keep the current seek position. No Review, approval, or immutable
154
- revision identifier is part of this URL. If `--no-split` is omitted, the
155
- command also starts WebHelm's native Split View with the currently active
156
- ChatGPT conversation. Keep the command running while designing; SIGINT/SIGTERM
157
- ends its WebHelm-owned Session. Comments are drafts in the viewer, readable by
158
- an Agent via `window.__markcutDesignNotes()`, not formal decisions.
159
-
160
- The source must be under an **already configured NeoY file mount**. This mode
161
- uses the existing read-only public `/files/` transport: do not mount private
162
- files that should not be accessible from that URL. Formal Review remains the
163
- existing `markcut.preview` / `--delivery event` workflow.
140
+ The **existing Markcut Previewer** can be opened as a standalone NeoY view
141
+ using only the mounted source `video.md`. There is no special Markcut CLI mode,
142
+ browser Session ID, revision identity, or file-watcher process.
143
+
144
+ 1. Call `markcut.preview({path: "/absolute/path/video.md", readonly: true})`.
145
+ Markcut compiles and publishes the latest player assets. For a source in an
146
+ existing NeoY file mount, the tool result includes `designUrl`, an HTTPS
147
+ link to the standalone player.
148
+ 2. Open `designUrl` in a browser. For interactive side-by-side design, call
149
+ WebHelm's **independent** `webhelm design start --url '<designUrl>'` while a
150
+ ChatGPT conversation tab is active. Markcut does not control Split View.
151
+ 3. After editing `video.md`, referenced media, or its Editor Decision sidecar,
152
+ call the same `markcut.preview` tool with `readonly: true` again. The open
153
+ page polls the published file pointer and updates **Original / variants /
154
+ Editor Decisions** in place. No user-facing Review or approval is required.
155
+ 4. Stop the WebHelm Session through WebHelm. Markcut has no browser lifecycle.
156
+
157
+ The source must be under a configured NeoY file mount. The URL uses the
158
+ existing public, read-only `/files/` transport, so mount only content suitable
159
+ for exposure at that address. This mode does not send review decisions.
164
160
 
165
161
  ## Multi-Variant Preview Server
166
162
 
package/bin/markcut CHANGED
@@ -6,11 +6,6 @@ import { fileURLToPath } from "node:url";
6
6
  const __filename = fileURLToPath(import.meta.url);
7
7
  const __dirname = dirname(__filename);
8
8
  const root = resolve(__dirname, "..");
9
- if (process.argv[2] === "preview" && process.argv.includes("--design")) {
10
- const result=spawnSync(process.execPath,[resolve(root,"src","mcp","design-cli.mjs"),...process.argv.slice(2)],{stdio:'inherit'});
11
- if(result.error)console.error(result.error.message);
12
- process.exit(result.status??1);
13
- }
14
9
  if (process.argv[2] === "preview") {
15
10
  const argv=process.argv.slice(2);
16
11
  const optionIndex=argv.indexOf("--delivery");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lalalic/markcut",
3
- "version": "3.2.62",
3
+ "version": "3.2.64",
4
4
  "description": "Markdown-to-video engine. Describe scenes in markdown, get a rendered video.",
5
5
  "bin": {
6
6
  "markcut": "bin/markcut"
@@ -59,7 +59,7 @@ Asset paths are relative to the Markdown document. A `prompt` without `src` asks
59
59
  ## Preview, review, and finish
60
60
 
61
61
  1. **Structure gate:** `npx @lalalic/markcut verify video.md`, then `npx @lalalic/markcut preview video.md --storyboard` when rapid scene review is useful. Storyboard placeholders do not verify generated media or final audio.
62
- 2. **Design iteration (before Review):** Run `markcut preview /absolute/video.md --design` on Neo Master for an already mounted `video.md` and an active WebHelm ChatGPT thread. This reuses the Markcut Previewer, watches source edits, and starts native Split View. `--no-split` opens NeoY without pairing. End the process to unsplit. Never treat design notes as formal approval.
62
+ 2. **Interactive design before Review:** Call `markcut.preview({path:"/absolute/video.md",readonly:true})` to compile/publish. When its result has `designUrl`, use WebHelm's independent `design start --url <designUrl>` action to show the existing player beside the active ChatGPT conversation. After editing `video.md` or its EDL, call the same readonly preview tool again; the open NeoY player refreshes automatically on publication. End the WebHelm Session separately when finished. No `markcut --design` CLI, Review approval, or Markcut-managed WebHelm lifecycle.
63
63
  3. **Playback gate:** `npx @lalalic/markcut preview video.md`. Play and seek representative scenes; check black tails, media loading, narration, BGM, subtitles, route movement, and timing. For browser failures, load [Preview Troubleshooting](references/preview-troubleshooting.md) on demand.
64
64
  4. **Human review gate:** Use Neo's `markcut.preview({path: "/absolute/path/video.md"})` when the user wants to review the hosted ChatGPT video player. For playback only, use `readonly:true` instead; do not supply `review`. This is **not** the CLI preview. Managed requests correlate through `review.relay`, not a top-level `relay` field. The tool compiles/publishes a revision for playback; it does not rewrite the source. Comments with `decision: changes_requested` require editing that Markdown and calling `markcut.preview` again. `decision: approved` applies **only** to the identified revision/content hash; never apply an old approval to changed content. Follow [Review Contract](review.md) for actual video assessment.
65
65
  5. **Codex / terminal human-review gate:** `npx @lalalic/markcut preview /absolute/video.md --delivery event --event-template /absolute/relay-event.json` on Neo Master. The Event Template must match Relay's canonical `task.interactive_decision` Contract (`type`, `source`, `data.interactive.{jobId,taskId,executionId}` only, without review-result fields). The CLI reuses the MCP compiler, publishes immutable preview assets, persists the review request on Neo Master and dispatches an APNs notification through the existing Neo Mobile provider. Exit receipt `review_requested` confirms only **durable wrapper delivery storage**, not that the phone has acquired it; human decisions arrive asynchronously on Events Bus. The phone need not be online. APNs delivery is best-effort; Neo Mobile synchronizes persisted requests on foreground. There is no automatic text fallback. Do not claim approval or Relay worker continuation from the receipt. For retries with an uncertain phone acknowledgment, pass a stable `--request-id UUID`. See [Codex/mobile review CLI](references/mobile-event-preview-cli.md).
@@ -0,0 +1,29 @@
1
+ // NeoY hosts the existing Markcut player as a standalone read-only document
2
+ // view. Browser split and session lifecycles belong to WebHelm, not Markcut.
3
+ import {readFileSync,writeFileSync,mkdirSync,renameSync} from 'node:fs';
4
+ import {join} from 'node:path';
5
+ import {EXPORT_ROOT,publicOrigin,resolveMountedFile} from './remote-assets.mjs';
6
+ import {buildPreviewHtml} from './preview.mjs';
7
+
8
+ export function designViewerUrl(path,origin=publicOrigin(),mount=resolveMountedFile){
9
+ const mounted=mount(path,origin);
10
+ if(!mounted)return null;
11
+ const url=new URL(mounted);
12
+ if(url.origin!==origin || url.search || url.hash ||
13
+ !/^\/files\/(?!_neoy\/)[a-zA-Z0-9_-]+\/(?:[^/?#]+\/)*[^/?#]+\.md$/i.test(url.pathname) ||
14
+ url.pathname.split('/').some(part=>part==='.'||part==='..'||part.startsWith('.')))
15
+ throw Error('Design source must be a mounted Markdown file');
16
+ return origin+'/files/_neoy/markcut/design.html?path='+encodeURIComponent(url.pathname);
17
+ }
18
+
19
+ // The published HTML and MCP iframe share exactly one React player and bridge.
20
+ // Publish once on provider startup; compiling does not own a browser process.
21
+ export function publishDesignViewer({root=EXPORT_ROOT,html=buildPreviewHtml()}={}){
22
+ mkdirSync(root,{recursive:true});
23
+ const target=join(root,'design.html');
24
+ try{if(readFileSync(target,'utf8')===html)return target;}catch{}
25
+ const temp=target+'.'+process.pid+'.tmp';
26
+ writeFileSync(temp,html,{mode:0o644});
27
+ renameSync(temp,target);
28
+ return target;
29
+ }
@@ -231,16 +231,31 @@ export function externalizePreviewMedia(compiled,revisionId,origin=publicOrigin(
231
231
  return {compiled:replace(compiled),assets};
232
232
  }
233
233
 
234
- // Fallback for hosts that deliver tool-input but omit tool-result notifications.
235
- export function publishPreviewRevision(requestedPath,payload) {
236
- const key=createHash("sha256").update(requestedPath).digest("hex");
237
- const dir=join(EXPORT_ROOT,"revisions");
234
+ // The MCP iframe identifies a preview by the requested path. The standalone
235
+ // NeoY viewer identifies the *same* video by its mounted /files/... path.
236
+ // Publish both pointers with identical content, preserving old callers.
237
+ export function publishPreviewRevision(requestedPath,payload,{
238
+ root=EXPORT_ROOT,origin=publicOrigin(),mount=resolveMountedFile,
239
+ }={}) {
240
+ const dir=join(root,"revisions");
238
241
  mkdirSync(dir,{recursive:true});
239
- const target=join(dir,key+".json");
240
- const temp=join(dir,key+"."+process.pid+".tmp");
241
- writeFileSync(temp,JSON.stringify(payload),{mode:0o644});
242
- renameSync(temp,target);
243
- return publicOrigin()+"/files/_neoy/markcut/revisions/"+key+".json";
242
+ function writePointer(identity,data){
243
+ const key=createHash("sha256").update(identity).digest("hex");
244
+ const target=join(dir,key+".json");
245
+ const temp=join(dir,key+"."+process.pid+".tmp");
246
+ writeFileSync(temp,JSON.stringify(data),{mode:0o644});
247
+ renameSync(temp,target);
248
+ return origin+"/files/_neoy/markcut/revisions/"+key+".json";
249
+ }
250
+ const url=writePointer(requestedPath,payload);
251
+ if(typeof payload?.path==="string"){
252
+ const mounted=mount(payload.path,origin);
253
+ if(mounted){
254
+ const canonical=new URL(mounted).pathname;
255
+ if(canonical!==requestedPath)writePointer(canonical,{...payload,requestedPath:canonical});
256
+ }
257
+ }
258
+ return url;
244
259
  }
245
260
 
246
261
 
@@ -7,6 +7,7 @@ import {normalizeReviewConfig} from "./review-delivery.mjs";
7
7
  import {publishPreviewRevision,publishPlayerBundle,publicOrigin} from "./remote-assets.mjs";
8
8
  import {fileURLToPath} from "node:url";
9
9
  import {startCompileOperation} from "./compile-operation.mjs";
10
+ import {designViewerUrl,publishDesignViewer} from "./design-viewer.mjs";
10
11
  import {
11
12
  TOOL_NAME, RESOURCE_URI, LEGACY_RESOURCE_URIS, buildPreviewResourceResult, previewCsp, getPreviewMedia, stopManagedVideoPreview,
12
13
  } from "./preview.mjs";
@@ -47,7 +48,7 @@ registerAppTool(
47
48
  server,
48
49
  TOOL_NAME,
49
50
  {
50
- description: "Compile and publish an immutable Markcut preview revision for this ChatGPT conversation. Review delivery defaults to ui/message, or submits an authorized caller-bound event when explicitly configured. Event-mode decisions use the caller-provided event envelope; Markcut does not interpret the event type or payload.",
51
+ description: "Compile and publish Markcut preview from video.md. With readonly:true, publish without review; mounted sources return designUrl for a separate NeoY player. WebHelm/browser lifecycle is caller-owned. With review enabled, use ui/message or a caller-bound event envelope; Markcut does not interpret event type or payload.",
51
52
  inputSchema: z.object({
52
53
  path: z.string().describe("Absolute .md path or NeoY HTTPS mounted file URL; Neo Wrapper also accepts single local image/audio/video files"),
53
54
  title: z.string().trim().min(1).max(160).optional().describe("Optional display title for Preview and mobile Review Inbox."),
@@ -66,7 +67,11 @@ registerAppTool(
66
67
  throw new Error("Read-only preview cannot request Relay or review delivery");
67
68
  const config={...normalizeReviewConfig(review),...(readonly ? {readonly:true} : {}),...(title ? {title} : {}),...(mode ? {mode} : {})};
68
69
  const operation=startCompileOperation(path,config);
69
- const payload=operation;
70
+ const designUrl=designViewerUrl(operation.path);
71
+ // Only publish the standalone HTML when a mounted source needs it;
72
+ // provider startup and ordinary unmounted previews stay independent.
73
+ if(designUrl)publishDesignViewer();
74
+ const payload={...operation,...(designUrl?{designUrl}:{})};
70
75
  return {
71
76
  content: [{ type: "text", text: `Compilation started: ${operation.path}` }],
72
77
  structuredContent: payload,
@@ -71,8 +71,6 @@ Commands:
71
71
  verify <file> Parse + validate descriptive file and linked EDL\n edl <video.md> [--output <file>] Convert Editor Decision sidecar to playable Markcut Markdown
72
72
 
73
73
  preview <file.json|.md> Open player with live preview
74
- --design Open NeoY standalone player, live-recompile video.md and split with ChatGPT
75
- --no-split Open NeoY design viewer without WebHelm Split View
76
74
  --delivery event Headless human review via Neo Mobile (requires .md)
77
75
  --event-template <file.json> Relay task.interactive_decision envelope from current Task
78
76
  (No phone URL) Neo Master stores and notifies through APNs
@@ -1,29 +1,43 @@
1
1
  import {describe,it,expect} from 'vitest';
2
- import {mkdtemp,writeFile,readFile,rm,mkdir} from 'node:fs/promises';
2
+ import {mkdtemp,readFile,rm} from 'node:fs/promises';
3
3
  import {tmpdir} from 'node:os';
4
4
  import {join} from 'node:path';
5
+ import {readFileSync} from 'node:fs';
5
6
  import vm from 'node:vm';
6
- import {webcrypto} from 'node:crypto';
7
- import {parseDesignArgs,designSourceUrl,designViewerUrl,publishDesignViewer,designInputStamp,compileDesign} from '../src/mcp/design-cli.mjs';
7
+ import {webcrypto,createHash} from 'node:crypto';
8
+ import {publishPreviewRevision} from '../src/mcp/remote-assets.mjs';
9
+ import {designViewerUrl,publishDesignViewer} from '../src/mcp/design-viewer.mjs';
8
10
  import {buildPreviewBridgeScript} from '../src/mcp/bridge.mjs';
9
11
 
10
12
  const hash='a'.repeat(64);
11
13
  const digest='b'.repeat(64);
12
14
 
13
15
  describe('NeoY standalone Markcut design mode',()=>{
14
- it('uses only a mounted video.md path, not a Session or Revision ID',()=>{
15
- expect(parseDesignArgs(['preview','/tmp/video.md','--design','--no-split'])).toEqual({file:'/tmp/video.md',split:false});
16
- expect(()=>parseDesignArgs(['preview','/tmp/video.md','--design','--delivery','event'])).toThrow();
17
- expect(()=>parseDesignArgs(['preview','/tmp/video.json','--design'])).toThrow();
16
+ it('returns a viewer URL only for an existing mounted video.md',()=>{
18
17
  const origin='https://neoy.example.test';
19
18
  const file='/mounted/vlog/video.md';
20
- const path=designSourceUrl(file,origin,()=>origin+'/files/vlog/video.md');
21
- expect(path).toBe('/files/vlog/video.md');
22
- const url=designViewerUrl(path,origin);
23
- expect(new URL(url).searchParams.get('path')).toBe(path);
19
+ const url=designViewerUrl(file,origin,()=>origin+'/files/vlog/video.md');
20
+ expect(new URL(url!).searchParams.get('path')).toBe('/files/vlog/video.md');
24
21
  expect(url).not.toMatch(/session|revision|review/);
25
- expect(()=>designSourceUrl(file,origin,()=>undefined)).toThrow(/NeoY file mount/);
26
- expect(()=>designViewerUrl('/files/_neoy/markcut/cache/evil.md',origin)).toThrow();
22
+ expect(designViewerUrl(file,origin,()=>null)).toBeNull();
23
+ expect(()=>designViewerUrl(file,origin,()=>origin+'/files/_neoy/markcut/cache/evil.md')).toThrow();
24
+ expect(()=>designViewerUrl(file,origin,()=>origin+'/files/vlog/../secret.md')).toThrow();
25
+ });
26
+ it('publishes the same revision by both caller path and canonical mounted video.md identity',async()=>{
27
+ const root=await mkdtemp(join(tmpdir(),'markcut-design-revisions-'));
28
+ const caller='/home/source/video.md',canonical='/files/vlog/video.md';
29
+ const payload={requestedPath:caller,path:caller,contentHash:hash,compiledUrl:'https://neoy.example.test/files/_neoy/markcut/cache/'+hash+'.json'};
30
+ const key=value=>createHash('sha256').update(value).digest('hex');
31
+ try {
32
+ const url=publishPreviewRevision(caller,payload,{root,origin:'https://neoy.example.test',
33
+ mount:()=> 'https://neoy.example.test'+canonical});
34
+ expect(url).toContain('/revisions/'+key(caller)+'.json');
35
+ const local=JSON.parse(await readFile(join(root,'revisions',key(caller)+'.json'),'utf8'));
36
+ const mounted=JSON.parse(await readFile(join(root,'revisions',key(canonical)+'.json'),'utf8'));
37
+ expect(local.requestedPath).toBe(caller);
38
+ expect(mounted.requestedPath).toBe(canonical);
39
+ expect(mounted.compiledUrl).toBe(local.compiledUrl);
40
+ }finally{await rm(root,{recursive:true,force:true});}
27
41
  });
28
42
  it('publishes the same player without creating a second viewer',async()=>{
29
43
  const root=await mkdtemp(join(tmpdir(),'markcut-design-ui-'));
@@ -34,34 +48,17 @@ describe('NeoY standalone Markcut design mode',()=>{
34
48
  expect(publishDesignViewer({root,html})).toBe(file);
35
49
  }finally{await rm(root,{force:true,recursive:true});}
36
50
  });
37
- it('detects source and editor-decision sidecar edits',async()=>{
38
- const root=await mkdtemp(join(tmpdir(),'markcut-design-watch-'));
39
- try{
40
- const file=join(root,'video.md');
41
- await writeFile(file,'# video\n## Intro\n- component duration:1 jsx:"Hello"\n---\nedl: video.edl.json\n---\n');
42
- const first=designInputStamp(file);
43
- await writeFile(join(root,'video.edl.json'),'{}');
44
- expect(designInputStamp(file)).not.toBe(first);
45
- const second=designInputStamp(file);
46
- await writeFile(file,'# video\n## Intro\n- component duration:1 jsx:"World"\n');
47
- expect(designInputStamp(file)).not.toBe(second);
48
- }finally{await rm(root,{force:true,recursive:true});}
49
- });
50
- it('observes existing Markcut compilation result instead of publishing a review',async()=>{
51
- const root=await mkdtemp(join(tmpdir(),'markcut-design-compile-'));
52
- try{
53
- await mkdir(join(root,'operations'));
54
- const output={revisionId:hash,contentHash:hash,compiledUrl:'https://neoy.example.test/files/_neoy/markcut/cache/'+hash+'.json'};
55
- const result=await compileDesign('/tmp/video.md','/files/vlog/video.md',{
56
- root,start:(input,review)=>{
57
- expect(input).toBe('/files/vlog/video.md');
58
- expect(review).toEqual({delivery:'text'});
59
- void writeFile(join(root,'operations','test.json'),JSON.stringify({state:'ready',result:output}));
60
- return {operationId:'test'};
61
- },limitMs:2000,
62
- });
63
- expect(result).toEqual(output);
64
- }finally{await rm(root,{force:true,recursive:true});}
51
+ it('uses the existing preview provider and does not couple Markcut CLI to browser lifecycle',()=>{
52
+ const server=readFileSync(new URL('../src/mcp/server.mjs',import.meta.url),'utf8');
53
+ const cli=readFileSync(new URL('../bin/markcut',import.meta.url),'utf8');
54
+ const viewer=readFileSync(new URL('../src/mcp/design-viewer.mjs',import.meta.url),'utf8');
55
+ expect(server).toContain('designUrl=designViewerUrl(operation.path)');
56
+ expect(server).toContain('if(designUrl)publishDesignViewer();');
57
+ expect(server).toContain('readonly');
58
+ expect(cli).not.toContain('--design');
59
+ expect(viewer).not.toContain('webhelm');
60
+ expect(viewer).not.toContain('spawn(');
61
+ expect(viewer).not.toContain('SIGINT');
65
62
  });
66
63
  it('loads and refreshes the original player without MCP initialize or review messages',async()=>{
67
64
  const path='/files/vlog/video.md';
@@ -1,126 +0,0 @@
1
- #!/usr/bin/env node
2
- // Standalone NeoY design view: the source video.md, not a review or browser
3
- // Session, is the stable identity. Compilation remains Markcut's concern.
4
- import {createHash} from 'node:crypto';
5
- import {execFileSync} from 'node:child_process';
6
- import {readFileSync,writeFileSync,mkdirSync,renameSync,statSync} from 'node:fs';
7
- import {resolve,dirname,join,basename} from 'node:path';
8
- import {pathToFileURL} from 'node:url';
9
- import {EXPORT_ROOT,publicOrigin,resolveMountedFile} from './remote-assets.mjs';
10
- import {buildPreviewHtml} from './preview.mjs';
11
- import {startCompileOperation} from './compile-operation.mjs';
12
-
13
- const delay=ms=>new Promise(ok=>setTimeout(ok,ms));
14
-
15
- export function parseDesignArgs(argv){
16
- if(argv[0]!=='preview'||typeof argv[1]!=='string'||!argv[1].endsWith('.md'))
17
- throw Error('Usage: markcut preview <video.md> --design [--no-split]');
18
- const flags=argv.slice(2);
19
- if(!flags.includes('--design')||flags.some(f=>!['--design','--no-split'].includes(f))||
20
- new Set(flags).size!==flags.length)
21
- throw Error('Design preview supports only --design and --no-split');
22
- return {file:resolve(argv[1]),split:!flags.includes('--no-split')};
23
- }
24
-
25
- export function designSourceUrl(file,origin=publicOrigin(),resolveSource=resolveMountedFile){
26
- const mounted=resolveSource(file,origin);
27
- if(!mounted)throw Error('Design video.md must be inside an existing NeoY file mount');
28
- const url=new URL(mounted);
29
- if(url.origin!==origin||!/^\/files\/(?!_neoy\/)[A-Za-z0-9_-]+\/.+\.md$/i.test(url.pathname))
30
- throw Error('Design source must be a mounted Markdown file');
31
- return url.pathname;
32
- }
33
-
34
- export function designViewerUrl(sourcePath,origin=publicOrigin()){
35
- if(!/^\/files\/(?!_neoy\/)[A-Za-z0-9_-]+\/.+\.md$/i.test(sourcePath))
36
- throw Error('Invalid design source URL');
37
- return origin+'/files/_neoy/markcut/design.html?path='+encodeURIComponent(sourcePath);
38
- }
39
-
40
- // The shared MCP player is published *unchanged* as the standalone page.
41
- export function publishDesignViewer({root=EXPORT_ROOT,html=buildPreviewHtml()}={}){
42
- mkdirSync(root,{recursive:true});
43
- const target=join(root,'design.html');
44
- try{if(readFileSync(target,'utf8')===html)return target;}catch{}
45
- const temp=target+'.'+process.pid+'.tmp';
46
- writeFileSync(temp,html,{mode:0o644});renameSync(temp,target);
47
- return target;
48
- }
49
-
50
- // Cheap watcher stamp: avoid hashing large videos every few seconds. The actual
51
- // compiler fingerprints media content when this metadata stamp changes.
52
- export function designInputStamp(file){
53
- const source=readFileSync(file,'utf8');
54
- const base=dirname(file),candidates=new Set([file,join(base,basename(file,'.md')+'.wav')]);
55
- for(const match of source.matchAll(/\b(?:src|audio|edl)\s*:\s*["']?([^"'\s;]+\.(?:png|jpe?g|webp|svg|gif|mp4|mov|webm|wav|mp3|m4a|ogg|vtt|srt|json))/gi)){
56
- if(match[1].includes('://')||match[1].startsWith('/'))continue;
57
- candidates.add(resolve(base,match[1]));
58
- }
59
- const stamp=[createHash('sha256').update(source).digest('hex')];
60
- for(const path of [...candidates].sort())try{
61
- const s=statSync(path);stamp.push(path,s.size,s.mtimeMs,s.ctimeMs);
62
- }catch{}
63
- return JSON.stringify(stamp);
64
- }
65
-
66
- export async function compileDesign(file,source,{start=startCompileOperation,root=EXPORT_ROOT,limitMs=300000}={}){
67
- const op=start(source,{delivery:'text'});
68
- const statusFile=join(root,'operations',op.operationId+'.json');
69
- const until=Date.now()+limitMs;
70
- while(Date.now()<until){
71
- let state;try{state=JSON.parse(readFileSync(statusFile,'utf8'));}catch{}
72
- if(state?.state==='ready')return state.result;
73
- if(state?.state==='failed')throw Error('Design compilation failed: '+state.error);
74
- await delay(300);
75
- }
76
- throw Error('Design compilation timed out');
77
- }
78
-
79
- export async function runDesignPreview(argv,{run=execFileSync,compile=compileDesign,
80
- publish=publishDesignViewer,stamp=designInputStamp,onReady=()=>{}}={}){
81
- const {file,split}=parseDesignArgs(argv);
82
- const source=designSourceUrl(file),url=designViewerUrl(source);
83
- const initialStamp=stamp(file);
84
- publish();
85
- await compile(file,source);
86
- let sessionId=null;
87
- if(split){
88
- const receipt=JSON.parse(run('webhelm',['design','start','--url',url],
89
- {encoding:'utf8',timeout:60000,stdio:['ignore','pipe','pipe']}));
90
- if(receipt.design_mode!==true||!receipt.session_id)throw Error('WebHelm Design Mode did not start');
91
- sessionId=receipt.session_id;
92
- }
93
- console.log(JSON.stringify({status:'design_ready',file,url,watching:true,split}));
94
- onReady({file,url,source});
95
- let running=true,stopping=false,previous=initialStamp,compileBusy=false;
96
- async function stop(){
97
- if(stopping)return;stopping=true;running=false;
98
- if(sessionId){
99
- try{run('webhelm',['design','stop',sessionId],{encoding:'utf8',timeout:90000,stdio:['ignore','pipe','pipe']});}
100
- catch(error){console.error('WebHelm Design Mode cleanup failed: '+String(error.message||error));}
101
- }
102
- }
103
- const sigint=()=>void stop(),sigterm=()=>void stop();
104
- process.once('SIGINT',sigint);process.once('SIGTERM',sigterm);
105
- try{
106
- while(running){
107
- await delay(1800);
108
- if(!running||compileBusy)continue;
109
- let next;try{next=stamp(file);}catch(error){console.error('Design source unavailable: '+error.message);continue;}
110
- if(next===previous)continue;
111
- previous=next;compileBusy=true;
112
- try{await compile(file,source);console.log(JSON.stringify({status:'design_refreshed',file,url}));}
113
- catch(error){console.error('Design recompile failed: '+String(error.message||error));}
114
- finally{compileBusy=false;}
115
- }
116
- }finally{
117
- process.removeListener('SIGINT',sigint);process.removeListener('SIGTERM',sigterm);
118
- await stop();
119
- }
120
- }
121
-
122
- if(process.argv[1]&&import.meta.url===pathToFileURL(resolve(process.argv[1])).href){
123
- runDesignPreview(process.argv.slice(2)).catch(error=>{
124
- console.error('Markcut Design Mode failed: '+String(error.message||error));process.exitCode=1;
125
- });
126
- }