@json-to-office/jto 0.1.0
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/LICENSE +18 -0
- package/README.md +23 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +5639 -0
- package/dist/cli.js.map +1 -0
- package/dist/client/assets/HomePage-CGK1cPFp.js +99 -0
- package/dist/client/assets/HomePage-CGK1cPFp.js.map +1 -0
- package/dist/client/assets/JsonEditorPage-DKaFqYpM.js +3 -0
- package/dist/client/assets/JsonEditorPage-DKaFqYpM.js.map +1 -0
- package/dist/client/assets/NotFoundPage-Et1QhbQw.js +2 -0
- package/dist/client/assets/NotFoundPage-Et1QhbQw.js.map +1 -0
- package/dist/client/assets/button-B5W5GwSc.js +2 -0
- package/dist/client/assets/button-B5W5GwSc.js.map +1 -0
- package/dist/client/assets/docx-preview-CUjVWdSJ.js +34 -0
- package/dist/client/assets/docx-preview-CUjVWdSJ.js.map +1 -0
- package/dist/client/assets/editor-CH_tiHyn.js +9 -0
- package/dist/client/assets/editor-CH_tiHyn.js.map +1 -0
- package/dist/client/assets/editor-monaco-json-8I2epq6g.js +6 -0
- package/dist/client/assets/editor-monaco-json-8I2epq6g.js.map +1 -0
- package/dist/client/assets/index-B9dV-vCI.css +1 -0
- package/dist/client/assets/index-DactvF4v.js +3 -0
- package/dist/client/assets/index-DactvF4v.js.map +1 -0
- package/dist/client/assets/monaco-editor-DzeBDgmk.js +12 -0
- package/dist/client/assets/monaco-editor-DzeBDgmk.js.map +1 -0
- package/dist/client/assets/preview-CJlTPgks.js +3 -0
- package/dist/client/assets/preview-CJlTPgks.js.map +1 -0
- package/dist/client/assets/query-vendor-UL64zsGL.js +15 -0
- package/dist/client/assets/query-vendor-UL64zsGL.js.map +1 -0
- package/dist/client/assets/radix-ui-CXavUarI.js +2 -0
- package/dist/client/assets/radix-ui-CXavUarI.js.map +1 -0
- package/dist/client/assets/react-vendor-DhdcN9D5.js +102 -0
- package/dist/client/assets/react-vendor-DhdcN9D5.js.map +1 -0
- package/dist/client/assets/settings-store-provider-DuCKtwqs.js +2 -0
- package/dist/client/assets/settings-store-provider-DuCKtwqs.js.map +1 -0
- package/dist/client/assets/state-vendor-CAMVKh-F.js +6 -0
- package/dist/client/assets/state-vendor-CAMVKh-F.js.map +1 -0
- package/dist/client/assets/ui-vendor-C6DsfOoA.js +247 -0
- package/dist/client/assets/ui-vendor-C6DsfOoA.js.map +1 -0
- package/dist/client/css/preview/docxjs.css +11 -0
- package/dist/client/icon.svg +5 -0
- package/dist/client/index.html +23 -0
- package/dist/client/templates/Charts Demo.pptx.json +174 -0
- package/dist/client/templates/Company Branding.pptx.json +143 -0
- package/dist/client/templates/Dashboard.pptx.json +91 -0
- package/dist/client/templates/Product Launch.pptx.json +87 -0
- package/dist/client/templates/Sales Deck.pptx.json +80 -0
- package/dist/client/templates/Wiseair.pptx.json +5382 -0
- package/dist/client/templates/themes/corporate.pptx.theme.json +32 -0
- package/dist/client/templates/themes/minimal.pptx.theme.json +32 -0
- package/dist/client/templates/themes/vibrant.pptx.theme.json +32 -0
- package/dist/index.d.ts +387 -0
- package/dist/index.js +2303 -0
- package/dist/index.js.map +1 -0
- package/package.json +147 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{j as B}from"./query-vendor-UL64zsGL.js";import{a as Q,r as y}from"./react-vendor-DhdcN9D5.js";import{u as re,g as ce,c as le,d as he,E as pe}from"./editor-monaco-json-8I2epq6g.js";import{g as be}from"./index-DactvF4v.js";import Ce,{DiffEditor as Ee}from"./monaco-editor-DzeBDgmk.js";import{u as X,v as we,a as ge,b as ye,d as Re,e as ve,f as Te,c as oe,t as Se}from"./settings-store-provider-DuCKtwqs.js";import{B as ue}from"./button-B5W5GwSc.js";import{T as Me,u as Le,a as Ne}from"./HomePage-CGK1cPFp.js";import{e as de}from"./state-vendor-CAMVKh-F.js";import"./radix-ui-CXavUarI.js";import"./ui-vendor-C6DsfOoA.js";const De={initWith:function(e){const T=document.createElement("div"),d=e.editor.create(T),M=d.constructor.name,V=d.getModel().constructor.name;return{isInstanceValid:function(a){return a.constructor.name===M},isModelValid:function(a){return a.constructor.name===V},isRangesValid:function(a){return Array.isArray(a)?a.every(function(w){return typeof w=="object"&&w.constructor.name==="Object"?!(!w.hasOwnProperty("range")||!Array.isArray(w.range)||w.range.length!==4||!w.range.every(b=>b>0&&parseInt(b)===b)||w.hasOwnProperty("allowMultiline")&&typeof w.allowMultiline!="boolean"||w.hasOwnProperty("label")&&typeof w.label!="string"||w.hasOwnProperty("validate")&&typeof w.validate!="function"):!1}):!1}}}},ne=function(e,T,d){return"The value for the "+T+" should be of type "+(Array.isArray(e)?e.join(" | "):e)+". "+(d||"")},se=function(){const e=function(l,_){return typeof l!="object"||l===null?this.freeze?Object.freeze(l):l:l instanceof Date?this.freeze?Object.freeze(new Date(l)):new Date(l):_.call(this,l)},T=function(l,_){const a=Object.keys(l),w=new Array(a.length);for(let b=0;b<a.length;b++)w[a[b]]=e.call(this,l[a[b]],_);return w},d=function(l){return e.call(this,l,function(_){if(Array.isArray(_))return T.call(this,_,d);const a={};for(let w in _)!this.withProto&&Object.hasOwnProperty.call(_,w)===!1||(a[w]=e.call(this,_[w],d));return a})},M=function(){const l=function(a){const w=["withProto","freeze"];this[a]=w.reduce((function(b,R){return(b[R]=a>=this[R])&&(a-=this[R]),b}).bind(this),{})},_=Object.create(Object.defineProperties({},{withProto:{value:1},freeze:{value:2}}));for(let a=0;a<=3;a++)l.call(_,a);return _}(),V={withProto:d.bind(M[1]),andFreeze:d.bind(M[2]),withProtoAndFreeze:d.bind(M[3])},D=d.bind(M[0]);for(let l in V)Object.defineProperty(D,l,{enumerable:!1,writable:!1,configurable:!1,value:V[l]});return D}(),fe={SINGLE_LINE_HIGHLIGHT_CLASS:"editableArea--single-line",MULTI_LINE_HIGHLIGHT_CLASS:"editableArea--multi-line"},xe=function(e,T,d){const M=d.Range,V=function(s,g){const c=s.range,f=g.range;if(c[0]<f[0]||c[0]===f[0]&&c[3]<f[1])return-1},D=function(s,g){const c=g.split(`
|
|
2
|
+
`),f=c.length,h=[];return s.forEach(function(C,S){if(C===0)throw new Error("Range values cannot be zero");switch(S){case 0:{if(C<0)throw new Error("Start Line of Range cannot be negative");if(C>f)throw new Error("Provided Start Line("+C+") is out of bounds. Max Lines in content is "+f);h[S]=C}break;case 1:{let N=C;const I=h[0],P=c[I-1].length;if(N<0){if(N=P-Math.abs(N),N<0)throw new Error("Provided Start Column("+C+") is out of bounds. Max Column in line "+I+" is "+P)}else if(N>P+1)throw new Error("Provided Start Column("+C+") is out of bounds. Max Column in line "+I+" is "+P);h[S]=N}break;case 2:{let N=C;if(N<0){if(N=f-Math.abs(C),N<0)throw new Error("Provided End Line("+C+") is out of bounds. Max Lines in content is "+f);N<h[0]&&console.warn("Provided End Line("+C+") is less than the start Line, the Restriction may not behave as expected")}else if(C>f)throw new Error("Provided End Line("+C+") is out of bounds. Max Lines in content is "+f);h[S]=N}break;case 3:{let N=C;const I=h[2],P=c[I-1].length;if(N<0){if(N=P-Math.abs(N),N<0)throw new Error("Provided End Column("+C+") is out of bounds. Max Column in line "+I+" is "+P)}else if(N>P+1)throw new Error("Provided Start Column("+C+") is out of bounds. Max Column in line "+I+" is "+P);h[S]=N}break}}),h};let l=se(T).sort(V);const _=function(s){const g=e.getValue();s.forEach(function(c,f){const h=D(c.range,g),C=h[0],S=h[1],N=h[2],I=h[3];c._originalRange=h.slice(),c.range=new M(C,S,N,I),c.index=f,c.allowMultiline||(c.allowMultiline=M.spansMultipleLines(c.range)),c.label||(c.label=`[${C},${S} -> ${N}${I}]`)})},a=function(){return l.reduce(function(s,g){return s[g.label]={allowMultiline:g.allowMultiline||!1,index:g.index,range:Object.assign({},g.range),originalRange:g._originalRange.slice()},s},{})},w=function(){return l.reduce(function(s,g){return s[g.label]=e.getValueInRange(g.range),s},{})},b=function(s,g){if(typeof s=="object"&&!Array.isArray(s)){g=typeof g=="boolean"?g:!1;const c=l.reduce(function(f,h){return h.label&&(f[h.label]=h),f},{});for(let f in s){const h=c[f];if(h){const C=s[f];if(Y(h,C))throw new Error("Multiline change is not allowed for "+f);const S=se(h.range);if(S.endLine=S.startLine+C.split(`
|
|
3
|
+
`).length-1,S.endColumn=C.split(`
|
|
4
|
+
`).pop().length,k(h,C,S))throw new Error("Change is invalidated by validate function of "+f);e.applyEdits([{forceMoveMarkers:!!g,range:h.range,text:C}])}else console.error("No restriction found for "+f)}}else throw new Error("Value must be an object")},R=function(){return e._restrictionChangeListener.dispose(),window.removeEventListener("error",L),delete e.editInRestrictedArea,delete e.disposeRestrictions,delete e.getValueInEditableRanges,delete e.updateValueInEditableRanges,delete e.updateRestrictions,delete e.getCurrentEditableRanges,delete e.toggleHighlightOfEditableAreas,delete e._hasHighlight,delete e._isRestrictedModel,delete e._isCursorAtCheckPoint,delete e._currentCursorPositions,delete e._editableRangeChangeListener,delete e._restrictionChangeListener,delete e._oldDecorations,delete e._oldDecorationsSource,e},q=function(s){s.some(function(g){const c=g.lineNumber,f=g.column,h=l.length;for(let C=0;C<h;C++){const S=l[C].range;if(S.startLineNumber===c&&S.startColumn===f||S.endLineNumber===c&&S.endColumn===f)return e.pushStackElement(),!0}})},$=function(s){typeof s=="function"&&e._editableRangeChangeListener.push(s)},v=function(s,g){const c=a();e._editableRangeChangeListener.forEach(function(f){f.call(e,s,g,c)})},O=function(){return Promise.resolve().then(function(){e.editInRestrictedArea=!0,e.undo(),e.editInRestrictedArea=!1,e._hasHighlight&&e._oldDecorationsSource&&(e.deltaDecorations(e._oldDecorations,e._oldDecorationsSource),e._oldDecorationsSource.forEach(function(s){s.range=e.getDecorationRange(s.id)}))})},G=function(s,g,c,f,h,C){let S=g.endLineNumber,N=g.endColumn;s.prevRange=g,s.range=g.setEndPosition(c,f);const I=l.length;let P=h.length;const j=f-N,U=c-S,t=e._currentCursorPositions||[],p=t.length;if(P!==p&&(h=h.filter(function(r){const o=r.range;for(let n=0;n<p;n++){const E=t[n];if(o.startLineNumber===E.startLineNumber&&o.endLineNumber===E.endLineNumber&&o.startColumn===E.startColumn&&o.endColumn===E.endColumn)return!0}return!1}),P=h.length),U!==0){for(let r=s.index+1;r<I;r++){const o=l[r],n=o.range;S===n.startLineNumber&&(n.startColumn+=j),S===n.endLineNumber&&(n.endColumn+=j),n.startLineNumber+=U,n.endLineNumber+=U,o.range=n}for(let r=C+1;r<P;r++){const o=h[r],n=o.range,E=n.toString(),A=rangeMap[E];delete rangeMap[E],S===n.startLineNumber&&(n.startColumn+=j),S===n.endLineNumber&&(n.endColumn+=j),n.startLineNumber+=U,n.endLineNumber+=U,o.range=n,rangeMap[n.toString()]=A}}else{for(let r=s.index+1;r<I;r++){const o=l[r],n=o.range;if(n.startLineNumber>S)break;n.startColumn+=j,n.endColumn+=j,o.range=n}for(let r=C+1;r<P;r++){const o=h[r],n=o.range,E=n.toString(),A=rangeMap[E];if(delete rangeMap[E],n.startLineNumber>S){rangeMap[n.toString()]=A;break}else n.startColumn+=j,n.endColumn+=j,o.range=n,rangeMap[n.toString()]=A}}},F=function(s,g){const c={},f=s.range;return s.text===""?c.isDeletion=!0:f.startLineNumber===f.endLineNumber&&f.startColumn===f.endColumn?c.isAddition=!0:c.isReplacement=!0,c.startLineOfRange=f.startLineNumber===g.startLineNumber,c.startColumnOfRange=f.startColumn===g.startColumn,c.endLineOfRange=f.endLineNumber===g.endLineNumber,c.endColumnOfRange=f.endColumn===g.endColumn,c.middleLineOfRange=!c.startLineOfRange&&!c.endLineOfRange,g.startLineNumber===g.endLineNumber?c.rangeIsSingleLine=!0:c.rangeIsMultiLine=!0,c},K=function(s){l=se(s).sort(V),_(l)},m=function(s){if(e._hasHighlight)e.deltaDecorations(e._oldDecorations,[]),delete e._oldDecorations,delete e._oldDecorationsSource,e._hasHighlight=!1;else{const g=s.cssClassForSingleLine||fe.SINGLE_LINE_HIGHLIGHT_CLASS,c=s.cssClassForMultiLine||fe.MULTI_LINE_HIGHLIGHT_CLASS,f=l.map(function(h){const C={range:h.range,options:{className:h.allowMultiline?c:g}};return h.label&&(C.hoverMessage=h.label),C});e._oldDecorations=e.deltaDecorations([],f),e._oldDecorationsSource=f.map(function(h,C){return Object.assign({},h,{id:e._oldDecorations[C]})}),e._hasHighlight=!0}},L=function(){console.debug("handler for unhandled promise rejection")},z=function(s){for(let g in s){const c=s[g];c.range=c.prevRange}},Y=function(s,g){return!s.allowMultiline&&g.includes(`
|
|
5
|
+
`)},k=function(s,g,c){return s.validate&&!s.validate(g,c,s.lastInfo)},J={_isRestrictedModel:!0,_isRestrictedValueValid:!0,_editableRangeChangeListener:[],_isCursorAtCheckPoint:q,_currentCursorPositions:[]};_(l),e._hasHighlight=!1,J._restrictionChangeListener=e.onDidChangeContent(function(s){const g=s.isUndoing;if(e._isRestrictedValueValid=!0,g&&e.editInRestrictedArea)e.editInRestrictedArea&&(e._isRestrictedValueValid=!1);else{const c=s.changes.sort(V),f={},h=l.length;if(c.every(function(S){const N=S.range,I=N.toString();f[I]=null;for(let P=0;P<h;P++){const j=l[P];if(j.range.containsRange(N))return Y(j,S.text)?!1:(f[I]=j,!0)}return!1})){c.forEach(function(I,P){const j=I.range,U=f[j.toString()],t=U.range,p=I.text||"",r=(p.match(/\n/g)||[]).length,o=p.split(/\n/g).pop().length,n=j.endLineNumber-j.startLineNumber,E=j.endColumn-j.startColumn;let A=t.endLineNumber,x=t.endColumn,i=0;(t.endLineNumber===j.startLineNumber||t.endLineNumber===j.endLineNumber)&&(i+=t.endColumn-j.startColumn+1);const u=F(I,t);U.lastInfo=u,(u.isAddition||u.isReplacement)&&(u.rangeIsSingleLine&&(r===0?x+=o:(A+=r,u.startColumnOfRange?x+=o:u.endColumnOfRange?x=o+1:x=o+i)),u.rangeIsMultiLine&&(A+=r,u.endLineOfRange&&(r===0?x+=o:x=i+o))),(u.isDeletion||u.isReplacement)&&(u.rangeIsSingleLine&&(x-=E),u.rangeIsMultiLine&&(u.endLineOfRange?(A-=n,x-=E):A-=n)),G(U,t,A,x,c,P)});const S=e.getValueInEditableRanges(),N={};for(let I in f){const P=f[I],j=P.range,U=P.label||j.toString(),t=S[U];if(k(P,t,j)){z(f),O();return}N[U]=t}e._hasHighlight&&e._oldDecorationsSource.forEach(function(I){I.range=e.getDecorationRange(I.id)}),v(N,S)}else O()}}),window.onerror=L;const Z={editInRestrictedArea:!1,getCurrentEditableRanges:a,getValueInEditableRanges:w,disposeRestrictions:R,onDidChangeContentInEditableRange:$,updateRestrictions:K,updateValueInEditableRanges:b,toggleHighlightOfEditableAreas:m};for(let s in J)Object.defineProperty(e,s,{enumerable:!1,configurable:!0,writable:!0,value:J[s]});for(let s in Z)Object.defineProperty(e,s,{enumerable:!1,configurable:!0,writable:!0,value:Z[s]});return e};function _e(e){if(e===void 0)throw new Error(["Please pass the monaco global variable into function as","(eg:)constrainedEditor({ range : monaco.range });"].join(`
|
|
6
|
+
`));const T=function(v){const O=v.getModel();if(O._isCursorAtCheckPoint){const G=v.getSelections(),F=G.map(function(K){return{lineNumber:K.positionLineNumber,column:K.positionColumn}});O._isCursorAtCheckPoint(F),O._currentCursorPositions=G}},d={},{isInstanceValid:M,isModelValid:V,isRangesValid:D}=De.initWith(e),l=function(v){if(M(v)){let O=v.getDomNode();return R._listener=T.bind(q,v),R._editorInstance=v,R._editorInstance._isInDevMode=!1,O.addEventListener("keydown",R._listener,!0),R._onChangeModelDisposable=v.onDidChangeModel(function(){O&&O.removeEventListener("keydown",R._listener,!0);const G=v.getDomNode();G&&G.addEventListener("keydown",R._listener,!0),O=G}),!0}else throw new Error(ne("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},_=function(v,O){if(V(v))if(D(O)){const G=xe(v,O,e);return d[G.uri.toString()]=G,G}else throw new Error(ne("Array<RangeRestrictionObject>","ranges","Please refer constrained editor documentation for proper structure"));else throw new Error(ne("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},a=function(v){if(V(v)){const O=v.uri.toString(),G=d[O];return G?G.disposeRestrictions():(console.warn("Current Model is not a restricted Model"),!1)}else throw new Error(ne("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},w=function(){if(R._editorInstance){const O=R._editorInstance.getDomNode();O&&O.removeEventListener("keydown",R._listener),R._onChangeModelDisposable&&R._onChangeModelDisposable.dispose(),delete R._listener,delete R._editorInstance._isInDevMode,delete R._editorInstance._devModeAction,delete R._editorInstance,delete R._onChangeModelDisposable;for(let G in d)delete d[G];return!0}return!1},b=function(){R._editorInstance._isInDevMode?(R._editorInstance._isInDevMode=!1,R._editorInstance._devModeAction.dispose(),delete R._editorInstance._devModeAction):(R._editorInstance._isInDevMode=!0,R._editorInstance._devModeAction=R._editorInstance.addAction({id:"showRange",label:"Show Range in console",contextMenuGroupId:"navigation",contextMenuOrder:1.5,run:function(v){const G=v.getSelections().reduce(function(F,{startLineNumber:K,endLineNumber:m,startColumn:L,endColumn:z}){return F.push("range : "+JSON.stringify([K,L,m,z])),F},[]).join(`
|
|
7
|
+
`);console.log(`Selected Ranges :
|
|
8
|
+
`+JSON.stringify(G,null,2))}}))},R={_listener:null,_editorInstance:null,_uriRestrictionMap:d,_injectedResources:e},q=Object.create(R),$={initializeIn:l,addRestrictionsTo:_,removeRestrictionsIn:a,disposeConstrainer:w,toggleDevMode:b};for(let v in $)Object.defineProperty(q,v,{enumerable:!1,writable:!1,configurable:!1,value:$[v]});return Object.freeze(q)}function Ie({document:e,readOnly:T=!1,onChange:d}){const M=y.useRef(null),V=y.useRef(null),D=y.useRef(null),{theme:l}=be(),[_,a]=Q.useState(!1),w=X(m=>m.pendingDiffs[e.name]),b=X(m=>m.clearPendingDiff),R=X(m=>m.saveDocument),{registerEditor:q,unregisterEditor:$,setActiveEditor:v}=re(),O=l==="system"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":l,G=y.useCallback(m=>{console.log("Monaco theme editor will mount"),V.current=m,a(!0)},[]),F=y.useCallback((m,L)=>{M.current=m,D.current=m.getModel(),q(e.name,m,L),v(e.name);const z=_e(L);m.getModel()&&z.initializeIn(m),m.updateOptions({formatOnType:!0,formatOnPaste:!0,automaticLayout:!0,minimap:{enabled:!1},scrollBeyondLastLine:!0,wordWrap:"on",folding:!0,foldingStrategy:"indentation",suggest:{showColors:!0,showConstants:!0,showEnums:!0,showFields:!0,showFunctions:!0,showKeywords:!0,showModules:!0,showProperties:!0,showSnippets:!0,showStructs:!0,showTypeParameters:!0,showUnits:!0,showValues:!0,showVariables:!0}}),m.addCommand(L.KeyMod.CtrlCmd|L.KeyCode.KeyK,()=>{const k=ce(m,L);if(k){const J=le(k);window.dispatchEvent(new CustomEvent("monaco-selection-to-ai",{detail:{documentName:e.name,selection:k,snippet:J,isTheme:!0}}))}}),m.addCommand(L.KeyMod.CtrlCmd|L.KeyCode.KeyS,()=>{console.log("Save command triggered in theme editor")}),m.addAction({id:"send-theme-to-ai-assistant",label:"Send to AI Assistant (⌘K)",contextMenuGroupId:"navigation",contextMenuOrder:1.5,keybindings:[L.KeyMod.CtrlCmd|L.KeyCode.KeyK],run:function(){const k=ce(m,L);if(k){const J=le(k);window.dispatchEvent(new CustomEvent("monaco-selection-to-ai",{detail:{documentName:e.name,selection:k,snippet:J,isTheme:!0}}))}}}),setTimeout(()=>{var k;(k=m.getAction("editor.action.formatDocument"))==null||k.run()},100),console.log("Monaco theme editor mounted")},[e.name,q,v]);y.useEffect(()=>()=>{$(e.name)},[e.name,$]);const K=y.useCallback((m,L)=>{m!==void 0&&d&&d(m)},[d]);return y.useEffect(()=>{if(!M.current||!V.current||!D.current||!_)return;const m=V.current,L=D.current;m.editor.setModelMarkers(L,"theme-validation",[]);const z=we(e.text);if(!z.valid&&z.errors){const Y=z.errors.map(k=>({severity:m.MarkerSeverity.Error,startLineNumber:k.line||1,startColumn:k.column||1,endLineNumber:k.line||1,endColumn:k.column||1e3,message:k.message,source:"theme-validation"}));m.editor.setModelMarkers(L,"theme-validation",Y)}},[e.text,_]),y.useEffect(()=>{if(M.current){const m=O==="dark"?"vs-dark":"vs";M.current.updateOptions({theme:m})}},[O]),B.jsx("div",{className:"relative h-full",children:w?B.jsxs(B.Fragment,{children:[B.jsxs("div",{className:"flex items-center justify-between px-2 py-1 border-b bg-muted/40 text-xs",children:[B.jsxs("div",{children:["Review changes for"," ",B.jsx("span",{className:"font-medium",children:e.name})]}),B.jsxs("div",{className:"flex gap-2",children:[B.jsx(ue,{variant:"secondary",size:"sm",onClick:()=>b(e.name),children:"Discard"}),B.jsx(ue,{size:"sm",onClick:()=>{R(e.name,w.modified),b(e.name,!0)},children:"Apply Changes"})]})]}),B.jsx(Ee,{height:"calc(100% - 32px)",original:w.original,modified:w.modified,language:"json",theme:O==="dark"?"vs-dark":"vs",options:{readOnly:!0,renderSideBySide:!0,originalEditable:!1,automaticLayout:!0,minimap:{enabled:!1}},beforeMount:G})]}):B.jsx(Ce,{height:"100%",language:"json",defaultPath:e.name,value:e.text,theme:O==="dark"?"vs-dark":"vs",onChange:K,beforeMount:G,onMount:F,options:{readOnly:T,lineNumbers:"on",glyphMargin:!0,folding:!0,lineDecorationsWidth:5,lineNumbersMinChars:3,renderValidationDecorations:"on",quickSuggestions:{other:!0,comments:!1,strings:!0},acceptSuggestionOnCommitCharacter:!0,acceptSuggestionOnEnter:"on",accessibilitySupport:"auto",autoIndent:"advanced",formatOnType:!0,formatOnPaste:!0,automaticLayout:!0,minimap:{enabled:!1},scrollBeyondLastLine:!0,wordWrap:"on"}})})}const Pe=Q.memo(Ie);function Ae({name:e,text:T,buildError:d,saveDocumentDebounceWait:M,documentType:V}){const{saveDocument:D}=X(b=>b),{updateTheme:l}=ge(b=>b),_=Q.useMemo(()=>he(l,M),[l,M]);Q.useEffect(()=>()=>{_.flush()},[_]);const a=Q.useCallback(b=>{D(e,b),V==="application/json+theme"&&(console.log("TabContent: Theme document change detected, debouncing update",{documentName:e,debounceWait:M}),_(e,b))},[e,D,_,V,M]),w=Q.useMemo(()=>({name:e,type:"application/json",text:T,mtime:new Date,ctime:new Date,atime:new Date}),[e,T]);return B.jsx(Me,{value:e,className:"mt-0 h-full p-0",tabIndex:-1,children:V==="application/json+theme"?B.jsx(Pe,{document:w,onChange:a}):B.jsx(pe,{name:e,value:T,saveDocumentDebounceWait:M})})}const Oe=Q.memo(Ae);function ke({openTabs:e,documents:T,buildErrors:d,saveDocumentDebounceWait:M}){const{documentTypes:V}=X(D=>D);return e.map(D=>T.find(l=>l.name===D)).filter(D=>D!==void 0).map(D=>{const l=V[D.name]||"application/json+report";return B.jsx(Oe,{name:D.name,text:D.text,buildError:d[D.name],saveDocumentDebounceWait:M,documentType:l},D.name)})}const je=Q.memo(ke);class Ve extends Error{constructor(T,d,M){super(T),this.lastError=d,this.attempts=M,this.name="RetryError"}}async function Ge(e,T={}){const{maxRetries:d=3,initialDelay:M=1e3,maxDelay:V=3e4,backoffFactor:D=2,onRetry:l,shouldRetry:_=()=>!0,signal:a}=T;let w;for(let b=0;b<=d;b++)try{if(a!=null&&a.aborted)throw new Error("Operation cancelled");return await e()}catch(R){if(w=R instanceof Error?R:new Error(String(R)),b===d)break;if(!_(w))throw w;const $=Math.min(M*Math.pow(D,b),V)*(.5+Math.random()*.5);l&&l(w,b+1),await new Promise(v=>{const O=setTimeout(v,$);a&&a.addEventListener("abort",()=>{clearTimeout(O),v(void 0)},{once:!0})})}throw new Ve(`Failed after ${d+1} attempts`,w,d+1)}const me={networkErrors:e=>["NetworkError","Failed to fetch","ERR_NETWORK","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","fetch failed"].some(d=>e.message.includes(d)||e.name.includes(d)),httpStatusCodes:e=>T=>{var d;return(d=T.response)!=null&&d.status?e.includes(T.response.status):!1},temporaryErrors:e=>["EBUSY","EAGAIN","temporarily unavailable","too many requests","rate limit"].some(d=>e.message.toLowerCase().includes(d.toLowerCase())),combine:(...e)=>T=>e.some(d=>d(T))};function He(){const e=ye(t=>t.setOutput),T=y.useContext(Re),d=y.useContext(ve),M=y.useContext(Te),V=oe(t=>t.saveDocumentDebounceWait),D=oe(t=>t.autoReload),l=oe(t=>t.renderingLibrary),{openTabs:_,activeTab:a,setActiveTab:w,documents:b,buildErrors:R,setBuildError:q,documentTypes:$}=X(de(t=>({openTabs:t.openTabs,activeTab:t.activeTab,setActiveTab:t.setActiveTab,documents:t.documents,buildErrors:t.buildErrors,setBuildError:t.setBuildError,documentTypes:t.documentTypes}))),{customThemes:v,getAllThemeNames:O,getTheme:G}=ge(de(t=>({customThemes:t.customThemes,getAllThemeNames:t.getAllThemeNames,getTheme:t.getTheme}))),{generatePresentation:F,cancelGeneration:K}=Le(),m=y.useRef(new Map),L=y.useRef(new Map),z=y.useRef(""),Y=y.useRef(new Map),k=y.useCallback(t=>{const r=(Y.current.get(t)||0)+1;return Y.current.set(t,r),r},[]),J=y.useCallback(async(t,p)=>{if(!t||!F)return;const r=m.current.get(t.name);r&&(r.abort(),m.current.delete(t.name));const o=new AbortController,n=o.signal;m.current.set(t.name,o);const E=`${t.name}-theme-${Date.now()}-${Math.random()}`,A=k(t.name);z.current=E,console.log("Editor: Starting theme-triggered build with fresh data",{docName:t.name,requestId:E,freshThemeCount:Object.keys(p).length,version:A});const x={id:E,docName:t.name,doc:t,signal:n,timestamp:Date.now()};await s.current(x,A,p)},[F,e,k]),Z=y.useCallback(async(t,p,r)=>{var x;const{doc:o,signal:n,id:E}=t;e({globalError:void 0,isGenerating:!0,generationProgress:{stage:"parsing",message:"Rebuilding with updated theme..."}});const A=(i,u)=>{n.aborted||z.current!==E||e({isGenerating:!0,generationProgress:{stage:i,message:u}})};try{console.log("Editor: Generating document with fresh themes",{docName:o.name,themeNames:Object.keys(r),requestId:E});const i=await F(o.name,o.text,r,A,{bypassCache:!0});if(n.aborted||z.current!==E){console.log("Theme build cancelled for:",o.name),e({isGenerating:!1,generationProgress:void 0});return}i&&typeof i=="object"&&"name"in i&&"text"in i&&"blob"in i&&(console.log("Editor: Theme-triggered build completed",{docName:i.name,blobSize:(x=i.blob)==null?void 0:x.size,timestamp:Date.now(),requestId:E}),e({name:i.name,text:i.text,blob:i.blob,globalError:void 0,isGenerating:!1,isPreviewStale:!1,generationProgress:void 0,lastBuiltSequence:T.getState().editSequence,cacheStatus:i.cacheStatus,cacheHitRate:i.cacheHitRate,warnings:i.warnings}),q(i.name,void 0))}catch(i){if(n.aborted||z.current!==E){console.log("Theme build cancelled with error for:",o.name),e({isGenerating:!1,generationProgress:void 0});return}const u=i instanceof Error?i.message:String(i);console.error("Theme build error:",u),e({globalError:`Theme rebuild failed: ${u}`,isGenerating:!1,generationProgress:void 0}),q(o.name,u)}finally{m.current.delete(o.name)}},[F,e,q,T]),s=y.useRef(Z);y.useEffect(()=>{s.current=Z});const g=y.useMemo(()=>{const t=Object.entries(v).map(([p,r])=>{let o=0;return r.lastModified&&(r.lastModified instanceof Date?o=r.lastModified.getTime():typeof r.lastModified=="string"&&(o=new Date(r.lastModified).getTime())),{key:p,name:r.name,content:r.content,valid:r.valid,lastModified:o}});return JSON.stringify(t)},[v]),c=y.useMemo(()=>{const t={};return Object.values(v).forEach(p=>{p.valid&&p.parsed&&(t[p.name]=p.parsed)}),t},[g]),f=y.useCallback(()=>{const t={},{customThemes:p}=M.getState();return Object.values(p).forEach(r=>{r.valid&&r.parsed&&(t[r.name]=r.parsed)}),t},[M]),h=y.useCallback(async(t,p,r)=>{if(!t||!F)return;const o=m.current.get(t.name);o&&(o.abort(),m.current.delete(t.name));const n=p?null:new AbortController,E=p||n.signal;n&&m.current.set(t.name,n);const A=`${t.name}-${Date.now()}-${Math.random()}`,x=k(t.name);z.current=A;const i={id:A,docName:t.name,doc:t,signal:E,timestamp:Date.now()};await S.current(i,x,r)},[F,e,k]),C=y.useCallback(async(t,p,r)=>{var x;const{doc:o,signal:n,id:E}=t;if(z.current!==E){console.log("Skipping outdated build request for:",o.name),e({isGenerating:!1,generationProgress:void 0});return}e({globalError:void 0,isGenerating:!0,generationProgress:{stage:"parsing",message:"Validating JSON structure..."}});const A=(i,u)=>{if(n.aborted||z.current!==E)return;if((Y.current.get(o.name)||0)!==p){console.log("Document version changed, aborting build"),n.dispatchEvent(new Event("abort"));return}e({isGenerating:!0,generationProgress:{stage:i,message:u}})};try{const i=f();console.log("Editor: Using themes for document build",{docName:o.name,freshThemeCount:Object.keys(i).length,freshThemeNames:Object.keys(i),memoizedCount:Object.keys(c).length,requestId:E});const u=await Ge(async()=>{if(n.aborted)throw new Error("Build cancelled");return await F(o.name,o.text,i,A,r)},{maxRetries:2,initialDelay:500,shouldRetry:H=>H.message.includes("cancelled")||H.message.includes("JSON")||H.message.includes("parse")||H.message.includes("syntax")?!1:me.combine(me.temporaryErrors,W=>W.message.includes("Worker")||W.message.includes("Proxy"))(H),onRetry:(H,W)=>{console.log(`Retrying presentation generation (attempt ${W}):`,H.message),e({isGenerating:!0,generationProgress:{stage:"parsing",message:`Retrying generation (attempt ${W})...`}})},signal:n});if(n.aborted||z.current!==E){console.log("Build cancelled for:",o.name),e({isGenerating:!1,generationProgress:void 0});return}u&&typeof u=="object"&&"name"in u&&"text"in u&&"blob"in u&&(console.log("Editor: Build completed",{docName:u.name,blobSize:(x=u.blob)==null?void 0:x.size,timestamp:Date.now(),requestId:E,version:p}),e({name:u.name,text:u.text,blob:u.blob,globalError:void 0,isGenerating:!1,isPreviewStale:!1,generationProgress:void 0,lastBuiltSequence:T.getState().editSequence,cacheStatus:u.cacheStatus,cacheHitRate:u.cacheHitRate,warnings:u.warnings}),q(u.name,void 0))}catch(i){if(n.aborted||z.current!==E){console.log("Build cancelled with error for:",o.name),e({isGenerating:!1,generationProgress:void 0});return}const u=i instanceof Error?i.message:String(i);e({globalError:u,isGenerating:!1,generationProgress:void 0}),q(o.name,u)}finally{m.current.delete(o.name)}},[F,f,e,q,T]),S=y.useRef(C);y.useEffect(()=>{S.current=C});const N=y.useRef(null);y.useEffect(()=>{console.log("Editor: Document rebuild effect triggered",{activeTab:a});const t=b.find(o=>o.name===a),p=$[a]||"application/json+report";p==="application/json+report"&&t&&(N.current=a);const r=L.current.get(a);if(r&&(clearTimeout(r),L.current.delete(a)),t&&p==="application/json+report")if(!D||l!=="docxjs")T.getState().isGenerating||e({isPreviewStale:!0});else{const o=t.text.length,n=o>1e4?300:o>5e3?200:100;m.current.forEach((A,x)=>{x!==a&&(A.abort(),m.current.delete(x))});const E=setTimeout(()=>{console.log("Editor: Triggering document build after debounce",{docName:t.name,debounceTime:n}),L.current.delete(a),k(t.name),h(t)},n);L.current.set(a,E)}else t&&p==="application/json+theme"&&K();return()=>{const o=L.current.get(a);o&&(clearTimeout(o),L.current.delete(a))}},[b,a,e,$,h,K,D,l]);const I=y.useMemo(()=>{var r;const t=new Map,p=b.find(o=>o.name===a);if(p&&$[p.name]==="application/json+report")try{const n=(r=JSON.parse(p.text).props)==null?void 0:r.theme;typeof n=="string"&&Object.values(v).some(A=>A.name===n&&A.valid)&&t.set(p.name,n)}catch{}return t},[a,b,$,v]);y.useEffect(()=>(console.log("Editor: Setting up theme change listener",{documentCount:b.length,dependencyCount:I.size,dependencies:Array.from(I.entries()),customThemes:Object.entries(v).map(([p,r])=>({key:p,name:r.name,valid:r.valid}))}),Se.onThemeChange(p=>{console.log("Editor: Theme change detected",{event:p,dependencies:Array.from(I.entries()),activeTab:a,customThemes:Object.entries(v).map(([i,u])=>({key:i,name:u.name,valid:u.valid}))});const r=[];if(I.forEach((i,u)=>{if(i===p.themeName){const H=b.find(W=>W.name===u);H&&r.push(H)}}),console.log("Editor: Documents using changed theme",{themeName:p.themeName,documentCount:r.length,documentNames:r.map(i=>i.name)}),r.length===0){console.log("Editor: No documents use this theme, skipping rebuild");return}const o=600,n=r.find(i=>i.name===a);if(!n){r.length>0&&e({isPreviewStale:!0});return}if(!D||l!=="docxjs"){T.getState().isGenerating||e({isPreviewStale:!0});return}console.log("Editor: Rebuilding only active document",{activeDocName:n.name,themeName:p.themeName,totalDocumentsUsingTheme:r.length}),["theme-event","backup",n.name].forEach(i=>{const u=`${i}-${n.name}`,H=L.current.get(u);H&&(clearTimeout(H),L.current.delete(u))});const E=m.current.get(n.name);E&&(E.abort(),m.current.delete(n.name));const A=`theme-event-${n.name}`,x=setTimeout(()=>{L.current.delete(A),console.log("Editor: Force rebuilding active document due to theme change",{docName:n.name,themeName:p.themeName,timestamp:Date.now()});const i={};O().forEach(H=>{const W=G(H);W&&(i[H]=W)}),console.log("Editor: Using fresh theme data for rebuild",{freshThemeCount:Object.keys(i).length,freshThemeNames:Object.keys(i),memoizedCount:Object.keys(c).length}),k(n.name),J(n,i)},o);L.current.set(A,x)})),[I,b,h,k,a,O,G,J,c,D,l,e]);const P=y.useRef(null),j=y.useRef(h);y.useEffect(()=>{j.current=h});const U=y.useRef(k);return y.useEffect(()=>{U.current=k}),y.useEffect(()=>{const t=()=>{e({isGenerating:!0});let p=!1;const r=re.getState().getActiveEditor();if(r&&!d.getState().pendingDiffs[r.documentName]){const i=r.editor.getValue();d.getState().saveDocument(r.documentName,i)}const{documents:o,documentTypes:n}=d.getState();for(const x of o)if(n[x.name]==="application/json+theme"){const i=re.getState().getEditor(x.name);if(i){const u=i.editor.getValue(),H=M.getState().customThemes[x.name];(!H||H.content!==u)&&(M.getState().updateTheme(x.name,u),p=!0)}}const E=d.getState().activeTab,A=L.current.get(E);A&&(clearTimeout(A),L.current.delete(E)),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{P.current=null;const{documents:x,activeTab:i,documentTypes:u}=d.getState();let H=i;if((u[i]||"application/json+report")==="application/json+theme")if(N.current)H=N.current;else{e({isGenerating:!1});return}const ee=x.find(te=>te.name===H);if(ee){const te=d.getState().pendingDiffs[H],ie=re.getState().getEditor(H),ae=te?{...ee,text:te.modified}:ie?{...ee,text:ie.editor.getValue()}:ee;U.current(ae.name),j.current(ae,void 0,p?{bypassCache:!0}:void 0)}else e({isGenerating:!1})},150)};return window.addEventListener("preview:flushAndBuild",t),()=>{window.removeEventListener("preview:flushAndBuild",t),P.current&&clearTimeout(P.current)}},[e,d,M]),y.useEffect(()=>()=>{m.current.forEach(t=>t.abort()),m.current.clear(),L.current.forEach(t=>clearTimeout(t)),L.current.clear(),K()},[K]),_.length?B.jsx(Ne,{value:a,onValueChange:w,className:"h-full",children:B.jsx(je,{openTabs:_,documents:b,buildErrors:R,saveDocumentDebounceWait:V})}):B.jsx("div",{className:"flex flex-col text-muted-foreground h-full items-center justify-center",children:b!=null&&b.length?"Open a document...":"Create a new document..."})}const Xe=y.memo(He);export{Xe as Editor};
|
|
9
|
+
//# sourceMappingURL=editor-CH_tiHyn.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"editor-CH_tiHyn.js","sources":["../../../../../node_modules/.pnpm/constrained-editor-plugin@1.4.0/node_modules/constrained-editor-plugin/dist/esm/utils/validators.js","../../../../../node_modules/.pnpm/constrained-editor-plugin@1.4.0/node_modules/constrained-editor-plugin/dist/esm/utils/definedErrors.js","../../../../../node_modules/.pnpm/constrained-editor-plugin@1.4.0/node_modules/constrained-editor-plugin/dist/esm/utils/deepClone.js","../../../../../node_modules/.pnpm/constrained-editor-plugin@1.4.0/node_modules/constrained-editor-plugin/dist/esm/utils/enums.js","../../../../../node_modules/.pnpm/constrained-editor-plugin@1.4.0/node_modules/constrained-editor-plugin/dist/esm/constrainedModel.js","../../../../../node_modules/.pnpm/constrained-editor-plugin@1.4.0/node_modules/constrained-editor-plugin/dist/esm/constrainedEditor.js","../../../src/client/components/json-editor/editor-monaco-theme.tsx","../../../src/client/components/playground/editor-tabs-content.tsx","../../../src/client/utils/retry.ts","../../../src/client/components/playground/editor.tsx"],"sourcesContent":["const validators = {\n initWith: function (monaco) {\n const dummyDiv = document.createElement('div');\n const dummyEditorInstance = monaco.editor.create(dummyDiv);\n const editorInstanceConstructorName = dummyEditorInstance.constructor.name;\n const editorModelConstructorName = dummyEditorInstance.getModel().constructor.name;\n const instanceCheck = function (valueToValidate) {\n return valueToValidate.constructor.name === editorInstanceConstructorName;\n }\n const modelCheck = function (valueToValidate) {\n return valueToValidate.constructor.name === editorModelConstructorName;\n }\n const rangesCheck = function (ranges) {\n if (Array.isArray(ranges)) {\n return ranges.every(function (rangeObj) {\n if (typeof rangeObj === 'object' && rangeObj.constructor.name === 'Object') {\n if (!rangeObj.hasOwnProperty('range')) return false;\n if (!Array.isArray(rangeObj.range)) return false;\n if (rangeObj.range.length !== 4) return false;\n if (!(rangeObj.range.every(num => num > 0 && parseInt(num) === num))) return false;\n if (rangeObj.hasOwnProperty('allowMultiline')) {\n if (typeof rangeObj.allowMultiline !== 'boolean') return false;\n }\n if (rangeObj.hasOwnProperty('label')) {\n if (typeof rangeObj.label !== 'string') return false;\n }\n if (rangeObj.hasOwnProperty('validate')) {\n if (typeof rangeObj.validate !== 'function') return false;\n }\n return true;\n }\n return false;\n });\n }\n return false;\n }\n return {\n isInstanceValid: instanceCheck,\n isModelValid: modelCheck,\n isRangesValid: rangesCheck\n }\n }\n}\nexport default validators;","export const TypeMustBe = function (type, key, additional) {\n return 'The value for the ' + key + ' should be of type ' + (Array.isArray(type) ? type.join(' | ') : type) + '. ' + (additional || '')\n}\nconst definedErrors = {\n TypeMustBe : TypeMustBe\n};\nexport default definedErrors;","export const deepClone = (function () {\n const byPassPrimitives = function (value, callback) {\n if (typeof value !== 'object' || value === null) {\n return this.freeze ? Object.freeze(value) : value;\n }\n if (value instanceof Date) {\n return this.freeze ? Object.freeze(new Date(value)) : new Date(value);\n }\n return callback.call(this, value);\n }\n const cloneArray = function (array, callback) {\n const keys = Object.keys(array);\n const arrayClone = new Array(keys.length)\n for (let i = 0; i < keys.length; i++) {\n arrayClone[keys[i]] = byPassPrimitives.call(this, array[keys[i]], callback);\n }\n return arrayClone;\n }\n const cloner = function (object) {\n return byPassPrimitives.call(this, object, function (object) {\n if (Array.isArray(object)) {\n return cloneArray.call(this, object, cloner)\n }\n const clone = {};\n for (let key in object) {\n if (!this.withProto && Object.hasOwnProperty.call(object, key) === false) {\n continue;\n }\n clone[key] = byPassPrimitives.call(this, object[key], cloner);\n }\n return clone;\n })\n }\n const config = (function () {\n const constructOptionForCode = function (value) {\n const options = [\n 'withProto',\n 'freeze'\n ]\n this[value] = options.reduce(function (acc, option) {\n if (acc[option] = (value >= this[option])) {\n value -= this[option]\n }\n return acc;\n }.bind(this), {})\n }\n const codes = Object.create(Object.defineProperties({}, {\n withProto: { value: 1 },\n freeze: { value: 2 }\n }));\n for (let i = 0; i <= 3; i++) {\n constructOptionForCode.call(codes, i);\n }\n return codes;\n }());\n const methods = {\n withProto: cloner.bind(config[1]),\n andFreeze: cloner.bind(config[2]),\n withProtoAndFreeze: cloner.bind(config[3])\n }\n const API = cloner.bind(config[0]);\n for (let methodName in methods) {\n Object.defineProperty(API, methodName, {\n enumerable: false,\n writable: false,\n configurable: false,\n value: methods[methodName]\n })\n }\n return API;\n}());\n\nexport default deepClone;","export const enums = {\n SINGLE_LINE_HIGHLIGHT_CLASS: 'editableArea--single-line',\n MULTI_LINE_HIGHLIGHT_CLASS: 'editableArea--multi-line'\n}\nexport default enums;","import deepClone from './utils/deepClone.js';\nimport enums from './utils/enums.js';\nexport const constrainedModel = function (model, ranges, monaco) {\n const rangeConstructor = monaco.Range;\n const sortRangesInAscendingOrder = function (rangeObject1, rangeObject2) {\n const rangeA = rangeObject1.range;\n const rangeB = rangeObject2.range;\n if (\n rangeA[0] < rangeB[0] ||\n (rangeA[0] === rangeB[0] && rangeA[3] < rangeB[1])\n ) {\n return -1;\n }\n }\n const normalizeRange = function (range, content) {\n const lines = content.split('\\n');\n const noOfLines = lines.length;\n const normalizedRange = [];\n range.forEach(function (value, index) {\n if (value === 0) {\n throw new Error('Range values cannot be zero');//No I18n\n }\n switch (index) {\n case 0: {\n if (value < 0) {\n throw new Error('Start Line of Range cannot be negative');//No I18n\n } else if (value > noOfLines) {\n throw new Error('Provided Start Line(' + value + ') is out of bounds. Max Lines in content is ' + noOfLines);//No I18n\n }\n normalizedRange[index] = value;\n }\n break;\n case 1: {\n let actualStartCol = value;\n const startLineNo = normalizedRange[0];\n const maxCols = lines[startLineNo - 1].length\n if (actualStartCol < 0) {\n actualStartCol = maxCols - Math.abs(actualStartCol);\n if (actualStartCol < 0) {\n throw new Error('Provided Start Column(' + value + ') is out of bounds. Max Column in line ' + startLineNo + ' is ' + maxCols);//No I18n\n }\n } else if (actualStartCol > (maxCols + 1)) {\n throw new Error('Provided Start Column(' + value + ') is out of bounds. Max Column in line ' + startLineNo + ' is ' + maxCols);//No I18n\n }\n normalizedRange[index] = actualStartCol;\n }\n break;\n case 2: {\n let actualEndLine = value;\n if (actualEndLine < 0) {\n actualEndLine = noOfLines - Math.abs(value);\n if (actualEndLine < 0) {\n throw new Error('Provided End Line(' + value + ') is out of bounds. Max Lines in content is ' + noOfLines);//No I18n\n }\n if (actualEndLine < normalizedRange[0]) {\n console.warn('Provided End Line(' + value + ') is less than the start Line, the Restriction may not behave as expected');//No I18n\n }\n } else if (value > noOfLines) {\n throw new Error('Provided End Line(' + value + ') is out of bounds. Max Lines in content is ' + noOfLines);//No I18n\n }\n normalizedRange[index] = actualEndLine;\n }\n break;\n case 3: {\n let actualEndCol = value;\n const endLineNo = normalizedRange[2];\n const maxCols = lines[endLineNo - 1].length\n if (actualEndCol < 0) {\n actualEndCol = maxCols - Math.abs(actualEndCol);\n if (actualEndCol < 0) {\n throw new Error('Provided End Column(' + value + ') is out of bounds. Max Column in line ' + endLineNo + ' is ' + maxCols);//No I18n\n }\n } else if (actualEndCol > (maxCols + 1)) {\n throw new Error('Provided Start Column(' + value + ') is out of bounds. Max Column in line ' + endLineNo + ' is ' + maxCols);//No I18n\n }\n normalizedRange[index] = actualEndCol;\n }\n break;\n }\n })\n return normalizedRange;\n }\n let restrictions = deepClone(ranges).sort(sortRangesInAscendingOrder);\n const prepareRestrictions = function (restrictions) {\n const content = model.getValue();\n restrictions.forEach(function (restriction, index) {\n const range = normalizeRange(restriction.range, content);\n const startLine = range[0];\n const startCol = range[1];\n const endLine = range[2];\n const endCol = range[3];\n restriction._originalRange = range.slice();\n restriction.range = new rangeConstructor(startLine, startCol, endLine, endCol);\n restriction.index = index;\n if (!restriction.allowMultiline) {\n restriction.allowMultiline = rangeConstructor.spansMultipleLines(restriction.range)\n }\n if (!restriction.label) {\n restriction.label = `[${startLine},${startCol} -> ${endLine}${endCol}]`;\n }\n });\n }\n const getCurrentEditableRanges = function () {\n return restrictions.reduce(function (acc, restriction) {\n acc[restriction.label] = {\n allowMultiline: restriction.allowMultiline || false,\n index: restriction.index,\n range: Object.assign({}, restriction.range),\n originalRange: restriction._originalRange.slice()\n };\n return acc;\n }, {});\n }\n const getValueInEditableRanges = function () {\n return restrictions.reduce(function (acc, restriction) {\n acc[restriction.label] = model.getValueInRange(restriction.range);\n return acc;\n }, {});\n }\n const updateValueInEditableRanges = function (object, forceMoveMarkers) {\n if (typeof object === 'object' && !Array.isArray(object)) {\n forceMoveMarkers = typeof forceMoveMarkers === 'boolean' ? forceMoveMarkers : false;\n const restrictionsMap = restrictions.reduce(function (acc, restriction) {\n if (restriction.label) {\n acc[restriction.label] = restriction;\n }\n return acc;\n }, {});\n for (let label in object) {\n const restriction = restrictionsMap[label];\n if (restriction) {\n const value = object[label];\n if (doesChangeHasMultilineConflict(restriction, value)) {\n throw new Error('Multiline change is not allowed for ' + label);\n }\n const newRange = deepClone(restriction.range);\n newRange.endLine = newRange.startLine + value.split('\\n').length - 1;\n newRange.endColumn = value.split('\\n').pop().length;\n if (isChangeInvalidAsPerUser(restriction, value, newRange)) {\n throw new Error('Change is invalidated by validate function of ' + label);\n }\n model.applyEdits([{\n forceMoveMarkers: !!forceMoveMarkers,\n range: restriction.range,\n text: value\n }]);\n } else {\n console.error('No restriction found for ' + label);\n }\n }\n } else {\n throw new Error('Value must be an object');//No I18n\n }\n }\n const disposeRestrictions = function () {\n model._restrictionChangeListener.dispose();\n window.removeEventListener(\"error\", handleUnhandledPromiseRejection);\n delete model.editInRestrictedArea;\n delete model.disposeRestrictions;\n delete model.getValueInEditableRanges;\n delete model.updateValueInEditableRanges;\n delete model.updateRestrictions;\n delete model.getCurrentEditableRanges;\n delete model.toggleHighlightOfEditableAreas;\n delete model._hasHighlight;\n delete model._isRestrictedModel;\n delete model._isCursorAtCheckPoint;\n delete model._currentCursorPositions;\n delete model._editableRangeChangeListener;\n delete model._restrictionChangeListener;\n delete model._oldDecorations;\n delete model._oldDecorationsSource;\n return model;\n }\n const isCursorAtCheckPoint = function (positions) {\n positions.some(function (position) {\n const posLineNumber = position.lineNumber;\n const posCol = position.column;\n const length = restrictions.length;\n for (let i = 0; i < length; i++) {\n const range = restrictions[i].range;\n if (\n (range.startLineNumber === posLineNumber && range.startColumn === posCol) ||\n (range.endLineNumber === posLineNumber && range.endColumn === posCol)\n ) {\n model.pushStackElement();\n return true;\n }\n }\n });\n };\n const addEditableRangeListener = function (callback) {\n if (typeof callback === 'function') {\n model._editableRangeChangeListener.push(callback);\n }\n };\n const triggerChangeListenersWith = function (currentChanges, allChanges) {\n const currentRanges = getCurrentEditableRanges();\n model._editableRangeChangeListener.forEach(function (callback) {\n callback.call(model, currentChanges, allChanges, currentRanges);\n });\n };\n const doUndo = function () {\n return Promise.resolve().then(function () {\n model.editInRestrictedArea = true;\n model.undo();\n model.editInRestrictedArea = false;\n if (model._hasHighlight && model._oldDecorationsSource) {\n // id present in the decorations info will be omitted by monaco\n // So we don't need to remove the old decorations id\n model.deltaDecorations(model._oldDecorations, model._oldDecorationsSource);\n model._oldDecorationsSource.forEach(function (object) {\n object.range = model.getDecorationRange(object.id);\n });\n }\n });\n };\n const updateRange = function (restriction, range, finalLine, finalColumn, changes, changeIndex) {\n let oldRangeEndLineNumber = range.endLineNumber;\n let oldRangeEndColumn = range.endColumn;\n restriction.prevRange = range;\n restriction.range = range.setEndPosition(finalLine, finalColumn);\n const length = restrictions.length;\n let changesLength = changes.length;\n const diffInCol = finalColumn - oldRangeEndColumn;\n const diffInRow = finalLine - oldRangeEndLineNumber;\n\n const cursorPositions = model._currentCursorPositions || [];\n const noOfCursorPositions = cursorPositions.length;\n // if (noOfCursorPositions > 0) {\n if (changesLength !== noOfCursorPositions) {\n changes = changes.filter(function (change) {\n const range = change.range;\n for (let i = 0; i < noOfCursorPositions; i++) {\n const cursorPosition = cursorPositions[i];\n if (\n (range.startLineNumber === cursorPosition.startLineNumber) &&\n (range.endLineNumber === cursorPosition.endLineNumber) &&\n (range.startColumn === cursorPosition.startColumn) &&\n (range.endColumn === cursorPosition.endColumn)\n ) {\n return true;\n }\n }\n return false;\n });\n changesLength = changes.length;\n }\n if (diffInRow !== 0) {\n for (let i = restriction.index + 1; i < length; i++) {\n const nextRestriction = restrictions[i];\n const nextRange = nextRestriction.range;\n if (oldRangeEndLineNumber === nextRange.startLineNumber) {\n nextRange.startColumn += diffInCol;\n }\n if (oldRangeEndLineNumber === nextRange.endLineNumber) {\n nextRange.endColumn += diffInCol;\n }\n nextRange.startLineNumber += diffInRow;\n nextRange.endLineNumber += diffInRow;\n nextRestriction.range = nextRange;\n }\n for (let i = changeIndex + 1; i < changesLength; i++) {\n const nextChange = changes[i];\n const rangeInChange = nextChange.range;\n const rangeAsString = rangeInChange.toString();\n const rangeMapValue = rangeMap[rangeAsString];\n delete rangeMap[rangeAsString];\n if (oldRangeEndLineNumber === rangeInChange.startLineNumber) {\n rangeInChange.startColumn += diffInCol;\n }\n if (oldRangeEndLineNumber === rangeInChange.endLineNumber) {\n rangeInChange.endColumn += diffInCol;\n }\n rangeInChange.startLineNumber += diffInRow;\n rangeInChange.endLineNumber += diffInRow;\n nextChange.range = rangeInChange;\n rangeMap[rangeInChange.toString()] = rangeMapValue;\n }\n } else {\n // Only Column might have changed\n for (let i = restriction.index + 1; i < length; i++) {\n const nextRestriction = restrictions[i];\n const nextRange = nextRestriction.range;\n if (nextRange.startLineNumber > oldRangeEndLineNumber) {\n break;\n } else {\n nextRange.startColumn += diffInCol;\n nextRange.endColumn += diffInCol;\n nextRestriction.range = nextRange;\n }\n }\n for (let i = changeIndex + 1; i < changesLength; i++) {\n // rangeMap\n const nextChange = changes[i];\n const rangeInChange = nextChange.range;\n const rangeAsString = rangeInChange.toString();\n const rangeMapValue = rangeMap[rangeAsString];\n delete rangeMap[rangeAsString];\n if (rangeInChange.startLineNumber > oldRangeEndLineNumber) {\n rangeMap[rangeInChange.toString()] = rangeMapValue;\n break;\n } else {\n rangeInChange.startColumn += diffInCol;\n rangeInChange.endColumn += diffInCol;\n nextChange.range = rangeInChange;\n rangeMap[rangeInChange.toString()] = rangeMapValue;\n }\n }\n }\n // }\n };\n const getInfoFrom = function (change, editableRange) {\n const info = {};\n const range = change.range;\n // Get State\n if (change.text === '') {\n info.isDeletion = true;\n } else if (\n (range.startLineNumber === range.endLineNumber) &&\n (range.startColumn === range.endColumn)\n ) {\n info.isAddition = true;\n } else {\n info.isReplacement = true;\n }\n // Get Position Of Range\n info.startLineOfRange = range.startLineNumber === editableRange.startLineNumber;\n info.startColumnOfRange = range.startColumn === editableRange.startColumn;\n\n info.endLineOfRange = range.endLineNumber === editableRange.endLineNumber;\n info.endColumnOfRange = range.endColumn === editableRange.endColumn;\n\n info.middleLineOfRange = !info.startLineOfRange && !info.endLineOfRange;\n\n // Editable Range Span\n if (editableRange.startLineNumber === editableRange.endLineNumber) {\n info.rangeIsSingleLine = true;\n } else {\n info.rangeIsMultiLine = true;\n }\n return info;\n };\n const updateRestrictions = function (ranges) {\n restrictions = deepClone(ranges).sort(sortRangesInAscendingOrder);\n prepareRestrictions(restrictions);\n };\n const toggleHighlightOfEditableAreas = function (cssClasses) {\n if (!model._hasHighlight) {\n const cssClassForSingleLine = cssClasses.cssClassForSingleLine ||enums.SINGLE_LINE_HIGHLIGHT_CLASS\n const cssClassForMultiLine = cssClasses.cssClassForMultiLine ||enums.MULTI_LINE_HIGHLIGHT_CLASS\n const decorations = restrictions.map(function (restriction) {\n const decoration = {\n range: restriction.range,\n options: {\n className: restriction.allowMultiline ?\n cssClassForMultiLine :\n cssClassForSingleLine\n }\n }\n if (restriction.label) {\n decoration.hoverMessage = restriction.label;\n }\n return decoration;\n });\n model._oldDecorations = model.deltaDecorations([], decorations);\n model._oldDecorationsSource = decorations.map(function (decoration, index) {\n return Object.assign({}, decoration, { id: model._oldDecorations[index] });\n });\n model._hasHighlight = true;\n } else {\n model.deltaDecorations(model._oldDecorations, []);\n delete model._oldDecorations;\n delete model._oldDecorationsSource;\n model._hasHighlight = false;\n }\n }\n const handleUnhandledPromiseRejection = function () {\n console.debug('handler for unhandled promise rejection');\n };\n const setAllRangesToPrev = function (rangeMap) {\n for (let key in rangeMap) {\n const restriction = rangeMap[key];\n restriction.range = restriction.prevRange;\n }\n };\n const doesChangeHasMultilineConflict = function (restriction, text) {\n return !restriction.allowMultiline && text.includes('\\n');\n };\n const isChangeInvalidAsPerUser = function (restriction, value, range) {\n return restriction.validate && !restriction.validate(value, range, restriction.lastInfo);\n }\n\n const manipulatorApi = {\n _isRestrictedModel: true,\n _isRestrictedValueValid: true,\n _editableRangeChangeListener: [],\n _isCursorAtCheckPoint: isCursorAtCheckPoint,\n _currentCursorPositions: []\n }\n\n prepareRestrictions(restrictions);\n model._hasHighlight = false;\n manipulatorApi._restrictionChangeListener = model.onDidChangeContent(function (contentChangedEvent) {\n const isUndoing = contentChangedEvent.isUndoing;\n model._isRestrictedValueValid = true;\n if (!(isUndoing && model.editInRestrictedArea)) {\n const changes = contentChangedEvent.changes.sort(sortRangesInAscendingOrder);\n const rangeMap = {};\n const length = restrictions.length;\n const isAllChangesValid = changes.every(function (change) {\n const editedRange = change.range;\n const rangeAsString = editedRange.toString();\n rangeMap[rangeAsString] = null;\n for (let i = 0; i < length; i++) {\n const restriction = restrictions[i];\n const range = restriction.range;\n if (range.containsRange(editedRange)) {\n if (doesChangeHasMultilineConflict(restriction, change.text)) {\n return false;\n }\n rangeMap[rangeAsString] = restriction;\n return true;\n }\n }\n return false;\n })\n if (isAllChangesValid) {\n changes.forEach(function (change, changeIndex) {\n const changedRange = change.range;\n const restriction = rangeMap[changedRange.toString()];\n const editableRange = restriction.range;\n const text = change.text || '';\n /**\n * Things to check before implementing the change\n * - A | D | R => Addition | Deletion | Replacement\n * - MC | SC => MultiLineChange | SingleLineChange\n * - SOR | MOR | EOR => Change Occured in - Start Of Range | Middle Of Range | End Of Range\n * - SSL | SML => Editable Range - Spans Single Line | Spans Multiple Line\n */\n const noOfLinesAdded = (text.match(/\\n/g) || []).length;\n const noOfColsAddedAtLastLine = text.split(/\\n/g).pop().length;\n\n const lineDiffInRange = changedRange.endLineNumber - changedRange.startLineNumber;\n const colDiffInRange = changedRange.endColumn - changedRange.startColumn;\n\n let finalLine = editableRange.endLineNumber;\n let finalColumn = editableRange.endColumn;\n\n let columnsCarriedToEnd = 0;\n if (\n (editableRange.endLineNumber === changedRange.startLineNumber) ||\n (editableRange.endLineNumber === changedRange.endLineNumber)\n ) {\n columnsCarriedToEnd += (editableRange.endColumn - changedRange.startColumn) + 1;\n }\n\n const info = getInfoFrom(change, editableRange);\n restriction.lastInfo = info;\n if (info.isAddition || info.isReplacement) {\n if (info.rangeIsSingleLine) {\n /**\n * Only Column Change has occurred , so regardless of the position of the change\n * Addition of noOfCols is enough\n */\n if (noOfLinesAdded === 0) {\n finalColumn += noOfColsAddedAtLastLine;\n } else {\n finalLine += noOfLinesAdded;\n if (info.startColumnOfRange) {\n finalColumn += noOfColsAddedAtLastLine\n } else if (info.endColumnOfRange) {\n finalColumn = (noOfColsAddedAtLastLine + 1)\n } else {\n finalColumn = (noOfColsAddedAtLastLine + columnsCarriedToEnd)\n }\n }\n }\n if (info.rangeIsMultiLine) {\n // Handling for Start Of Range is not required\n finalLine += noOfLinesAdded;\n if (info.endLineOfRange) {\n if (noOfLinesAdded === 0) {\n finalColumn += noOfColsAddedAtLastLine;\n } else {\n finalColumn = (columnsCarriedToEnd + noOfColsAddedAtLastLine);\n }\n }\n }\n }\n if (info.isDeletion || info.isReplacement) {\n if (info.rangeIsSingleLine) {\n finalColumn -= colDiffInRange;\n }\n if (info.rangeIsMultiLine) {\n if (info.endLineOfRange) {\n finalLine -= lineDiffInRange;\n finalColumn -= colDiffInRange;\n } else {\n finalLine -= lineDiffInRange;\n }\n }\n }\n updateRange(restriction, editableRange, finalLine, finalColumn, changes, changeIndex);\n });\n const values = model.getValueInEditableRanges();\n const currentlyEditedRanges = {};\n for (let key in rangeMap) {\n const restriction = rangeMap[key];\n const range = restriction.range;\n const rangeString = restriction.label || range.toString();\n const value = values[rangeString];\n if (isChangeInvalidAsPerUser(restriction, value, range)) {\n setAllRangesToPrev(rangeMap);\n doUndo();\n return; // Breaks the loop and prevents the triggerChangeListener\n }\n currentlyEditedRanges[rangeString] = value;\n }\n if (model._hasHighlight) {\n model._oldDecorationsSource.forEach(function (object) {\n object.range = model.getDecorationRange(object.id);\n });\n }\n triggerChangeListenersWith(currentlyEditedRanges, values);\n } else {\n doUndo();\n }\n } else if (model.editInRestrictedArea) {\n model._isRestrictedValueValid = false;\n }\n });\n window.onerror = handleUnhandledPromiseRejection;\n const exposedApi = {\n editInRestrictedArea: false,\n getCurrentEditableRanges: getCurrentEditableRanges,\n getValueInEditableRanges: getValueInEditableRanges,\n disposeRestrictions: disposeRestrictions,\n onDidChangeContentInEditableRange: addEditableRangeListener,\n updateRestrictions: updateRestrictions,\n updateValueInEditableRanges: updateValueInEditableRanges,\n toggleHighlightOfEditableAreas: toggleHighlightOfEditableAreas\n }\n for (let funcName in manipulatorApi) {\n Object.defineProperty(model, funcName, {\n enumerable: false,\n configurable: true,\n writable: true,\n value: manipulatorApi[funcName]\n })\n }\n for (let apiName in exposedApi) {\n Object.defineProperty(model, apiName, {\n enumerable: false,\n configurable: true,\n writable: true,\n value: exposedApi[apiName]\n })\n }\n return model;\n}\nexport default constrainedModel;","import validators from './utils/validators.js';\nimport { TypeMustBe } from './utils/definedErrors.js';\nimport constrainedModel from './constrainedModel.js';\n\nexport function constrainedEditor(monaco) {\n /**\n * Injected Dependencies\n */\n if (monaco === undefined) {\n throw new Error([\n \"Please pass the monaco global variable into function as\",\n \"(eg:)constrainedEditor({ range : monaco.range });\",\n ].join('\\n'));\n }\n /**\n *\n * @param {Object} editorInstance This should be the monaco editor instance.\n * @description This is the listener function to check whether the cursor is at checkpoints\n * (i.e) the point where editable and non editable portions meet\n */\n const listenerFn = function (editorInstance) {\n const model = editorInstance.getModel();\n if (model._isCursorAtCheckPoint) {\n const selections = editorInstance.getSelections();\n const positions = selections.map(function (selection) {\n return {\n lineNumber: selection.positionLineNumber,\n column: selection.positionColumn\n }\n });\n model._isCursorAtCheckPoint(positions);\n model._currentCursorPositions = selections;\n }\n }\n const _uriRestrictionMap = {};\n const { isInstanceValid, isModelValid, isRangesValid } = validators.initWith(monaco);\n /**\n *\n * @param {Object} editorInstance This should be the monaco editor instance\n * @returns {Boolean}\n */\n const initInEditorInstance = function (editorInstance) {\n if (isInstanceValid(editorInstance)) {\n let domNode = editorInstance.getDomNode();\n manipulator._listener = listenerFn.bind(API, editorInstance);\n manipulator._editorInstance = editorInstance;\n manipulator._editorInstance._isInDevMode = false;\n domNode.addEventListener('keydown', manipulator._listener, true);\n manipulator._onChangeModelDisposable = editorInstance.onDidChangeModel(function () {\n // domNode - refers old dom node\n domNode && domNode.removeEventListener('keydown', manipulator._listener, true)\n const newDomNode = editorInstance.getDomNode(); // Gets Current dom node\n newDomNode && newDomNode.addEventListener('keydown', manipulator._listener, true);\n domNode = newDomNode;\n })\n return true;\n } else {\n throw new Error(\n TypeMustBe(\n 'ICodeEditor',\n 'editorInstance',\n 'This type interface can be found in monaco editor documentation'\n )\n )\n }\n }\n /**\n *\n * @param {Object} model This should be the monaco editor model instance. Refer https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.itextmodel.html\n * @param {*} ranges This should be the array of range objects. Refer constrained editor plugin documentation\n * @returns model\n */\n const addRestrictionsTo = function (model, ranges) {\n if (isModelValid(model)) {\n if (isRangesValid(ranges)) {\n const modelToConstrain = constrainedModel(model, ranges, monaco, manipulator._editorInstance);\n _uriRestrictionMap[modelToConstrain.uri.toString()] = modelToConstrain;\n return modelToConstrain;\n } else {\n throw new Error(\n TypeMustBe(\n 'Array<RangeRestrictionObject>',\n 'ranges',\n 'Please refer constrained editor documentation for proper structure'\n )\n )\n }\n } else {\n throw new Error(\n TypeMustBe(\n 'ICodeEditor',\n 'editorInstance',\n 'This type interface can be found in monaco editor documentation'\n )\n )\n }\n }\n /**\n *\n * @param {Object} model This should be the monaco editor model instance. Refer https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.itextmodel.html\n * @returns {Boolean} True if the restrictions are removed\n */\n const removeRestrictionsIn = function (model) {\n if (isModelValid(model)) {\n const uri = model.uri.toString();\n const restrictedModel = _uriRestrictionMap[uri];\n if (restrictedModel) {\n return restrictedModel.disposeRestrictions();\n } else {\n console.warn('Current Model is not a restricted Model');\n return false;\n }\n } else {\n throw new Error(\n TypeMustBe(\n 'ICodeEditor',\n 'editorInstance',\n 'This type interface can be found in monaco editor documentation'\n )\n )\n }\n }\n /**\n *\n * @returns {Boolean} True if the constrainer is disposed\n */\n const disposeConstrainer = function () {\n if (manipulator._editorInstance) {\n const instance = manipulator._editorInstance;\n const domNode = instance.getDomNode();\n domNode && domNode.removeEventListener('keydown', manipulator._listener);\n manipulator._onChangeModelDisposable && manipulator._onChangeModelDisposable.dispose();\n delete manipulator._listener;\n delete manipulator._editorInstance._isInDevMode;\n delete manipulator._editorInstance._devModeAction;\n delete manipulator._editorInstance;\n delete manipulator._onChangeModelDisposable;\n for (let key in _uriRestrictionMap) {\n delete _uriRestrictionMap[key];\n }\n return true;\n }\n return false;\n }\n /**\n * @description This function used to make the developer to find the ranges of selected portions\n */\n const toggleDevMode = function () {\n if (manipulator._editorInstance._isInDevMode) {\n manipulator._editorInstance._isInDevMode = false;\n manipulator._editorInstance._devModeAction.dispose();\n delete manipulator._editorInstance._devModeAction;\n } else {\n manipulator._editorInstance._isInDevMode = true;\n manipulator._editorInstance._devModeAction = manipulator._editorInstance.addAction({\n id: 'showRange',\n label: 'Show Range in console',\n contextMenuGroupId: 'navigation',\n contextMenuOrder: 1.5,\n run: function (editor) {\n const selections = editor.getSelections();\n const ranges = selections.reduce(function (acc, { startLineNumber, endLineNumber, startColumn, endColumn }) {\n acc.push('range : ' + JSON.stringify([\n startLineNumber,\n startColumn,\n endLineNumber,\n endColumn\n ]));\n return acc;\n }, []).join('\\n');\n console.log(`Selected Ranges : \\n` + JSON.stringify(ranges, null, 2));\n }\n });\n }\n }\n\n /**\n * Main Function starts here\n */\n // @internal\n const manipulator = {\n /**\n * These variables should not be modified by external code\n * This has to be used for debugging and testing\n */\n _listener: null,\n _editorInstance: null,\n _uriRestrictionMap: _uriRestrictionMap,\n _injectedResources: monaco\n }\n const API = Object.create(manipulator);\n const exposedMethods = {\n /**\n * These functions are exposed to the user\n * These functions should be protected from editing\n */\n initializeIn: initInEditorInstance,\n addRestrictionsTo: addRestrictionsTo,\n removeRestrictionsIn: removeRestrictionsIn,\n disposeConstrainer: disposeConstrainer,\n toggleDevMode: toggleDevMode\n }\n for (let methodName in exposedMethods) {\n Object.defineProperty(API, methodName, {\n enumerable: false,\n writable: false,\n configurable: false,\n value: exposedMethods[methodName]\n })\n }\n return Object.freeze(API);\n}\n\nexport default constrainedEditor;\n","import React, { useCallback, useEffect, useRef } from 'react';\nimport { useTheme } from '../theme-provider';\nimport { constrainedEditor } from 'constrained-editor-plugin';\nimport MonacoEditor, { Monaco, DiffEditor } from '@monaco-editor/react';\nimport type { editor as MonacoEditorType } from 'monaco-editor';\nimport type { TextFile } from '../../lib/types';\nimport { validateThemeJson } from '../../lib/theme-validation';\nimport { useDocumentsStore } from '../../store/documents-store-provider';\nimport { Button } from '../ui/button';\nimport { useEditorRefsStore } from '../../store/editor-refs-store';\nimport {\n getSelectionContext,\n createContextSnippet,\n} from '../../lib/monaco-selection-utils';\n\n/**\n * EditorMonacoTheme component for editing JSON theme files with schema validation\n */\nfunction EditorMonacoTheme({\n document,\n readOnly = false,\n onChange,\n}: {\n document: TextFile;\n readOnly?: boolean;\n onChange?: (value: string) => void;\n}) {\n const editorRef = useRef<MonacoEditorType.IStandaloneCodeEditor | null>(null);\n const monacoRef = useRef<Monaco | null>(null);\n const modelRef = useRef<MonacoEditorType.ITextModel | null>(null);\n const { theme } = useTheme();\n const [isReady, setIsReady] = React.useState(false);\n const pendingDiff = useDocumentsStore((s) => s.pendingDiffs[document.name]);\n const clearPendingDiff = useDocumentsStore((s) => s.clearPendingDiff);\n const saveDocument = useDocumentsStore((s) => s.saveDocument);\n const { registerEditor, unregisterEditor, setActiveEditor } =\n useEditorRefsStore();\n\n // Get resolved theme - convert 'system' to actual theme\n const resolvedTheme =\n theme === 'system'\n ? window.matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light'\n : theme;\n\n // Initialize Monaco editor\n const handleEditorWillMount = useCallback((monaco: Monaco) => {\n console.log('Monaco theme editor will mount');\n monacoRef.current = monaco;\n\n // Ensure global schemas (report + theme) are configured.\n // Don't call setDiagnosticsOptions here — it would clobber the global\n // config. The theme schema is already registered by configureMonacoInstance\n // and matched via defaultPath → fileMatch.\n\n setIsReady(true);\n }, []);\n\n // Handle editor mount\n const handleEditorMount = useCallback(\n (editor: MonacoEditorType.IStandaloneCodeEditor, monaco: Monaco) => {\n editorRef.current = editor;\n modelRef.current = editor.getModel();\n\n // Register editor in the refs store\n registerEditor(document.name, editor, monaco);\n setActiveEditor(document.name);\n\n // Enable constrained editing\n const constrainedInstance = constrainedEditor(monaco);\n const model = editor.getModel();\n if (model) {\n constrainedInstance.initializeIn(editor);\n }\n\n // Configure editor options\n editor.updateOptions({\n formatOnType: true,\n formatOnPaste: true,\n automaticLayout: true,\n minimap: { enabled: false },\n scrollBeyondLastLine: true,\n wordWrap: 'on',\n folding: true,\n foldingStrategy: 'indentation',\n suggest: {\n showColors: true,\n showConstants: true,\n showEnums: true,\n showFields: true,\n showFunctions: true,\n showKeywords: true,\n showModules: true,\n showProperties: true,\n showSnippets: true,\n showStructs: true,\n showTypeParameters: true,\n showUnits: true,\n showValues: true,\n showVariables: true,\n },\n });\n\n // Add keyboard shortcuts\n // Cmd+K => send selection to AI assistant\n editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyK, () => {\n const selection = getSelectionContext(editor, monaco);\n if (selection) {\n const snippet = createContextSnippet(selection);\n window.dispatchEvent(\n new CustomEvent('monaco-selection-to-ai', {\n detail: {\n documentName: document.name,\n selection,\n snippet,\n isTheme: true,\n },\n })\n );\n }\n });\n\n // Cmd+S => save command\n editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {\n // Save command - parent component handles this\n console.log('Save command triggered in theme editor');\n });\n\n // Add context menu action for AI assistant\n editor.addAction({\n id: 'send-theme-to-ai-assistant',\n label: 'Send to AI Assistant (⌘K)',\n contextMenuGroupId: 'navigation',\n contextMenuOrder: 1.5,\n keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyK],\n run: function () {\n // Use the editor reference from closure instead of the parameter\n const selection = getSelectionContext(editor, monaco);\n if (selection) {\n const snippet = createContextSnippet(selection);\n // Dispatch event for the chat panel to capture\n window.dispatchEvent(\n new CustomEvent('monaco-selection-to-ai', {\n detail: {\n documentName: document.name,\n selection,\n snippet,\n isTheme: true,\n },\n })\n );\n }\n },\n });\n\n // Format document on mount\n setTimeout(() => {\n editor.getAction('editor.action.formatDocument')?.run();\n }, 100);\n\n console.log('Monaco theme editor mounted');\n },\n [document.name, registerEditor, setActiveEditor]\n );\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n unregisterEditor(document.name);\n };\n }, [document.name, unregisterEditor]);\n\n // Handle content changes\n const handleChange = useCallback(\n (\n value: string | undefined,\n _event: MonacoEditorType.IModelContentChangedEvent\n ) => {\n if (value !== undefined && onChange) {\n onChange(value);\n }\n },\n [onChange]\n );\n\n // Validate theme content\n useEffect(() => {\n if (\n !editorRef.current ||\n !monacoRef.current ||\n !modelRef.current ||\n !isReady\n ) {\n return;\n }\n\n const monaco = monacoRef.current;\n const model = modelRef.current;\n\n // Clear existing markers\n monaco.editor.setModelMarkers(model, 'theme-validation', []);\n\n // Validate theme JSON\n const validationResult = validateThemeJson(document.text);\n if (!validationResult.valid && validationResult.errors) {\n const markers = validationResult.errors.map((error) => ({\n severity: monaco.MarkerSeverity.Error,\n startLineNumber: error.line || 1,\n startColumn: error.column || 1,\n endLineNumber: error.line || 1,\n endColumn: error.column || 1000,\n message: error.message,\n source: 'theme-validation',\n }));\n\n monaco.editor.setModelMarkers(model, 'theme-validation', markers);\n }\n }, [document.text, isReady]);\n\n // Update theme\n useEffect(() => {\n if (editorRef.current) {\n const newTheme = resolvedTheme === 'dark' ? 'vs-dark' : 'vs';\n editorRef.current.updateOptions({ theme: newTheme });\n }\n }, [resolvedTheme]);\n\n return (\n <div className=\"relative h-full\">\n {pendingDiff ? (\n <>\n <div className=\"flex items-center justify-between px-2 py-1 border-b bg-muted/40 text-xs\">\n <div>\n Review changes for{' '}\n <span className=\"font-medium\">{document.name}</span>\n </div>\n <div className=\"flex gap-2\">\n <Button\n variant=\"secondary\"\n size=\"sm\"\n onClick={() => clearPendingDiff(document.name)}\n >\n Discard\n </Button>\n <Button\n size=\"sm\"\n onClick={() => {\n saveDocument(document.name, pendingDiff.modified);\n clearPendingDiff(document.name, true);\n }}\n >\n Apply Changes\n </Button>\n </div>\n </div>\n <DiffEditor\n height=\"calc(100% - 32px)\"\n original={pendingDiff.original}\n modified={pendingDiff.modified}\n language=\"json\"\n theme={resolvedTheme === 'dark' ? 'vs-dark' : 'vs'}\n options={{\n readOnly: true,\n renderSideBySide: true,\n originalEditable: false,\n automaticLayout: true,\n minimap: { enabled: false },\n }}\n beforeMount={handleEditorWillMount}\n />\n </>\n ) : (\n <MonacoEditor\n height=\"100%\"\n language=\"json\"\n defaultPath={document.name}\n value={document.text}\n theme={resolvedTheme === 'dark' ? 'vs-dark' : 'vs'}\n onChange={handleChange}\n beforeMount={handleEditorWillMount}\n onMount={handleEditorMount}\n options={{\n readOnly,\n lineNumbers: 'on',\n glyphMargin: true,\n folding: true,\n lineDecorationsWidth: 5,\n lineNumbersMinChars: 3,\n renderValidationDecorations: 'on',\n quickSuggestions: {\n other: true,\n comments: false,\n strings: true,\n },\n acceptSuggestionOnCommitCharacter: true,\n acceptSuggestionOnEnter: 'on',\n accessibilitySupport: 'auto',\n autoIndent: 'advanced',\n formatOnType: true,\n formatOnPaste: true,\n automaticLayout: true,\n minimap: { enabled: false },\n scrollBeyondLastLine: true,\n wordWrap: 'on',\n }}\n />\n )}\n </div>\n );\n}\n\nexport const EditorMonacoThemeMemoized = React.memo(EditorMonacoTheme);\n","import React from 'react';\nimport { EditorMonacoJsonMemoized } from '../json-editor/editor-monaco-json';\nimport { EditorMonacoThemeMemoized } from '../json-editor/editor-monaco-theme';\nimport { TabsContent } from '../ui/tabs';\nimport { useDocumentsStore } from '../../store/documents-store-provider';\nimport { useThemesStore } from '../../store/themes-store-provider';\nimport type { TextFile } from '../../lib/types';\nimport type { DocumentType } from '../../store/documents-store';\nimport debounce from 'lodash.debounce';\n\nfunction TabContent({\n name,\n text,\n buildError: _buildError,\n saveDocumentDebounceWait,\n documentType,\n}: {\n name: string;\n text: string;\n buildError?: string;\n saveDocumentDebounceWait: number;\n documentType: DocumentType;\n}) {\n const { saveDocument } = useDocumentsStore((state) => state);\n const { updateTheme } = useThemesStore((state) => state);\n\n // Create a debounced version of updateTheme\n const debouncedUpdateTheme = React.useMemo(\n () => debounce(updateTheme, saveDocumentDebounceWait),\n [updateTheme, saveDocumentDebounceWait]\n );\n\n // Flush pending theme updates on unmount so the themes store is always\n // up-to-date when the user switches away from a theme tab.\n React.useEffect(() => {\n return () => {\n debouncedUpdateTheme.flush();\n };\n }, [debouncedUpdateTheme]);\n\n const handleChange = React.useCallback(\n (value: string) => {\n saveDocument(name, value);\n\n // If this is a theme document, update the themes store with debouncing\n if (documentType === 'application/json+theme') {\n console.log(\n 'TabContent: Theme document change detected, debouncing update',\n {\n documentName: name,\n debounceWait: saveDocumentDebounceWait,\n }\n );\n debouncedUpdateTheme(name, value);\n }\n },\n [\n name,\n saveDocument,\n debouncedUpdateTheme,\n documentType,\n saveDocumentDebounceWait,\n ]\n );\n\n // Create a fake document object for the theme editor\n const document: TextFile = React.useMemo(\n () => ({\n name,\n type: 'application/json',\n text,\n mtime: new Date(),\n ctime: new Date(),\n atime: new Date(),\n }),\n [name, text]\n );\n\n return (\n <TabsContent\n value={name}\n className=\"mt-0 h-full p-0\"\n tabIndex={-1} // to prevent focus on Tab trigger (fix for accessibility size issue)\n >\n {documentType === 'application/json+theme' ? (\n <EditorMonacoThemeMemoized\n document={document}\n onChange={handleChange}\n />\n ) : (\n <EditorMonacoJsonMemoized\n name={name}\n value={text}\n saveDocumentDebounceWait={saveDocumentDebounceWait}\n />\n )}\n </TabsContent>\n );\n}\n\nconst TabContentMemoized = React.memo(TabContent);\n\nfunction EditorTabsContent({\n openTabs,\n documents,\n buildErrors,\n saveDocumentDebounceWait,\n}: {\n openTabs: string[];\n documents: TextFile[];\n buildErrors: Record<string, string>;\n saveDocumentDebounceWait: number;\n}) {\n const { documentTypes } = useDocumentsStore((state) => state);\n\n return openTabs\n .map((name) => documents.find((d) => d.name === name))\n .filter((doc): doc is TextFile => doc !== undefined)\n .map((doc) => {\n const documentType = documentTypes[doc.name] || 'application/json+report';\n\n return (\n <TabContentMemoized\n key={doc.name}\n name={doc.name}\n text={doc.text}\n buildError={buildErrors[doc.name]}\n saveDocumentDebounceWait={saveDocumentDebounceWait}\n documentType={documentType}\n />\n );\n });\n}\n\nexport const EditorTabsContentMemoized = React.memo(EditorTabsContent);\n","export interface RetryOptions {\n maxRetries?: number;\n initialDelay?: number;\n maxDelay?: number;\n backoffFactor?: number;\n onRetry?: (error: Error, attempt: number) => void;\n shouldRetry?: (error: Error) => boolean;\n signal?: AbortSignal;\n}\n\nexport class RetryError extends Error {\n constructor(\n message: string,\n public readonly lastError: Error,\n public readonly attempts: number\n ) {\n super(message);\n this.name = 'RetryError';\n }\n}\n\n/**\n * Retry a function with exponential backoff\n */\nexport async function retry<T>(\n fn: () => Promise<T>,\n options: RetryOptions = {}\n): Promise<T> {\n const {\n maxRetries = 3,\n initialDelay = 1000,\n maxDelay = 30000,\n backoffFactor = 2,\n onRetry,\n shouldRetry = () => true,\n signal,\n } = options;\n\n let lastError: Error;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n // Check if operation was cancelled\n if (signal?.aborted) {\n throw new Error('Operation cancelled');\n }\n\n return await fn();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Don't retry if it's the last attempt\n if (attempt === maxRetries) {\n break;\n }\n\n // Check if we should retry this error\n if (!shouldRetry(lastError)) {\n throw lastError;\n }\n\n // Calculate delay with exponential backoff\n const delay = Math.min(\n initialDelay * Math.pow(backoffFactor, attempt),\n maxDelay\n );\n\n // Add some jitter to prevent thundering herd\n const jitteredDelay = delay * (0.5 + Math.random() * 0.5);\n\n // Call retry callback if provided\n if (onRetry) {\n onRetry(lastError, attempt + 1);\n }\n\n // Wait before retrying\n await new Promise((resolve) => {\n const timeoutId = setTimeout(resolve, jitteredDelay);\n\n // Clean up timeout if cancelled\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timeoutId);\n resolve(undefined);\n },\n { once: true }\n );\n }\n });\n }\n }\n\n throw new RetryError(\n `Failed after ${maxRetries + 1} attempts`,\n lastError!,\n maxRetries + 1\n );\n}\n\n/**\n * Retry decorator for class methods\n */\nexport function Retryable(options: RetryOptions = {}) {\n return function (\n _target: any,\n _propertyKey: string,\n descriptor: PropertyDescriptor\n ) {\n const originalMethod = descriptor.value;\n\n descriptor.value = async function (...args: any[]) {\n return retry(() => originalMethod.apply(this, args), options);\n };\n\n return descriptor;\n };\n}\n\n/**\n * Common retry strategies\n */\nexport const RetryStrategies = {\n // Retry on network errors\n networkErrors: (error: Error) => {\n const networkErrorPatterns = [\n 'NetworkError',\n 'Failed to fetch',\n 'ERR_NETWORK',\n 'ECONNREFUSED',\n 'ETIMEDOUT',\n 'ENOTFOUND',\n 'fetch failed',\n ];\n\n return networkErrorPatterns.some(\n (pattern) =>\n error.message.includes(pattern) || error.name.includes(pattern)\n );\n },\n\n // Retry on specific HTTP status codes\n httpStatusCodes: (statusCodes: number[]) => (error: any) => {\n if (error.response?.status) {\n return statusCodes.includes(error.response.status);\n }\n return false;\n },\n\n // Retry on temporary errors\n temporaryErrors: (error: Error) => {\n const temporaryPatterns = [\n 'EBUSY',\n 'EAGAIN',\n 'temporarily unavailable',\n 'too many requests',\n 'rate limit',\n ];\n\n return temporaryPatterns.some((pattern) =>\n error.message.toLowerCase().includes(pattern.toLowerCase())\n );\n },\n\n // Combine multiple strategies\n combine:\n (...strategies: ((error: Error) => boolean)[]) =>\n (error: Error) => {\n return strategies.some((strategy) => strategy(error));\n },\n};\n","import { useEffect, useCallback, useRef, useMemo, memo, useContext } from 'react';\nimport { EditorTabsContentMemoized } from './editor-tabs-content';\nimport { Tabs } from '../ui/tabs';\nimport { useDocumentsStore, DocumentsStoreContext } from '../../store/documents-store-provider';\nimport { useOutputStore, OutputStoreContext } from '../../store/output-store-provider';\nimport { useSettingsStore } from '../../store/settings-store-provider';\nimport { useEditorRefsStore } from '../../store/editor-refs-store';\nimport { useThemesStore, ThemesStoreContext } from '../../store/themes-store-provider';\nimport { usePresentationGenerator } from '../../hooks/usePresentationGenerator';\nimport { retry, RetryStrategies } from '../../utils/retry';\nimport { themeChangeEmitter } from '../../utils/theme-change-emitter';\nimport { useShallow } from 'zustand/react/shallow';\n\ninterface BuildRequest {\n id: string;\n docName: string;\n doc: any;\n signal: AbortSignal;\n timestamp: number;\n}\n\nfunction EditorComponent() {\n const setOutput = useOutputStore((state) => state.setOutput);\n const outputStore = useContext(OutputStoreContext)!;\n const documentsStore = useContext(DocumentsStoreContext)!;\n const themesStore = useContext(ThemesStoreContext)!;\n const saveDocumentDebounceWait = useSettingsStore(\n (state) => state.saveDocumentDebounceWait\n );\n const autoReload = useSettingsStore((state) => state.autoReload);\n const renderingLibrary = useSettingsStore((state) => state.renderingLibrary);\n const {\n openTabs,\n activeTab,\n setActiveTab,\n documents,\n buildErrors,\n setBuildError,\n documentTypes,\n } = useDocumentsStore(\n useShallow((state) => ({\n openTabs: state.openTabs,\n activeTab: state.activeTab,\n setActiveTab: state.setActiveTab,\n documents: state.documents,\n buildErrors: state.buildErrors,\n setBuildError: state.setBuildError,\n documentTypes: state.documentTypes,\n }))\n );\n const { customThemes, getAllThemeNames, getTheme } = useThemesStore(\n useShallow((state) => ({\n customThemes: state.customThemes,\n getAllThemeNames: state.getAllThemeNames,\n getTheme: state.getTheme,\n }))\n );\n const { generatePresentation, cancelGeneration } = usePresentationGenerator();\n\n // Refs to track ongoing operations and prevent race conditions\n const buildAbortControllersRef = useRef<Map<string, AbortController>>(\n new Map()\n );\n const buildTimeoutsRef = useRef<Map<string, NodeJS.Timeout>>(new Map());\n const lastBuildRequestIdRef = useRef<string>('');\n const documentVersionsRef = useRef<Map<string, number>>(new Map());\n\n // Get or create a document version number\n const getDocumentVersion = useCallback((docName: string) => {\n const currentVersion = documentVersionsRef.current.get(docName) || 0;\n const newVersion = currentVersion + 1;\n documentVersionsRef.current.set(docName, newVersion);\n return newVersion;\n }, []);\n\n // Build document with specific theme data (bypasses memoization)\n const buildDocumentWithThemes = useCallback(\n async (doc: any, themesData: { [key: string]: any }) => {\n if (!doc || !generatePresentation) {\n return;\n }\n\n // Cancel any existing build operation for this document\n const existingController = buildAbortControllersRef.current.get(doc.name);\n if (existingController) {\n existingController.abort();\n buildAbortControllersRef.current.delete(doc.name);\n }\n\n const abortController = new AbortController();\n const signal = abortController.signal;\n buildAbortControllersRef.current.set(doc.name, abortController);\n\n // Create build request\n const requestId = `${doc.name}-theme-${Date.now()}-${Math.random()}`;\n const version = getDocumentVersion(doc.name);\n lastBuildRequestIdRef.current = requestId;\n\n console.log('Editor: Starting theme-triggered build with fresh data', {\n docName: doc.name,\n requestId,\n freshThemeCount: Object.keys(themesData).length,\n version,\n });\n\n const buildRequest: BuildRequest = {\n id: requestId,\n docName: doc.name,\n doc,\n signal,\n timestamp: Date.now(),\n };\n\n // Process immediately (bypass queue for theme changes)\n await processBuildRequestWithThemesRef.current(buildRequest, version, themesData);\n },\n [generatePresentation, setOutput, getDocumentVersion]\n );\n\n // Process build request with specific theme data\n const processBuildRequestWithThemes = useCallback(\n async (\n request: BuildRequest,\n _version: number,\n themesData: { [key: string]: any }\n ) => {\n const { doc, signal, id } = request;\n\n setOutput({\n globalError: undefined,\n isGenerating: true,\n generationProgress: {\n stage: 'parsing',\n message: 'Rebuilding with updated theme...',\n },\n });\n\n const onProgress = (\n stage: 'parsing' | 'building' | 'rendering' | 'finalizing',\n message?: string\n ) => {\n if (signal.aborted || lastBuildRequestIdRef.current !== id) return;\n\n setOutput({\n isGenerating: true,\n generationProgress: { stage, message },\n });\n };\n\n try {\n console.log('Editor: Generating document with fresh themes', {\n docName: doc.name,\n themeNames: Object.keys(themesData),\n requestId: id,\n });\n\n const result = await generatePresentation(\n doc.name,\n doc.text,\n themesData,\n onProgress,\n { bypassCache: true }\n );\n\n if (signal.aborted || lastBuildRequestIdRef.current !== id) {\n console.log('Theme build cancelled for:', doc.name);\n setOutput({ isGenerating: false, generationProgress: undefined });\n return;\n }\n\n if (\n result &&\n typeof result === 'object' &&\n 'name' in result &&\n 'text' in result &&\n 'blob' in result\n ) {\n console.log('Editor: Theme-triggered build completed', {\n docName: result.name,\n blobSize: (result.blob as Blob)?.size,\n timestamp: Date.now(),\n requestId: id,\n });\n\n setOutput({\n name: result.name as string,\n text: result.text as string,\n blob: result.blob as Blob,\n globalError: undefined,\n isGenerating: false,\n isPreviewStale: false,\n generationProgress: undefined,\n lastBuiltSequence: outputStore.getState().editSequence,\n cacheStatus: (result as any).cacheStatus as\n | 'HIT'\n | 'MISS'\n | 'UNKNOWN'\n | undefined,\n cacheHitRate: (result as any).cacheHitRate as string | undefined,\n warnings: (result as any).warnings as any,\n });\n setBuildError(result.name as string, undefined);\n }\n } catch (error) {\n if (signal.aborted || lastBuildRequestIdRef.current !== id) {\n console.log('Theme build cancelled with error for:', doc.name);\n setOutput({ isGenerating: false, generationProgress: undefined });\n return;\n }\n\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n console.error('Theme build error:', errorMessage);\n\n setOutput({\n globalError: `Theme rebuild failed: ${errorMessage}`,\n isGenerating: false,\n generationProgress: undefined,\n });\n setBuildError(doc.name, errorMessage);\n } finally {\n buildAbortControllersRef.current.delete(doc.name);\n }\n },\n [generatePresentation, setOutput, setBuildError, outputStore]\n );\n const processBuildRequestWithThemesRef = useRef(processBuildRequestWithThemes);\n useEffect(() => { processBuildRequestWithThemesRef.current = processBuildRequestWithThemes; });\n\n // Prepare valid custom themes with deep comparison\n const customThemesContentHash = useMemo(() => {\n // Create a content hash of all themes to detect deep changes\n const themeData = Object.entries(customThemes).map(([key, theme]) => {\n // Handle lastModified that might be a string (from localStorage) or Date\n let lastModifiedTime = 0;\n if (theme.lastModified) {\n if (theme.lastModified instanceof Date) {\n lastModifiedTime = theme.lastModified.getTime();\n } else if (typeof theme.lastModified === 'string') {\n lastModifiedTime = new Date(theme.lastModified).getTime();\n }\n }\n\n return {\n key,\n name: theme.name,\n content: theme.content,\n valid: theme.valid,\n lastModified: lastModifiedTime,\n };\n });\n return JSON.stringify(themeData);\n }, [customThemes]);\n\n const validCustomThemes = useMemo(() => {\n const themes: { [key: string]: any } = {};\n Object.values(customThemes).forEach((theme) => {\n if (theme.valid && theme.parsed) {\n themes[theme.name] = theme.parsed;\n }\n });\n return themes;\n }, [customThemesContentHash]);\n\n // Helper function to get fresh theme data (bypasses memo)\n const getFreshThemeData = useCallback(() => {\n const freshThemes: { [key: string]: any } = {};\n const { customThemes } = themesStore.getState();\n Object.values(customThemes).forEach((theme) => {\n if (theme.valid && theme.parsed) {\n freshThemes[theme.name] = theme.parsed;\n }\n });\n return freshThemes;\n }, [themesStore]);\n\n // Helper function to build a document with proper cancellation and retry\n const buildDocument = useCallback(\n async (doc: any, signal?: AbortSignal, options?: { bypassCache?: boolean }) => {\n if (!doc || !generatePresentation) {\n return;\n }\n\n // Cancel any existing build operation for this document\n const existingController = buildAbortControllersRef.current.get(doc.name);\n if (existingController) {\n existingController.abort();\n buildAbortControllersRef.current.delete(doc.name);\n }\n\n // Create new abort controller if not provided\n const abortController = signal ? null : new AbortController();\n const finalSignal = signal || abortController!.signal;\n if (abortController) {\n buildAbortControllersRef.current.set(doc.name, abortController);\n }\n\n // Create build request\n const requestId = `${doc.name}-${Date.now()}-${Math.random()}`;\n const version = getDocumentVersion(doc.name);\n lastBuildRequestIdRef.current = requestId;\n\n const buildRequest: BuildRequest = {\n id: requestId,\n docName: doc.name,\n doc,\n signal: finalSignal,\n timestamp: Date.now(),\n };\n\n await processBuildRequestRef.current(buildRequest, version, options);\n },\n [generatePresentation, setOutput, getDocumentVersion]\n );\n\n // Process a build request from the queue\n const processBuildRequest = useCallback(\n async (request: BuildRequest, version: number, options?: { bypassCache?: boolean }) => {\n const { doc, signal, id } = request;\n\n // Check if this is still the latest request\n if (lastBuildRequestIdRef.current !== id) {\n console.log('Skipping outdated build request for:', doc.name);\n setOutput({ isGenerating: false, generationProgress: undefined });\n return;\n }\n\n setOutput({\n globalError: undefined,\n isGenerating: true,\n generationProgress: {\n stage: 'parsing',\n message: 'Validating JSON structure...',\n },\n });\n\n const onProgress = (\n stage: 'parsing' | 'building' | 'rendering' | 'finalizing',\n message?: string\n ) => {\n if (signal.aborted || lastBuildRequestIdRef.current !== id) return;\n\n // Check document version to ensure we're still building the latest\n const currentVersion = documentVersionsRef.current.get(doc.name) || 0;\n if (currentVersion !== version) {\n console.log('Document version changed, aborting build');\n signal.dispatchEvent(new Event('abort'));\n return;\n }\n\n setOutput({\n isGenerating: true,\n generationProgress: { stage, message },\n });\n };\n\n try {\n // Always get fresh theme data to ensure latest changes are applied\n const freshThemeData = getFreshThemeData();\n\n console.log('Editor: Using themes for document build', {\n docName: doc.name,\n freshThemeCount: Object.keys(freshThemeData).length,\n freshThemeNames: Object.keys(freshThemeData),\n memoizedCount: Object.keys(validCustomThemes).length,\n requestId: id,\n });\n\n // Retry logic for temporary failures\n const result = await retry(\n async () => {\n if (signal.aborted) throw new Error('Build cancelled');\n return await generatePresentation(\n doc.name,\n doc.text,\n freshThemeData,\n onProgress,\n options\n );\n },\n {\n maxRetries: 2,\n initialDelay: 500,\n shouldRetry: (error) => {\n // Don't retry on cancellation or syntax errors\n if (\n error.message.includes('cancelled') ||\n error.message.includes('JSON') ||\n error.message.includes('parse') ||\n error.message.includes('syntax')\n ) {\n return false;\n }\n // Retry on worker errors\n return RetryStrategies.combine(\n RetryStrategies.temporaryErrors,\n (e) =>\n e.message.includes('Worker') || e.message.includes('Proxy')\n )(error);\n },\n onRetry: (error, attempt) => {\n console.log(\n `Retrying presentation generation (attempt ${attempt}):`,\n error.message\n );\n setOutput({\n isGenerating: true,\n generationProgress: {\n stage: 'parsing',\n message: `Retrying generation (attempt ${attempt})...`,\n },\n });\n },\n signal,\n }\n );\n\n if (signal.aborted || lastBuildRequestIdRef.current !== id) {\n console.log('Build cancelled for:', doc.name);\n setOutput({ isGenerating: false, generationProgress: undefined });\n return;\n }\n\n if (\n result &&\n typeof result === 'object' &&\n 'name' in result &&\n 'text' in result &&\n 'blob' in result\n ) {\n console.log('Editor: Build completed', {\n docName: result.name,\n blobSize: (result.blob as Blob)?.size,\n timestamp: Date.now(),\n requestId: id,\n version,\n });\n\n setOutput({\n name: result.name as string,\n text: result.text as string,\n blob: result.blob as Blob,\n globalError: undefined,\n isGenerating: false,\n isPreviewStale: false,\n generationProgress: undefined,\n lastBuiltSequence: outputStore.getState().editSequence,\n cacheStatus: (result as any).cacheStatus as\n | 'HIT'\n | 'MISS'\n | 'UNKNOWN'\n | undefined,\n cacheHitRate: (result as any).cacheHitRate as string | undefined,\n warnings: (result as any).warnings as any,\n });\n setBuildError(result.name as string, undefined);\n }\n } catch (error) {\n if (signal.aborted || lastBuildRequestIdRef.current !== id) {\n console.log('Build cancelled with error for:', doc.name);\n setOutput({ isGenerating: false, generationProgress: undefined });\n return;\n }\n\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n\n setOutput({\n globalError: errorMessage,\n isGenerating: false,\n generationProgress: undefined,\n });\n\n setBuildError(doc.name, errorMessage);\n } finally {\n buildAbortControllersRef.current.delete(doc.name);\n }\n },\n [generatePresentation, getFreshThemeData, setOutput, setBuildError, outputStore]\n );\n const processBuildRequestRef = useRef(processBuildRequest);\n useEffect(() => { processBuildRequestRef.current = processBuildRequest; });\n\n // Track the last viewed document for theme updates\n const lastViewedDocumentRef = useRef<string | null>(null);\n\n\n // re-build on active tab change or any document change\n useEffect(() => {\n console.log('Editor: Document rebuild effect triggered', {\n activeTab,\n });\n\n const activeFile = documents.find((doc) => doc.name === activeTab);\n const docType = documentTypes[activeTab] || 'application/json+report';\n\n // Track last viewed document\n if (docType === 'application/json+report' && activeFile) {\n lastViewedDocumentRef.current = activeTab;\n }\n\n // Clear any pending build timeout for this document\n const existingTimeout = buildTimeoutsRef.current.get(activeTab);\n if (existingTimeout) {\n clearTimeout(existingTimeout);\n buildTimeoutsRef.current.delete(activeTab);\n }\n\n if (activeFile && docType === 'application/json+report') {\n // Skip auto-build when auto-generation is disabled;\n // also don't clobber an in-progress build (e.g. triggered by Run button)\n if (!autoReload || renderingLibrary !== 'docxjs') {\n if (!outputStore.getState().isGenerating) {\n setOutput({ isPreviewStale: true });\n }\n } else {\n // Use adaptive debounce based on document size\n const docSize = activeFile.text.length;\n const debounceTime = docSize > 10000 ? 300 : docSize > 5000 ? 200 : 100;\n\n // Cancel any builds for other documents\n buildAbortControllersRef.current.forEach((controller, docName) => {\n if (docName !== activeTab) {\n controller.abort();\n buildAbortControllersRef.current.delete(docName);\n }\n });\n\n // Debounce the build to avoid rapid rebuilds\n const timeout = setTimeout(() => {\n console.log('Editor: Triggering document build after debounce', {\n docName: activeFile.name,\n debounceTime,\n });\n buildTimeoutsRef.current.delete(activeTab);\n\n // Force new version when themes change to ensure rebuild\n getDocumentVersion(activeFile.name);\n buildDocument(activeFile);\n }, debounceTime);\n\n buildTimeoutsRef.current.set(activeTab, timeout);\n }\n } else if (activeFile && docType === 'application/json+theme') {\n // Theme tab active — no document preview to build.\n // Don't clear blob: preserve the last document preview in the background.\n cancelGeneration();\n }\n\n // Cleanup function to cancel pending operations\n return () => {\n const timeout = buildTimeoutsRef.current.get(activeTab);\n if (timeout) {\n clearTimeout(timeout);\n buildTimeoutsRef.current.delete(activeTab);\n }\n };\n }, [\n documents,\n activeTab,\n setOutput,\n documentTypes,\n buildDocument,\n cancelGeneration,\n autoReload,\n renderingLibrary,\n ]);\n\n // Track which documents use which themes (only parse the active doc to avoid O(n) JSON.parse)\n const documentThemeDependencies = useMemo(() => {\n const deps = new Map<string, string>();\n const activeDoc = documents.find((d) => d.name === activeTab);\n if (activeDoc && documentTypes[activeDoc.name] === 'application/json+report') {\n try {\n const parsed = JSON.parse(activeDoc.text);\n const themeName = parsed.props?.theme;\n if (typeof themeName === 'string') {\n const themeExists = Object.values(customThemes).some(\n (t) => t.name === themeName && t.valid\n );\n if (themeExists) {\n deps.set(activeDoc.name, themeName);\n }\n }\n } catch {\n // Ignore parse errors\n }\n }\n return deps;\n }, [activeTab, documents, documentTypes, customThemes]);\n\n // Listen for theme change events and force immediate rebuild\n useEffect(() => {\n console.log('Editor: Setting up theme change listener', {\n documentCount: documents.length,\n dependencyCount: documentThemeDependencies.size,\n dependencies: Array.from(documentThemeDependencies.entries()),\n customThemes: Object.entries(customThemes).map(([key, theme]) => ({\n key,\n name: theme.name,\n valid: theme.valid,\n })),\n });\n\n const unsubscribe = themeChangeEmitter.onThemeChange((event) => {\n console.log('Editor: Theme change detected', {\n event,\n dependencies: Array.from(documentThemeDependencies.entries()),\n activeTab,\n customThemes: Object.entries(customThemes).map(([key, theme]) => ({\n key,\n name: theme.name,\n valid: theme.valid,\n })),\n });\n\n // Find all documents that use this theme\n const documentsUsingTheme: any[] = [];\n\n documentThemeDependencies.forEach((themeName, docName) => {\n if (themeName === event.themeName) {\n const doc = documents.find((d) => d.name === docName);\n if (doc) {\n documentsUsingTheme.push(doc);\n }\n }\n });\n\n console.log('Editor: Documents using changed theme', {\n themeName: event.themeName,\n documentCount: documentsUsingTheme.length,\n documentNames: documentsUsingTheme.map((d) => d.name),\n });\n\n if (documentsUsingTheme.length === 0) {\n console.log('Editor: No documents use this theme, skipping rebuild');\n return;\n }\n\n // Force immediate rebuild to ensure fresh theme data is used\n // Use longer delay to ensure theme store has updated\n // Add extra delay to account for debouncing in theme updates\n const THEME_UPDATE_DELAY = 600;\n\n // Only rebuild the currently active document\n const activeDocument = documentsUsingTheme.find(\n (doc) => doc.name === activeTab\n );\n\n if (!activeDocument) {\n // Active tab is a theme or unrelated doc — mark stale if a dependent doc exists\n if (documentsUsingTheme.length > 0) {\n setOutput({ isPreviewStale: true });\n }\n return;\n }\n\n // Skip auto-build when auto-generation is disabled\n if (!autoReload || renderingLibrary !== 'docxjs') {\n if (!outputStore.getState().isGenerating) {\n setOutput({ isPreviewStale: true });\n }\n return;\n }\n\n console.log('Editor: Rebuilding only active document', {\n activeDocName: activeDocument.name,\n themeName: event.themeName,\n totalDocumentsUsingTheme: documentsUsingTheme.length,\n });\n\n // Clear any existing rebuild timeouts for the active document\n ['theme-event', 'backup', activeDocument.name].forEach((prefix) => {\n const timeoutKey = `${prefix}-${activeDocument.name}`;\n const existingTimeout = buildTimeoutsRef.current.get(timeoutKey);\n if (existingTimeout) {\n clearTimeout(existingTimeout);\n buildTimeoutsRef.current.delete(timeoutKey);\n }\n });\n\n // Cancel any ongoing builds for the active document\n const existingController = buildAbortControllersRef.current.get(\n activeDocument.name\n );\n if (existingController) {\n existingController.abort();\n buildAbortControllersRef.current.delete(activeDocument.name);\n }\n\n const themeTimeoutKey = `theme-event-${activeDocument.name}`;\n const timeout = setTimeout(() => {\n buildTimeoutsRef.current.delete(themeTimeoutKey);\n console.log(\n 'Editor: Force rebuilding active document due to theme change',\n {\n docName: activeDocument.name,\n themeName: event.themeName,\n timestamp: Date.now(),\n }\n );\n\n // Get fresh theme data directly from store to bypass stale memoization\n const freshThemes: { [key: string]: any } = {};\n const allThemeNames = getAllThemeNames();\n allThemeNames.forEach((name) => {\n const themeData = getTheme(name);\n if (themeData) {\n freshThemes[name] = themeData;\n }\n });\n\n console.log('Editor: Using fresh theme data for rebuild', {\n freshThemeCount: Object.keys(freshThemes).length,\n freshThemeNames: Object.keys(freshThemes),\n memoizedCount: Object.keys(validCustomThemes).length,\n });\n\n // Force a new document version and rebuild with fresh themes\n getDocumentVersion(activeDocument.name);\n buildDocumentWithThemes(activeDocument, freshThemes);\n }, THEME_UPDATE_DELAY);\n\n buildTimeoutsRef.current.set(themeTimeoutKey, timeout);\n });\n\n return unsubscribe;\n }, [\n documentThemeDependencies,\n documents,\n buildDocument,\n getDocumentVersion,\n activeTab,\n getAllThemeNames,\n getTheme,\n buildDocumentWithThemes,\n validCustomThemes,\n autoReload,\n renderingLibrary,\n setOutput,\n ]);\n\n // Flush debounces and immediately build — triggered by Run button via custom event\n // Debounced at 150ms to coalesce rapid clicks\n const flushBuildTimerRef = useRef<NodeJS.Timeout | null>(null);\n // Stable refs so the event handler never goes stale and doesn't need\n // reactive deps that would cause cleanup to cancel the pending timeout\n const buildDocumentRef = useRef(buildDocument);\n useEffect(() => { buildDocumentRef.current = buildDocument; });\n const getDocumentVersionRef = useRef(getDocumentVersion);\n useEffect(() => { getDocumentVersionRef.current = getDocumentVersion; });\n\n useEffect(() => {\n const handler = () => {\n // Mark generating early so the rebuild effect (triggered by saveDocument\n // below) doesn't clobber this build with isPreviewStale\n setOutput({ isGenerating: true });\n\n // 1. Flush Monaco debounce: read live text, save to store immediately\n let themeDirty = false;\n const editorRef = useEditorRefsStore.getState().getActiveEditor();\n if (editorRef) {\n // Don't flush if a pending diff is active — editor may be disposed\n const hasPendingDiff = documentsStore.getState().pendingDiffs[editorRef.documentName];\n if (!hasPendingDiff) {\n const liveText = editorRef.editor.getValue();\n documentsStore.getState().saveDocument(editorRef.documentName, liveText);\n }\n }\n\n // Flush all open theme editors whose live text differs from the\n // themes store so the build always uses up-to-date theme data.\n const { documents: allDocs, documentTypes: allDtypes } = documentsStore.getState();\n for (const doc of allDocs) {\n if (allDtypes[doc.name] === 'application/json+theme') {\n const ref = useEditorRefsStore.getState().getEditor(doc.name);\n if (ref) {\n const liveText = ref.editor.getValue();\n const existing = themesStore.getState().customThemes[doc.name];\n if (!existing || existing.content !== liveText) {\n themesStore.getState().updateTheme(doc.name, liveText);\n themeDirty = true;\n }\n }\n }\n }\n\n // 2. Cancel any pending build timeout for active doc\n const currentTab = documentsStore.getState().activeTab;\n const timeout = buildTimeoutsRef.current.get(currentTab);\n if (timeout) {\n clearTimeout(timeout);\n buildTimeoutsRef.current.delete(currentTab);\n }\n\n // 3. Debounce the actual build to coalesce rapid Run clicks\n if (flushBuildTimerRef.current) {\n clearTimeout(flushBuildTimerRef.current);\n }\n flushBuildTimerRef.current = setTimeout(() => {\n flushBuildTimerRef.current = null;\n const { documents: docs, activeTab: tab, documentTypes: dtypes } = documentsStore.getState();\n\n // Determine target: if active tab is a theme, build the last-viewed document instead\n let targetName = tab;\n const tabType = dtypes[tab] || 'application/json+report';\n if (tabType === 'application/json+theme') {\n if (lastViewedDocumentRef.current) {\n targetName = lastViewedDocumentRef.current;\n } else {\n // No document was viewed yet — nothing to build\n setOutput({ isGenerating: false });\n return;\n }\n }\n\n const freshDoc = docs.find((d) => d.name === targetName);\n if (freshDoc) {\n // If a pending diff exists (AI suggestion), preview the modified version\n const pending = documentsStore.getState().pendingDiffs[targetName];\n const ref = useEditorRefsStore.getState().getEditor(targetName);\n const doc = pending\n ? { ...freshDoc, text: pending.modified }\n : ref\n ? { ...freshDoc, text: ref.editor.getValue() }\n : freshDoc;\n getDocumentVersionRef.current(doc.name);\n // Bypass cache only when a theme was updated during this flush\n buildDocumentRef.current(doc, undefined, themeDirty ? { bypassCache: true } : undefined);\n } else {\n setOutput({ isGenerating: false });\n }\n }, 150);\n };\n\n window.addEventListener('preview:flushAndBuild', handler);\n return () => {\n window.removeEventListener('preview:flushAndBuild', handler);\n if (flushBuildTimerRef.current) {\n clearTimeout(flushBuildTimerRef.current);\n }\n };\n }, [setOutput, documentsStore, themesStore]);\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n // Cancel all pending builds\n buildAbortControllersRef.current.forEach((controller) =>\n controller.abort()\n );\n buildAbortControllersRef.current.clear();\n\n // Clear all timeouts\n buildTimeoutsRef.current.forEach((timeout) => clearTimeout(timeout));\n buildTimeoutsRef.current.clear();\n\n // Cancel any ongoing generation\n cancelGeneration();\n };\n }, [cancelGeneration]);\n\n if (!openTabs.length) {\n return (\n <div className=\"flex flex-col text-muted-foreground h-full items-center justify-center\">\n {!documents?.length ? 'Create a new document...' : 'Open a document...'}\n </div>\n );\n }\n\n return (\n <Tabs value={activeTab} onValueChange={setActiveTab} className=\"h-full\">\n {/* Tabs header removed to gain vertical space */}\n <EditorTabsContentMemoized\n openTabs={openTabs}\n documents={documents}\n buildErrors={buildErrors}\n saveDocumentDebounceWait={saveDocumentDebounceWait}\n />\n </Tabs>\n );\n}\n\n// Export memoized version of Editor component\nexport const Editor = memo(EditorComponent);\n"],"names":["validators","monaco","dummyDiv","dummyEditorInstance","editorInstanceConstructorName","editorModelConstructorName","valueToValidate","ranges","rangeObj","num","TypeMustBe","type","key","additional","deepClone","byPassPrimitives","value","callback","cloneArray","array","keys","arrayClone","i","cloner","object","clone","config","constructOptionForCode","options","acc","option","codes","methods","API","methodName","enums","constrainedModel","model","rangeConstructor","sortRangesInAscendingOrder","rangeObject1","rangeObject2","rangeA","rangeB","normalizeRange","range","content","lines","noOfLines","normalizedRange","index","actualStartCol","startLineNo","maxCols","actualEndLine","actualEndCol","endLineNo","restrictions","prepareRestrictions","restriction","startLine","startCol","endLine","endCol","getCurrentEditableRanges","getValueInEditableRanges","updateValueInEditableRanges","forceMoveMarkers","restrictionsMap","label","doesChangeHasMultilineConflict","newRange","isChangeInvalidAsPerUser","disposeRestrictions","handleUnhandledPromiseRejection","isCursorAtCheckPoint","positions","position","posLineNumber","posCol","length","addEditableRangeListener","triggerChangeListenersWith","currentChanges","allChanges","currentRanges","doUndo","updateRange","finalLine","finalColumn","changes","changeIndex","oldRangeEndLineNumber","oldRangeEndColumn","changesLength","diffInCol","diffInRow","cursorPositions","noOfCursorPositions","change","cursorPosition","nextRestriction","nextRange","nextChange","rangeInChange","rangeAsString","rangeMapValue","getInfoFrom","editableRange","info","updateRestrictions","toggleHighlightOfEditableAreas","cssClasses","cssClassForSingleLine","cssClassForMultiLine","decorations","decoration","setAllRangesToPrev","rangeMap","text","manipulatorApi","contentChangedEvent","isUndoing","editedRange","changedRange","noOfLinesAdded","noOfColsAddedAtLastLine","lineDiffInRange","colDiffInRange","columnsCarriedToEnd","values","currentlyEditedRanges","rangeString","exposedApi","funcName","apiName","constrainedEditor","listenerFn","editorInstance","selections","selection","_uriRestrictionMap","isInstanceValid","isModelValid","isRangesValid","initInEditorInstance","domNode","manipulator","newDomNode","addRestrictionsTo","modelToConstrain","removeRestrictionsIn","uri","restrictedModel","disposeConstrainer","toggleDevMode","editor","startLineNumber","endLineNumber","startColumn","endColumn","exposedMethods","EditorMonacoTheme","document","readOnly","onChange","editorRef","useRef","monacoRef","modelRef","theme","useTheme","isReady","setIsReady","React","pendingDiff","useDocumentsStore","s","clearPendingDiff","saveDocument","registerEditor","unregisterEditor","setActiveEditor","useEditorRefsStore","resolvedTheme","handleEditorWillMount","useCallback","handleEditorMount","constrainedInstance","getSelectionContext","snippet","createContextSnippet","_a","useEffect","handleChange","_event","validationResult","validateThemeJson","markers","error","newTheme","jsx","jsxs","Fragment","Button","DiffEditor","MonacoEditor","EditorMonacoThemeMemoized","TabContent","name","_buildError","saveDocumentDebounceWait","documentType","state","updateTheme","useThemesStore","debouncedUpdateTheme","debounce","TabsContent","EditorMonacoJsonMemoized","TabContentMemoized","EditorTabsContent","openTabs","documents","buildErrors","documentTypes","d","doc","EditorTabsContentMemoized","RetryError","message","lastError","attempts","retry","fn","maxRetries","initialDelay","maxDelay","backoffFactor","onRetry","shouldRetry","signal","attempt","jitteredDelay","resolve","timeoutId","RetryStrategies","pattern","statusCodes","strategies","strategy","EditorComponent","setOutput","useOutputStore","outputStore","useContext","OutputStoreContext","documentsStore","DocumentsStoreContext","themesStore","ThemesStoreContext","useSettingsStore","autoReload","renderingLibrary","activeTab","setActiveTab","setBuildError","useShallow","customThemes","getAllThemeNames","getTheme","generatePresentation","cancelGeneration","usePresentationGenerator","buildAbortControllersRef","buildTimeoutsRef","lastBuildRequestIdRef","documentVersionsRef","getDocumentVersion","docName","newVersion","buildDocumentWithThemes","themesData","existingController","abortController","requestId","version","buildRequest","processBuildRequestWithThemesRef","processBuildRequestWithThemes","request","_version","id","onProgress","stage","result","errorMessage","customThemesContentHash","useMemo","themeData","lastModifiedTime","validCustomThemes","themes","getFreshThemeData","freshThemes","buildDocument","finalSignal","processBuildRequestRef","processBuildRequest","freshThemeData","e","lastViewedDocumentRef","activeFile","docType","existingTimeout","docSize","debounceTime","controller","timeout","documentThemeDependencies","deps","activeDoc","themeName","t","themeChangeEmitter","event","documentsUsingTheme","THEME_UPDATE_DELAY","activeDocument","prefix","timeoutKey","themeTimeoutKey","flushBuildTimerRef","buildDocumentRef","getDocumentVersionRef","handler","themeDirty","liveText","allDocs","allDtypes","ref","existing","currentTab","docs","tab","dtypes","targetName","freshDoc","pending","Tabs","Editor","memo"],"mappings":"inBAAA,MAAMA,GAAa,CACjB,SAAU,SAAUC,EAAQ,CAC1B,MAAMC,EAAW,SAAS,cAAc,KAAK,EACvCC,EAAsBF,EAAO,OAAO,OAAOC,CAAQ,EACnDE,EAAgCD,EAAoB,YAAY,KAChEE,EAA6BF,EAAoB,SAAQ,EAAG,YAAY,KA+B9E,MAAO,CACL,gBA/BoB,SAAUG,EAAiB,CAC/C,OAAOA,EAAgB,YAAY,OAASF,CAC9C,EA8BE,aA7BiB,SAAUE,EAAiB,CAC5C,OAAOA,EAAgB,YAAY,OAASD,CAC9C,EA4BE,cA3BkB,SAAUE,EAAQ,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CAAgB,CAAC,EAEhBlD,EAAS,aASX+H,GAAA,CAAK,MAAOrF,EAAW,cAAeC,EAAc,UAAU,SAE7D,SAAAhE,EAAAA,IAAC2B,GAAA,CACC,SAAAN,EACA,UAAAC,EACA,YAAAC,EACA,yBAAAb,CAAA,CAAA,EAEJ,EAfEV,MAAC,OAAI,UAAU,yEACZ,SAACsB,GAAA,MAAAA,EAAW,OAAsC,qBAA7B,0BAA6B,CACrD,CAeN,CAGO,MAAM+H,GAASC,EAAAA,KAAKpG,EAAe","x_google_ignoreList":[0,1,2,3,4,5]}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{j as t}from"./query-vendor-UL64zsGL.js";import{c as A,g as re,r as y,a as oe}from"./react-vendor-DhdcN9D5.js";import{c as $,g as ie,k as ae}from"./index-DactvF4v.js";import le,{DiffEditor as ue}from"./monaco-editor-DzeBDgmk.js";import{u as R,b as ce}from"./settings-store-provider-DuCKtwqs.js";import{B as Q}from"./button-B5W5GwSc.js";import{c as de}from"./state-vendor-CAMVKh-F.js";import{Q as W,C as fe,d as me,X as he,b as ge,m as pe,T as xe}from"./ui-vendor-C6DsfOoA.js";var q,X;function be(){if(X)return q;X=1;var e="Expected a function",o=NaN,r="[object Symbol]",n=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,l=/^0o[0-7]+$/i,f=parseInt,x=typeof A=="object"&&A&&A.Object===Object&&A,v=typeof self=="object"&&self&&self.Object===Object&&self,b=x||v||Function("return this")(),p=Object.prototype,j=p.toString,w=Math.max,D=Math.min,L=function(){return b.Date.now()};function V(u,h,C){var E,T,k,s,c,m,d=0,N=!1,S=!1,J=!0;if(typeof u!="function")throw new TypeError(e);h=I(h)||0,P(C)&&(N=!!C.leading,S="maxWait"in C,k=S?w(I(C.maxWait)||0,h):k,J="trailing"in C?!!C.trailing:J);function B(g){var M=E,O=T;return E=T=void 0,d=g,s=u.apply(O,M),s}function ee(g){return d=g,c=setTimeout(K,h),N?B(g):s}function te(g){var M=g-m,O=g-d,H=h-M;return S?D(H,k-O):H}function U(g){var M=g-m,O=g-d;return m===void 0||M>=h||M<0||S&&O>=k}function K(){var g=L();if(U(g))return G(g);c=setTimeout(K,te(g))}function G(g){return c=void 0,J&&E?B(g):(E=T=void 0,s)}function ne(){c!==void 0&&clearTimeout(c),d=0,E=m=T=c=void 0}function se(){return c===void 0?s:G(L())}function z(){var g=L(),M=U(g);if(E=arguments,T=this,m=g,M){if(c===void 0)return ee(m);if(S)return c=setTimeout(K,h),B(m)}return c===void 0&&(c=setTimeout(K,h)),s}return z.cancel=ne,z.flush=se,z}function P(u){var h=typeof u;return!!u&&(h=="object"||h=="function")}function F(u){return!!u&&typeof u=="object"}function _(u){return typeof u=="symbol"||F(u)&&j.call(u)==r}function I(u){if(typeof u=="number")return u;if(_(u))return o;if(P(u)){var h=typeof u.valueOf=="function"?u.valueOf():u;u=P(h)?h+"":h}if(typeof u!="string")return u===0?u:+u;u=u.replace(n,"");var C=a.test(u);return C||l.test(u)?f(u.slice(2),C?2:8):i.test(u)?o:+u}return q=V,q}var ve=be();const ye=re(ve),je=de((e,o)=>({editors:new Map,activeEditorName:null,registerEditor:(r,n,i)=>{e(a=>{const l=new Map(a.editors);return l.set(r,{editor:n,monaco:i,documentName:r}),{editors:l}})},unregisterEditor:r=>{e(n=>{const i=new Map(n.editors);return i.delete(r),{editors:i,activeEditorName:n.activeEditorName===r?null:n.activeEditorName}})},setActiveEditor:r=>{e({activeEditorName:r})},getActiveEditor:()=>{const r=o();return r.activeEditorName&&r.editors.get(r.activeEditorName)||null},getEditor:r=>o().editors.get(r)||null}));function Y(e,o){if(!e||!o)return null;const r=e.getModel();if(!r)return null;const n=e.getSelection();if(!n)return null;const a=r.getValueInRange(n)||Ce(e);if(!a)return null;const l=r.getValue();let f=null,x=!1;try{f=JSON.parse(l),x=!0}catch{}const v=x?we(l,n.startLineNumber,n.startColumn):void 0,b=Ne(l,n.startLineNumber,n.startColumn);return{selectedText:a,jsonPath:v,propertyKey:b,fullDocument:f,isValidJson:x,startLine:n.startLineNumber,endLine:n.endLineNumber}}function Ce(e,o){const r=e.getModel(),n=e.getPosition();if(!r||!n)return"";const i=r.getWordAtPosition(n);return i?r.getValueInRange({startLineNumber:n.lineNumber,startColumn:i.startColumn,endLineNumber:n.lineNumber,endColumn:i.endColumn}):""}function we(e,o,r){var n;try{const i=e.split(`
|
|
2
|
+
`),a=[];let l=0,f=!1,x=0;for(let v=0;v<Math.min(o,i.length);v++){const b=i[v];for(let j=0;j<b.length;j++){const w=b[j];if(v===o-1&&j>=r)break;w==="{"?l++:w==="}"?(l--,a.length>l&&a.pop()):w==="["?(f=!0,x=0):w==="]"?(f=!1,(n=a[a.length-1])!=null&&n.match(/\[\d+\]$/)&&a.pop()):w===","&&f&&x++}const p=b.match(/^\s*"([^"]+)"\s*:/);if(p){for(;a.length>=l;)a.pop();f?a.push(`${p[1]}[${x}]`):a.push(p[1])}}return a.length>0?a.join("."):void 0}catch{return}}function Ne(e,o,r){try{const n=e.split(`
|
|
3
|
+
`);if(o>n.length)return;const a=n[o-1].match(/^\s*"([^"]+)"\s*:/);if(a)return a[1];for(let l=o-2;l>=0;l--){const f=n[l],x=f.match(/^\s*"([^"]+)"\s*:/);if(x)return x[1];if(f.includes("}"))break}return}catch{return}}function Ee(e,o){if(!e||!o)return;const r=o.split(".");let n=e;for(const i of r){if(!n)return;const a=i.match(/^([^[]+)\[(\d+)\]$/);if(a){const[,l,f]=a;if(n=n[l],Array.isArray(n))n=n[parseInt(f,10)];else return}else n=n[i]}return n}function Z(e){const o=[];if(e.jsonPath&&o.push(`JSON Path: ${e.jsonPath}`),e.selectedText.length>500?o.push(`Selected Text (truncated): ${e.selectedText.substring(0,500)}...`):o.push(`Selected Text: ${e.selectedText}`),e.isValidJson&&e.fullDocument&&e.jsonPath){const r=Ee(e.fullDocument,e.jsonPath);if(r!==void 0){const n=JSON.stringify(r,null,2);n.length>500?o.push(`Context Value (truncated): ${n.substring(0,500)}...`):o.push(`Context Value: ${n}`)}}return o.join(`
|
|
4
|
+
`)}function Se({errors:e,onErrorClick:o,onClose:r,className:n,isMinimized:i=!1,onToggleMinimize:a}){const[l,f]=y.useState(!i);y.useEffect(()=>{f(!i)},[i]);const x=e.length>0,v=e.length;if(!x)return null;const b=()=>{f(!l),a==null||a()};return t.jsxs("div",{className:$("absolute bottom-0 left-0 right-0 z-50 bg-background border-t shadow-lg transition-all duration-200",l?"h-48":"h-10",n),children:[t.jsxs("div",{className:$("flex items-center justify-between px-3 py-2 cursor-pointer","bg-destructive/10 border-b border-destructive/20","hover:bg-destructive/15 transition-colors"),onClick:b,children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(W,{className:"w-4 h-4 text-destructive"}),t.jsxs("span",{className:"text-sm font-medium text-destructive",children:[v," Validation Error",v!==1?"s":""]})]}),t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(Me,{errors:e}),t.jsx("button",{onClick:p=>{p.stopPropagation(),b()},className:"p-1 hover:bg-destructive/20 rounded transition-colors","aria-label":l?"Minimize":"Expand",children:l?t.jsx(fe,{className:"w-4 h-4"}):t.jsx(me,{className:"w-4 h-4"})}),r&&t.jsx("button",{onClick:p=>{p.stopPropagation(),r()},className:"p-1 hover:bg-destructive/20 rounded transition-colors","aria-label":"Close validation panel",children:t.jsx(he,{className:"w-4 h-4"})})]})]}),l&&t.jsx("div",{className:"overflow-y-auto h-[calc(100%-2.5rem)]",children:t.jsx("div",{className:"divide-y divide-border/50",children:e.map((p,j)=>t.jsx(Le,{error:p,onClick:()=>o==null?void 0:o(p)},`${p.path}-${j}`))})})]})}function Me({errors:e}){const[o,r]=y.useState(!1),n=i=>{i.stopPropagation();const a=e.map(l=>`${l.startLineNumber&&l.startColumn?`Line ${l.startLineNumber}:${l.startColumn}`:"Unknown location"} — ${l.message}`).join(`
|
|
5
|
+
`);navigator.clipboard.writeText(a).then(()=>{r(!0),setTimeout(()=>r(!1),2e3)})};return t.jsx("button",{onClick:n,className:$("flex items-center gap-1 px-1.5 py-1 rounded transition-all duration-200 cursor-pointer",o?"bg-green-500/15 text-green-500":"hover:bg-destructive/20"),"aria-label":"Copy all errors",children:o?t.jsxs(t.Fragment,{children:[t.jsx(ge,{className:"w-3.5 h-3.5"}),t.jsx("span",{className:"text-xs font-medium",children:"Copied"})]}):t.jsx(pe,{className:"w-4 h-4"})})}function Le({error:e,onClick:o}){const r=i=>{switch(i){case"error":return t.jsx(W,{className:"w-4 h-4 text-destructive flex-shrink-0"});case"warning":return t.jsx(xe,{className:"w-4 h-4 text-yellow-500 flex-shrink-0"});default:return t.jsx(W,{className:"w-4 h-4 text-blue-500 flex-shrink-0"})}},n=i=>i?i.replace(/^\//,"").replace(/\//g," → "):"Document root";return t.jsx("div",{className:$("px-3 py-2 hover:bg-muted/50 cursor-pointer transition-colors","group"),onClick:o,children:t.jsxs("div",{className:"flex items-start gap-2",children:[r(e.severity),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[t.jsx("span",{className:"text-xs font-mono text-muted-foreground",children:e.startLineNumber&&e.startColumn?`Line ${e.startLineNumber}:${e.startColumn}`:"Unknown location"}),e.path&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-xs text-muted-foreground",children:"•"}),t.jsx("span",{className:"text-xs text-muted-foreground truncate",children:n(e.path)})]})]}),t.jsx("p",{className:"text-sm text-foreground",children:e.message}),e.code&&e.code!=="validation_error"&&t.jsxs("span",{className:"text-xs text-muted-foreground font-mono mt-1 inline-block",children:["Code: ",e.code]})]})]})})}function Pe({errors:e,onClick:o,className:r}){if(e.length!==0)return t.jsxs("div",{className:$("flex items-center gap-2 px-2 py-1 text-xs cursor-pointer","bg-destructive/10 text-destructive hover:bg-destructive/15 transition-colors",r),onClick:o,children:[t.jsx(W,{className:"w-3 h-3"}),t.jsxs("span",{children:[e.length," error",e.length!==1?"s":""]})]})}function Te({name:e,defaultValue:o,value:r,saveDocumentDebounceWait:n}){console.debug(`Render EditorMonacoJson (name: ${e})`);const i=y.useRef(null),a=y.useRef(null),{resolvedTheme:l}=ie(),f=R(s=>s.saveDocument),x=ce(s=>s.bumpEditSequence),v=R(s=>s.closeDocument),b=R(s=>s.pendingDiffs[e]),p=R(s=>s.clearPendingDiff),[j,w]=y.useState([]),[D,L]=y.useState(!0),[V,P]=y.useState(!1),F=y.useRef([]),{registerEditor:_,unregisterEditor:I,setActiveEditor:u}=je(),h=y.useRef(ye(f,n)),C=y.useCallback(s=>{console.debug("Setting up Monaco for JSON editor"),ae(s)},[]);function E(s,c){console.debug(`EditorDidMount: (name: ${e})`),i.current=s,a.current=c,_(e,s,c),u(e);const m=s.getModel();m&&(c.editor.setModelLanguage(m,"json"),console.debug("Model language set to JSON for:",m.uri.toString())),s.addAction({id:"send-to-ai-assistant",label:"Send to AI Assistant (⌘K)",contextMenuGroupId:"navigation",contextMenuOrder:1.5,keybindings:[c.KeyMod.CtrlCmd|c.KeyCode.KeyK],run:function(){const d=Y(s,c);if(d){const N=Z(d);window.dispatchEvent(new CustomEvent("monaco-selection-to-ai",{detail:{documentName:e,selection:d,snippet:N}}))}}}),s.addCommand(c.KeyMod.CtrlCmd|c.KeyCode.KeyK,()=>{const d=Y(s,c);if(d){const N=Z(d);window.dispatchEvent(new CustomEvent("monaco-selection-to-ai",{detail:{documentName:e,selection:d,snippet:N}}))}}),s.addCommand(c.KeyMod.CtrlCmd|c.KeyCode.KeyS,()=>{const d=s.getValue();d&&f(e,d)}),s.addCommand(c.KeyMod.CtrlCmd|c.KeyCode.KeyW,()=>{const d=s.getValue();d&&f(e,d),v(e)}),s.addCommand(c.KeyMod.Shift|c.KeyMod.Alt|c.KeyCode.KeyF,()=>{var d;(d=s.getAction("editor.action.formatDocument"))==null||d.run()})}function T(s){console.debug("Monaco validation markers:",s);const c=s.map(m=>{var d,N,S;return{path:"",message:m.message,code:typeof m.code=="string"?m.code:((d=m.code)==null?void 0:d.value)||"validation_error",startLineNumber:m.startLineNumber,startColumn:m.startColumn,endLineNumber:m.endLineNumber,endColumn:m.endColumn,severity:m.severity===((N=a.current)==null?void 0:N.MarkerSeverity.Error)?"error":m.severity===((S=a.current)==null?void 0:S.MarkerSeverity.Warning)?"warning":"info"}});w(c),F.current=[],c.length>0&&!D&&(L(!0),P(!1))}y.useEffect(()=>{const s=h==null?void 0:h.current;return()=>{s==null||s.cancel(),I(e),console.debug(`EditorWillUnMount: (name: ${e})`)}},[e,I]);const k=y.useCallback(s=>{i.current&&s.startLineNumber&&s.startColumn&&(i.current.setPosition({lineNumber:s.startLineNumber,column:s.startColumn}),i.current.revealLineInCenter(s.startLineNumber),i.current.focus())},[]);return t.jsxs("div",{className:"relative h-full",children:[b?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center justify-between px-2 py-1 border-b bg-muted/40 text-xs",children:[t.jsxs("div",{children:["Review changes for ",t.jsx("span",{className:"font-medium",children:e})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(Q,{variant:"secondary",size:"sm",onClick:()=>p(e),children:"Discard"}),t.jsx(Q,{size:"sm",onClick:()=>{f(e,b.modified),p(e,!0)},children:"Apply Changes"})]})]}),t.jsx(ue,{height:"calc(100% - 32px)",original:b.original,modified:b.modified,language:"json",theme:`vs-${l}`,options:{readOnly:!0,renderSideBySide:!0,originalEditable:!1,automaticLayout:!0,minimap:{enabled:!1}},beforeMount:C})]}):t.jsx(le,{height:"100%",defaultLanguage:"json",theme:`vs-${l}`,defaultPath:e.endsWith(".json")?e:`${e}.json`,value:r??o,beforeMount:C,onMount:E,onValidate:T,onChange:s=>{s&&(x(),h.current(e,s))},options:{minimap:{enabled:!0},scrollBeyondLastLine:!0,wordWrap:"on",automaticLayout:!0,formatOnPaste:!0,formatOnType:!0,tabSize:2,insertSpaces:!0,detectIndentation:!1,folding:!0,foldingStrategy:"indentation",showFoldingControls:"always",bracketPairColorization:{enabled:!0},guides:{bracketPairs:!0,indentation:!0},suggest:{showProperties:!0,showMethods:!0,showFunctions:!0,showConstructors:!0,showDeprecated:!0,showFields:!0,showVariables:!0,showClasses:!0,showStructs:!0,showInterfaces:!0,showModules:!0,showTypeParameters:!0,showValues:!0,showConstants:!0,showEnums:!0,showEnumMembers:!0,showKeywords:!0,showWords:!1,showColors:!0,showFiles:!1,showReferences:!0,showFolders:!1,showOperators:!0,showUnits:!0,showSnippets:!0,snippetsPreventQuickSuggestions:!1,insertMode:"insert",filterGraceful:!0,localityBonus:!0,shareSuggestSelections:!0,showIcons:!0},quickSuggestions:{strings:!0,comments:!1,other:!0},quickSuggestionsDelay:10,suggestSelection:"first",suggestOnTriggerCharacters:!0,acceptSuggestionOnEnter:"on",acceptSuggestionOnCommitCharacter:!0,wordBasedSuggestions:"off",parameterHints:{enabled:!0,cycle:!0},hover:{enabled:!0,delay:300,sticky:!0},tabCompletion:"on",snippetSuggestions:"inline",inlineSuggest:{enabled:!0}}}),t.jsx("div",{className:"absolute top-0 right-0",children:t.jsx(Pe,{errors:j,onClick:()=>{L(!0),P(!1)}})}),D&&j.length>0&&t.jsx(Se,{errors:j,isMinimized:V,onToggleMinimize:()=>P(!V),onErrorClick:k,onClose:()=>L(!1),className:"z-40"})]})}const ke=oe.memo(Te,(e,o)=>e.name===o.name&&e.value===o.value&&e.saveDocumentDebounceWait===o.saveDocumentDebounceWait),We=Object.freeze(Object.defineProperty({__proto__:null,EditorMonacoJsonMemoized:ke},Symbol.toStringTag,{value:"Module"}));export{ke as E,Z as c,ye as d,We as e,Y as g,je as u};
|
|
6
|
+
//# sourceMappingURL=editor-monaco-json-8I2epq6g.js.map
|