plotlink-ows 1.0.22 → 1.0.24
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/app/routes/publish.ts
CHANGED
|
@@ -81,7 +81,7 @@ publish.post("/file", async (c) => {
|
|
|
81
81
|
// Enforce character limits
|
|
82
82
|
const isGenesis = body.fileName === "genesis.md";
|
|
83
83
|
const isPlot = /^plot-\d+\.md$/.test(body.fileName);
|
|
84
|
-
const charLimit = isGenesis
|
|
84
|
+
const charLimit = (isGenesis || isPlot) ? 10000 : null;
|
|
85
85
|
if (charLimit && body.content.length > charLimit) {
|
|
86
86
|
return c.json({
|
|
87
87
|
error: `Content exceeds ${charLimit.toLocaleString()} character limit (${body.content.length.toLocaleString()} chars). Reduce content before publishing.`,
|
|
@@ -150,7 +150,7 @@ export function PreviewPanel({ storyName, fileName, authFetch, onPublish, publis
|
|
|
150
150
|
const isGenesis = fileName === "genesis.md";
|
|
151
151
|
const isPlot = fileName ? /^plot-\d+\.md$/.test(fileName) : false;
|
|
152
152
|
const isPublished = fileData?.status === "published" || fileData?.status === "published-not-indexed";
|
|
153
|
-
const charLimit = isGenesis
|
|
153
|
+
const charLimit = (isGenesis || isPlot) ? 10000 : null;
|
|
154
154
|
// Don't show over-limit warning for already-published files
|
|
155
155
|
const overLimit = !isPublished && charLimit !== null && charCount > charLimit;
|
|
156
156
|
|
|
@@ -126,5 +126,5 @@ WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){t
|
|
|
126
126
|
`))+1))}const c="#".repeat(a),f=n.enter("headingAtx"),p=n.enter("phrasing");o.move(c+" ");let h=n.containerPhrasing(e,{before:"# ",after:`
|
|
127
127
|
`,...o.current()});return/^[\t ]/.test(h)&&(h=_a(h.charCodeAt(0))+h.slice(1)),h=h?c+" "+h:c,n.options.closeAtx&&(h+=" "+c),p(),f(),h}LS.peek=vA;function LS(e){return e.value||""}function vA(){return"<"}zS.peek=yA;function zS(e,t,n,s){const a=Xd(n),o=a==='"'?"Quote":"Apostrophe",c=n.enter("image");let f=n.enter("label");const p=n.createTracker(s);let h=p.move("![");return h+=p.move(n.safe(e.alt,{before:h,after:"]",...p.current()})),h+=p.move("]("),f(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(f=n.enter("destinationLiteral"),h+=p.move("<"),h+=p.move(n.safe(e.url,{before:h,after:">",...p.current()})),h+=p.move(">")):(f=n.enter("destinationRaw"),h+=p.move(n.safe(e.url,{before:h,after:e.title?" ":")",...p.current()}))),f(),e.title&&(f=n.enter(`title${o}`),h+=p.move(" "+a),h+=p.move(n.safe(e.title,{before:h,after:a,...p.current()})),h+=p.move(a),f()),h+=p.move(")"),c(),h}function yA(){return"!"}OS.peek=bA;function OS(e,t,n,s){const a=e.referenceType,o=n.enter("imageReference");let c=n.enter("label");const f=n.createTracker(s);let p=f.move("![");const h=n.safe(e.alt,{before:p,after:"]",...f.current()});p+=f.move(h+"]["),c();const g=n.stack;n.stack=[],c=n.enter("reference");const _=n.safe(n.associationId(e),{before:p,after:"]",...f.current()});return c(),n.stack=g,o(),a==="full"||!h||h!==_?p+=f.move(_+"]"):a==="shortcut"?p=p.slice(0,-1):p+=f.move("]"),p}function bA(){return"!"}jS.peek=SA;function jS(e,t,n){let s=e.value||"",a="`",o=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(s);)a+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++o<n.unsafe.length;){const c=n.unsafe[o],f=n.compilePattern(c);let p;if(c.atBreak)for(;p=f.exec(s);){let h=p.index;s.charCodeAt(h)===10&&s.charCodeAt(h-1)===13&&h--,s=s.slice(0,h)+" "+s.slice(p.index+1)}}return a+s+a}function SA(){return"`"}function HS(e,t){const n=Ud(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}US.peek=xA;function US(e,t,n,s){const a=Xd(n),o=a==='"'?"Quote":"Apostrophe",c=n.createTracker(s);let f,p;if(HS(e,n)){const g=n.stack;n.stack=[],f=n.enter("autolink");let _=c.move("<");return _+=c.move(n.containerPhrasing(e,{before:_,after:">",...c.current()})),_+=c.move(">"),f(),n.stack=g,_}f=n.enter("link"),p=n.enter("label");let h=c.move("[");return h+=c.move(n.containerPhrasing(e,{before:h,after:"](",...c.current()})),h+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=n.enter("destinationLiteral"),h+=c.move("<"),h+=c.move(n.safe(e.url,{before:h,after:">",...c.current()})),h+=c.move(">")):(p=n.enter("destinationRaw"),h+=c.move(n.safe(e.url,{before:h,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=n.enter(`title${o}`),h+=c.move(" "+a),h+=c.move(n.safe(e.title,{before:h,after:a,...c.current()})),h+=c.move(a),p()),h+=c.move(")"),f(),h}function xA(e,t,n){return HS(e,n)?"<":"["}PS.peek=wA;function PS(e,t,n,s){const a=e.referenceType,o=n.enter("linkReference");let c=n.enter("label");const f=n.createTracker(s);let p=f.move("[");const h=n.containerPhrasing(e,{before:p,after:"]",...f.current()});p+=f.move(h+"]["),c();const g=n.stack;n.stack=[],c=n.enter("reference");const _=n.safe(n.associationId(e),{before:p,after:"]",...f.current()});return c(),n.stack=g,o(),a==="full"||!h||h!==_?p+=f.move(_+"]"):a==="shortcut"?p=p.slice(0,-1):p+=f.move("]"),p}function wA(){return"["}function $d(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function CA(e){const t=$d(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function kA(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function IS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function EA(e,t,n,s){const a=n.enter("list"),o=n.bulletCurrent;let c=e.ordered?kA(n):$d(n);const f=e.ordered?c==="."?")":".":CA(n);let p=t&&n.bulletLastUsed?c===n.bulletLastUsed:!1;if(!e.ordered){const g=e.children?e.children[0]:void 0;if((c==="*"||c==="-")&&g&&(!g.children||!g.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(p=!0),IS(n)===c&&g){let _=-1;for(;++_<e.children.length;){const b=e.children[_];if(b&&b.type==="listItem"&&b.children&&b.children[0]&&b.children[0].type==="thematicBreak"){p=!0;break}}}}p&&(c=f),n.bulletCurrent=c;const h=n.containerFlow(e,s);return n.bulletLastUsed=c,n.bulletCurrent=o,a(),h}function TA(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function AA(e,t,n,s){const a=TA(n);let o=n.bulletCurrent||$d(n);t&&t.type==="list"&&t.ordered&&(o=(typeof t.start=="number"&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+o);let c=o.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(c=Math.ceil(c/4)*4);const f=n.createTracker(s);f.move(o+" ".repeat(c-o.length)),f.shift(c);const p=n.enter("listItem"),h=n.indentLines(n.containerFlow(e,f.current()),g);return p(),h;function g(_,b,y){return b?(y?"":" ".repeat(c))+_:(y?o:o+" ".repeat(c-o.length))+_}}function DA(e,t,n,s){const a=n.enter("paragraph"),o=n.enter("phrasing"),c=n.containerPhrasing(e,s);return o(),a(),c}const RA=ku(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function MA(e,t,n,s){return(e.children.some(function(c){return RA(c)})?n.containerPhrasing:n.containerFlow).call(n,e,s)}function BA(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}FS.peek=NA;function FS(e,t,n,s){const a=BA(n),o=n.enter("strong"),c=n.createTracker(s),f=c.move(a+a);let p=c.move(n.containerPhrasing(e,{after:a,before:f,...c.current()}));const h=p.charCodeAt(0),g=_u(s.before.charCodeAt(s.before.length-1),h,a);g.inside&&(p=_a(h)+p.slice(1));const _=p.charCodeAt(p.length-1),b=_u(s.after.charCodeAt(0),_,a);b.inside&&(p=p.slice(0,-1)+_a(_));const y=c.move(a+a);return o(),n.attentionEncodeSurroundingInfo={after:b.outside,before:g.outside},f+p+y}function NA(e,t,n){return n.options.strong||"*"}function LA(e,t,n,s){return n.safe(e.value,s)}function zA(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function OA(e,t,n){const s=(IS(n)+(n.options.ruleSpaces?" ":"")).repeat(zA(n));return n.options.ruleSpaces?s.slice(0,-1):s}const qS={blockquote:sA,break:Py,code:hA,definition:dA,emphasis:NS,hardBreak:Py,heading:gA,html:LS,image:zS,imageReference:OS,inlineCode:jS,link:US,linkReference:PS,list:EA,listItem:AA,paragraph:DA,root:MA,strong:FS,text:LA,thematicBreak:OA};function jA(){return{enter:{table:HA,tableData:Iy,tableHeader:Iy,tableRow:PA},exit:{codeText:IA,table:UA,tableData:Cf,tableHeader:Cf,tableRow:Cf}}}function HA(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function UA(e){this.exit(e),this.data.inTable=void 0}function PA(e){this.enter({type:"tableRow",children:[]},e)}function Cf(e){this.exit(e)}function Iy(e){this.enter({type:"tableCell",children:[]},e)}function IA(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,FA));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function FA(e,t){return t==="|"?t:e}function qA(e){const t=e||{},n=t.tableCellPadding,s=t.tablePipeAlign,a=t.stringLength,o=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
128
128
|
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:b,table:c,tableCell:p,tableRow:f}};function c(y,x,E,L){return h(g(y,E,L),y.align)}function f(y,x,E,L){const R=_(y,E,L),$=h([R]);return $.slice(0,$.indexOf(`
|
|
129
|
-
`))}function p(y,x,E,L){const R=E.enter("tableCell"),$=E.enter("phrasing"),I=E.containerPhrasing(y,{...L,before:o,after:o});return $(),R(),I}function h(y,x){return nA(y,{align:x,alignDelimiters:s,padding:n,stringLength:a})}function g(y,x,E){const L=y.children;let R=-1;const $=[],I=x.enter("table");for(;++R<L.length;)$[R]=_(L[R],x,E);return I(),$}function _(y,x,E){const L=y.children;let R=-1;const $=[],I=x.enter("tableRow");for(;++R<L.length;)$[R]=p(L[R],y,x,E);return I(),$}function b(y,x,E){let L=qS.inlineCode(y,x,E);return E.stack.includes("tableCell")&&(L=L.replace(/\|/g,"\\$&")),L}}function WA(){return{exit:{taskListCheckValueChecked:Fy,taskListCheckValueUnchecked:Fy,paragraph:VA}}}function YA(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:KA}}}function Fy(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function VA(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const s=n.children[0];if(s&&s.type==="text"){const a=t.children;let o=-1,c;for(;++o<a.length;){const f=a[o];if(f.type==="paragraph"){c=f;break}}c===n&&(s.value=s.value.slice(1),s.value.length===0?n.children.shift():n.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,n.position.start=Object.assign({},s.position.start)))}}this.exit(e)}function KA(e,t,n,s){const a=e.children[0],o=typeof e.checked=="boolean"&&a&&a.type==="paragraph",c="["+(e.checked?"x":" ")+"] ",f=n.createTracker(s);o&&f.move(c);let p=qS.listItem(e,t,n,{...s,...f.current()});return o&&(p=p.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,h)),p;function h(g){return g+c}}function XA(){return[E3(),K3(),Z3(),jA(),WA()]}function $A(e){return{extensions:[T3(),X3(e),Q3(),qA(e),YA()]}}const GA={tokenize:iD,partial:!0},WS={tokenize:nD,partial:!0},YS={tokenize:rD,partial:!0},VS={tokenize:sD,partial:!0},ZA={tokenize:lD,partial:!0},KS={name:"wwwAutolink",tokenize:eD,previous:$S},XS={name:"protocolAutolink",tokenize:tD,previous:GS},jn={name:"emailAutolink",tokenize:JA,previous:ZS},hn={};function QA(){return{text:hn}}let Ur=48;for(;Ur<123;)hn[Ur]=jn,Ur++,Ur===58?Ur=65:Ur===91&&(Ur=97);hn[43]=jn;hn[45]=jn;hn[46]=jn;hn[95]=jn;hn[72]=[jn,XS];hn[104]=[jn,XS];hn[87]=[jn,KS];hn[119]=[jn,KS];function JA(e,t,n){const s=this;let a,o;return c;function c(_){return!bd(_)||!ZS.call(s,s.previous)||Gd(s.events)?n(_):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(_))}function f(_){return bd(_)?(e.consume(_),f):_===64?(e.consume(_),p):n(_)}function p(_){return _===46?e.check(ZA,g,h)(_):_===45||_===95||Gt(_)?(o=!0,e.consume(_),p):g(_)}function h(_){return e.consume(_),a=!0,p}function g(_){return o&&a&&ri(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(_)):n(_)}}function eD(e,t,n){const s=this;return a;function a(c){return c!==87&&c!==119||!$S.call(s,s.previous)||Gd(s.events)?n(c):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(GA,e.attempt(WS,e.attempt(YS,o),n),n)(c))}function o(c){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(c)}}function tD(e,t,n){const s=this;let a="",o=!1;return c;function c(_){return(_===72||_===104)&&GS.call(s,s.previous)&&!Gd(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(_),e.consume(_),f):n(_)}function f(_){if(ri(_)&&a.length<5)return a+=String.fromCodePoint(_),e.consume(_),f;if(_===58){const b=a.toLowerCase();if(b==="http"||b==="https")return e.consume(_),p}return n(_)}function p(_){return _===47?(e.consume(_),o?h:(o=!0,p)):n(_)}function h(_){return _===null||pu(_)||Qe(_)||Kr(_)||xu(_)?n(_):e.attempt(WS,e.attempt(YS,g),n)(_)}function g(_){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(_)}}function iD(e,t,n){let s=0;return a;function a(c){return(c===87||c===119)&&s<3?(s++,e.consume(c),a):c===46&&s===3?(e.consume(c),o):n(c)}function o(c){return c===null?n(c):t(c)}}function nD(e,t,n){let s,a,o;return c;function c(h){return h===46||h===95?e.check(VS,p,f)(h):h===null||Qe(h)||Kr(h)||h!==45&&xu(h)?p(h):(o=!0,e.consume(h),c)}function f(h){return h===95?s=!0:(a=s,s=void 0),e.consume(h),c}function p(h){return a||s||!o?n(h):t(h)}}function rD(e,t){let n=0,s=0;return a;function a(c){return c===40?(n++,e.consume(c),a):c===41&&s<n?o(c):c===33||c===34||c===38||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===60||c===63||c===93||c===95||c===126?e.check(VS,t,o)(c):c===null||Qe(c)||Kr(c)?t(c):(e.consume(c),a)}function o(c){return c===41&&s++,e.consume(c),a}}function sD(e,t,n){return s;function s(f){return f===33||f===34||f===39||f===41||f===42||f===44||f===46||f===58||f===59||f===63||f===95||f===126?(e.consume(f),s):f===38?(e.consume(f),o):f===93?(e.consume(f),a):f===60||f===null||Qe(f)||Kr(f)?t(f):n(f)}function a(f){return f===null||f===40||f===91||Qe(f)||Kr(f)?t(f):s(f)}function o(f){return ri(f)?c(f):n(f)}function c(f){return f===59?(e.consume(f),s):ri(f)?(e.consume(f),c):n(f)}}function lD(e,t,n){return s;function s(o){return e.consume(o),a}function a(o){return Gt(o)?n(o):t(o)}}function $S(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Qe(e)}function GS(e){return!ri(e)}function ZS(e){return!(e===47||bd(e))}function bd(e){return e===43||e===45||e===46||e===95||Gt(e)}function Gd(e){let t=e.length,n=!1;for(;t--;){const s=e[t][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){n=!0;break}if(s._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const aD={tokenize:mD,partial:!0};function oD(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:fD,continuation:{tokenize:dD},exit:pD}},text:{91:{name:"gfmFootnoteCall",tokenize:hD},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:uD,resolveTo:cD}}}}function uD(e,t,n){const s=this;let a=s.events.length;const o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;a--;){const p=s.events[a][1];if(p.type==="labelImage"){c=p;break}if(p.type==="gfmFootnoteCall"||p.type==="labelLink"||p.type==="label"||p.type==="image"||p.type==="link")break}return f;function f(p){if(!c||!c._balanced)return n(p);const h=Qi(s.sliceSerialize({start:c.end,end:s.now()}));return h.codePointAt(0)!==94||!o.includes(h.slice(1))?n(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function cD(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},f=[e[n+1],e[n+2],["enter",s,t],e[n+3],e[n+4],["enter",a,t],["exit",a,t],["enter",o,t],["enter",c,t],["exit",c,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(n,e.length-n+1,...f),e}function hD(e,t,n){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o=0,c;return f;function f(_){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(_),e.exit("gfmFootnoteCallLabelMarker"),p}function p(_){return _!==94?n(_):(e.enter("gfmFootnoteCallMarker"),e.consume(_),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",h)}function h(_){if(o>999||_===93&&!c||_===null||_===91||Qe(_))return n(_);if(_===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(Qi(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(_),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(_)}return Qe(_)||(c=!0),o++,e.consume(_),_===92?g:h}function g(_){return _===91||_===92||_===93?(e.consume(_),o++,h):h(_)}}function fD(e,t,n){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,f;return p;function p(x){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionLabelMarker"),h}function h(x){return x===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",g):n(x)}function g(x){if(c>999||x===93&&!f||x===null||x===91||Qe(x))return n(x);if(x===93){e.exit("chunkString");const E=e.exit("gfmFootnoteDefinitionLabelString");return o=Qi(s.sliceSerialize(E)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return Qe(x)||(f=!0),c++,e.consume(x),x===92?_:g}function _(x){return x===91||x===92||x===93?(e.consume(x),c++,g):g(x)}function b(x){return x===58?(e.enter("definitionMarker"),e.consume(x),e.exit("definitionMarker"),a.includes(o)||a.push(o),He(e,y,"gfmFootnoteDefinitionWhitespace")):n(x)}function y(x){return t(x)}}function dD(e,t,n){return e.check(xa,t,e.attempt(aD,t,n))}function pD(e){e.exit("gfmFootnoteDefinition")}function mD(e,t,n){const s=this;return He(e,a,"gfmFootnoteDefinitionIndent",5);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(o):n(o)}}function _D(e){let n=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:a};return n==null&&(n=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(c,f){let p=-1;for(;++p<c.length;)if(c[p][0]==="enter"&&c[p][1].type==="strikethroughSequenceTemporary"&&c[p][1]._close){let h=p;for(;h--;)if(c[h][0]==="exit"&&c[h][1].type==="strikethroughSequenceTemporary"&&c[h][1]._open&&c[p][1].end.offset-c[p][1].start.offset===c[h][1].end.offset-c[h][1].start.offset){c[p][1].type="strikethroughSequence",c[h][1].type="strikethroughSequence";const g={type:"strikethrough",start:Object.assign({},c[h][1].start),end:Object.assign({},c[p][1].end)},_={type:"strikethroughText",start:Object.assign({},c[h][1].end),end:Object.assign({},c[p][1].start)},b=[["enter",g,f],["enter",c[h][1],f],["exit",c[h][1],f],["enter",_,f]],y=f.parser.constructs.insideSpan.null;y&&Mi(b,b.length,0,wu(y,c.slice(h+1,p),f)),Mi(b,b.length,0,[["exit",_,f],["enter",c[p][1],f],["exit",c[p][1],f],["exit",g,f]]),Mi(c,h-1,p-h+3,b),p=h+b.length-2;break}}for(p=-1;++p<c.length;)c[p][1].type==="strikethroughSequenceTemporary"&&(c[p][1].type="data");return c}function o(c,f,p){const h=this.previous,g=this.events;let _=0;return b;function b(x){return h===126&&g[g.length-1][1].type!=="characterEscape"?p(x):(c.enter("strikethroughSequenceTemporary"),y(x))}function y(x){const E=Vs(h);if(x===126)return _>1?p(x):(c.consume(x),_++,y);if(_<2&&!n)return p(x);const L=c.exit("strikethroughSequenceTemporary"),R=Vs(x);return L._open=!R||R===2&&!!E,L._close=!E||E===2&&!!R,f(x)}}}class gD{constructor(){this.map=[]}add(t,n,s){vD(this,t,n,s)}consume(t){if(this.map.sort(function(o,c){return o[0]-c[0]}),this.map.length===0)return;let n=this.map.length;const s=[];for(;n>0;)n-=1,s.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];s.push(t.slice()),t.length=0;let a=s.pop();for(;a;){for(const o of a)t.push(o);a=s.pop()}this.map.length=0}}function vD(e,t,n,s){let a=0;if(!(n===0&&s.length===0)){for(;a<e.map.length;){if(e.map[a][0]===t){e.map[a][1]+=n,e.map[a][2].push(...s);return}a+=1}e.map.push([t,n,s])}}function yD(e,t){let n=!1;const s=[];for(;t<e.length;){const a=e[t];if(n){if(a[0]==="enter")a[1].type==="tableContent"&&s.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(a[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const o=s.length-1;s[o]=s[o]==="left"?"center":"right"}}else if(a[1].type==="tableDelimiterRow")break}else a[0]==="enter"&&a[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return s}function bD(){return{flow:{null:{name:"table",tokenize:SD,resolveAll:xD}}}}function SD(e,t,n){const s=this;let a=0,o=0,c;return f;function f(F){let le=s.events.length-1;for(;le>-1;){const B=s.events[le][1].type;if(B==="lineEnding"||B==="linePrefix")le--;else break}const H=le>-1?s.events[le][1].type:null,T=H==="tableHead"||H==="tableRow"?O:p;return T===O&&s.parser.lazy[s.now().line]?n(F):T(F)}function p(F){return e.enter("tableHead"),e.enter("tableRow"),h(F)}function h(F){return F===124||(c=!0,o+=1),g(F)}function g(F){return F===null?n(F):ve(F)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(F),e.exit("lineEnding"),y):n(F):Ne(F)?He(e,g,"whitespace")(F):(o+=1,c&&(c=!1,a+=1),F===124?(e.enter("tableCellDivider"),e.consume(F),e.exit("tableCellDivider"),c=!0,g):(e.enter("data"),_(F)))}function _(F){return F===null||F===124||Qe(F)?(e.exit("data"),g(F)):(e.consume(F),F===92?b:_)}function b(F){return F===92||F===124?(e.consume(F),_):_(F)}function y(F){return s.interrupt=!1,s.parser.lazy[s.now().line]?n(F):(e.enter("tableDelimiterRow"),c=!1,Ne(F)?He(e,x,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(F):x(F))}function x(F){return F===45||F===58?L(F):F===124?(c=!0,e.enter("tableCellDivider"),e.consume(F),e.exit("tableCellDivider"),E):Y(F)}function E(F){return Ne(F)?He(e,L,"whitespace")(F):L(F)}function L(F){return F===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(F),e.exit("tableDelimiterMarker"),R):F===45?(o+=1,R(F)):F===null||ve(F)?Z(F):Y(F)}function R(F){return F===45?(e.enter("tableDelimiterFiller"),$(F)):Y(F)}function $(F){return F===45?(e.consume(F),$):F===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(F),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(F))}function I(F){return Ne(F)?He(e,Z,"whitespace")(F):Z(F)}function Z(F){return F===124?x(F):F===null||ve(F)?!c||a!==o?Y(F):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(F)):Y(F)}function Y(F){return n(F)}function O(F){return e.enter("tableRow"),J(F)}function J(F){return F===124?(e.enter("tableCellDivider"),e.consume(F),e.exit("tableCellDivider"),J):F===null||ve(F)?(e.exit("tableRow"),t(F)):Ne(F)?He(e,J,"whitespace")(F):(e.enter("data"),ae(F))}function ae(F){return F===null||F===124||Qe(F)?(e.exit("data"),J(F)):(e.consume(F),F===92?de:ae)}function de(F){return F===92||F===124?(e.consume(F),ae):ae(F)}}function xD(e,t){let n=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],f=!1,p=0,h,g,_;const b=new gD;for(;++n<e.length;){const y=e[n],x=y[1];y[0]==="enter"?x.type==="tableHead"?(f=!1,p!==0&&(qy(b,t,p,h,g),g=void 0,p=0),h={type:"table",start:Object.assign({},x.start),end:Object.assign({},x.end)},b.add(n,0,[["enter",h,t]])):x.type==="tableRow"||x.type==="tableDelimiterRow"?(s=!0,_=void 0,o=[0,0,0,0],c=[0,n+1,0,0],f&&(f=!1,g={type:"tableBody",start:Object.assign({},x.start),end:Object.assign({},x.end)},b.add(n,0,[["enter",g,t]])),a=x.type==="tableDelimiterRow"?2:g?3:1):a&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")?(s=!1,c[2]===0&&(o[1]!==0&&(c[0]=c[1],_=Jo(b,t,o,a,void 0,_),o=[0,0,0,0]),c[2]=n)):x.type==="tableCellDivider"&&(s?s=!1:(o[1]!==0&&(c[0]=c[1],_=Jo(b,t,o,a,void 0,_)),o=c,c=[o[1],n,0,0])):x.type==="tableHead"?(f=!0,p=n):x.type==="tableRow"||x.type==="tableDelimiterRow"?(p=n,o[1]!==0?(c[0]=c[1],_=Jo(b,t,o,a,n,_)):c[1]!==0&&(_=Jo(b,t,c,a,n,_)),a=0):a&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")&&(c[3]=n)}for(p!==0&&qy(b,t,p,h,g),b.consume(t.events),n=-1;++n<t.events.length;){const y=t.events[n];y[0]==="enter"&&y[1].type==="table"&&(y[1]._align=yD(t.events,n))}return e}function Jo(e,t,n,s,a,o){const c=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",f="tableContent";n[0]!==0&&(o.end=Object.assign({},Fs(t.events,n[0])),e.add(n[0],0,[["exit",o,t]]));const p=Fs(t.events,n[1]);if(o={type:c,start:Object.assign({},p),end:Object.assign({},p)},e.add(n[1],0,[["enter",o,t]]),n[2]!==0){const h=Fs(t.events,n[2]),g=Fs(t.events,n[3]),_={type:f,start:Object.assign({},h),end:Object.assign({},g)};if(e.add(n[2],0,[["enter",_,t]]),s!==2){const b=t.events[n[2]],y=t.events[n[3]];if(b[1].end=Object.assign({},y[1].end),b[1].type="chunkText",b[1].contentType="text",n[3]>n[2]+1){const x=n[2]+1,E=n[3]-n[2]-1;e.add(x,E,[])}}e.add(n[3]+1,0,[["exit",_,t]])}return a!==void 0&&(o.end=Object.assign({},Fs(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function qy(e,t,n,s,a){const o=[],c=Fs(t.events,n);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(n+1,0,o)}function Fs(e,t){const n=e[t],s=n[0]==="enter"?"start":"end";return n[1][s]}const wD={name:"tasklistCheck",tokenize:kD};function CD(){return{text:{91:wD}}}function kD(e,t,n){const s=this;return a;function a(p){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?n(p):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),o)}function o(p){return Qe(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),c):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),c):n(p)}function c(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),f):n(p)}function f(p){return ve(p)?t(p):Ne(p)?e.check({tokenize:ED},t,n)(p):n(p)}}function ED(e,t,n){return He(e,s,"whitespace");function s(a){return a===null?n(a):t(a)}}function TD(e){return aS([QA(),oD(),_D(e),bD(),CD()])}const AD={};function DD(e){const t=this,n=e||AD,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(TD(n)),o.push(XA()),c.push($A(n))}const Pr=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],Wy={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...Pr,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...Pr],h2:[["className","sr-only"]],img:[...Pr,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...Pr,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...Pr],table:[...Pr],ul:[...Pr,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},pr={}.hasOwnProperty;function RD(e,t){let n={type:"root",children:[]};const s={schema:t?{...Wy,...t}:Wy,stack:[]},a=QS(s,e);return a&&(Array.isArray(a)?a.length===1?n=a[0]:n.children=a:n=a),n}function QS(e,t){if(t&&typeof t=="object"){const n=t;switch(typeof n.type=="string"?n.type:""){case"comment":return MD(e,n);case"doctype":return BD(e,n);case"element":return ND(e,n);case"root":return LD(e,n);case"text":return zD(e,n)}}}function MD(e,t){if(e.schema.allowComments){const n=typeof t.value=="string"?t.value:"",s=n.indexOf("-->"),o={type:"comment",value:s<0?n:n.slice(0,s)};return Ca(o,t),o}}function BD(e,t){if(e.schema.allowDoctypes){const n={type:"doctype"};return Ca(n,t),n}}function ND(e,t){const n=typeof t.tagName=="string"?t.tagName:"";e.stack.push(n);const s=JS(e,t.children),a=OD(e,t.properties);e.stack.pop();let o=!1;if(n&&n!=="*"&&(!e.schema.tagNames||e.schema.tagNames.includes(n))&&(o=!0,e.schema.ancestors&&pr.call(e.schema.ancestors,n))){const f=e.schema.ancestors[n];let p=-1;for(o=!1;++p<f.length;)e.stack.includes(f[p])&&(o=!0)}if(!o)return e.schema.strip&&!e.schema.strip.includes(n)?s:void 0;const c={type:"element",tagName:n,properties:a,children:s};return Ca(c,t),c}function LD(e,t){const s={type:"root",children:JS(e,t.children)};return Ca(s,t),s}function zD(e,t){const s={type:"text",value:typeof t.value=="string"?t.value:""};return Ca(s,t),s}function JS(e,t){const n=[];if(Array.isArray(t)){const s=t;let a=-1;for(;++a<s.length;){const o=QS(e,s[a]);o&&(Array.isArray(o)?n.push(...o):n.push(o))}}return n}function OD(e,t){const n=e.stack[e.stack.length-1],s=e.schema.attributes,a=e.schema.required,o=s&&pr.call(s,n)?s[n]:void 0,c=s&&pr.call(s,"*")?s["*"]:void 0,f=t&&typeof t=="object"?t:{},p={};let h;for(h in f)if(pr.call(f,h)){const g=f[h];let _=Yy(e,Vy(o,h),h,g);_==null&&(_=Yy(e,Vy(c,h),h,g)),_!=null&&(p[h]=_)}if(a&&pr.call(a,n)){const g=a[n];for(h in g)pr.call(g,h)&&!pr.call(p,h)&&(p[h]=g[h])}return p}function Yy(e,t,n,s){return t?Array.isArray(s)?jD(e,t,n,s):e0(e,t,n,s):void 0}function jD(e,t,n,s){let a=-1;const o=[];for(;++a<s.length;){const c=e0(e,t,n,s[a]);(typeof c=="number"||typeof c=="string")&&o.push(c)}return o}function e0(e,t,n,s){if(!(typeof s!="boolean"&&typeof s!="number"&&typeof s!="string")&&HD(e,n,s)){if(typeof t=="object"&&t.length>1){let a=!1,o=0;for(;++o<t.length;){const c=t[o];if(c&&typeof c=="object"&&"flags"in c){if(c.test(String(s))){a=!0;break}}else if(c===s){a=!0;break}}if(!a)return}return e.schema.clobber&&e.schema.clobberPrefix&&e.schema.clobber.includes(n)?e.schema.clobberPrefix+s:s}}function HD(e,t,n){const s=e.schema.protocols&&pr.call(e.schema.protocols,t)?e.schema.protocols[t]:void 0;if(!s||s.length===0)return!0;const a=String(n),o=a.indexOf(":"),c=a.indexOf("?"),f=a.indexOf("#"),p=a.indexOf("/");if(o<0||p>-1&&o>p||c>-1&&o>c||f>-1&&o>f)return!0;let h=-1;for(;++h<s.length;){const g=s[h];if(o===g.length&&a.slice(0,g.length)===g)return!0}return!1}function Ca(e,t){const n=tS(t);t.data&&(e.data=ma(t.data)),n&&(e.position=n)}function Vy(e,t){let n,s=-1;if(e)for(;++s<e.length;){const a=e[s],o=typeof a=="string"?a:a[0];if(o===t)return a;o==="data*"&&(n=a)}if(t.length>4&&t.slice(0,4).toLowerCase()==="data")return n}function UD(e){return function(t){return RD(t,e)}}function PD({storyName:e,fileName:t,authFetch:n,onPublish:s,publishingFile:a}){const[o,c]=ie.useState(null),[f,p]=ie.useState(!1),[h,g]=ie.useState("preview"),[_,b]=ie.useState(""),[y,x]=ie.useState(!1),[E,L]=ie.useState(!1),[R,$]=ie.useState(!1),[I,Z]=ie.useState(null),Y=ie.useRef(null),O=ie.useRef(!1),J=ie.useRef(null),ae=ie.useCallback(async()=>{if(!e||!t){c(null);return}const se=`${e}/${t}`,k=J.current!==se;k&&(J.current=se);try{const D=await n(`/api/stories/${e}/${t}`);if(D.ok){const V=await D.json();c(V),(k||!O.current)&&(b(V.content??""),k&&(L(!1),O.current=!1))}}catch{}},[e,t,n]);ie.useEffect(()=>{p(!0),ae().finally(()=>p(!1))},[ae]),ie.useEffect(()=>{if(!e||!t||h==="edit"&&E)return;const se=setInterval(ae,3e3);return()=>clearInterval(se)},[e,t,ae,h,E]);const de=ie.useCallback(async()=>{if(!(!e||!t)){x(!0);try{(await n(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:_})})).ok&&(L(!1),O.current=!1,c(k=>k&&{...k,content:_}))}catch{}x(!1)}},[e,t,n,_]);ie.useEffect(()=>{if(h!=="edit")return;const se=k=>{(k.metaKey||k.ctrlKey)&&k.key==="s"&&(k.preventDefault(),de())};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[h,de]),ie.useEffect(()=>{if((o==null?void 0:o.status)!=="published-not-indexed"||!o.publishedAt)return;const se=new Date(o.publishedAt).getTime(),k=300*1e3,D=()=>{const C=Math.max(0,k-(Date.now()-se));Z(C)};D();const V=setInterval(D,1e3);return()=>clearInterval(V)},[o==null?void 0:o.status,o==null?void 0:o.publishedAt]);const F=I!==null&&I<=0,le=I!==null&&I>0?`${Math.floor(I/6e4)}:${String(Math.floor(I%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return S.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:S.jsxs("div",{className:"text-center",children:[S.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),S.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(f&&!o)return S.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const T=(h==="edit"?_:(o==null?void 0:o.content)??"").length,B=t==="genesis.md",N=t?/^plot-\d+\.md$/.test(t):!1,A=(o==null?void 0:o.status)==="published"||(o==null?void 0:o.status)==="published-not-indexed",j=B?1e3:N?1e4:null,P=!A&&j!==null&&T>j;return S.jsxs("div",{className:"h-full flex flex-col",children:[S.jsxs("div",{className:"border-b border-border",children:[S.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[S.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[S.jsxs("span",{children:[e,"/",t]}),(o==null?void 0:o.status)==="published"&&S.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(o==null?void 0:o.status)==="published-not-indexed"&&S.jsx("span",{className:"text-amber-700 font-medium",title:o.indexError,children:"Published (not indexed)"}),(o==null?void 0:o.status)==="pending"&&S.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),S.jsxs("div",{className:"flex items-center gap-2",children:[S.jsxs("span",{className:`text-xs font-mono ${P?"text-error font-medium":"text-muted"}`,children:[T.toLocaleString(),j!==null?`/${j.toLocaleString()}`:" chars"]}),P&&S.jsxs("span",{className:"text-error text-xs font-medium",children:[(T-j).toLocaleString()," over limit"]})]})]}),S.jsxs("div",{className:"flex px-3 gap-1",children:[S.jsx("button",{onClick:()=>g("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${h==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),S.jsxs("button",{onClick:()=>g("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${h==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",E&&S.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),h==="preview"?S.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:o!=null&&o.content?S.jsx("div",{className:"prose max-w-none",children:S.jsx(p3,{remarkPlugins:[k3,DD],rehypePlugins:[UD],children:o.content})}):S.jsx("p",{className:"text-muted italic",children:"No content"})}):S.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[S.jsx("textarea",{ref:Y,value:_,onChange:se=>{b(se.target.value),L(!0),O.current=!0},className:"flex-1 min-h-0 w-full resize-none px-4 py-3 text-sm leading-relaxed focus:outline-none",style:{fontFamily:'"Geist Mono", ui-monospace, monospace',background:"var(--paper-bg)",color:"var(--text)"},spellCheck:!1}),S.jsxs("div",{className:"px-3 py-1.5 border-t border-border flex items-center justify-between",children:[S.jsx("span",{className:"text-xs text-muted",children:E?"Unsaved changes":"No changes"}),S.jsx("button",{onClick:de,disabled:!E||y,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:y?"Saving...":"Save"})]})]}),S.jsx("div",{className:"px-3 py-2 border-t border-border flex items-center justify-between",children:t==="structure.md"?S.jsx("p",{className:"text-muted text-xs italic",children:"This is your story outline — not publishable. Ask AI to write the genesis next."}):(o==null?void 0:o.status)==="published-not-indexed"?S.jsxs("div",{className:"flex flex-col gap-1",children:[S.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[S.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!F&&S.jsx("button",{onClick:async()=>{if(!(!e||!t||!o.txHash)){$(!0);try{(await(await n("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:o.txHash,content:o.content,storylineId:o.storylineId})})).json()).ok&&(await n(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:o.txHash,storylineId:o.storylineId,contentCid:"",gasCost:""})}),ae())}catch{}$(!1)}},disabled:R,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:R?"Retrying...":`Retry Index${le?` (${le})`:""}`}),N&&S.jsx("button",{onClick:()=>e&&t&&(s==null?void 0:s(e,t)),disabled:!!a,className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),o.txHash&&S.jsx("a",{href:`https://basescan.org/tx/${o.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),S.jsx("p",{className:"text-muted text-xs",children:F?N?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":N?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),o.indexError&&S.jsx("p",{className:"text-error text-xs",children:o.indexError})]}):(o==null?void 0:o.status)==="published"?S.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[S.jsx("span",{className:"text-green-700",children:"Published"}),o.storylineId&&S.jsx("a",{href:(()=>{var D;const se=`https://plotlink.xyz/story/${o.storylineId}`;if(!N)return se;const k=o.plotIndex!=null&&o.plotIndex>0?o.plotIndex:parseInt(((D=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:D[1])??"1");return`${se}/${k}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),o.txHash&&S.jsx("a",{href:`https://basescan.org/tx/${o.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}):S.jsxs("div",{className:"flex items-center gap-2",children:[S.jsx("button",{onClick:()=>e&&t&&(s==null?void 0:s(e,t)),disabled:!!a||P,className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:a===t?"Publishing...":"Publish to PlotLink"}),P&&S.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"})]})})]})}const t0="plotlink-panel-ratio",ID=.6,Ky=300,kf=224,Ef=6;function FD(){try{const e=localStorage.getItem(t0);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return ID}function Xy(e,t){if(t<=0)return e;const n=Ky/t,s=1-Ky/t;return n>=s?.5:Math.min(s,Math.max(n,e))}function qD({token:e,authFetch:t}){const[n,s]=ie.useState(null),[a,o]=ie.useState(null),[c,f]=ie.useState(null),[p,h]=ie.useState(""),[g,_]=ie.useState(FD),[b,y]=ie.useState([]),x=ie.useRef(new Set),E=ie.useRef(null),L=ie.useRef(null),R=ie.useRef(!1);ie.useEffect(()=>{try{localStorage.setItem(t0,String(g))}catch{}},[g]),ie.useEffect(()=>{const H=()=>{if(!L.current)return;const T=L.current.getBoundingClientRect().width-kf-Ef;_(B=>Xy(B,T))};return window.addEventListener("resize",H),H(),()=>window.removeEventListener("resize",H)},[]);const $=ie.useCallback(()=>{const H=`_new_${Date.now()}`;y(T=>[...T,H]),s(H),o(null)},[]);ie.useEffect(()=>{if(b.length===0)return;const H=setInterval(async()=>{try{const T=await t("/api/stories");if(!T.ok)return;const B=await T.json(),N=new Set(B.stories.filter(A=>A.name!=="_example").map(A=>A.name));for(const A of N)if(!x.current.has(A)&&b.length>0){const j=b[0];let P=!1;E.current&&(P=await E.current(j,A).catch(()=>!1)),P&&y(se=>se.slice(1)),s(A),o(null)}x.current=N}catch{}},3e3);return()=>clearInterval(H)},[t,b]),ie.useEffect(()=>{t("/api/stories").then(H=>{if(H.ok)return H.json()}).then(H=>{H!=null&&H.stories&&(x.current=new Set(H.stories.filter(T=>T.name!=="_example").map(T=>T.name)))}).catch(()=>{})},[t]);const I=ie.useCallback((H,T)=>{s(H),o(T)},[]),Z=ie.useRef(null),Y=ie.useCallback(async H=>{var T,B,N,A;Z.current=H,s(H),o(null);try{const j=await t(`/api/stories/${H}`);if(j.ok&&Z.current===H){const se=(await j.json()).files||[],D=((T=se.map(V=>{var C;return{file:V.file,num:(C=V.file.match(/^plot-(\d+)\.md$/))==null?void 0:C[1]}}).filter(V=>V.num!=null).sort((V,C)=>parseInt(C.num)-parseInt(V.num))[0])==null?void 0:T.file)??((B=se.find(V=>V.file==="genesis.md"))==null?void 0:B.file)??((N=se.find(V=>V.file==="structure.md"))==null?void 0:N.file)??((A=se[0])==null?void 0:A.file);D&&Z.current===H&&o(D)}}catch{}},[t]),O=ie.useCallback(H=>{H.preventDefault(),R.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const T=N=>{if(!R.current||!L.current)return;const A=L.current.getBoundingClientRect(),j=A.width-kf-Ef,P=N.clientX-A.left-kf;_(Xy(P/j,j))},B=()=>{R.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",T),window.removeEventListener("mouseup",B)};window.addEventListener("mousemove",T),window.addEventListener("mouseup",B)},[]),J=ie.useCallback(async(H,T)=>{var B;f(T),h("Reading file...");try{const N=await t(`/api/stories/${H}/${T}`);if(!N.ok)throw new Error("Failed to read file");const A=await N.json(),j=A.content.match(/^#\s+(.+)$/m),P=j?j[1].slice(0,60):T.replace(".md","");let se="Fiction";try{const ee=await t(`/api/stories/${H}/structure.md`);if(ee.ok){const he=(await ee.json()).content.match(/genre[:\s]+(.+)/i);he&&(se=he[1].trim().slice(0,30))}}catch{}let k;if(T.match(/^plot-\d+\.md$/)){try{const ee=await t(`/api/stories/${H}`);if(ee.ok){const he=(await ee.json()).files.find(be=>be.file==="genesis.md"&&be.storylineId);k=he==null?void 0:he.storylineId}}catch{}if(!k){h("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),h("")},3e3);return}}h("Publishing...");const D=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:H,fileName:T,title:P,content:A.content,genre:se,storylineId:k})});if(!D.ok){const ee=await D.json();throw new Error(ee.error||"Publish failed")}const V=(B=D.body)==null?void 0:B.getReader(),C=new TextDecoder;if(V)for(;;){const{done:ee,value:pe}=await V.read();if(ee)break;const be=C.decode(pe).split(`
|
|
129
|
+
`))}function p(y,x,E,L){const R=E.enter("tableCell"),$=E.enter("phrasing"),I=E.containerPhrasing(y,{...L,before:o,after:o});return $(),R(),I}function h(y,x){return nA(y,{align:x,alignDelimiters:s,padding:n,stringLength:a})}function g(y,x,E){const L=y.children;let R=-1;const $=[],I=x.enter("table");for(;++R<L.length;)$[R]=_(L[R],x,E);return I(),$}function _(y,x,E){const L=y.children;let R=-1;const $=[],I=x.enter("tableRow");for(;++R<L.length;)$[R]=p(L[R],y,x,E);return I(),$}function b(y,x,E){let L=qS.inlineCode(y,x,E);return E.stack.includes("tableCell")&&(L=L.replace(/\|/g,"\\$&")),L}}function WA(){return{exit:{taskListCheckValueChecked:Fy,taskListCheckValueUnchecked:Fy,paragraph:VA}}}function YA(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:KA}}}function Fy(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function VA(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const s=n.children[0];if(s&&s.type==="text"){const a=t.children;let o=-1,c;for(;++o<a.length;){const f=a[o];if(f.type==="paragraph"){c=f;break}}c===n&&(s.value=s.value.slice(1),s.value.length===0?n.children.shift():n.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,n.position.start=Object.assign({},s.position.start)))}}this.exit(e)}function KA(e,t,n,s){const a=e.children[0],o=typeof e.checked=="boolean"&&a&&a.type==="paragraph",c="["+(e.checked?"x":" ")+"] ",f=n.createTracker(s);o&&f.move(c);let p=qS.listItem(e,t,n,{...s,...f.current()});return o&&(p=p.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,h)),p;function h(g){return g+c}}function XA(){return[E3(),K3(),Z3(),jA(),WA()]}function $A(e){return{extensions:[T3(),X3(e),Q3(),qA(e),YA()]}}const GA={tokenize:iD,partial:!0},WS={tokenize:nD,partial:!0},YS={tokenize:rD,partial:!0},VS={tokenize:sD,partial:!0},ZA={tokenize:lD,partial:!0},KS={name:"wwwAutolink",tokenize:eD,previous:$S},XS={name:"protocolAutolink",tokenize:tD,previous:GS},jn={name:"emailAutolink",tokenize:JA,previous:ZS},hn={};function QA(){return{text:hn}}let Ur=48;for(;Ur<123;)hn[Ur]=jn,Ur++,Ur===58?Ur=65:Ur===91&&(Ur=97);hn[43]=jn;hn[45]=jn;hn[46]=jn;hn[95]=jn;hn[72]=[jn,XS];hn[104]=[jn,XS];hn[87]=[jn,KS];hn[119]=[jn,KS];function JA(e,t,n){const s=this;let a,o;return c;function c(_){return!bd(_)||!ZS.call(s,s.previous)||Gd(s.events)?n(_):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(_))}function f(_){return bd(_)?(e.consume(_),f):_===64?(e.consume(_),p):n(_)}function p(_){return _===46?e.check(ZA,g,h)(_):_===45||_===95||Gt(_)?(o=!0,e.consume(_),p):g(_)}function h(_){return e.consume(_),a=!0,p}function g(_){return o&&a&&ri(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(_)):n(_)}}function eD(e,t,n){const s=this;return a;function a(c){return c!==87&&c!==119||!$S.call(s,s.previous)||Gd(s.events)?n(c):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(GA,e.attempt(WS,e.attempt(YS,o),n),n)(c))}function o(c){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(c)}}function tD(e,t,n){const s=this;let a="",o=!1;return c;function c(_){return(_===72||_===104)&&GS.call(s,s.previous)&&!Gd(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(_),e.consume(_),f):n(_)}function f(_){if(ri(_)&&a.length<5)return a+=String.fromCodePoint(_),e.consume(_),f;if(_===58){const b=a.toLowerCase();if(b==="http"||b==="https")return e.consume(_),p}return n(_)}function p(_){return _===47?(e.consume(_),o?h:(o=!0,p)):n(_)}function h(_){return _===null||pu(_)||Qe(_)||Kr(_)||xu(_)?n(_):e.attempt(WS,e.attempt(YS,g),n)(_)}function g(_){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(_)}}function iD(e,t,n){let s=0;return a;function a(c){return(c===87||c===119)&&s<3?(s++,e.consume(c),a):c===46&&s===3?(e.consume(c),o):n(c)}function o(c){return c===null?n(c):t(c)}}function nD(e,t,n){let s,a,o;return c;function c(h){return h===46||h===95?e.check(VS,p,f)(h):h===null||Qe(h)||Kr(h)||h!==45&&xu(h)?p(h):(o=!0,e.consume(h),c)}function f(h){return h===95?s=!0:(a=s,s=void 0),e.consume(h),c}function p(h){return a||s||!o?n(h):t(h)}}function rD(e,t){let n=0,s=0;return a;function a(c){return c===40?(n++,e.consume(c),a):c===41&&s<n?o(c):c===33||c===34||c===38||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===60||c===63||c===93||c===95||c===126?e.check(VS,t,o)(c):c===null||Qe(c)||Kr(c)?t(c):(e.consume(c),a)}function o(c){return c===41&&s++,e.consume(c),a}}function sD(e,t,n){return s;function s(f){return f===33||f===34||f===39||f===41||f===42||f===44||f===46||f===58||f===59||f===63||f===95||f===126?(e.consume(f),s):f===38?(e.consume(f),o):f===93?(e.consume(f),a):f===60||f===null||Qe(f)||Kr(f)?t(f):n(f)}function a(f){return f===null||f===40||f===91||Qe(f)||Kr(f)?t(f):s(f)}function o(f){return ri(f)?c(f):n(f)}function c(f){return f===59?(e.consume(f),s):ri(f)?(e.consume(f),c):n(f)}}function lD(e,t,n){return s;function s(o){return e.consume(o),a}function a(o){return Gt(o)?n(o):t(o)}}function $S(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Qe(e)}function GS(e){return!ri(e)}function ZS(e){return!(e===47||bd(e))}function bd(e){return e===43||e===45||e===46||e===95||Gt(e)}function Gd(e){let t=e.length,n=!1;for(;t--;){const s=e[t][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){n=!0;break}if(s._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const aD={tokenize:mD,partial:!0};function oD(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:fD,continuation:{tokenize:dD},exit:pD}},text:{91:{name:"gfmFootnoteCall",tokenize:hD},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:uD,resolveTo:cD}}}}function uD(e,t,n){const s=this;let a=s.events.length;const o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;a--;){const p=s.events[a][1];if(p.type==="labelImage"){c=p;break}if(p.type==="gfmFootnoteCall"||p.type==="labelLink"||p.type==="label"||p.type==="image"||p.type==="link")break}return f;function f(p){if(!c||!c._balanced)return n(p);const h=Qi(s.sliceSerialize({start:c.end,end:s.now()}));return h.codePointAt(0)!==94||!o.includes(h.slice(1))?n(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function cD(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},f=[e[n+1],e[n+2],["enter",s,t],e[n+3],e[n+4],["enter",a,t],["exit",a,t],["enter",o,t],["enter",c,t],["exit",c,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(n,e.length-n+1,...f),e}function hD(e,t,n){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o=0,c;return f;function f(_){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(_),e.exit("gfmFootnoteCallLabelMarker"),p}function p(_){return _!==94?n(_):(e.enter("gfmFootnoteCallMarker"),e.consume(_),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",h)}function h(_){if(o>999||_===93&&!c||_===null||_===91||Qe(_))return n(_);if(_===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(Qi(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(_),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(_)}return Qe(_)||(c=!0),o++,e.consume(_),_===92?g:h}function g(_){return _===91||_===92||_===93?(e.consume(_),o++,h):h(_)}}function fD(e,t,n){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,f;return p;function p(x){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionLabelMarker"),h}function h(x){return x===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",g):n(x)}function g(x){if(c>999||x===93&&!f||x===null||x===91||Qe(x))return n(x);if(x===93){e.exit("chunkString");const E=e.exit("gfmFootnoteDefinitionLabelString");return o=Qi(s.sliceSerialize(E)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return Qe(x)||(f=!0),c++,e.consume(x),x===92?_:g}function _(x){return x===91||x===92||x===93?(e.consume(x),c++,g):g(x)}function b(x){return x===58?(e.enter("definitionMarker"),e.consume(x),e.exit("definitionMarker"),a.includes(o)||a.push(o),He(e,y,"gfmFootnoteDefinitionWhitespace")):n(x)}function y(x){return t(x)}}function dD(e,t,n){return e.check(xa,t,e.attempt(aD,t,n))}function pD(e){e.exit("gfmFootnoteDefinition")}function mD(e,t,n){const s=this;return He(e,a,"gfmFootnoteDefinitionIndent",5);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(o):n(o)}}function _D(e){let n=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:a};return n==null&&(n=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(c,f){let p=-1;for(;++p<c.length;)if(c[p][0]==="enter"&&c[p][1].type==="strikethroughSequenceTemporary"&&c[p][1]._close){let h=p;for(;h--;)if(c[h][0]==="exit"&&c[h][1].type==="strikethroughSequenceTemporary"&&c[h][1]._open&&c[p][1].end.offset-c[p][1].start.offset===c[h][1].end.offset-c[h][1].start.offset){c[p][1].type="strikethroughSequence",c[h][1].type="strikethroughSequence";const g={type:"strikethrough",start:Object.assign({},c[h][1].start),end:Object.assign({},c[p][1].end)},_={type:"strikethroughText",start:Object.assign({},c[h][1].end),end:Object.assign({},c[p][1].start)},b=[["enter",g,f],["enter",c[h][1],f],["exit",c[h][1],f],["enter",_,f]],y=f.parser.constructs.insideSpan.null;y&&Mi(b,b.length,0,wu(y,c.slice(h+1,p),f)),Mi(b,b.length,0,[["exit",_,f],["enter",c[p][1],f],["exit",c[p][1],f],["exit",g,f]]),Mi(c,h-1,p-h+3,b),p=h+b.length-2;break}}for(p=-1;++p<c.length;)c[p][1].type==="strikethroughSequenceTemporary"&&(c[p][1].type="data");return c}function o(c,f,p){const h=this.previous,g=this.events;let _=0;return b;function b(x){return h===126&&g[g.length-1][1].type!=="characterEscape"?p(x):(c.enter("strikethroughSequenceTemporary"),y(x))}function y(x){const E=Vs(h);if(x===126)return _>1?p(x):(c.consume(x),_++,y);if(_<2&&!n)return p(x);const L=c.exit("strikethroughSequenceTemporary"),R=Vs(x);return L._open=!R||R===2&&!!E,L._close=!E||E===2&&!!R,f(x)}}}class gD{constructor(){this.map=[]}add(t,n,s){vD(this,t,n,s)}consume(t){if(this.map.sort(function(o,c){return o[0]-c[0]}),this.map.length===0)return;let n=this.map.length;const s=[];for(;n>0;)n-=1,s.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];s.push(t.slice()),t.length=0;let a=s.pop();for(;a;){for(const o of a)t.push(o);a=s.pop()}this.map.length=0}}function vD(e,t,n,s){let a=0;if(!(n===0&&s.length===0)){for(;a<e.map.length;){if(e.map[a][0]===t){e.map[a][1]+=n,e.map[a][2].push(...s);return}a+=1}e.map.push([t,n,s])}}function yD(e,t){let n=!1;const s=[];for(;t<e.length;){const a=e[t];if(n){if(a[0]==="enter")a[1].type==="tableContent"&&s.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(a[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const o=s.length-1;s[o]=s[o]==="left"?"center":"right"}}else if(a[1].type==="tableDelimiterRow")break}else a[0]==="enter"&&a[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return s}function bD(){return{flow:{null:{name:"table",tokenize:SD,resolveAll:xD}}}}function SD(e,t,n){const s=this;let a=0,o=0,c;return f;function f(F){let le=s.events.length-1;for(;le>-1;){const B=s.events[le][1].type;if(B==="lineEnding"||B==="linePrefix")le--;else break}const H=le>-1?s.events[le][1].type:null,T=H==="tableHead"||H==="tableRow"?O:p;return T===O&&s.parser.lazy[s.now().line]?n(F):T(F)}function p(F){return e.enter("tableHead"),e.enter("tableRow"),h(F)}function h(F){return F===124||(c=!0,o+=1),g(F)}function g(F){return F===null?n(F):ve(F)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(F),e.exit("lineEnding"),y):n(F):Ne(F)?He(e,g,"whitespace")(F):(o+=1,c&&(c=!1,a+=1),F===124?(e.enter("tableCellDivider"),e.consume(F),e.exit("tableCellDivider"),c=!0,g):(e.enter("data"),_(F)))}function _(F){return F===null||F===124||Qe(F)?(e.exit("data"),g(F)):(e.consume(F),F===92?b:_)}function b(F){return F===92||F===124?(e.consume(F),_):_(F)}function y(F){return s.interrupt=!1,s.parser.lazy[s.now().line]?n(F):(e.enter("tableDelimiterRow"),c=!1,Ne(F)?He(e,x,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(F):x(F))}function x(F){return F===45||F===58?L(F):F===124?(c=!0,e.enter("tableCellDivider"),e.consume(F),e.exit("tableCellDivider"),E):Y(F)}function E(F){return Ne(F)?He(e,L,"whitespace")(F):L(F)}function L(F){return F===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(F),e.exit("tableDelimiterMarker"),R):F===45?(o+=1,R(F)):F===null||ve(F)?Z(F):Y(F)}function R(F){return F===45?(e.enter("tableDelimiterFiller"),$(F)):Y(F)}function $(F){return F===45?(e.consume(F),$):F===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(F),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(F))}function I(F){return Ne(F)?He(e,Z,"whitespace")(F):Z(F)}function Z(F){return F===124?x(F):F===null||ve(F)?!c||a!==o?Y(F):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(F)):Y(F)}function Y(F){return n(F)}function O(F){return e.enter("tableRow"),J(F)}function J(F){return F===124?(e.enter("tableCellDivider"),e.consume(F),e.exit("tableCellDivider"),J):F===null||ve(F)?(e.exit("tableRow"),t(F)):Ne(F)?He(e,J,"whitespace")(F):(e.enter("data"),ae(F))}function ae(F){return F===null||F===124||Qe(F)?(e.exit("data"),J(F)):(e.consume(F),F===92?de:ae)}function de(F){return F===92||F===124?(e.consume(F),ae):ae(F)}}function xD(e,t){let n=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],f=!1,p=0,h,g,_;const b=new gD;for(;++n<e.length;){const y=e[n],x=y[1];y[0]==="enter"?x.type==="tableHead"?(f=!1,p!==0&&(qy(b,t,p,h,g),g=void 0,p=0),h={type:"table",start:Object.assign({},x.start),end:Object.assign({},x.end)},b.add(n,0,[["enter",h,t]])):x.type==="tableRow"||x.type==="tableDelimiterRow"?(s=!0,_=void 0,o=[0,0,0,0],c=[0,n+1,0,0],f&&(f=!1,g={type:"tableBody",start:Object.assign({},x.start),end:Object.assign({},x.end)},b.add(n,0,[["enter",g,t]])),a=x.type==="tableDelimiterRow"?2:g?3:1):a&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")?(s=!1,c[2]===0&&(o[1]!==0&&(c[0]=c[1],_=Jo(b,t,o,a,void 0,_),o=[0,0,0,0]),c[2]=n)):x.type==="tableCellDivider"&&(s?s=!1:(o[1]!==0&&(c[0]=c[1],_=Jo(b,t,o,a,void 0,_)),o=c,c=[o[1],n,0,0])):x.type==="tableHead"?(f=!0,p=n):x.type==="tableRow"||x.type==="tableDelimiterRow"?(p=n,o[1]!==0?(c[0]=c[1],_=Jo(b,t,o,a,n,_)):c[1]!==0&&(_=Jo(b,t,c,a,n,_)),a=0):a&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")&&(c[3]=n)}for(p!==0&&qy(b,t,p,h,g),b.consume(t.events),n=-1;++n<t.events.length;){const y=t.events[n];y[0]==="enter"&&y[1].type==="table"&&(y[1]._align=yD(t.events,n))}return e}function Jo(e,t,n,s,a,o){const c=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",f="tableContent";n[0]!==0&&(o.end=Object.assign({},Fs(t.events,n[0])),e.add(n[0],0,[["exit",o,t]]));const p=Fs(t.events,n[1]);if(o={type:c,start:Object.assign({},p),end:Object.assign({},p)},e.add(n[1],0,[["enter",o,t]]),n[2]!==0){const h=Fs(t.events,n[2]),g=Fs(t.events,n[3]),_={type:f,start:Object.assign({},h),end:Object.assign({},g)};if(e.add(n[2],0,[["enter",_,t]]),s!==2){const b=t.events[n[2]],y=t.events[n[3]];if(b[1].end=Object.assign({},y[1].end),b[1].type="chunkText",b[1].contentType="text",n[3]>n[2]+1){const x=n[2]+1,E=n[3]-n[2]-1;e.add(x,E,[])}}e.add(n[3]+1,0,[["exit",_,t]])}return a!==void 0&&(o.end=Object.assign({},Fs(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function qy(e,t,n,s,a){const o=[],c=Fs(t.events,n);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(n+1,0,o)}function Fs(e,t){const n=e[t],s=n[0]==="enter"?"start":"end";return n[1][s]}const wD={name:"tasklistCheck",tokenize:kD};function CD(){return{text:{91:wD}}}function kD(e,t,n){const s=this;return a;function a(p){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?n(p):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),o)}function o(p){return Qe(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),c):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),c):n(p)}function c(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),f):n(p)}function f(p){return ve(p)?t(p):Ne(p)?e.check({tokenize:ED},t,n)(p):n(p)}}function ED(e,t,n){return He(e,s,"whitespace");function s(a){return a===null?n(a):t(a)}}function TD(e){return aS([QA(),oD(),_D(e),bD(),CD()])}const AD={};function DD(e){const t=this,n=e||AD,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(TD(n)),o.push(XA()),c.push($A(n))}const Pr=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],Wy={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...Pr,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...Pr],h2:[["className","sr-only"]],img:[...Pr,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...Pr,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...Pr],table:[...Pr],ul:[...Pr,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},pr={}.hasOwnProperty;function RD(e,t){let n={type:"root",children:[]};const s={schema:t?{...Wy,...t}:Wy,stack:[]},a=QS(s,e);return a&&(Array.isArray(a)?a.length===1?n=a[0]:n.children=a:n=a),n}function QS(e,t){if(t&&typeof t=="object"){const n=t;switch(typeof n.type=="string"?n.type:""){case"comment":return MD(e,n);case"doctype":return BD(e,n);case"element":return ND(e,n);case"root":return LD(e,n);case"text":return zD(e,n)}}}function MD(e,t){if(e.schema.allowComments){const n=typeof t.value=="string"?t.value:"",s=n.indexOf("-->"),o={type:"comment",value:s<0?n:n.slice(0,s)};return Ca(o,t),o}}function BD(e,t){if(e.schema.allowDoctypes){const n={type:"doctype"};return Ca(n,t),n}}function ND(e,t){const n=typeof t.tagName=="string"?t.tagName:"";e.stack.push(n);const s=JS(e,t.children),a=OD(e,t.properties);e.stack.pop();let o=!1;if(n&&n!=="*"&&(!e.schema.tagNames||e.schema.tagNames.includes(n))&&(o=!0,e.schema.ancestors&&pr.call(e.schema.ancestors,n))){const f=e.schema.ancestors[n];let p=-1;for(o=!1;++p<f.length;)e.stack.includes(f[p])&&(o=!0)}if(!o)return e.schema.strip&&!e.schema.strip.includes(n)?s:void 0;const c={type:"element",tagName:n,properties:a,children:s};return Ca(c,t),c}function LD(e,t){const s={type:"root",children:JS(e,t.children)};return Ca(s,t),s}function zD(e,t){const s={type:"text",value:typeof t.value=="string"?t.value:""};return Ca(s,t),s}function JS(e,t){const n=[];if(Array.isArray(t)){const s=t;let a=-1;for(;++a<s.length;){const o=QS(e,s[a]);o&&(Array.isArray(o)?n.push(...o):n.push(o))}}return n}function OD(e,t){const n=e.stack[e.stack.length-1],s=e.schema.attributes,a=e.schema.required,o=s&&pr.call(s,n)?s[n]:void 0,c=s&&pr.call(s,"*")?s["*"]:void 0,f=t&&typeof t=="object"?t:{},p={};let h;for(h in f)if(pr.call(f,h)){const g=f[h];let _=Yy(e,Vy(o,h),h,g);_==null&&(_=Yy(e,Vy(c,h),h,g)),_!=null&&(p[h]=_)}if(a&&pr.call(a,n)){const g=a[n];for(h in g)pr.call(g,h)&&!pr.call(p,h)&&(p[h]=g[h])}return p}function Yy(e,t,n,s){return t?Array.isArray(s)?jD(e,t,n,s):e0(e,t,n,s):void 0}function jD(e,t,n,s){let a=-1;const o=[];for(;++a<s.length;){const c=e0(e,t,n,s[a]);(typeof c=="number"||typeof c=="string")&&o.push(c)}return o}function e0(e,t,n,s){if(!(typeof s!="boolean"&&typeof s!="number"&&typeof s!="string")&&HD(e,n,s)){if(typeof t=="object"&&t.length>1){let a=!1,o=0;for(;++o<t.length;){const c=t[o];if(c&&typeof c=="object"&&"flags"in c){if(c.test(String(s))){a=!0;break}}else if(c===s){a=!0;break}}if(!a)return}return e.schema.clobber&&e.schema.clobberPrefix&&e.schema.clobber.includes(n)?e.schema.clobberPrefix+s:s}}function HD(e,t,n){const s=e.schema.protocols&&pr.call(e.schema.protocols,t)?e.schema.protocols[t]:void 0;if(!s||s.length===0)return!0;const a=String(n),o=a.indexOf(":"),c=a.indexOf("?"),f=a.indexOf("#"),p=a.indexOf("/");if(o<0||p>-1&&o>p||c>-1&&o>c||f>-1&&o>f)return!0;let h=-1;for(;++h<s.length;){const g=s[h];if(o===g.length&&a.slice(0,g.length)===g)return!0}return!1}function Ca(e,t){const n=tS(t);t.data&&(e.data=ma(t.data)),n&&(e.position=n)}function Vy(e,t){let n,s=-1;if(e)for(;++s<e.length;){const a=e[s],o=typeof a=="string"?a:a[0];if(o===t)return a;o==="data*"&&(n=a)}if(t.length>4&&t.slice(0,4).toLowerCase()==="data")return n}function UD(e){return function(t){return RD(t,e)}}function PD({storyName:e,fileName:t,authFetch:n,onPublish:s,publishingFile:a}){const[o,c]=ie.useState(null),[f,p]=ie.useState(!1),[h,g]=ie.useState("preview"),[_,b]=ie.useState(""),[y,x]=ie.useState(!1),[E,L]=ie.useState(!1),[R,$]=ie.useState(!1),[I,Z]=ie.useState(null),Y=ie.useRef(null),O=ie.useRef(!1),J=ie.useRef(null),ae=ie.useCallback(async()=>{if(!e||!t){c(null);return}const se=`${e}/${t}`,k=J.current!==se;k&&(J.current=se);try{const D=await n(`/api/stories/${e}/${t}`);if(D.ok){const V=await D.json();c(V),(k||!O.current)&&(b(V.content??""),k&&(L(!1),O.current=!1))}}catch{}},[e,t,n]);ie.useEffect(()=>{p(!0),ae().finally(()=>p(!1))},[ae]),ie.useEffect(()=>{if(!e||!t||h==="edit"&&E)return;const se=setInterval(ae,3e3);return()=>clearInterval(se)},[e,t,ae,h,E]);const de=ie.useCallback(async()=>{if(!(!e||!t)){x(!0);try{(await n(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:_})})).ok&&(L(!1),O.current=!1,c(k=>k&&{...k,content:_}))}catch{}x(!1)}},[e,t,n,_]);ie.useEffect(()=>{if(h!=="edit")return;const se=k=>{(k.metaKey||k.ctrlKey)&&k.key==="s"&&(k.preventDefault(),de())};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[h,de]),ie.useEffect(()=>{if((o==null?void 0:o.status)!=="published-not-indexed"||!o.publishedAt)return;const se=new Date(o.publishedAt).getTime(),k=300*1e3,D=()=>{const C=Math.max(0,k-(Date.now()-se));Z(C)};D();const V=setInterval(D,1e3);return()=>clearInterval(V)},[o==null?void 0:o.status,o==null?void 0:o.publishedAt]);const F=I!==null&&I<=0,le=I!==null&&I>0?`${Math.floor(I/6e4)}:${String(Math.floor(I%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return S.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:S.jsxs("div",{className:"text-center",children:[S.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),S.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(f&&!o)return S.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const T=(h==="edit"?_:(o==null?void 0:o.content)??"").length,B=t==="genesis.md",N=t?/^plot-\d+\.md$/.test(t):!1,A=(o==null?void 0:o.status)==="published"||(o==null?void 0:o.status)==="published-not-indexed",j=B||N?1e4:null,P=!A&&j!==null&&T>j;return S.jsxs("div",{className:"h-full flex flex-col",children:[S.jsxs("div",{className:"border-b border-border",children:[S.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[S.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[S.jsxs("span",{children:[e,"/",t]}),(o==null?void 0:o.status)==="published"&&S.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(o==null?void 0:o.status)==="published-not-indexed"&&S.jsx("span",{className:"text-amber-700 font-medium",title:o.indexError,children:"Published (not indexed)"}),(o==null?void 0:o.status)==="pending"&&S.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),S.jsxs("div",{className:"flex items-center gap-2",children:[S.jsxs("span",{className:`text-xs font-mono ${P?"text-error font-medium":"text-muted"}`,children:[T.toLocaleString(),j!==null?`/${j.toLocaleString()}`:" chars"]}),P&&S.jsxs("span",{className:"text-error text-xs font-medium",children:[(T-j).toLocaleString()," over limit"]})]})]}),S.jsxs("div",{className:"flex px-3 gap-1",children:[S.jsx("button",{onClick:()=>g("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${h==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),S.jsxs("button",{onClick:()=>g("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${h==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",E&&S.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),h==="preview"?S.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:o!=null&&o.content?S.jsx("div",{className:"prose max-w-none",children:S.jsx(p3,{remarkPlugins:[k3,DD],rehypePlugins:[UD],children:o.content})}):S.jsx("p",{className:"text-muted italic",children:"No content"})}):S.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[S.jsx("textarea",{ref:Y,value:_,onChange:se=>{b(se.target.value),L(!0),O.current=!0},className:"flex-1 min-h-0 w-full resize-none px-4 py-3 text-sm leading-relaxed focus:outline-none",style:{fontFamily:'"Geist Mono", ui-monospace, monospace',background:"var(--paper-bg)",color:"var(--text)"},spellCheck:!1}),S.jsxs("div",{className:"px-3 py-1.5 border-t border-border flex items-center justify-between",children:[S.jsx("span",{className:"text-xs text-muted",children:E?"Unsaved changes":"No changes"}),S.jsx("button",{onClick:de,disabled:!E||y,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:y?"Saving...":"Save"})]})]}),S.jsx("div",{className:"px-3 py-2 border-t border-border flex items-center justify-between",children:t==="structure.md"?S.jsx("p",{className:"text-muted text-xs italic",children:"This is your story outline — not publishable. Ask AI to write the genesis next."}):(o==null?void 0:o.status)==="published-not-indexed"?S.jsxs("div",{className:"flex flex-col gap-1",children:[S.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[S.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!F&&S.jsx("button",{onClick:async()=>{if(!(!e||!t||!o.txHash)){$(!0);try{(await(await n("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:o.txHash,content:o.content,storylineId:o.storylineId})})).json()).ok&&(await n(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:o.txHash,storylineId:o.storylineId,contentCid:"",gasCost:""})}),ae())}catch{}$(!1)}},disabled:R,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:R?"Retrying...":`Retry Index${le?` (${le})`:""}`}),N&&S.jsx("button",{onClick:()=>e&&t&&(s==null?void 0:s(e,t)),disabled:!!a,className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),o.txHash&&S.jsx("a",{href:`https://basescan.org/tx/${o.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),S.jsx("p",{className:"text-muted text-xs",children:F?N?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":N?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),o.indexError&&S.jsx("p",{className:"text-error text-xs",children:o.indexError})]}):(o==null?void 0:o.status)==="published"?S.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[S.jsx("span",{className:"text-green-700",children:"Published"}),o.storylineId&&S.jsx("a",{href:(()=>{var D;const se=`https://plotlink.xyz/story/${o.storylineId}`;if(!N)return se;const k=o.plotIndex!=null&&o.plotIndex>0?o.plotIndex:parseInt(((D=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:D[1])??"1");return`${se}/${k}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),o.txHash&&S.jsx("a",{href:`https://basescan.org/tx/${o.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}):S.jsxs("div",{className:"flex items-center gap-2",children:[S.jsx("button",{onClick:()=>e&&t&&(s==null?void 0:s(e,t)),disabled:!!a||P,className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:a===t?"Publishing...":"Publish to PlotLink"}),P&&S.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"})]})})]})}const t0="plotlink-panel-ratio",ID=.6,Ky=300,kf=224,Ef=6;function FD(){try{const e=localStorage.getItem(t0);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return ID}function Xy(e,t){if(t<=0)return e;const n=Ky/t,s=1-Ky/t;return n>=s?.5:Math.min(s,Math.max(n,e))}function qD({token:e,authFetch:t}){const[n,s]=ie.useState(null),[a,o]=ie.useState(null),[c,f]=ie.useState(null),[p,h]=ie.useState(""),[g,_]=ie.useState(FD),[b,y]=ie.useState([]),x=ie.useRef(new Set),E=ie.useRef(null),L=ie.useRef(null),R=ie.useRef(!1);ie.useEffect(()=>{try{localStorage.setItem(t0,String(g))}catch{}},[g]),ie.useEffect(()=>{const H=()=>{if(!L.current)return;const T=L.current.getBoundingClientRect().width-kf-Ef;_(B=>Xy(B,T))};return window.addEventListener("resize",H),H(),()=>window.removeEventListener("resize",H)},[]);const $=ie.useCallback(()=>{const H=`_new_${Date.now()}`;y(T=>[...T,H]),s(H),o(null)},[]);ie.useEffect(()=>{if(b.length===0)return;const H=setInterval(async()=>{try{const T=await t("/api/stories");if(!T.ok)return;const B=await T.json(),N=new Set(B.stories.filter(A=>A.name!=="_example").map(A=>A.name));for(const A of N)if(!x.current.has(A)&&b.length>0){const j=b[0];let P=!1;E.current&&(P=await E.current(j,A).catch(()=>!1)),P&&y(se=>se.slice(1)),s(A),o(null)}x.current=N}catch{}},3e3);return()=>clearInterval(H)},[t,b]),ie.useEffect(()=>{t("/api/stories").then(H=>{if(H.ok)return H.json()}).then(H=>{H!=null&&H.stories&&(x.current=new Set(H.stories.filter(T=>T.name!=="_example").map(T=>T.name)))}).catch(()=>{})},[t]);const I=ie.useCallback((H,T)=>{s(H),o(T)},[]),Z=ie.useRef(null),Y=ie.useCallback(async H=>{var T,B,N,A;Z.current=H,s(H),o(null);try{const j=await t(`/api/stories/${H}`);if(j.ok&&Z.current===H){const se=(await j.json()).files||[],D=((T=se.map(V=>{var C;return{file:V.file,num:(C=V.file.match(/^plot-(\d+)\.md$/))==null?void 0:C[1]}}).filter(V=>V.num!=null).sort((V,C)=>parseInt(C.num)-parseInt(V.num))[0])==null?void 0:T.file)??((B=se.find(V=>V.file==="genesis.md"))==null?void 0:B.file)??((N=se.find(V=>V.file==="structure.md"))==null?void 0:N.file)??((A=se[0])==null?void 0:A.file);D&&Z.current===H&&o(D)}}catch{}},[t]),O=ie.useCallback(H=>{H.preventDefault(),R.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const T=N=>{if(!R.current||!L.current)return;const A=L.current.getBoundingClientRect(),j=A.width-kf-Ef,P=N.clientX-A.left-kf;_(Xy(P/j,j))},B=()=>{R.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",T),window.removeEventListener("mouseup",B)};window.addEventListener("mousemove",T),window.addEventListener("mouseup",B)},[]),J=ie.useCallback(async(H,T)=>{var B;f(T),h("Reading file...");try{const N=await t(`/api/stories/${H}/${T}`);if(!N.ok)throw new Error("Failed to read file");const A=await N.json(),j=A.content.match(/^#\s+(.+)$/m),P=j?j[1].slice(0,60):T.replace(".md","");let se="Fiction";try{const ee=await t(`/api/stories/${H}/structure.md`);if(ee.ok){const he=(await ee.json()).content.match(/genre[:\s]+(.+)/i);he&&(se=he[1].trim().slice(0,30))}}catch{}let k;if(T.match(/^plot-\d+\.md$/)){try{const ee=await t(`/api/stories/${H}`);if(ee.ok){const he=(await ee.json()).files.find(be=>be.file==="genesis.md"&&be.storylineId);k=he==null?void 0:he.storylineId}}catch{}if(!k){h("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),h("")},3e3);return}}h("Publishing...");const D=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:H,fileName:T,title:P,content:A.content,genre:se,storylineId:k})});if(!D.ok){const ee=await D.json();throw new Error(ee.error||"Publish failed")}const V=(B=D.body)==null?void 0:B.getReader(),C=new TextDecoder;if(V)for(;;){const{done:ee,value:pe}=await V.read();if(ee)break;const be=C.decode(pe).split(`
|
|
130
130
|
`).filter(Ue=>Ue.startsWith("data: "));for(const Ue of be)try{const Se=JSON.parse(Ue.slice(6));Se.step&&h(Se.message||Se.step),Se.step==="done"&&Se.txHash&&await t(`/api/stories/${H}/${T}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Se.txHash,storylineId:Se.storylineId,plotIndex:Se.plotIndex,contentCid:Se.contentCid,gasCost:Se.gasCost,indexError:Se.indexError})})}catch{}}h("Published!")}catch(N){const A=N instanceof Error?N.message:"Publish failed";h(`Error: ${A}`)}finally{setTimeout(()=>{f(null),h("")},3e3)}},[t]),ae=ie.useCallback(H=>{H.startsWith("_new_")&&y(T=>T.filter(B=>B!==H))},[]),[de,F]=ie.useState(new Set);ie.useEffect(()=>{t("/api/stories").then(T=>T.ok?T.json():null).then(T=>{T!=null&&T.stories&&F(new Set(T.stories.filter(B=>B.hasStructure).map(B=>B.name)))}).catch(()=>{});const H=setInterval(async()=>{try{const T=await t("/api/stories");if(T.ok){const B=await T.json();F(new Set(B.stories.filter(N=>N.hasStructure).map(N=>N.name)))}}catch{}},5e3);return()=>clearInterval(H)},[t]);const le=ie.useCallback(H=>{n===H&&(s(null),o(null))},[n]);return S.jsxs("div",{ref:L,className:"h-[calc(100vh-3.5rem)] flex",children:[S.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:S.jsx(zx,{authFetch:t,selectedStory:n,selectedFile:a,onSelectFile:I,onNewStory:$,untitledSessions:b})}),S.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${g} 0 0`},children:S.jsx(rk,{token:e,storyName:n,authFetch:t,onSelectStory:Y,onDestroySession:ae,onArchiveStory:le,confirmedStories:de,renameRef:E})}),S.jsx("div",{onMouseDown:O,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Ef,cursor:"col-resize",background:"var(--border)"},children:S.jsxs("div",{className:"flex flex-col gap-1",children:[S.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),S.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),S.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),S.jsxs("div",{className:"min-w-0 flex flex-col",style:{flex:`${1-g} 0 0`},children:[S.jsx(PD,{storyName:n,fileName:a,authFetch:t,onPublish:J,publishingFile:c}),p&&S.jsx("div",{className:"px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:p})]})]})}function WD({token:e,onComplete:t}){const[n,s]=ie.useState(!1),[a,o]=ie.useState(null),[c,f]=ie.useState(!1),p=async()=>{s(!0),o(null);try{const h=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),g=await h.json();if(!h.ok)throw new Error(g.error||"Wallet creation failed");f(!0)}catch(h){o(h instanceof Error?h.message:"Wallet creation failed")}s(!1)};return ie.useEffect(()=>{p()},[]),S.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[S.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),S.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),n&&S.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&S.jsxs("div",{className:"space-y-4",children:[S.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),S.jsx("button",{onClick:p,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"retry"})]}),c&&S.jsxs("div",{className:"space-y-4",children:[S.jsx("div",{className:"text-accent text-2xl",children:"✓"}),S.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),S.jsx("button",{onClick:t,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"continue"})]})]})}function YD({token:e,onLogout:t}){const[n,s]=ie.useState("home"),[a,o]=ie.useState(0),c=ie.useCallback(async(f,p)=>fetch(f,{...p,headers:{...(p==null?void 0:p.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return ie.useEffect(()=>{async function f(){try{if(!(await(await c("/api/wallet")).json()).exists){s("wallet-setup");return}const g=await c("/api/stories");if(g.ok){const _=await g.json();o(_.stories.filter(b=>b.name!=="_example").length)}}catch{}}f()},[e]),S.jsxs("div",{className:"flex h-screen flex-col",children:[S.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[S.jsxs("div",{className:"flex items-center gap-3",children:[S.jsx("button",{onClick:()=>{n!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:S.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),S.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"writer"})]}),n!=="wallet-setup"&&S.jsxs("nav",{className:"flex items-center gap-4",children:[S.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${n==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),S.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${n==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),S.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${n==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),S.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),S.jsxs("main",{className:"flex-1 min-h-0",children:[n==="home"&&S.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[S.jsxs("div",{className:"text-center space-y-2",children:[S.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),S.jsx("p",{className:"text-muted text-sm",children:"Claude CLI writes stories. You publish them on-chain."})]}),S.jsxs("div",{className:"text-center space-y-3",children:[S.jsx("button",{onClick:()=>s("stories"),className:"bg-accent text-white hover:bg-accent-dim px-6 py-2.5 rounded text-sm font-medium transition-colors",children:"Start Writing"}),a>0&&S.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),S.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[S.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),S.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[S.jsxs("li",{children:["Open the ",S.jsx("strong",{children:"Stories"})," tab — Claude CLI launches in the terminal"]}),S.jsx("li",{children:"Tell Claude your story idea — it brainstorms, outlines, and writes"}),S.jsx("li",{children:"Review the live preview as Claude creates files"}),S.jsxs("li",{children:["Click ",S.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),S.jsxs("li",{children:["Earn 5% royalties on every trade at ",S.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]})]}),S.jsx(Qy,{token:e})]}),n==="stories"&&S.jsx(qD,{token:e,authFetch:c}),n==="dashboard"&&S.jsx(Bx,{token:e}),n==="wallet-setup"&&S.jsx(WD,{token:e,onComplete:()=>s("home")}),n==="settings"&&S.jsx(Rx,{token:e,onLogout:t})]})]})}function VD(){const[e,t]=ie.useState(()=>localStorage.getItem("ows-token")),[n,s]=ie.useState(null),[a,o]=ie.useState(!0);ie.useEffect(()=>{fetch("/api/auth/status").then(h=>h.json()).then(h=>s(h.configured)).catch(()=>s(null))},[]),ie.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(h=>{h.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async h=>{try{const g=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:h})}),_=await g.json();return g.ok?(localStorage.setItem("ows-token",_.token),t(_.token),null):_.error||"Login failed"}catch{return"Cannot connect to server"}},f=async h=>{try{const g=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:h})}),_=await g.json();return g.ok?(localStorage.setItem("ows-token",_.token),t(_.token),s(!0),null):_.error||"Setup failed"}catch{return"Cannot connect to server"}},p=()=>{localStorage.removeItem("ows-token"),t(null)};return a||n===null?S.jsx("div",{className:"flex h-screen items-center justify-center",children:S.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):n?e?S.jsx(YD,{token:e,onLogout:p}):S.jsx(Ax,{onLogin:c}):S.jsx(Dx,{onSetup:f})}Tx.createRoot(document.getElementById("root")).render(S.jsx(yx.StrictMode,{children:S.jsx(VD,{})}));
|
package/app/web/dist/index.html
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
8
8
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
|
9
9
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Lora:wght@400;600;700&family=Geist+Mono:wght@400;500&display=swap" rel="stylesheet" />
|
|
10
|
-
<script type="module" crossorigin src="/assets/index-
|
|
10
|
+
<script type="module" crossorigin src="/assets/index-CU2rL-Z3.js"></script>
|
|
11
11
|
<link rel="stylesheet" crossorigin href="/assets/index-DHjiVVCV.css">
|
|
12
12
|
</head>
|
|
13
13
|
<body>
|