@json-to-office/jto 1.2.0 → 1.6.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.
Files changed (58) hide show
  1. package/dist/cli.js +178 -31
  2. package/dist/cli.js.map +1 -1
  3. package/dist/client/assets/{HomePage-jkIz_s7u.js → HomePage-CeUQIXch.js} +44 -44
  4. package/dist/client/assets/HomePage-CeUQIXch.js.map +1 -0
  5. package/dist/client/assets/{JsonEditorPage-DR8UoROz.js → JsonEditorPage-4LrF2fB9.js} +3 -3
  6. package/dist/client/assets/{JsonEditorPage-DR8UoROz.js.map → JsonEditorPage-4LrF2fB9.js.map} +1 -1
  7. package/dist/client/assets/{MonacoPluginProvider-CE5NPGwN.js → MonacoPluginProvider-Bx_V_FaE.js} +3 -3
  8. package/dist/client/assets/MonacoPluginProvider-Bx_V_FaE.js.map +1 -0
  9. package/dist/client/assets/editor-D-REaAU9.js +9 -0
  10. package/dist/client/assets/editor-D-REaAU9.js.map +1 -0
  11. package/dist/client/assets/editor-monaco-json-BgziSLMV.js +24 -0
  12. package/dist/client/assets/editor-monaco-json-BgziSLMV.js.map +1 -0
  13. package/dist/client/assets/editor-refs-store-vzLK2-Zo.js +2 -0
  14. package/dist/client/assets/{editor-refs-store-DKOJcTAk.js.map → editor-refs-store-vzLK2-Zo.js.map} +1 -1
  15. package/dist/client/assets/index-B7bDnXoC.js +5 -0
  16. package/dist/client/assets/index-B7bDnXoC.js.map +1 -0
  17. package/dist/client/assets/index-CrzIwHLS.css +1 -0
  18. package/dist/client/assets/preview-BGqIip90.js +2 -0
  19. package/dist/client/assets/preview-BGqIip90.js.map +1 -0
  20. package/dist/client/assets/{ui-vendor-DpjQWJgX.js → ui-vendor-Bq4-oNFL.js} +92 -57
  21. package/dist/client/assets/ui-vendor-Bq4-oNFL.js.map +1 -0
  22. package/dist/client/assets/useQualityAnalysis-CowAaoA9.js +6 -0
  23. package/dist/client/assets/useQualityAnalysis-CowAaoA9.js.map +1 -0
  24. package/dist/client/index.html +3 -3
  25. package/dist/client/templates/data-report-presentation.pptx.json +22 -22
  26. package/dist/client/templates/media/vermilion-annual-report/fonts/ClashDisplay-Bold.otf +0 -0
  27. package/dist/client/templates/media/vermilion-annual-report/fonts/ClashDisplay-Light.otf +0 -0
  28. package/dist/client/templates/media/vermilion-annual-report/fonts/ClashDisplay-Medium.otf +0 -0
  29. package/dist/client/templates/media/vermilion-annual-report/fonts/ClashDisplay-Regular.otf +0 -0
  30. package/dist/client/templates/media/vermilion-annual-report/fonts/ClashDisplay-Semibold.otf +0 -0
  31. package/dist/client/templates/media/vermilion-annual-report/fonts/FFL.txt +132 -0
  32. package/dist/client/templates/minimalist-pitch-deck.pptx.json +52 -52
  33. package/dist/client/templates/modern-annual-report-1.docx.json +2 -2
  34. package/dist/client/templates/modern-annual-report-2.docx.json +2 -2
  35. package/dist/client/templates/modern-annual-report-3.docx.json +1 -1
  36. package/dist/client/templates/tech-report.docx.json +8 -8
  37. package/dist/client/templates/themes/corporate.pptx.theme.json +12 -2
  38. package/dist/client/templates/themes/minimal.pptx.theme.json +12 -2
  39. package/dist/client/templates/themes/vibrant.pptx.theme.json +12 -2
  40. package/dist/client/templates/vermilion-annual-report.docx.json +10541 -0
  41. package/package.json +8 -7
  42. package/dist/client/assets/HomePage-jkIz_s7u.js.map +0 -1
  43. package/dist/client/assets/MonacoPluginProvider-CE5NPGwN.js.map +0 -1
  44. package/dist/client/assets/editor-edmvhW9F.js +0 -9
  45. package/dist/client/assets/editor-edmvhW9F.js.map +0 -1
  46. package/dist/client/assets/editor-monaco-json-CAlvfPc7.js +0 -24
  47. package/dist/client/assets/editor-monaco-json-CAlvfPc7.js.map +0 -1
  48. package/dist/client/assets/editor-refs-store-DKOJcTAk.js +0 -2
  49. package/dist/client/assets/index-CNvLzaJ7.css +0 -1
  50. package/dist/client/assets/index-DLlW4q4v.js +0 -5
  51. package/dist/client/assets/index-DLlW4q4v.js.map +0 -1
  52. package/dist/client/assets/preview-zo-CHAU0.js +0 -2
  53. package/dist/client/assets/preview-zo-CHAU0.js.map +0 -1
  54. package/dist/client/assets/ui-vendor-DpjQWJgX.js.map +0 -1
  55. package/dist/client/templates/Alternative deck 16_9.pptx.json +0 -3103
  56. package/dist/client/templates/Brand template 16_9.pptx.json +0 -2013
  57. package/dist/client/templates/Company deck 16_9.pptx.json +0 -6384
  58. package/dist/client/templates/Company deck 4_3.pptx.json +0 -5426
@@ -1 +0,0 @@
1
- {"version":3,"mappings":";gZAAA,SAASA,EAAiBC,EAAS,CAC/B,OAAO,IAAI,QAAQ,CAACC,EAASC,IAAW,CAEpCF,EAAQ,WAAaA,EAAQ,UAAY,IAAMC,EAAQD,EAAQ,MAAM,EAErEA,EAAQ,QAAUA,EAAQ,QAAU,IAAME,EAAOF,EAAQ,KAAK,CAClE,CAAC,CACL,CACA,SAASG,EAAYC,EAAQC,EAAW,CACpC,IAAIC,EACJ,MAAMC,EAAQ,IAAM,CAChB,GAAID,EACA,OAAOA,EACX,MAAMN,EAAU,UAAU,KAAKI,CAAM,EACrC,OAAAJ,EAAQ,gBAAkB,IAAMA,EAAQ,OAAO,kBAAkBK,CAAS,EAC1EC,EAAMP,EAAiBC,CAAO,EAC9BM,EAAI,KAAME,GAAO,CAGbA,EAAG,QAAU,IAAOF,EAAM,MAC9B,EAAG,IAAM,CAAE,CAAC,EACLA,CACX,EACA,MAAO,CAACG,EAAQC,IAAaH,EAAK,EAAG,KAAMC,GAAOE,EAASF,EAAG,YAAYH,EAAWI,CAAM,EAAE,YAAYJ,CAAS,CAAC,CAAC,CACxH,CACA,IAAIM,EACJ,SAASC,GAAkB,CACvB,OAAKD,IACDA,EAAsBR,EAAY,eAAgB,QAAQ,GAEvDQ,CACX,CAOA,SAASE,EAAIC,EAAKC,EAAcH,IAAmB,CAC/C,OAAOG,EAAY,WAAaC,GAAUjB,EAAiBiB,EAAM,IAAIF,CAAG,CAAC,CAAC,CAC9E,CAQA,SAASG,EAAIH,EAAKI,EAAO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AM,KAC3BzC,EAAgB,WAAW,iBAEvB0C,IACJC,EAAAN,EAAe,UAAf,YAAAM,EAAwB,WAAW,qBAAsB,GAC3DhC,EAAwBE,EAAQ4B,EAAgBC,CAAa,EAC1D,KAAME,GAAY,CACbA,EACF,QAAQ,IACN,sDACAH,CAAA,EAGF,QAAQ,KACN,mEAGN,CAAC,EACA,MAAO3B,GAAU,CAChB,QAAQ,MACN,2DACAA,CAAA,CAEJ,CAAC,EACHwB,EAAmB,QAAU,CAAC,GAAGG,CAAc,EAC/CF,EAAkB,QAAU,CAAC,GAAGG,CAAa,CAC/C,CAAC,EACA,MAAO5B,GAAU,CAChB,QAAQ,MAAM,+BAAgCA,CAAK,CACrD,CAAC,CACL,EAAG,EAAE,EAEL0B,YAAU,IAAM,CACd,MAAMK,EACJrC,EAAoB,SAAW8B,EAAmB,QAAQ,QAC1D9B,EAAoB,KAClB,CAAChG,EAAMsB,IAAUtB,IAAS8H,EAAmB,QAAQxG,CAAK,GAGxDgH,EACJX,EAAiB,SAAWI,EAAkB,QAAQ,QACtDJ,EAAiB,KACf,CAAC3H,EAAMsB,IAAUtB,IAAS+H,EAAkB,QAAQzG,CAAK,GAGzD,CAAC+G,GAAkB,CAACC,GAIpBb,EAAU,UACZtB,EACEsB,EAAU,QACVzB,EACA2B,CAAA,EACA,MAAOrB,GAAU,CACjB,QAAQ,MACN,sDACAA,CAAA,CAEJ,CAAC,EACDwB,EAAmB,QAAU,CAAC,GAAG9B,CAAmB,EACpD+B,EAAkB,QAAU,CAAC,GAAGJ,CAAgB,EAEpD,EAAG,CAAC3B,EAAqB2B,CAAgB,CAAC,EAEnC,CACL,OAAQF,EAAU,QAClB,gBAAiBzB,CAAA,CAErB,CC5HO,SAASuC,GAAqB,CACnC,SAAAhG,CACF,EAEG,CAED,OAAAiF,GAAA,oBAEU,SAAAjF,EAAS,CACrB","names":["promisifyRequest","request","resolve","reject","createStore","dbName","storeName","dbp","getDB","db","txMode","callback","defaultGetStoreFunc","defaultGetStore","get","key","customStore","store","set","value","del","idbStorage","name","MAX_OPEN_TABS","initDocumentsStore","defaultInitDocumentsState","createDocumentsStore","initState","devtools","persist","text","state","doc","docType","parsed","newDoc","newDocumentTypes","k","docIndex","oldName","newName","documents","i","openTabs","index","tab","activeTab","buildError","buildErrors","original","modified","applyId","accepted","diff","next","ids","acceptedApplyIds","createJSONStorage","DocumentsStoreContext","createContext","DocumentsStoreProvider","children","storeRef","useRef","useDocumentsStore","selector","documentsStoreContext","useContext","useStore","validateThemeJson","jsonString","getThemeName","themeJson","_ThemeChangeEmitter","event","handler","e","__publicField","ThemeChangeEmitter","themeChangeEmitter","initThemesStore","defaultInitThemesState","createThemesStore","documentName","content","validation","themeName","parsedContent","extractedName","existingTheme","isUpdate","hasContentChanged","customTheme","removedTheme","newCustomThemes","names","theme","ThemesStoreContext","ThemesStoreProvider","useThemesStore","themesStoreContext","initOutputStore","defaultInitOutputState","createOutputStore","partialState","s","OutputStoreContext","OutputStoreProvider","useOutputStore","outputStoreContext","usePluginsStore","create","plugin","newSelectedPlugins","newMetadata","pluginName","onSuccess","onError","selectedPluginNames","loader","__vitePreload","updateMonacoWithPlugins","n","monaco","error","errorMessage","str","serialized","initSettingsStore","defaultInitSettingsState","createSettingsStore","settings","SettingsStoreContext","SettingsStoreProvider","useSettingsStore","settingsStoreContext","emptyNames","subscribe","useCustomThemeNames","cachedRef","getSnapshot","useSyncExternalStore","useMonacoPlugins","monacoRef","selectedPlugins","customThemeNames","themesStore","themesStoreRef","previousPluginsRef","previousThemesRef","useEffect","currentPlugins","currentThemes","_a","success","pluginsChanged","themesChanged","MonacoPluginProvider"],"ignoreList":[0],"sources":["../../../../../node_modules/.pnpm/idb-keyval@6.2.2/node_modules/idb-keyval/dist/index.js","../../../src/client/lib/idb-storage.ts","../../../src/client/store/documents-store.ts","../../../src/client/store/documents-store-provider.tsx","../../../src/client/lib/theme-validation.ts","../../../src/client/utils/theme-change-emitter.ts","../../../src/client/store/themes-store.ts","../../../src/client/store/themes-store-provider.tsx","../../../src/client/store/output-store.ts","../../../src/client/store/output-store-provider.tsx","../../../src/client/store/plugins-store.ts","../../../src/client/store/settings-store.ts","../../../src/client/store/settings-store-provider.tsx","../../../src/client/hooks/useMonacoPlugins.ts","../../../src/client/components/MonacoPluginProvider.tsx"],"sourcesContent":["function promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n let dbp;\n const getDB = () => {\n if (dbp)\n return dbp;\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n dbp = promisifyRequest(request);\n dbp.then((db) => {\n // It seems like Safari sometimes likes to just close the connection.\n // It's supposed to fire this event when that happens. Let's hope it does!\n db.onclose = () => (dbp = undefined);\n }, () => { });\n return dbp;\n };\n return (txMode, callback) => getDB().then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Delete multiple keys at once.\n *\n * @param keys List of keys to delete.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction delMany(keys, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n keys.forEach((key) => store.delete(key));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(store, callback) {\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAllKeys) {\n return promisifyRequest(store.getAllKeys());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.key)).then(() => items);\n });\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n return customStore('readonly', (store) => {\n // Fast path for modern browsers\n if (store.getAll) {\n return promisifyRequest(store.getAll());\n }\n const items = [];\n return eachCursor(store, (cursor) => items.push(cursor.value)).then(() => items);\n });\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n return customStore('readonly', (store) => {\n // Fast path for modern browsers\n // (although, hopefully we'll get a simpler path some day)\n if (store.getAll && store.getAllKeys) {\n return Promise.all([\n promisifyRequest(store.getAllKeys()),\n promisifyRequest(store.getAll()),\n ]).then(([keys, values]) => keys.map((key, i) => [key, values[i]]));\n }\n const items = [];\n return customStore('readonly', (store) => eachCursor(store, (cursor) => items.push([cursor.key, cursor.value])).then(() => items));\n });\n}\n\nexport { clear, createStore, del, delMany, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","/**\n * IndexedDB storage adapter for Zustand persist middleware using idb-keyval.\n */\nimport { get, set, del } from 'idb-keyval';\nimport type { StateStorage } from 'zustand/middleware';\n\nexport const idbStorage: StateStorage = {\n getItem: async (name: string): Promise<string | null> => {\n return (await get(name)) ?? null;\n },\n setItem: async (name: string, value: string): Promise<void> => {\n await set(name, value);\n },\n removeItem: async (name: string): Promise<void> => {\n await del(name);\n },\n};\n","import { persist, devtools, createJSONStorage } from 'zustand/middleware';\nimport { createStore } from 'zustand/vanilla';\nimport type { TextFile } from '../lib/types';\nimport { idbStorage } from '../lib/idb-storage';\n\nconst MAX_OPEN_TABS = 3;\n\nexport type DocumentType = 'application/json+report' | 'application/json+theme';\n\nexport type DocumentsState = {\n documents: TextFile[];\n openTabs: string[];\n activeTab: string;\n buildErrors: { [key: string]: string };\n documentTypes: { [key: string]: DocumentType };\n pendingDiffs: { [key: string]: { original: string; modified: string; applyId?: string } };\n acceptedApplyIds: string[];\n};\n\nexport type DocumentsActions = {\n createDocument: (name: string, text: string) => void;\n deleteDocument: (name: string) => void;\n saveDocument: (name: string, text: string) => void;\n renameDocument: (oldName: string, newName: string) => void;\n openDocument: (name: string) => void;\n closeDocument: (name: string) => void;\n setActiveTab: (name: string) => void;\n setBuildError: (name: string, buildError?: string) => void;\n setPendingDiff: (name: string, original: string, modified: string, applyId?: string) => void;\n clearPendingDiff: (name: string, accepted?: boolean) => void;\n};\n\nexport type DocumentsStore = DocumentsState & DocumentsActions;\n\nexport const initDocumentsStore = (): DocumentsState => {\n return {\n documents: [],\n openTabs: [],\n activeTab: '',\n buildErrors: {},\n documentTypes: {},\n pendingDiffs: {},\n acceptedApplyIds: [],\n };\n};\n\nexport const defaultInitDocumentsState: DocumentsState = {\n ...initDocumentsStore(),\n};\n\nexport const createDocumentsStore = (\n initState: DocumentsState = defaultInitDocumentsState\n) => {\n return createStore<DocumentsStore>()(\n devtools(\n persist(\n (set) => ({\n ...initState,\n createDocument: (name, text) =>\n set((state) => {\n const docIndex = state.documents.findIndex(\n (doc) => doc.name === name\n );\n if (docIndex === -1) {\n // if the document does not exist\n // Determine document type based on file name and content\n let docType: DocumentType = 'application/json+report';\n if (\n name.toLowerCase().includes('theme') ||\n name.toLowerCase().includes('.theme.')\n ) {\n docType = 'application/json+theme';\n } else {\n // Try to parse JSON to check if it's a theme\n try {\n const parsed = JSON.parse(text);\n if (parsed.colors && parsed.fonts && parsed.styles) {\n docType = 'application/json+theme';\n }\n } catch {\n // If not valid JSON, default to report\n }\n }\n\n const newDoc = {\n name,\n type: 'application/json',\n text,\n mtime: new Date(),\n ctime: new Date(),\n atime: new Date(),\n };\n return {\n documents: [...state.documents, newDoc],\n documentTypes: { ...state.documentTypes, [name]: docType },\n };\n }\n return state;\n }),\n deleteDocument: (name) =>\n set((state) => {\n const newDocumentTypes = { ...state.documentTypes };\n delete newDocumentTypes[name];\n return {\n documents: state.documents.filter((doc) => doc.name !== name),\n documentTypes: newDocumentTypes,\n pendingDiffs: Object.fromEntries(\n Object.entries(state.pendingDiffs).filter(([k]) => k !== name)\n ),\n };\n }),\n saveDocument: (name, text) =>\n set((state) => {\n const docIndex = state.documents.findIndex(\n (doc) => doc.name === name\n );\n if (docIndex === -1) return state;\n // Skip update if text is unchanged to avoid spurious re-renders\n if (state.documents[docIndex].text === text) return state;\n const documents = state.documents.map((doc, i) =>\n i === docIndex ? { ...doc, text, mtime: new Date() } : doc\n );\n return { documents };\n }),\n renameDocument: (oldName, newName) =>\n set((state) => {\n const docIndex = state.documents.findIndex(\n (doc) => doc.name === oldName\n );\n if (docIndex === -1) return state;\n const documents = state.documents.map((doc, i) =>\n i === docIndex ? { ...doc, name: newName, ctime: new Date() } : doc\n );\n const docType = state.documentTypes[oldName];\n if (docType) {\n const newDocumentTypes = { ...state.documentTypes };\n delete newDocumentTypes[oldName];\n newDocumentTypes[newName] = docType;\n return { documents, documentTypes: newDocumentTypes };\n }\n return { documents };\n }),\n openDocument: (name) =>\n set((state) => {\n const docIndex = state.documents.findIndex(\n (doc) => doc.name === name\n );\n if (docIndex === -1) return state;\n const documents = state.documents.map((doc, i) =>\n i === docIndex ? { ...doc, atime: new Date() } : doc\n );\n let openTabs = state.openTabs;\n if (!openTabs.includes(name)) {\n openTabs = openTabs.length >= MAX_OPEN_TABS\n ? [...openTabs.slice(1), name]\n : [...openTabs, name];\n }\n return { documents, openTabs, activeTab: name };\n }),\n closeDocument: (name) =>\n set((state) => {\n const index = state.openTabs.indexOf(name);\n if (index === -1) return state;\n const openTabs = state.openTabs.filter((tab) => tab !== name);\n let activeTab = state.activeTab;\n if (activeTab === name) {\n if (openTabs.length) {\n activeTab = index === 0 ? openTabs[0] : openTabs[index - 1];\n } else {\n activeTab = '';\n }\n }\n return { openTabs, activeTab };\n }),\n setActiveTab: (name) => set({ activeTab: name }),\n setBuildError: (name, buildError) =>\n set((state) => {\n if (state.buildErrors[name] === buildError) return state;\n const buildErrors = { ...state.buildErrors };\n if (buildError) buildErrors[name] = buildError;\n else delete buildErrors[name];\n return { buildErrors };\n }),\n setPendingDiff: (name, original, modified, applyId) =>\n set((state) => {\n return {\n pendingDiffs: {\n ...state.pendingDiffs,\n [name]: { original, modified, applyId },\n },\n };\n }),\n clearPendingDiff: (name, accepted) =>\n set((state) => {\n const diff = state.pendingDiffs[name];\n if (!diff) return state;\n const next = { ...state.pendingDiffs };\n delete next[name];\n const ids = state.acceptedApplyIds || [];\n const acceptedApplyIds =\n accepted && diff.applyId\n ? [...ids.slice(-(200 - 1)), diff.applyId]\n : ids;\n return { pendingDiffs: next, acceptedApplyIds };\n }),\n }),\n {\n name: 'documents-storage',\n version: 1,\n storage: createJSONStorage(() => idbStorage),\n partialize: (state) => ({\n documents: state.documents,\n openTabs: state.openTabs,\n activeTab: state.activeTab,\n documentTypes: state.documentTypes,\n // buildErrors + pendingDiffs + acceptedApplyIds excluded — transient UI state\n }),\n onRehydrateStorage: () => (state) => {\n if (state?.documents) {\n for (const doc of state.documents) {\n for (const key of ['mtime', 'ctime', 'atime'] as const) {\n if (doc[key] && typeof doc[key] === 'string') {\n (doc as Record<string, unknown>)[key] = new Date(doc[key] as unknown as string);\n }\n }\n }\n }\n },\n }\n )\n )\n );\n};\n","import { type ReactNode, createContext, useRef, useContext } from 'react';\nimport { useStore } from 'zustand';\nimport {\n type DocumentsStore,\n createDocumentsStore,\n initDocumentsStore,\n} from './documents-store';\n\nexport type DocumentsStoreApi = ReturnType<typeof createDocumentsStore>;\n\nexport const DocumentsStoreContext = createContext<\n DocumentsStoreApi | undefined\n>(undefined);\n\nexport interface DocumentsStoreProviderProps {\n children: ReactNode;\n}\n\nexport const DocumentsStoreProvider = ({\n children,\n}: DocumentsStoreProviderProps) => {\n const storeRef = useRef<DocumentsStoreApi | null>(null);\n if (!storeRef.current) {\n storeRef.current = createDocumentsStore(initDocumentsStore());\n }\n\n return (\n <DocumentsStoreContext.Provider value={storeRef.current}>\n {children}\n </DocumentsStoreContext.Provider>\n );\n};\n\nexport const useDocumentsStore = <T,>(\n selector: (store: DocumentsStore) => T\n): T => {\n const documentsStoreContext = useContext(DocumentsStoreContext);\n\n if (!documentsStoreContext) {\n throw new Error(\n 'useDocumentsStore must be used within DocumentsStoreProvider'\n );\n }\n\n return useStore(documentsStoreContext, selector);\n};\n","export interface ThemeValidationError {\n message: string;\n line?: number;\n column?: number;\n path?: string;\n}\n\nexport interface ThemeValidationResult {\n valid: boolean;\n errors?: ThemeValidationError[];\n}\n\n/**\n * Basic structural validation for theme JSON (used by themes store).\n * Full schema validation is handled by Monaco's JSON language service.\n */\nexport function validateThemeJson(jsonString: string): ThemeValidationResult {\n try {\n const parsed = JSON.parse(jsonString);\n\n if (!parsed || typeof parsed !== 'object') {\n return {\n valid: false,\n errors: [{ message: 'Theme must be a JSON object' }],\n };\n }\n\n if (typeof parsed.name !== 'string' || !parsed.name.trim()) {\n return {\n valid: false,\n errors: [{ message: 'Theme must have a non-empty \"name\" property' }],\n };\n }\n\n return { valid: true };\n } catch (e) {\n return {\n valid: false,\n errors: [\n {\n message:\n e instanceof SyntaxError\n ? `Invalid JSON: ${e.message}`\n : 'Failed to parse theme JSON',\n },\n ],\n };\n }\n}\n\n/**\n * Gets theme name from a theme JSON object\n */\nexport function getThemeName(themeJson: unknown): string | null {\n try {\n if (\n themeJson &&\n typeof themeJson === 'object' &&\n 'name' in (themeJson as any) &&\n typeof (themeJson as any).name === 'string'\n ) {\n return (themeJson as any).name as string;\n }\n return null;\n } catch {\n return null;\n }\n}\n","// Theme change event emitter for coordinating theme updates across components\nexport interface ThemeChangeEvent {\n themeName: string;\n timestamp: number;\n changeType: 'create' | 'update' | 'delete';\n}\n\nexport class ThemeChangeEmitter extends EventTarget {\n private static instance: ThemeChangeEmitter;\n\n private constructor() {\n super();\n }\n\n static getInstance(): ThemeChangeEmitter {\n if (!ThemeChangeEmitter.instance) {\n ThemeChangeEmitter.instance = new ThemeChangeEmitter();\n }\n return ThemeChangeEmitter.instance;\n }\n\n emitThemeChange(event: ThemeChangeEvent): void {\n this.dispatchEvent(new CustomEvent('themechange', { detail: event }));\n }\n\n onThemeChange(callback: (event: ThemeChangeEvent) => void): () => void {\n const handler = (e: Event) => {\n const customEvent = e as CustomEvent<ThemeChangeEvent>;\n callback(customEvent.detail);\n };\n\n this.addEventListener('themechange', handler);\n\n // Track listener count\n (this as any)._listenerCount = ((this as any)._listenerCount || 0) + 1;\n\n // Return unsubscribe function\n return () => {\n this.removeEventListener('themechange', handler);\n (this as any)._listenerCount = Math.max(\n 0,\n ((this as any)._listenerCount || 1) - 1\n );\n };\n }\n}\n\nexport const themeChangeEmitter = ThemeChangeEmitter.getInstance();\n","import { persist, devtools, createJSONStorage } from 'zustand/middleware';\nimport { createStore } from 'zustand/vanilla';\nimport type { ThemeConfigJson } from '@json-to-office/shared-pptx';\nimport { validateThemeJson, getThemeName } from '../lib/theme-validation';\nimport { themeChangeEmitter } from '../utils/theme-change-emitter';\nimport { idbStorage } from '../lib/idb-storage';\n\nexport type CustomTheme = {\n name: string;\n content: string;\n parsed?: ThemeConfigJson;\n valid: boolean;\n lastModified: Date;\n};\n\nexport type ThemesState = {\n customThemes: { [name: string]: CustomTheme };\n};\n\nexport type ThemesActions = {\n updateTheme: (documentName: string, content: string) => void;\n removeTheme: (documentName: string) => void;\n getTheme: (themeName: string) => ThemeConfigJson | null;\n getAllThemeNames: () => string[];\n isThemeValid: (themeName: string) => boolean;\n};\n\nexport type ThemesStore = ThemesState & ThemesActions;\n\nexport const initThemesStore = (): ThemesState => {\n return {\n customThemes: {},\n };\n};\n\nexport const defaultInitThemesState: ThemesState = {\n ...initThemesStore(),\n};\n\nexport const createThemesStore = (\n initState: ThemesState = defaultInitThemesState\n) => {\n return createStore<ThemesStore>()(\n devtools(\n persist(\n (set, get) => ({\n ...initState,\n\n updateTheme: (documentName, content) =>\n set((state) => {\n const validation = validateThemeJson(content);\n\n let parsed: ThemeConfigJson | undefined;\n let themeName = documentName;\n\n if (validation.valid) {\n try {\n const parsedContent = JSON.parse(content);\n parsed = parsedContent;\n const extractedName = getThemeName(parsedContent);\n if (extractedName) {\n themeName = extractedName;\n }\n } catch {\n // Keep the document name if parsing fails\n }\n }\n\n const existingTheme = state.customThemes[documentName];\n const isUpdate = !!existingTheme;\n const hasContentChanged = existingTheme?.content !== content;\n\n const customTheme: CustomTheme = {\n name: themeName,\n content,\n parsed,\n valid: validation.valid,\n lastModified: new Date(),\n };\n\n // Emit theme change if content changed OR if this is a newly valid theme\n const shouldEmitEvent =\n (hasContentChanged ||\n (!existingTheme?.valid && validation.valid)) &&\n validation.valid;\n\n if (shouldEmitEvent) {\n // Use setTimeout to ensure state is updated before event is processed\n setTimeout(() => {\n themeChangeEmitter.emitThemeChange({\n themeName,\n timestamp: Date.now(),\n changeType: isUpdate ? 'update' : 'create',\n });\n }, 0);\n }\n\n return {\n customThemes: {\n ...state.customThemes,\n [documentName]: customTheme,\n },\n };\n }),\n\n removeTheme: (documentName) =>\n set((state) => {\n const removedTheme = state.customThemes[documentName];\n const newCustomThemes = { ...state.customThemes };\n delete newCustomThemes[documentName];\n\n // Emit theme deletion event\n if (removedTheme) {\n setTimeout(() => {\n themeChangeEmitter.emitThemeChange({\n themeName: removedTheme.name,\n timestamp: Date.now(),\n changeType: 'delete',\n });\n }, 0);\n }\n\n return {\n customThemes: newCustomThemes,\n };\n }),\n\n getTheme: (themeName) => {\n const state = get();\n\n // First check custom themes by theme name\n for (const customTheme of Object.values(state.customThemes)) {\n if (\n customTheme.valid &&\n customTheme.name === themeName &&\n customTheme.parsed\n ) {\n return customTheme.parsed;\n }\n }\n\n // Theme not found in custom themes\n return null;\n },\n\n getAllThemeNames: () => {\n const state = get();\n const names: string[] = [];\n\n // Add custom theme names\n for (const customTheme of Object.values(state.customThemes)) {\n if (customTheme.valid && customTheme.name) {\n names.push(customTheme.name);\n }\n }\n\n return names;\n },\n\n isThemeValid: (themeName) => {\n const state = get();\n\n // Check custom themes\n for (const customTheme of Object.values(state.customThemes)) {\n if (customTheme.name === themeName) {\n return customTheme.valid;\n }\n }\n\n return false;\n },\n }),\n {\n name: 'themes-storage',\n version: 4, // v4: migrate from localStorage to IndexedDB\n storage: createJSONStorage(() => idbStorage),\n // Only persist the themes data, not the functions\n partialize: (state) => ({ customThemes: state.customThemes }),\n // Handle date deserialization when loading from storage\n onRehydrateStorage: () => (state) => {\n if (state && state.customThemes) {\n // Convert lastModified strings back to Date objects\n Object.keys(state.customThemes).forEach((key) => {\n const theme = state.customThemes[key];\n if (\n theme.lastModified &&\n typeof theme.lastModified === 'string'\n ) {\n theme.lastModified = new Date(theme.lastModified);\n }\n });\n }\n },\n }\n )\n )\n );\n};\n","import { type ReactNode, createContext, useRef, useContext } from 'react';\nimport { useStore } from 'zustand';\n\nimport {\n type ThemesStore,\n createThemesStore,\n initThemesStore,\n} from './themes-store';\n\nexport type ThemesStoreApi = ReturnType<typeof createThemesStore>;\n\nexport const ThemesStoreContext = createContext<ThemesStoreApi | undefined>(\n undefined\n);\n\nexport interface ThemesStoreProviderProps {\n children: ReactNode;\n}\n\nexport const ThemesStoreProvider = ({ children }: ThemesStoreProviderProps) => {\n const storeRef = useRef<ThemesStoreApi>(undefined);\n if (!storeRef.current) {\n storeRef.current = createThemesStore(initThemesStore());\n }\n\n return (\n <ThemesStoreContext.Provider value={storeRef.current}>\n {children}\n </ThemesStoreContext.Provider>\n );\n};\n\nexport const useThemesStore = <T,>(selector: (store: ThemesStore) => T): T => {\n const themesStoreContext = useContext(ThemesStoreContext);\n\n if (!themesStoreContext) {\n throw new Error('useThemesStore must be used within ThemesStoreProvider');\n }\n\n return useStore(themesStoreContext, selector);\n};\n","import { devtools } from 'zustand/middleware';\nimport { createStore } from 'zustand/vanilla';\n\nexport interface GenerationWarning {\n component: string;\n message: string;\n severity?: 'warning' | 'info';\n context?: Record<string, unknown>;\n}\n\nexport type OutputState = {\n name?: string; // last success => document name\n text?: string; // last success => code used to generate the document\n blob?: Blob; // last success => generated document\n renderer?: string; // last success => backend captured with the generated bytes\n globalError?: string; // last failed => global error message\n isGenerating?: boolean; // document generation in progress\n generationProgress?: {\n stage: 'parsing' | 'building' | 'rendering' | 'finalizing';\n message?: string;\n };\n generationStartedAt?: number; // Date.now() when the current build started\n cancelGeneration?: () => void; // registered by the editor; aborts the in-flight build\n cacheStatus?: 'HIT' | 'MISS' | 'UNKNOWN'; // cache hit/miss status\n cacheHitRate?: string; // cache hit rate percentage\n warnings?: GenerationWarning[] | null; // warnings from custom component processing\n isRendering?: boolean; // preview rendering in progress (iframe/LibreOffice)\n isPreviewStale?: boolean; // preview outdated (new blob generated but not yet rendered)\n editSequence?: number; // incremented on every Monaco keystroke (init 0)\n lastBuiltSequence?: number; // stamped when generation completes (init 0)\n editTimestamp?: number; // Date.now() of the last edit (for debounce countdown)\n hasValidationErrors?: boolean; // true when Monaco reports schema validation errors\n // ⚠️ name doesn't necessarily correspond to the global error message\n};\n\nexport type OutputActions = {\n setOutput: (partialState: OutputState) => void;\n bumpEditSequence: () => void;\n};\n\nexport type OutputStore = OutputState & OutputActions;\n\nexport const initOutputStore = (): OutputState => {\n return {\n name: undefined,\n text: undefined,\n blob: undefined,\n globalError: undefined,\n isGenerating: false,\n generationProgress: undefined,\n isRendering: false,\n isPreviewStale: false,\n editSequence: 0,\n lastBuiltSequence: 0,\n hasValidationErrors: false,\n };\n};\n\nexport const defaultInitOutputState: OutputState = {\n ...initOutputStore(),\n};\n\nexport const createOutputStore = (\n initState: OutputState = defaultInitOutputState\n) => {\n return createStore<OutputStore>()(\n devtools((set) => ({\n ...initState,\n setOutput: (partialState) => set({ ...partialState }),\n bumpEditSequence: () =>\n set((s) => ({\n editSequence: (s.editSequence ?? 0) + 1,\n editTimestamp: Date.now(),\n })),\n }))\n );\n};\n","import { type ReactNode, createContext, useRef, useContext } from 'react';\nimport { useStore } from 'zustand';\nimport {\n type OutputStore,\n createOutputStore,\n initOutputStore,\n} from './output-store';\n\nexport type OutputStoreApi = ReturnType<typeof createOutputStore>;\n\nexport const OutputStoreContext = createContext<OutputStoreApi | undefined>(\n undefined\n);\n\nexport interface OutputStoreProviderProps {\n children: ReactNode;\n}\n\nexport const OutputStoreProvider = ({ children }: OutputStoreProviderProps) => {\n const storeRef = useRef<OutputStoreApi | null>(null);\n if (!storeRef.current) {\n storeRef.current = createOutputStore(initOutputStore());\n }\n\n return (\n <OutputStoreContext.Provider value={storeRef.current}>\n {children}\n </OutputStoreContext.Provider>\n );\n};\n\nexport const useOutputStore = <T,>(selector: (store: OutputStore) => T): T => {\n const outputStoreContext = useContext(OutputStoreContext);\n\n if (!outputStoreContext) {\n throw new Error('useOutputStore must be used within OutputStoreProvider');\n }\n\n return useStore(outputStoreContext, selector);\n};\n","import { create } from 'zustand';\nimport { persist } from 'zustand/middleware';\nimport type { PluginMetadata } from '../hooks/useDiscovery';\n\ninterface PluginsState {\n // Selected plugin names (used for schema generation)\n selectedPlugins: Set<string>;\n\n // Full plugin metadata for selected plugins\n selectedPluginMetadata: Map<string, PluginMetadata>;\n\n // Schema application state\n isApplyingPlugins: boolean;\n lastApplyError: string | null;\n\n // Actions\n selectPlugin: (plugin: PluginMetadata) => void;\n deselectPlugin: (pluginName: string) => void;\n togglePlugin: (plugin: PluginMetadata) => void;\n clearSelections: () => void;\n isPluginSelected: (pluginName: string) => boolean;\n getSelectedPluginsList: () => PluginMetadata[];\n getSelectedPluginNames: () => string[];\n applyPluginsWithValidation: (\n onSuccess?: () => void,\n onError?: (error: string) => void\n ) => Promise<boolean>;\n}\n\nexport const usePluginsStore = create<PluginsState>()(\n persist(\n (set, get) => ({\n selectedPlugins: new Set<string>(),\n selectedPluginMetadata: new Map<string, PluginMetadata>(),\n isApplyingPlugins: false,\n lastApplyError: null,\n\n selectPlugin: (plugin: PluginMetadata) => {\n set((state) => {\n const newSelectedPlugins = new Set(state.selectedPlugins);\n const newMetadata = new Map(state.selectedPluginMetadata);\n\n newSelectedPlugins.add(plugin.name);\n newMetadata.set(plugin.name, plugin);\n\n return {\n selectedPlugins: newSelectedPlugins,\n selectedPluginMetadata: newMetadata,\n };\n });\n },\n\n deselectPlugin: (pluginName: string) => {\n set((state) => {\n const newSelectedPlugins = new Set(state.selectedPlugins);\n const newMetadata = new Map(state.selectedPluginMetadata);\n\n newSelectedPlugins.delete(pluginName);\n newMetadata.delete(pluginName);\n\n return {\n selectedPlugins: newSelectedPlugins,\n selectedPluginMetadata: newMetadata,\n };\n });\n },\n\n togglePlugin: (plugin: PluginMetadata) => {\n const isSelected = get().isPluginSelected(plugin.name);\n if (isSelected) {\n get().deselectPlugin(plugin.name);\n } else {\n get().selectPlugin(plugin);\n }\n // Auto-apply schema changes\n get().applyPluginsWithValidation().catch(console.error);\n },\n\n clearSelections: () => {\n set({\n selectedPlugins: new Set<string>(),\n selectedPluginMetadata: new Map<string, PluginMetadata>(),\n });\n // Auto-apply schema changes\n get().applyPluginsWithValidation().catch(console.error);\n },\n\n isPluginSelected: (pluginName: string) => {\n return get().selectedPlugins.has(pluginName);\n },\n\n getSelectedPluginsList: () => {\n return Array.from(get().selectedPluginMetadata.values());\n },\n\n getSelectedPluginNames: () => {\n return Array.from(get().selectedPlugins);\n },\n\n applyPluginsWithValidation: async (onSuccess, onError) => {\n set({ isApplyingPlugins: true, lastApplyError: null });\n\n try {\n // Get the current selected plugins\n const selectedPluginNames = Array.from(get().selectedPlugins);\n\n // Import Monaco and schema update function dynamically\n const { loader } = await import('@monaco-editor/react');\n const { updateMonacoWithPlugins } = await import(\n '../lib/monaco-config'\n );\n\n // Get Monaco instance\n const monaco = await loader.init();\n\n // Apply the plugins and wait for validation\n const success = await updateMonacoWithPlugins(\n monaco,\n selectedPluginNames\n );\n\n if (!success) {\n throw new Error('Schema validation failed');\n }\n\n // Success - schema has been applied and validated\n set({ isApplyingPlugins: false, lastApplyError: null });\n\n if (onSuccess) {\n onSuccess();\n }\n\n return true;\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : 'Failed to apply plugin schemas';\n\n set({\n isApplyingPlugins: false,\n lastApplyError: errorMessage,\n });\n\n if (onError) {\n onError(errorMessage);\n }\n\n console.error('Failed to apply plugins with validation:', error);\n return false;\n }\n },\n }),\n {\n name: 'jtp-selected-plugins',\n // Custom storage to handle Set and Map serialization\n storage: {\n getItem: (name) => {\n const str = localStorage.getItem(name);\n if (!str) return null;\n\n const { state } = JSON.parse(str);\n return {\n state: {\n ...state,\n selectedPlugins: new Set(state.selectedPlugins || []),\n selectedPluginMetadata: new Map(\n state.selectedPluginMetadata || []\n ),\n },\n };\n },\n setItem: (name, value) => {\n const { state } = value as { state: PluginsState };\n const serialized = JSON.stringify({\n state: {\n ...state,\n selectedPlugins: Array.from(state.selectedPlugins),\n selectedPluginMetadata: Array.from(\n state.selectedPluginMetadata.entries()\n ),\n },\n });\n localStorage.setItem(name, serialized);\n },\n removeItem: (name) => localStorage.removeItem(name),\n },\n }\n )\n);\n","import { devtools, persist } from 'zustand/middleware';\nimport { createStore } from 'zustand/vanilla';\nimport type { Settings } from '../lib/types';\n\nexport type SettingsState = Settings;\n\nexport type SettingsActions = {\n setSettings: (settings: Partial<Settings>) => void;\n};\n\nexport type SettingsStore = SettingsState & SettingsActions;\n\nexport const initSettingsStore = (): SettingsState => {\n return {\n saveDocumentDebounceWait: 300,\n // UI preference to use a single preview header spanning editor + preview\n useGlobalPreviewHeader: true,\n };\n};\n\nexport const defaultInitSettingsState: SettingsState = {\n ...initSettingsStore(),\n};\n\nexport const createSettingsStore = (\n initState: SettingsState = defaultInitSettingsState\n) => {\n return createStore<SettingsStore>()(\n devtools(\n persist(\n (set) => ({\n ...initState,\n setSettings: (settings) => set({ ...settings }),\n }),\n {\n name: 'settings-storage', // name of the item in the storage (must be unique)\n // (optional) by default, 'localStorage' is used as storage\n }\n )\n )\n );\n};\n","import { type ReactNode, createContext, useRef, useContext } from 'react';\nimport { useStore } from 'zustand';\nimport {\n type SettingsStore,\n createSettingsStore,\n initSettingsStore,\n} from './settings-store';\n\nexport type SettingsStoreApi = ReturnType<typeof createSettingsStore>;\n\nexport const SettingsStoreContext = createContext<SettingsStoreApi | undefined>(\n undefined\n);\n\nexport interface SettingsStoreProviderProps {\n children: ReactNode;\n}\n\nexport const SettingsStoreProvider = ({\n children,\n}: SettingsStoreProviderProps) => {\n const storeRef = useRef<SettingsStoreApi | null>(null);\n if (!storeRef.current) {\n storeRef.current = createSettingsStore(initSettingsStore());\n }\n\n return (\n <SettingsStoreContext.Provider value={storeRef.current}>\n {children}\n </SettingsStoreContext.Provider>\n );\n};\n\nexport const useSettingsStore = <T,>(\n selector: (store: SettingsStore) => T\n): T => {\n const settingsStoreContext = useContext(SettingsStoreContext);\n\n if (!settingsStoreContext) {\n throw new Error(\n 'useSettingsStore must be used within SettingsStoreProvider'\n );\n }\n\n return useStore(settingsStoreContext, selector);\n};\n","import { useEffect, useRef, useContext, useSyncExternalStore } from 'react';\nimport { loader } from '@monaco-editor/react';\nimport type { Monaco } from '@monaco-editor/react';\nimport { usePluginsStore } from '../store/plugins-store';\nimport { ThemesStoreContext } from '../store/themes-store-provider';\nimport { updateMonacoWithPlugins } from '../lib/monaco-config';\n\nconst emptyNames: string[] = [];\nconst subscribe = () => () => {};\n\n/**\n * Read custom theme names from the ThemesStore if available,\n * returning [] when outside a ThemesStoreProvider.\n *\n * getSnapshot must return a referentially stable value to avoid\n * infinite re-renders with useSyncExternalStore.\n */\nfunction useCustomThemeNames(): string[] {\n const store = useContext(ThemesStoreContext);\n const cachedRef = useRef<string[]>(emptyNames);\n\n const getSnapshot = store\n ? () => {\n const next = store.getState().getAllThemeNames();\n // Only update the cached reference when the list actually changes\n if (\n next.length !== cachedRef.current.length ||\n next.some((n, i) => n !== cachedRef.current[i])\n ) {\n cachedRef.current = next;\n }\n return cachedRef.current;\n }\n : () => emptyNames;\n\n return useSyncExternalStore(store ? store.subscribe : subscribe, getSnapshot);\n}\n\n/**\n * Hook to synchronize selected plugins and custom themes with Monaco editor schemas.\n * Ensures real-time validation and autocomplete include plugin-specific schemas\n * and custom theme names.\n */\nexport function useMonacoPlugins() {\n const monacoRef = useRef<Monaco | null>(null);\n const selectedPlugins = usePluginsStore((state) => state.selectedPlugins);\n const selectedPluginNames = Array.from(selectedPlugins);\n const customThemeNames = useCustomThemeNames();\n const themesStore = useContext(ThemesStoreContext);\n const themesStoreRef = useRef(themesStore);\n themesStoreRef.current = themesStore;\n const previousPluginsRef = useRef<string[]>([]);\n const previousThemesRef = useRef<string[]>([]);\n\n useEffect(() => {\n loader\n .init()\n .then((monaco) => {\n monacoRef.current = monaco;\n // Read current state from stores (not stale closure) since\n // zustand persist may have hydrated while loader.init() was pending\n const currentPlugins = Array.from(\n usePluginsStore.getState().selectedPlugins\n );\n const currentThemes =\n themesStoreRef.current?.getState().getAllThemeNames() ?? [];\n updateMonacoWithPlugins(monaco, currentPlugins, currentThemes)\n .then((success) => {\n if (success) {\n console.log(\n '[useMonacoPlugins] Monaco initialized with plugins:',\n currentPlugins\n );\n } else {\n console.warn(\n '[useMonacoPlugins] Monaco initialization completed with warnings'\n );\n }\n })\n .catch((error) => {\n console.error(\n '[useMonacoPlugins] Failed to update Monaco with plugins:',\n error\n );\n });\n previousPluginsRef.current = [...currentPlugins];\n previousThemesRef.current = [...currentThemes];\n })\n .catch((error) => {\n console.error('Failed to initialize Monaco:', error);\n });\n }, []); // Keep empty dependency to run only once\n\n useEffect(() => {\n const pluginsChanged =\n selectedPluginNames.length !== previousPluginsRef.current.length ||\n selectedPluginNames.some(\n (name, index) => name !== previousPluginsRef.current[index]\n );\n\n const themesChanged =\n customThemeNames.length !== previousThemesRef.current.length ||\n customThemeNames.some(\n (name, index) => name !== previousThemesRef.current[index]\n );\n\n if (!pluginsChanged && !themesChanged) {\n return;\n }\n\n if (monacoRef.current) {\n updateMonacoWithPlugins(\n monacoRef.current,\n selectedPluginNames,\n customThemeNames\n ).catch((error) => {\n console.error(\n '[useMonacoPlugins] Failed to update Monaco schemas:',\n error\n );\n });\n previousPluginsRef.current = [...selectedPluginNames];\n previousThemesRef.current = [...customThemeNames];\n }\n }, [selectedPluginNames, customThemeNames]);\n\n return {\n monaco: monacoRef.current,\n selectedPlugins: selectedPluginNames,\n };\n}\n","import { useMonacoPlugins } from '../hooks/useMonacoPlugins';\n\n/**\n * Provider component that manages Monaco plugin synchronization\n * This must be rendered within the app after stores are initialized\n */\nexport function MonacoPluginProvider({\n children,\n}: {\n children: React.ReactNode;\n}) {\n // Initialize Monaco plugin synchronization\n useMonacoPlugins();\n\n return <>{children}</>;\n}\n"],"file":"assets/MonacoPluginProvider-CE5NPGwN.js"}
@@ -1,9 +0,0 @@
1
- import{c as W,r as E,j as x}from"./react-vendor-BmQ2Ko_D.js";import{g as ne,c as re,V as le,a as ue,E as de}from"./editor-monaco-json-CAlvfPc7.js";import{g as fe,r as ge,o as ee,F as me}from"./index-DLlW4q4v.js";import he,{DiffEditor as pe}from"./monaco-editor-DJsdM0WK.js";import{u as Q,a as ce,b as be,f as Ce,h as Ee,T as we,d as Re,t as ye}from"./MonacoPluginProvider-CE5NPGwN.js";import{u as Z,B as oe,d as Se}from"./editor-refs-store-DKOJcTAk.js";import{T as ve,u as Le,a as Me}from"./HomePage-jkIz_s7u.js";import{u as se}from"./state-vendor-Cq67_JbF.js";import"./ui-vendor-DpjQWJgX.js";import"./query-vendor--rhYD8mC.js";import"./radix-ui-DFNP5I4e.js";const Te={initWith:function(e){const S=document.createElement("div"),f=e.editor.create(S),R=f.constructor.name,I=f.getModel().constructor.name;return{isInstanceValid:function(g){return g.constructor.name===R},isModelValid:function(g){return g.constructor.name===I},isRangesValid:function(g){return Array.isArray(g)?g.every(function(y){return typeof y=="object"&&y.constructor.name==="Object"?!(!y.hasOwnProperty("range")||!Array.isArray(y.range)||y.range.length!==4||!y.range.every(v=>v>0&&parseInt(v)===v)||y.hasOwnProperty("allowMultiline")&&typeof y.allowMultiline!="boolean"||y.hasOwnProperty("label")&&typeof y.label!="string"||y.hasOwnProperty("validate")&&typeof y.validate!="function"):!1}):!1}}}},X=function(e,S,f){return"The value for the "+S+" should be of type "+(Array.isArray(e)?e.join(" | "):e)+". "+(f||"")},te=function(){const e=function(i,T){return typeof i!="object"||i===null?this.freeze?Object.freeze(i):i:i instanceof Date?this.freeze?Object.freeze(new Date(i)):new Date(i):T.call(this,i)},S=function(i,T){const g=Object.keys(i),y=new Array(g.length);for(let v=0;v<g.length;v++)y[g[v]]=e.call(this,i[g[v]],T);return y},f=function(i){return e.call(this,i,function(T){if(Array.isArray(T))return S.call(this,T,f);const g={};for(let y in T)!this.withProto&&Object.hasOwnProperty.call(T,y)===!1||(g[y]=e.call(this,T[y],f));return g})},R=function(){const i=function(g){const y=["withProto","freeze"];this[g]=y.reduce((function(v,b){return(v[b]=g>=this[b])&&(g-=this[b]),v}).bind(this),{})},T=Object.create(Object.defineProperties({},{withProto:{value:1},freeze:{value:2}}));for(let g=0;g<=3;g++)i.call(T,g);return T}(),I={withProto:f.bind(R[1]),andFreeze:f.bind(R[2]),withProtoAndFreeze:f.bind(R[3])},N=f.bind(R[0]);for(let i in I)Object.defineProperty(N,i,{enumerable:!1,writable:!1,configurable:!1,value:I[i]});return N}(),ie={SINGLE_LINE_HIGHLIGHT_CLASS:"editableArea--single-line",MULTI_LINE_HIGHLIGHT_CLASS:"editableArea--multi-line"},Ne=function(e,S,f){const R=f.Range,I=function(t,s){const r=t.range,c=s.range;if(r[0]<c[0]||r[0]===c[0]&&r[3]<c[1])return-1},N=function(t,s){const r=s.split(`
2
- `),c=r.length,u=[];return t.forEach(function(h,n){if(h===0)throw new Error("Range values cannot be zero");switch(n){case 0:{if(h<0)throw new Error("Start Line of Range cannot be negative");if(h>c)throw new Error("Provided Start Line("+h+") is out of bounds. Max Lines in content is "+c);u[n]=h}break;case 1:{let a=h;const o=u[0],l=r[o-1].length;if(a<0){if(a=l-Math.abs(a),a<0)throw new Error("Provided Start Column("+h+") is out of bounds. Max Column in line "+o+" is "+l)}else if(a>l+1)throw new Error("Provided Start Column("+h+") is out of bounds. Max Column in line "+o+" is "+l);u[n]=a}break;case 2:{let a=h;if(a<0){if(a=c-Math.abs(h),a<0)throw new Error("Provided End Line("+h+") is out of bounds. Max Lines in content is "+c);a<u[0]&&console.warn("Provided End Line("+h+") is less than the start Line, the Restriction may not behave as expected")}else if(h>c)throw new Error("Provided End Line("+h+") is out of bounds. Max Lines in content is "+c);u[n]=a}break;case 3:{let a=h;const o=u[2],l=r[o-1].length;if(a<0){if(a=l-Math.abs(a),a<0)throw new Error("Provided End Column("+h+") is out of bounds. Max Column in line "+o+" is "+l)}else if(a>l+1)throw new Error("Provided Start Column("+h+") is out of bounds. Max Column in line "+o+" is "+l);u[n]=a}break}}),u};let i=te(S).sort(I);const T=function(t){const s=e.getValue();t.forEach(function(r,c){const u=N(r.range,s),h=u[0],n=u[1],a=u[2],o=u[3];r._originalRange=u.slice(),r.range=new R(h,n,a,o),r.index=c,r.allowMultiline||(r.allowMultiline=R.spansMultipleLines(r.range)),r.label||(r.label=`[${h},${n} -> ${a}${o}]`)})},g=function(){return i.reduce(function(t,s){return t[s.label]={allowMultiline:s.allowMultiline||!1,index:s.index,range:Object.assign({},s.range),originalRange:s._originalRange.slice()},t},{})},y=function(){return i.reduce(function(t,s){return t[s.label]=e.getValueInRange(s.range),t},{})},v=function(t,s){if(typeof t=="object"&&!Array.isArray(t)){s=typeof s=="boolean"?s:!1;const r=i.reduce(function(c,u){return u.label&&(c[u.label]=u),c},{});for(let c in t){const u=r[c];if(u){const h=t[c];if(J(u,h))throw new Error("Multiline change is not allowed for "+c);const n=te(u.range);if(n.endLine=n.startLine+h.split(`
3
- `).length-1,n.endColumn=h.split(`
4
- `).pop().length,Y(u,h,n))throw new Error("Change is invalidated by validate function of "+c);e.applyEdits([{forceMoveMarkers:!!s,range:u.range,text:h}])}else console.error("No restriction found for "+c)}}else throw new Error("Value must be an object")},b=function(){return e._restrictionChangeListener.dispose(),window.removeEventListener("error",B),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},O=function(t){t.some(function(s){const r=s.lineNumber,c=s.column,u=i.length;for(let h=0;h<u;h++){const n=i[h].range;if(n.startLineNumber===r&&n.startColumn===c||n.endLineNumber===r&&n.endColumn===c)return e.pushStackElement(),!0}})},G=function(t){typeof t=="function"&&e._editableRangeChangeListener.push(t)},w=function(t,s){const r=g();e._editableRangeChangeListener.forEach(function(c){c.call(e,t,s,r)})},L=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(t){t.range=e.getDecorationRange(t.id)}))})},M=function(t,s,r,c,u,h){let n=s.endLineNumber,a=s.endColumn;t.prevRange=s,t.range=s.setEndPosition(r,c);const o=i.length;let l=u.length;const p=c-a,_=r-n,D=e._currentCursorPositions||[],j=D.length;if(l!==j&&(u=u.filter(function(C){const m=C.range;for(let d=0;d<j;d++){const A=D[d];if(m.startLineNumber===A.startLineNumber&&m.endLineNumber===A.endLineNumber&&m.startColumn===A.startColumn&&m.endColumn===A.endColumn)return!0}return!1}),l=u.length),_!==0){for(let C=t.index+1;C<o;C++){const m=i[C],d=m.range;n===d.startLineNumber&&(d.startColumn+=p),n===d.endLineNumber&&(d.endColumn+=p),d.startLineNumber+=_,d.endLineNumber+=_,m.range=d}for(let C=h+1;C<l;C++){const m=u[C],d=m.range,A=d.toString(),z=rangeMap[A];delete rangeMap[A],n===d.startLineNumber&&(d.startColumn+=p),n===d.endLineNumber&&(d.endColumn+=p),d.startLineNumber+=_,d.endLineNumber+=_,m.range=d,rangeMap[d.toString()]=z}}else{for(let C=t.index+1;C<o;C++){const m=i[C],d=m.range;if(d.startLineNumber>n)break;d.startColumn+=p,d.endColumn+=p,m.range=d}for(let C=h+1;C<l;C++){const m=u[C],d=m.range,A=d.toString(),z=rangeMap[A];if(delete rangeMap[A],d.startLineNumber>n){rangeMap[d.toString()]=z;break}else d.startColumn+=p,d.endColumn+=p,m.range=d,rangeMap[d.toString()]=z}}},P=function(t,s){const r={},c=t.range;return t.text===""?r.isDeletion=!0:c.startLineNumber===c.endLineNumber&&c.startColumn===c.endColumn?r.isAddition=!0:r.isReplacement=!0,r.startLineOfRange=c.startLineNumber===s.startLineNumber,r.startColumnOfRange=c.startColumn===s.startColumn,r.endLineOfRange=c.endLineNumber===s.endLineNumber,r.endColumnOfRange=c.endColumn===s.endColumn,r.middleLineOfRange=!r.startLineOfRange&&!r.endLineOfRange,s.startLineNumber===s.endLineNumber?r.rangeIsSingleLine=!0:r.rangeIsMultiLine=!0,r},V=function(t){i=te(t).sort(I),T(i)},U=function(t){if(e._hasHighlight)e.deltaDecorations(e._oldDecorations,[]),delete e._oldDecorations,delete e._oldDecorationsSource,e._hasHighlight=!1;else{const s=t.cssClassForSingleLine||ie.SINGLE_LINE_HIGHLIGHT_CLASS,r=t.cssClassForMultiLine||ie.MULTI_LINE_HIGHLIGHT_CLASS,c=i.map(function(u){const h={range:u.range,options:{className:u.allowMultiline?r:s}};return u.label&&(h.hoverMessage=u.label),h});e._oldDecorations=e.deltaDecorations([],c),e._oldDecorationsSource=c.map(function(u,h){return Object.assign({},u,{id:e._oldDecorations[h]})}),e._hasHighlight=!0}},B=function(){console.debug("handler for unhandled promise rejection")},F=function(t){for(let s in t){const r=t[s];r.range=r.prevRange}},J=function(t,s){return!t.allowMultiline&&s.includes(`
5
- `)},Y=function(t,s,r){return t.validate&&!t.validate(s,r,t.lastInfo)},K={_isRestrictedModel:!0,_isRestrictedValueValid:!0,_editableRangeChangeListener:[],_isCursorAtCheckPoint:O,_currentCursorPositions:[]};T(i),e._hasHighlight=!1,K._restrictionChangeListener=e.onDidChangeContent(function(t){const s=t.isUndoing;if(e._isRestrictedValueValid=!0,s&&e.editInRestrictedArea)e.editInRestrictedArea&&(e._isRestrictedValueValid=!1);else{const r=t.changes.sort(I),c={},u=i.length;if(r.every(function(n){const a=n.range,o=a.toString();c[o]=null;for(let l=0;l<u;l++){const p=i[l];if(p.range.containsRange(a))return J(p,n.text)?!1:(c[o]=p,!0)}return!1})){r.forEach(function(o,l){const p=o.range,_=c[p.toString()],D=_.range,j=o.text||"",C=(j.match(/\n/g)||[]).length,m=j.split(/\n/g).pop().length,d=p.endLineNumber-p.startLineNumber,A=p.endColumn-p.startColumn;let z=D.endLineNumber,H=D.endColumn,q=0;(D.endLineNumber===p.startLineNumber||D.endLineNumber===p.endLineNumber)&&(q+=D.endColumn-p.startColumn+1);const k=P(o,D);_.lastInfo=k,(k.isAddition||k.isReplacement)&&(k.rangeIsSingleLine&&(C===0?H+=m:(z+=C,k.startColumnOfRange?H+=m:k.endColumnOfRange?H=m+1:H=m+q)),k.rangeIsMultiLine&&(z+=C,k.endLineOfRange&&(C===0?H+=m:H=q+m))),(k.isDeletion||k.isReplacement)&&(k.rangeIsSingleLine&&(H-=A),k.rangeIsMultiLine&&(k.endLineOfRange?(z-=d,H-=A):z-=d)),M(_,D,z,H,r,l)});const n=e.getValueInEditableRanges(),a={};for(let o in c){const l=c[o],p=l.range,_=l.label||p.toString(),D=n[_];if(Y(l,D,p)){F(c),L();return}a[_]=D}e._hasHighlight&&e._oldDecorationsSource.forEach(function(o){o.range=e.getDecorationRange(o.id)}),w(a,n)}else L()}}),window.onerror=B;const $={editInRestrictedArea:!1,getCurrentEditableRanges:g,getValueInEditableRanges:y,disposeRestrictions:b,onDidChangeContentInEditableRange:G,updateRestrictions:V,updateValueInEditableRanges:v,toggleHighlightOfEditableAreas:U};for(let t in K)Object.defineProperty(e,t,{enumerable:!1,configurable:!0,writable:!0,value:K[t]});for(let t in $)Object.defineProperty(e,t,{enumerable:!1,configurable:!0,writable:!0,value:$[t]});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 S=function(w){const L=w.getModel();if(L._isCursorAtCheckPoint){const M=w.getSelections(),P=M.map(function(V){return{lineNumber:V.positionLineNumber,column:V.positionColumn}});L._isCursorAtCheckPoint(P),L._currentCursorPositions=M}},f={},{isInstanceValid:R,isModelValid:I,isRangesValid:N}=Te.initWith(e),i=function(w){if(R(w)){let L=w.getDomNode();return b._listener=S.bind(O,w),b._editorInstance=w,b._editorInstance._isInDevMode=!1,L.addEventListener("keydown",b._listener,!0),b._onChangeModelDisposable=w.onDidChangeModel(function(){L&&L.removeEventListener("keydown",b._listener,!0);const M=w.getDomNode();M&&M.addEventListener("keydown",b._listener,!0),L=M}),!0}else throw new Error(X("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},T=function(w,L){if(I(w))if(N(L)){const M=Ne(w,L,e);return f[M.uri.toString()]=M,M}else throw new Error(X("Array<RangeRestrictionObject>","ranges","Please refer constrained editor documentation for proper structure"));else throw new Error(X("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},g=function(w){if(I(w)){const L=w.uri.toString(),M=f[L];return M?M.disposeRestrictions():(console.warn("Current Model is not a restricted Model"),!1)}else throw new Error(X("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},y=function(){if(b._editorInstance){const L=b._editorInstance.getDomNode();L&&L.removeEventListener("keydown",b._listener),b._onChangeModelDisposable&&b._onChangeModelDisposable.dispose(),delete b._listener,delete b._editorInstance._isInDevMode,delete b._editorInstance._devModeAction,delete b._editorInstance,delete b._onChangeModelDisposable;for(let M in f)delete f[M];return!0}return!1},v=function(){b._editorInstance._isInDevMode?(b._editorInstance._isInDevMode=!1,b._editorInstance._devModeAction.dispose(),delete b._editorInstance._devModeAction):(b._editorInstance._isInDevMode=!0,b._editorInstance._devModeAction=b._editorInstance.addAction({id:"showRange",label:"Show Range in console",contextMenuGroupId:"navigation",contextMenuOrder:1.5,run:function(w){const M=w.getSelections().reduce(function(P,{startLineNumber:V,endLineNumber:U,startColumn:B,endColumn:F}){return P.push("range : "+JSON.stringify([V,B,U,F])),P},[]).join(`
7
- `);console.log(`Selected Ranges :
8
- `+JSON.stringify(M,null,2))}}))},b={_listener:null,_editorInstance:null,_uriRestrictionMap:f,_injectedResources:e},O=Object.create(b),G={initializeIn:i,addRestrictionsTo:T,removeRestrictionsIn:g,disposeConstrainer:y,toggleDevMode:v};for(let w in G)Object.defineProperty(O,w,{enumerable:!1,writable:!1,configurable:!1,value:G[w]});return Object.freeze(O)}function De(e){const S=`.${me}.theme.json`;return e.endsWith(S)?e:e.replace(/\.\w+\.theme\.json$/,"").replace(/\.theme\.json$/,"").replace(/\.json$/,"")+S}function Ie({document:e,readOnly:S=!1,onChange:f}){const R=E.useRef(null),I=E.useRef(null),N=E.useRef(null),{theme:i}=fe(),[T,g]=E.useState([]),[y,v]=E.useState(!0),[b,O]=E.useState(!1),G=E.useRef(!1),w=Q(t=>t.pendingDiffs[e.name]),L=Q(t=>t.clearPendingDiff),M=Q(t=>t.saveDocument),{registerEditor:P,unregisterEditor:V,setActiveEditor:U}=Z(),B=i==="system"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":i,F=E.useCallback(t=>{I.current=t,ge(t)},[]),J=E.useCallback((t,s)=>{R.current=t,N.current=t.getModel(),P(e.name,t,s),U(e.name);const r=_e(s);t.getModel()&&r.initializeIn(t),t.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}}),t.addCommand(s.KeyMod.CtrlCmd|s.KeyCode.KeyK,()=>{const u=ne(t,s);if(u){const h=re(u);window.dispatchEvent(new CustomEvent("monaco-selection-to-ai",{detail:{documentName:e.name,selection:u,snippet:h,isTheme:!0}}))}}),t.addCommand(s.KeyMod.CtrlCmd|s.KeyCode.KeyS,()=>{console.log("Save command triggered in theme editor")}),t.addAction({id:"send-theme-to-ai-assistant",label:"Send to AI Assistant (⌘K)",contextMenuGroupId:"navigation",contextMenuOrder:1.5,keybindings:[s.KeyMod.CtrlCmd|s.KeyCode.KeyK],run:function(){const u=ne(t,s);if(u){const h=re(u);window.dispatchEvent(new CustomEvent("monaco-selection-to-ai",{detail:{documentName:e.name,selection:u,snippet:h,isTheme:!0}}))}}}),setTimeout(()=>{var u;(u=t.getAction("editor.action.formatDocument"))==null||u.run()},100),console.log("Monaco theme editor mounted")},[e.name,P,U]);E.useEffect(()=>()=>{V(e.name)},[e.name,V]);const Y=E.useCallback((t,s)=>{t!==void 0&&f&&f(t)},[f]),K=E.useCallback(t=>{const s=t.map(r=>{var c;return{path:"",message:r.message,code:typeof r.code=="string"?r.code:((c=r.code)==null?void 0:c.value)||"validation_error",startLineNumber:r.startLineNumber,startColumn:r.startColumn,endLineNumber:r.endLineNumber,endColumn:r.endColumn,severity:r.severity>=8?"error":r.severity>=4?"warning":"info"}});g(s),s.length>0&&!G.current&&(v(!0),O(!1)),s.length===0&&(G.current=!1)},[]),$=E.useCallback(t=>{R.current&&t.startLineNumber&&t.startColumn&&(R.current.setPosition({lineNumber:t.startLineNumber,column:t.startColumn}),R.current.revealLineInCenter(t.startLineNumber),R.current.focus())},[]);return E.useEffect(()=>{R.current&&R.current.updateOptions({theme:ee(B)})},[B]),x.jsxs("div",{className:"relative h-full",children:[w?x.jsxs(x.Fragment,{children:[x.jsxs("div",{className:"flex items-center justify-between px-2 py-1 border-b bg-muted/40 text-xs",children:[x.jsxs("div",{children:["Review changes for"," ",x.jsx("span",{className:"font-medium",children:e.name})]}),x.jsxs("div",{className:"flex gap-2",children:[x.jsx(oe,{variant:"secondary",size:"sm",onClick:()=>L(e.name),children:"Discard"}),x.jsx(oe,{size:"sm",onClick:()=>{M(e.name,w.modified),L(e.name,!0)},children:"Apply Changes"})]})]}),x.jsx(pe,{height:"calc(100% - 32px)",original:w.original,modified:w.modified,language:"json",theme:ee(B),options:{readOnly:!0,renderSideBySide:!0,originalEditable:!1,automaticLayout:!0,minimap:{enabled:!1}},beforeMount:F})]}):x.jsx(he,{height:"100%",language:"json",defaultPath:De(e.name),value:e.text,theme:ee(B),onChange:Y,beforeMount:F,onMount:J,onValidate:K,options:{readOnly:S,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"}}),x.jsx("div",{className:"absolute top-0 right-0",children:x.jsx(le,{errors:T,onClick:()=>{v(!0),O(!1)}})}),y&&T.length>0&&x.jsx(ue,{errors:T,isMinimized:b,onToggleMinimize:()=>O(!b),onErrorClick:$,onClose:()=>{v(!1),G.current=!0},className:"z-40"})]})}const xe=W.memo(Ie);function Ae({name:e,text:S,buildError:f,saveDocumentDebounceWait:R,documentType:I}){const{saveDocument:N}=Q(v=>v),{updateTheme:i}=ce(v=>v),T=W.useMemo(()=>Se(i,R),[i,R]);W.useEffect(()=>()=>{T.flush()},[T]);const g=W.useCallback(v=>{N(e,v),I==="application/json+theme"&&(console.log("TabContent: Theme document change detected, debouncing update",{documentName:e,debounceWait:R}),T(e,v))},[e,N,T,I,R]),y=W.useMemo(()=>({name:e,type:"application/json",text:S,mtime:new Date,ctime:new Date,atime:new Date}),[e,S]);return x.jsx(ve,{value:e,className:"mt-0 h-full p-0",tabIndex:-1,children:I==="application/json+theme"?x.jsx(xe,{document:y,onChange:g}):x.jsx(de,{name:e,value:S,saveDocumentDebounceWait:R})})}const Pe=W.memo(Ae);function Oe({openTabs:e,documents:S,buildErrors:f,saveDocumentDebounceWait:R}){const{documentTypes:I}=Q(N=>N);return e.map(N=>S.find(i=>i.name===N)).filter(N=>N!==void 0).map(N=>{const i=I[N.name]||"application/json+report";return x.jsx(Pe,{name:N.name,text:N.text,buildError:f[N.name],saveDocumentDebounceWait:R,documentType:i},N.name)})}const je=W.memo(Oe);class Ve extends Error{constructor(S,f,R){super(S),this.lastError=f,this.attempts=R,this.name="RetryError"}}async function ke(e,S={}){const{maxRetries:f=3,initialDelay:R=1e3,maxDelay:I=3e4,backoffFactor:N=2,onRetry:i,shouldRetry:T=()=>!0,signal:g}=S;let y;for(let v=0;v<=f;v++)try{if(g!=null&&g.aborted)throw new Error("Operation cancelled");return await e()}catch(b){if(y=b instanceof Error?b:new Error(String(b)),v===f)break;if(!T(y))throw y;const G=Math.min(R*Math.pow(N,v),I)*(.5+Math.random()*.5);i&&i(y,v+1),await new Promise(w=>{const L=setTimeout(w,G);g&&g.addEventListener("abort",()=>{clearTimeout(L),w(void 0)},{once:!0})})}throw new Ve(`Failed after ${f+1} attempts`,y,f+1)}const ae={networkErrors:e=>["NetworkError","Failed to fetch","ERR_NETWORK","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","fetch failed"].some(f=>e.message.includes(f)||e.name.includes(f)),httpStatusCodes:e=>S=>{var f;return(f=S.response)!=null&&f.status?e.includes(S.response.status):!1},temporaryErrors:e=>["EBUSY","EAGAIN","temporarily unavailable","too many requests","rate limit"].some(f=>e.message.toLowerCase().includes(f.toLowerCase())),combine:(...e)=>S=>e.some(f=>f(S))};function Ge(){const e=be(n=>n.setOutput),S=E.useContext(Ce),f=E.useContext(Ee),R=E.useContext(we),I=Re(n=>n.saveDocumentDebounceWait),{openTabs:N,activeTab:i,setActiveTab:T,documents:g,buildErrors:y,setBuildError:v,documentTypes:b}=Q(se(n=>({openTabs:n.openTabs,activeTab:n.activeTab,setActiveTab:n.setActiveTab,documents:n.documents,buildErrors:n.buildErrors,setBuildError:n.setBuildError,documentTypes:n.documentTypes}))),{customThemes:O}=ce(se(n=>({customThemes:n.customThemes}))),{generatePresentation:G,cancelGeneration:w}=Le(),L=E.useRef(new Map),M=E.useRef(new Map),P=E.useRef(null),V=E.useRef(""),U=E.useRef(new Map),B=E.useCallback(()=>{V.current=`cancelled-${Date.now()}`;for(const n of M.current.values())clearTimeout(n);M.current.clear(),P.current&&(clearTimeout(P.current),P.current=null);for(const n of L.current.values())n.abort();L.current.clear(),w(),e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0})},[w,e]);E.useEffect(()=>{e({cancelGeneration:B})},[B,e]);const F=E.useCallback(n=>{const o=(U.current.get(n)||0)+1;return U.current.set(n,o),o},[]),J=E.useMemo(()=>{const n=Object.entries(O).map(([a,o])=>{let l=0;return o.lastModified&&(o.lastModified instanceof Date?l=o.lastModified.getTime():typeof o.lastModified=="string"&&(l=new Date(o.lastModified).getTime())),{key:a,name:o.name,content:o.content,valid:o.valid,lastModified:l}});return JSON.stringify(n)},[O]),Y=E.useMemo(()=>{const n={};return Object.values(O).forEach(a=>{a.valid&&a.parsed&&(n[a.name]=a.parsed)}),n},[J]),K=E.useCallback(()=>{const n={},{customThemes:a}=R.getState();return Object.values(a).forEach(o=>{o.valid&&o.parsed&&(n[o.name]=o.parsed)}),n},[R]),$=E.useCallback(async(n,a,o)=>{if(!n||!G)return;const l=L.current.get(n.name);l&&(l.abort(),L.current.delete(n.name));const p=a?null:new AbortController,_=a||p.signal;p&&L.current.set(n.name,p);const D=`${n.name}-${Date.now()}-${Math.random()}`,j=F(n.name);V.current=D;const C={id:D,docName:n.name,doc:n,signal:_,timestamp:Date.now()};await s.current(C,j,o)},[G,e,F]),t=E.useCallback(async(n,a,o)=>{var j;const{doc:l,signal:p,id:_}=n;if(V.current!==_){console.log("Skipping outdated build request for:",l.name),e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0});return}e({globalError:void 0,isGenerating:!0,generationStartedAt:Date.now(),generationProgress:{stage:"parsing",message:"Validating JSON structure..."}});const D=(C,m)=>{if(p.aborted||V.current!==_)return;if((U.current.get(l.name)||0)!==a){console.log("Document version changed, aborting build"),p.dispatchEvent(new Event("abort"));return}e({isGenerating:!0,generationProgress:{stage:C,message:m}})};try{const C=K();console.log("Editor: Using themes for document build",{docName:l.name,freshThemeCount:Object.keys(C).length,freshThemeNames:Object.keys(C),memoizedCount:Object.keys(Y).length,requestId:_});const m=await ke(async()=>{if(p.aborted)throw new Error("Build cancelled");return await G(l.name,l.text,C,D,o)},{maxRetries:2,initialDelay:500,shouldRetry:d=>d.message.includes("cancelled")||d.message.includes("JSON")||d.message.includes("parse")||d.message.includes("syntax")?!1:ae.combine(ae.temporaryErrors,A=>A.message.includes("Worker")||A.message.includes("Proxy"))(d),onRetry:(d,A)=>{console.log(`Retrying presentation generation (attempt ${A}):`,d.message),e({isGenerating:!0,generationProgress:{stage:"parsing",message:`Retrying generation (attempt ${A})...`}})},signal:p});if(p.aborted||V.current!==_){console.log("Build cancelled for:",l.name),e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0});return}m&&typeof m=="object"&&"name"in m&&"text"in m&&"blob"in m&&(console.log("Editor: Build completed",{docName:m.name,blobSize:(j=m.blob)==null?void 0:j.size,timestamp:Date.now(),requestId:_,version:a}),e({name:m.name,text:m.text,blob:m.blob,renderer:m.renderer,globalError:void 0,isGenerating:!1,isPreviewStale:!1,generationProgress:void 0,generationStartedAt:void 0,lastBuiltSequence:S.getState().editSequence,cacheStatus:m.cacheStatus,cacheHitRate:m.cacheHitRate,warnings:m.warnings}),v(m.name,void 0))}catch(C){if(p.aborted||V.current!==_){console.log("Build cancelled with error for:",l.name),e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0});return}const m=C instanceof Error?C.message:String(C);e({globalError:m,isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0}),v(l.name,m)}finally{L.current.delete(l.name)}},[G,K,e,v,S]),s=E.useRef(t);E.useEffect(()=>{s.current=t});const r=E.useRef(null);E.useEffect(()=>{console.log("Editor: Document rebuild effect triggered",{activeTab:i});const n=g.find(l=>l.name===i),a=b[i]||"application/json+report";a==="application/json+report"&&n&&(r.current=i);const o=M.current.get(i);return o&&(clearTimeout(o),M.current.delete(i)),n&&a==="application/json+report"?S.getState().isGenerating||e({isPreviewStale:!0}):n&&a==="application/json+theme"&&w(),()=>{const l=M.current.get(i);l&&(clearTimeout(l),M.current.delete(i))}},[g,i,e,b,$,w]);const c=E.useMemo(()=>{var o;const n=new Map,a=g.find(l=>l.name===i);if(a&&b[a.name]==="application/json+report")try{const p=(o=JSON.parse(a.text).props)==null?void 0:o.theme;typeof p=="string"&&Object.values(O).some(D=>D.name===p&&D.valid)&&n.set(a.name,p)}catch{}return n},[i,g,b,O]);E.useEffect(()=>(console.log("Editor: Setting up theme change listener",{documentCount:g.length,dependencyCount:c.size,dependencies:Array.from(c.entries()),customThemes:Object.entries(O).map(([a,o])=>({key:a,name:o.name,valid:o.valid}))}),ye.onThemeChange(a=>{console.log("Editor: Theme change detected",{event:a,dependencies:Array.from(c.entries()),activeTab:i,customThemes:Object.entries(O).map(([l,p])=>({key:l,name:p.name,valid:p.valid}))});const o=[];if(c.forEach((l,p)=>{if(l===a.themeName){const _=g.find(D=>D.name===p);_&&o.push(_)}}),console.log("Editor: Documents using changed theme",{themeName:a.themeName,documentCount:o.length,documentNames:o.map(l=>l.name)}),o.length===0){console.log("Editor: No documents use this theme, skipping rebuild");return}S.getState().isGenerating||e({isPreviewStale:!0})})),[c,g,$,F,i,e]);const u=E.useRef($);E.useEffect(()=>{u.current=$});const h=E.useRef(F);return E.useEffect(()=>{h.current=F}),E.useEffect(()=>{const n=()=>{e({isGenerating:!0});let a=!1;const o=Z.getState().getActiveEditor();if(o&&!f.getState().pendingDiffs[o.documentName]){const C=o.toStorageValue(o.editor.getValue());f.getState().saveDocument(o.documentName,C)}const{documents:l,documentTypes:p}=f.getState();for(const j of l)if(p[j.name]==="application/json+theme"){const C=Z.getState().getEditor(j.name);if(C){const m=C.toStorageValue(C.editor.getValue()),d=R.getState().customThemes[j.name];(!d||d.content!==m)&&(R.getState().updateTheme(j.name,m),a=!0)}}const _=f.getState().activeTab,D=M.current.get(_);D&&(clearTimeout(D),M.current.delete(_)),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{P.current=null;const{documents:j,activeTab:C,documentTypes:m}=f.getState();let d=C;if((m[C]||"application/json+report")==="application/json+theme")if(r.current)d=r.current;else{e({isGenerating:!1});return}const z=j.find(H=>H.name===d);if(z){const H=f.getState().pendingDiffs[d],q=Z.getState().getEditor(d),k=H?{...z,text:H.modified}:q?{...z,text:q.toStorageValue(q.editor.getValue())}:z;h.current(k.name),u.current(k,void 0,a?{bypassCache:!0}:void 0)}else e({isGenerating:!1})},150)};return window.addEventListener("preview:flushAndBuild",n),()=>{window.removeEventListener("preview:flushAndBuild",n),P.current&&clearTimeout(P.current)}},[e,f,R]),E.useEffect(()=>()=>{L.current.forEach(n=>n.abort()),L.current.clear(),M.current.forEach(n=>clearTimeout(n)),M.current.clear(),w()},[w]),N.length?x.jsx(Me,{value:i,onValueChange:T,className:"h-full",children:x.jsx(je,{openTabs:N,documents:g,buildErrors:y,saveDocumentDebounceWait:I})}):x.jsx("div",{className:"flex flex-col text-muted-foreground h-full items-center justify-center",children:g!=null&&g.length?"Open a document...":"Create a new document..."})}const Qe=E.memo(Ge);export{Qe as Editor};
9
- //# sourceMappingURL=editor-edmvhW9F.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"editor-edmvhW9F.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, useState } 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 { type JsonEditorError } from '../../lib/json-types';\nimport { FORMAT } from '../../lib/env';\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';\nimport { ValidationPanel, ValidationStatusBar } from './validation-panel';\nimport { monacoThemeFor, registerMonacoThemes } from '../../lib/monaco-theme';\n\n/** Ensure defaultPath matches the schema fileMatch pattern (*.FORMAT.theme.json) */\nfunction resolveThemeDefaultPath(name: string): string {\n const ext = `.${FORMAT}.theme.json`;\n if (name.endsWith(ext)) return name;\n const base = name\n .replace(/\\.\\w+\\.theme\\.json$/, '')\n .replace(/\\.theme\\.json$/, '')\n .replace(/\\.json$/, '');\n return base + ext;\n}\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 [validationErrors, setValidationErrors] = useState<JsonEditorError[]>(\n []\n );\n const [showValidationPanel, setShowValidationPanel] = useState(true);\n const [isValidationPanelMinimized, setIsValidationPanelMinimized] =\n useState(false);\n const userDismissedRef = useRef(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 monacoRef.current = monaco;\n // Idempotent; guards the case where an editor mounts before the global\n // configureMonaco() promise has resolved.\n registerMonacoThemes(monaco);\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\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 // Handle Monaco's built-in schema validation markers\n const handleEditorValidation = useCallback(\n (markers: MonacoEditorType.IMarker[]) => {\n const errors: JsonEditorError[] = markers.map((marker) => ({\n path: '',\n message: marker.message,\n code:\n typeof marker.code === 'string'\n ? marker.code\n : marker.code?.value || 'validation_error',\n startLineNumber: marker.startLineNumber,\n startColumn: marker.startColumn,\n endLineNumber: marker.endLineNumber,\n endColumn: marker.endColumn,\n severity:\n marker.severity >= 8\n ? 'error'\n : marker.severity >= 4\n ? 'warning'\n : 'info',\n }));\n\n setValidationErrors(errors);\n\n if (errors.length > 0 && !userDismissedRef.current) {\n setShowValidationPanel(true);\n setIsValidationPanelMinimized(false);\n }\n if (errors.length === 0) {\n userDismissedRef.current = false;\n }\n },\n []\n );\n\n const handleErrorClick = useCallback((error: JsonEditorError) => {\n if (editorRef.current && error.startLineNumber && error.startColumn) {\n editorRef.current.setPosition({\n lineNumber: error.startLineNumber,\n column: error.startColumn,\n });\n editorRef.current.revealLineInCenter(error.startLineNumber);\n editorRef.current.focus();\n }\n }, []);\n\n // Update theme\n useEffect(() => {\n if (editorRef.current) {\n editorRef.current.updateOptions({ theme: monacoThemeFor(resolvedTheme) });\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={monacoThemeFor(resolvedTheme)}\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={resolveThemeDefaultPath(document.name)}\n value={document.text}\n theme={monacoThemeFor(resolvedTheme)}\n onChange={handleChange}\n beforeMount={handleEditorWillMount}\n onMount={handleEditorMount}\n onValidate={handleEditorValidation}\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\n {/* Validation Status Bar */}\n <div className=\"absolute top-0 right-0\">\n <ValidationStatusBar\n errors={validationErrors}\n onClick={() => {\n setShowValidationPanel(true);\n setIsValidationPanelMinimized(false);\n }}\n />\n </div>\n\n {/* Validation Panel */}\n {showValidationPanel && validationErrors.length > 0 && (\n <ValidationPanel\n errors={validationErrors}\n isMinimized={isValidationPanelMinimized}\n onToggleMinimize={() =>\n setIsValidationPanelMinimized(!isValidationPanelMinimized)\n }\n onErrorClick={handleErrorClick}\n onClose={() => {\n setShowValidationPanel(false);\n userDismissedRef.current = true;\n }}\n className=\"z-40\"\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 {\n useEffect,\n useCallback,\n useRef,\n useMemo,\n memo,\n useContext,\n} from 'react';\nimport { EditorTabsContentMemoized } from './editor-tabs-content';\nimport { Tabs } from '../ui/tabs';\nimport {\n useDocumentsStore,\n DocumentsStoreContext,\n} from '../../store/documents-store-provider';\nimport {\n useOutputStore,\n OutputStoreContext,\n} from '../../store/output-store-provider';\nimport { useSettingsStore } from '../../store/settings-store-provider';\nimport { useEditorRefsStore } from '../../store/editor-refs-store';\nimport {\n useThemesStore,\n ThemesStoreContext,\n} 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 {\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 } = useThemesStore(\n useShallow((state) => ({ customThemes: state.customThemes }))\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 // Debounce timer for Run-button builds (150ms to coalesce rapid clicks).\n const flushBuildTimerRef = useRef<NodeJS.Timeout | null>(null);\n const lastBuildRequestIdRef = useRef<string>('');\n const documentVersionsRef = useRef<Map<string, number>>(new Map());\n\n // User-initiated cancel from the loading UI: invalidate the current request\n // id first (so both build paths take their quiet \"cancelled\" exit instead of\n // surfacing a global error), then abort the controllers and the in-flight\n // fetch.\n const cancelActiveBuild = useCallback(() => {\n lastBuildRequestIdRef.current = `cancelled-${Date.now()}`;\n // Also drop queued debounced builds — without this, a pending auto-build\n // timer could start a new generation right after the user cancelled.\n for (const timeout of buildTimeoutsRef.current.values()) {\n clearTimeout(timeout);\n }\n buildTimeoutsRef.current.clear();\n if (flushBuildTimerRef.current) {\n clearTimeout(flushBuildTimerRef.current);\n flushBuildTimerRef.current = null;\n }\n for (const controller of buildAbortControllersRef.current.values()) {\n controller.abort();\n }\n buildAbortControllersRef.current.clear();\n cancelGeneration();\n setOutput({\n isGenerating: false,\n generationProgress: undefined,\n generationStartedAt: undefined,\n });\n }, [cancelGeneration, setOutput]);\n\n useEffect(() => {\n setOutput({ cancelGeneration: cancelActiveBuild });\n }, [cancelActiveBuild, setOutput]);\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 // 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 (\n doc: any,\n signal?: AbortSignal,\n options?: { bypassCache?: boolean }\n ) => {\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 (\n request: BuildRequest,\n version: number,\n options?: { bypassCache?: boolean }\n ) => {\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({\n isGenerating: false,\n generationProgress: undefined,\n generationStartedAt: undefined,\n });\n return;\n }\n\n setOutput({\n globalError: undefined,\n isGenerating: true,\n generationStartedAt: Date.now(),\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({\n isGenerating: false,\n generationProgress: undefined,\n generationStartedAt: undefined,\n });\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 renderer: result.renderer as string | undefined,\n globalError: undefined,\n isGenerating: false,\n isPreviewStale: false,\n generationProgress: undefined,\n generationStartedAt: 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({\n isGenerating: false,\n generationProgress: undefined,\n generationStartedAt: undefined,\n });\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 generationStartedAt: undefined,\n });\n\n setBuildError(doc.name, errorMessage);\n } finally {\n buildAbortControllersRef.current.delete(doc.name);\n }\n },\n [\n generatePresentation,\n getFreshThemeData,\n setOutput,\n setBuildError,\n outputStore,\n ]\n );\n const processBuildRequestRef = useRef(processBuildRequest);\n useEffect(() => {\n processBuildRequestRef.current = processBuildRequest;\n });\n\n // Track the last viewed document for theme updates\n const lastViewedDocumentRef = useRef<string | null>(null);\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 // Editing marks the preview stale rather than rebuilding: a build costs\n // a LibreOffice conversion, so it waits for Run. Do not clobber a build\n // already in flight (e.g. one the Run button started).\n if (!outputStore.getState().isGenerating) {\n setOutput({ isPreviewStale: true });\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 ]);\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 (\n activeDoc &&\n documentTypes[activeDoc.name] === 'application/json+report'\n ) {\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 // A theme change invalidates the preview of every document using it;\n // rebuilding is the author’s call, as it is for a document edit.\n if (!outputStore.getState().isGenerating) {\n setOutput({ isPreviewStale: true });\n }\n });\n\n return unsubscribe;\n }, [\n documentThemeDependencies,\n documents,\n buildDocument,\n getDocumentVersion,\n activeTab,\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 // 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(() => {\n buildDocumentRef.current = buildDocument;\n });\n const getDocumentVersionRef = useRef(getDocumentVersion);\n useEffect(() => {\n getDocumentVersionRef.current = getDocumentVersion;\n });\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 =\n documentsStore.getState().pendingDiffs[editorRef.documentName];\n if (!hasPendingDiff) {\n const liveText = editorRef.toStorageValue(\n editorRef.editor.getValue()\n );\n documentsStore\n .getState()\n .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 } =\n 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.toStorageValue(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 {\n documents: docs,\n activeTab: tab,\n documentTypes: dtypes,\n } = 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.toStorageValue(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(\n doc,\n undefined,\n themeDirty ? { bypassCache: true } : undefined\n );\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","resolveThemeDefaultPath","name","ext","FORMAT","EditorMonacoTheme","document","readOnly","onChange","editorRef","useRef","monacoRef","modelRef","theme","useTheme","validationErrors","setValidationErrors","useState","showValidationPanel","setShowValidationPanel","isValidationPanelMinimized","setIsValidationPanelMinimized","userDismissedRef","pendingDiff","useDocumentsStore","s","clearPendingDiff","saveDocument","registerEditor","unregisterEditor","setActiveEditor","useEditorRefsStore","resolvedTheme","handleEditorWillMount","useCallback","registerMonacoThemes","handleEditorMount","constrainedInstance","getSelectionContext","snippet","createContextSnippet","_a","useEffect","handleChange","_event","handleEditorValidation","markers","errors","marker","handleErrorClick","error","monacoThemeFor","jsxs","Fragment","jsx","Button","DiffEditor","MonacoEditor","ValidationStatusBar","ValidationPanel","EditorMonacoThemeMemoized","React","TabContent","_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","activeTab","setActiveTab","setBuildError","useShallow","customThemes","generatePresentation","cancelGeneration","usePresentationGenerator","buildAbortControllersRef","buildTimeoutsRef","flushBuildTimerRef","lastBuildRequestIdRef","documentVersionsRef","cancelActiveBuild","timeout","controller","getDocumentVersion","docName","newVersion","customThemesContentHash","useMemo","themeData","lastModifiedTime","validCustomThemes","themes","getFreshThemeData","freshThemes","buildDocument","existingController","abortController","finalSignal","requestId","version","buildRequest","processBuildRequestRef","processBuildRequest","request","id","onProgress","stage","freshThemeData","result","e","errorMessage","lastViewedDocumentRef","activeFile","docType","existingTimeout","documentThemeDependencies","deps","activeDoc","themeName","t","themeChangeEmitter","event","documentsUsingTheme","buildDocumentRef","getDocumentVersionRef","handler","themeDirty","liveText","allDocs","allDtypes","ref","existing","currentTab","docs","tab","dtypes","targetName","freshDoc","pending","Tabs","Editor","memo"],"mappings":"mpBAAA,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,CACpC,OAAI,MAAM,QAAQA,CAAM,EACfA,EAAO,MAAM,SAAUC,EAAU,CACtC,OAAI,OAAOA,GAAa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