/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@mxtommy/kip@4.8.0/plugin/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,s)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),s=0;s<i.length;s++)"default"!==i[s]&&__createBinding(r,t,i[s]);return __setModuleDefault(r,t),r}}();Object.defineProperty(exports,"__esModule",{value:!0});const server_api_1=require("@signalk/server-api"),openapi=__importStar(require("./openApi.json")),history_series_service_1=require("./history-series.service"),sqlite_history_storage_service_1=require("./sqlite-history-storage.service");async function defaultGetSqliteModule(){try{return await Promise.resolve().then((()=>__importStar(require("node:sqlite"))))}catch{return null}}const start=e=>{const t=JSON.parse(JSON.stringify(openapi.default??openapi)),r={DISPLAYS:"/displays",INSTANCE:"/displays/:displayId",SCREEN_INDEX:"/displays/:displayId/screenIndex",ACTIVATE_SCREEN:"/displays/:displayId/activeScreen",SERIES:"/series",SERIES_INSTANCE:"/series/:seriesId",SERIES_RECONCILE:"/series/reconcile"},i="vessels.self",s="kip.remote.setDisplay",n="kip.remote.setScreenIndex",a="kip.remote.requestActiveScreen",o={type:"object",title:"Remote Control and Data Series",description:"NOTE: All plugin settings are also managed from within KIP's Display Options panel. Changes made here will be overridden when KIP applies settings from the Display Options.",properties:{nodeSqliteAvailable:{type:"boolean",title:"node:sqlite Available",description:"Indicates if node:sqlite is available in the current runtime (requires Node.js version 22.5.0 or newer). This is set automatically and is read-only.\n\nBefore upgrading Node.js, always verify compatibility with your Signal K server version at https://demo.signalk.org/documentation.",readOnly:!0},historySeriesServiceEnabled:{type:"boolean",title:"Enable Automatic Historical Time-Series Capture and Management",description:"Historical Time-Series are data captures that supply the widget historical data and seed the Data Chart and Wind Trends widgets. If disabled, data capture must be configured in your chosen history provider plugin.",default:!0},registerAsHistoryApiProvider:{type:"boolean",title:"Enable Query Provider",description:"The built-in History-API query provider is a feature that enables the plugin to respond to History-API requests. If you want to use another History-API provider, disable this option and configure your chosen History-API compatible provider accordingly and KIP will query that provider.",default:!0}}},l=new history_series_service_1.HistorySeriesService((()=>Date.now()),"string"==typeof e.selfId&&e.selfId.trim().length>0?`vessels.${e.selfId.trim()}`:null);let d,u=null,c=null,p=null;const f="22.5.0";let g=[],y=!1,S=null;function h(){if(!Q||!Q.nodeSqliteAvailable)return`node:sqlite is not supported in the installed Node.js runtime. Node ${f}+ is required.`;const e=d.getLastInitError();return e?`node:sqlite storage unavailable: ${e}`:"node:sqlite storage unavailable"}const m={batteries:"bms",solar:"solar",chargers:"charger",inverters:"inverter",alternators:"alternator",ac:"ac"},I={batteries:"electrical.batteries",solar:"electrical.solar",chargers:"electrical.chargers",inverters:"electrical.inverters",alternators:"electrical.alternators",ac:"electrical.ac"},E={batteries:["capacity.stateOfCharge","current"],solar:["current","panelPower"],chargers:["voltage","current"],inverters:["voltage","current"],alternators:["voltage","current"],ac:["line1.voltage","line1.current","line1.frequency","line2.voltage","line2.current","line2.frequency","line3.voltage","line3.current","line3.frequency"]};function v(e){if(!(0,history_series_service_1.isKipElectricalTemplateSeriesDefinition)(e))return null;if(e.familyKey)return e.familyKey;switch(e.expansionMode){case"bms-battery-tree":return"batteries";case"solar-tree":return"solar";case"charger-tree":return"chargers";case"inverter-tree":return"inverters";case"alternator-tree":return"alternators";case"ac-tree":return"ac";default:return null}}function b(e){if(!Array.isArray(e.trackedDevices))return[];const t=new Map;return e.trackedDevices.forEach((e=>{if(!e||"object"!=typeof e)return;const r="string"==typeof e.id?e.id.trim():"",i="string"==typeof e.source?e.source.trim():"",s=i.length>0?i:"default";r&&t.set(`${r}||${s}`,{id:r,source:s})})),Array.from(t.values()).sort(((e,t)=>{const r=e.id.localeCompare(t.id);return 0!==r?r:e.source.localeCompare(t.source)}))}function $(t){const r=(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e;if(Object.prototype.hasOwnProperty.call(t,"value")){const e=t.value;return e&&"object"==typeof e&&!Array.isArray(e)?e:null}return t})(e.getSelfPath(t));return r?Object.keys(r).filter((e=>/^[a-z0-9_-]+$/i.test(e))).sort(((e,t)=>e.localeCompare(t))):[]}function A(e,t,r){const i=`${I[t]}.`;return r.filter((t=>t.ownerWidgetUuid===e.ownerWidgetUuid)).filter(history_series_service_1.isKipConcreteSeriesDefinition).filter((t=>t.seriesId!==e.seriesId)).filter((e=>e.path.startsWith(i))).map((e=>({...e})))}function P(e){const t=new Map;return e.forEach((e=>{t.set(e.seriesId,e)})),Array.from(t.values())}function N(e,t=[]){const r=new Map,i=new Map;return e.forEach((e=>{if(!(0,history_series_service_1.isKipTemplateSeriesDefinition)(e))return void r.set(e.seriesId,e);const s=v(e);if(!s)return void r.set(e.seriesId,e);const n=m[s],a=E[s],o=`self.${I[s]}`;let l=b(e);if(0===l.length){const n=(e=>{if(!i.has(e)){const t=$(I[e]);i.set(e,t)}return i.get(e)??[]})(s);if(0===n.length)return void A(e,s,t).forEach((e=>{r.set(e.seriesId,e)}));const a=function(e){const t=Array.isArray(e.allowedIds)?e.allowedIds:null;return Array.isArray(t)?t.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter((e=>e.length>0)):[]}(e),o=a.length>0?new Set(a):null,d=n.filter((e=>!o||o.has(e)));if(0===d.length)return;const u=e.source??"default";l=d.map((e=>({id:e,source:u})))}l.forEach((t=>{const i=(t.source||"default").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"default";a.forEach((s=>{const a=`${o}.${t.id}.${s}`,l=`${e.ownerWidgetUuid}:${n}:${t.id}:${s}:${i}`;r.set(l,{...e,seriesId:l,datasetUuid:`${e.ownerWidgetUuid}:${n}:${t.id}:${s}:${i}`,path:a,source:t.source,retentionDurationMs:Number.isFinite(e.retentionDurationMs)?e.retentionDurationMs:864e5,expansionMode:null,familyKey:null,allowedIds:null,trackedDevices:null})}))}))})),Array.from(r.values())}function T(t,r){const i=`displays.${t}${r?`.${r}`:""}`,s=e.getSelfPath(i);return e.debug(`[KIP][SELF_PATH] displayId=${t} suffix=${String(r??"")} requested=${i} resolved=${JSON.stringify(s)}`),"object"==typeof s&&null!==s?s:void 0}function R(e,t){return void 0===t?e.status(204).end():e.status(200).json(t)}function C(e,t,r){return e.status(t).json({state:"FAILED",statusCode:t,message:r})}async function O(t=5e3){if(!p)return d.isSqliteReady();try{const r=await Promise.race([p,new Promise((e=>{setTimeout((()=>e(!1)),t)}))]);return r||d.isSqliteReady()||e.error(`[SERIES STORAGE] node:sqlite initialization wait timed out after ${t}ms`),r}catch{return!1}}function _(e,t){const r=e?.message?.trim()||t,i=r.toLowerCase();return i.includes("invalid ")||i.includes("missing ")||i.includes("required")?{statusCode:400,message:r}:i.includes("sqlite")||i.includes("database")||i.includes("storage unavailable")||i.includes("not initialized")||!Q||!Q.nodeSqliteAvailable||Boolean(d.getLastInitError())?{statusCode:503,message:r}:{statusCode:500,message:r}}function w(e){const t=l.findSeriesById(e);return t?JSON.parse(JSON.stringify(t)):null}function q(){return!!(Q&&Q.historySeriesServiceEnabled&&Q.nodeSqliteAvailable)}function H(){return!!(Q&&Q.registerAsHistoryApiProvider&&Q.nodeSqliteAvailable)}function M(t){e.debug(`[HISTORY MODE] stage=${t} historySeriesServiceEnabled=${q()} historyApiProviderEnabled=${H()} historyApiProviderRegistered=${y}`)}async function D(e){return await O(),!!d.isSqliteReady()||(C(e,503,h()),!1)}function K(e){return Q&&Q.nodeSqliteAvailable?!!q()||(C(e,503,"KIP history-series service is disabled by plugin configuration"),!1):(C(e,503,h()),!1)}function x(t,r){const i="string"==typeof t.headers.authorization&&t.headers.authorization.length>0,s="string"==typeof t.headers.cookie&&t.headers.cookie.length>0,n=t.headers.origin??null,a=t.headers["user-agent"]??null,o=t.headers["content-type"]??null;e.debug(`[AUTH TRACE] stage=${r} method=${t.method} path=${t.path} ip=${t.ip} origin=${String(n)} authHeader=${i} cookieHeader=${s} contentType=${String(o)} userAgent=${String(a)}`)}function j(e,t){return{state:"COMPLETED",statusCode:e,message:t}}function U(e){return"string"==typeof e&&/^[A-Za-z0-9-]+$/.test(e)}function J(t,r,i){const s=r?`displays.${t}.${r}`:`displays.${t}`;e.debug(`[KIP][WRITE] applyDisplayWrite path=${s} value=${JSON.stringify(i)}`);try{return e.handleMessage(ee.id,{updates:[{values:[{path:s,value:i??null}]}]},server_api_1.SKVersion.v1),e.debug(`[KIP][WRITE] handleMessage success path=${s}`),j(200)}catch(t){const r=t?.message??"Unable to write display path";return e.error(`[WRITE TRACE] handleMessage failure path=${s} message=${r}`),j(400,r)}}function L(t){e.debug(`[KIP][COMMAND] handleSetDisplay payload=${JSON.stringify(t)}`);const r=t;if(!r||"object"!=typeof r)return j(400,"Command payload is required");if(!U(r.displayId))return j(400,"Invalid displayId format");const i=r.display??null;return null!==i&&"object"!=typeof i?j(400,"display must be an object or null"):J(r.displayId,null,i)}function k(t,r){e.debug(`[KIP][COMMAND] handleScreenWrite suffix=${r} payload=${JSON.stringify(t)}`);const i=t;if(!i||"object"!=typeof i)return j(400,"Command payload is required");if(!U(i.displayId))return j(400,"Invalid displayId format");const s=i.screenIdx??null;return null!==s&&"number"!=typeof s?j(400,"screenIdx must be a number or null"):J(i.displayId,r,s)}function G(t,r){return e.debug(`[KIP][REST] sendActionAsRest statusCode=${r.statusCode} message=${r.message??""}`),200===r.statusCode?t.status(200).json({state:"SUCCESS",statusCode:200}):C(t,r.statusCode||400,r.message||"Command failed")}function W(){g.forEach((e=>{try{e()}catch{}})),g=[]}function V(e){if("string"==typeof e&&e.trim())return e;if(e instanceof Date)return e.toISOString();if(e&&"object"==typeof e&&"function"==typeof e.toString){const t=e.toString();return t&&"[object Object]"!==t?t:void 0}}function B(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim())return e;if(e&&"object"==typeof e&&"function"==typeof e.toString){const t=e.toString();return t&&"[object Object]"!==t?t:void 0}}function Y(e){if(!Array.isArray(e))return"";return e.map((e=>{const t=function(e){const t="string"==typeof e?e.trim():"";return t?t.startsWith("vessels.self.")?t.slice(13):t.startsWith("self.")?t.slice(5):t:""}(e.path);if(!t)return"";return[t,function(e){const t=String(e??"avg").trim().toLowerCase();return"average"===t?"avg":"min"===t||"max"===t||"sma"===t||"ema"===t||"avg"===t?t:"avg"}(e.aggregate),...Array.isArray(e.parameter)?e.parameter.map((e=>String(e).trim())).filter(Boolean):[]].join(":")})).filter(Boolean).join(",")}function F(e){return{from:V(e?.from),to:V(e?.to),duration:B(e?.duration)}}function z(){if(y=!1,!H())return void e.debug("[KIP][HISTORY_PROVIDER] registration skipped reason=config-disabled");const t=e,r="function"==typeof t.registerHistoryApiProvider?t.registerHistoryApiProvider.bind(t):"function"==typeof t.history?.registerHistoryApiProvider?t.history.registerHistoryApiProvider.bind(t.history):null;if(!r)return void e.debug("[KIP][HISTORY_PROVIDER] registration skipped reason=api-unavailable");r({getValues:async t=>{const r=await async function(t){if(await O(),!d.isSqliteReady())throw new Error(h());try{await d.flush()}catch(t){e.error(`[SERIES STORAGE] pre-query flush failed: ${String(t.message||t)}`)}const r=await d.getValues({...t});if(!r)throw new Error("node:sqlite storage did not return history values.");return r}(function(e){const t=V(e?.from),r=V(e?.to),i=B(e?.duration);return{paths:Y(e?.pathSpecs),context:"string"==typeof e?.context?e.context:void 0,from:t,to:r,duration:i,resolution:"number"==typeof e?.resolution||"string"==typeof e?.resolution?e.resolution:void 0}}(t));return{...r,values:r.values.map((e=>({path:e.path,method:"avg"===e.method?"average":e.method})))}},getPaths:t=>async function(t){if(await O(),!d.isSqliteReady())throw new Error(h());try{await d.flush()}catch(t){e.error(`[SERIES STORAGE] pre-paths flush failed: ${String(t.message||t)}`)}return d.getStoredPaths({...t??{}})}(F(t)),getContexts:t=>async function(t){if(await O(),!d.isSqliteReady())throw new Error(h());try{await d.flush()}catch(t){e.error(`[SERIES STORAGE] pre-contexts flush failed: ${String(t.message||t)}`)}return d.getStoredContexts({...t??{}})}(F(t))}),y=!0,e.debug("[KIP][HISTORY_PROVIDER] registration success provider=kip")}function X(){if(W(),!q())return;const t=e.streambundle;if(!t||"function"!=typeof t.getBus)return;const r=new Map,i=(e,t)=>{const i="string"==typeof e?e.trim():"";if(!i)return;const s=r.get(i);s?s.allSelfContext=s.allSelfContext&&t:r.set(i,{allSelfContext:t})};l.listSeries().filter(history_series_service_1.isKipSeriesEnabled).forEach((e=>{const t="vessels.self"===(e.context??"vessels.self");i(e.path,t);const r=e.path.lastIndexOf(".");r>0&&i(e.path.slice(0,r),t)}));Array.from(r.entries()).map((([e,t])=>({path:e,allSelfContext:t.allSelfContext}))).forEach((r=>{try{const i=r.allSelfContext&&"function"==typeof t.getSelfBus?t.getSelfBus(r.path):t.getBus(r.path);if(!i||"function"!=typeof i.onValue)return;const s=i.onValue((t=>{try{l.recordFromSignalKSample(t)}catch(t){e.error(`[SERIES CAPTURE] failed to record sample path=${r.path}: ${String(t.message||t)}`)}}));"function"==typeof s&&g.push(s)}catch(t){e.error(`[SERIES CAPTURE] failed to subscribe path=${r.path}: ${String(t.message||t)}`)}}))}function Z(t){c&&(clearInterval(c),c=null),d.isSqliteEnabled()&&(c=setInterval((()=>{d.flush().catch((t=>{e.error(`[SERIES STORAGE] flush failed: ${String(t.message||t)}`)}))}),t),c.unref?.())}let Q=null;const ee={id:"kip",name:"KIP",description:"KIP server plugin",start:async t=>{e.debug("[KIP][LIFECYCLE] start"),d=new sqlite_history_storage_service_1.SqliteHistoryStorageService(e.getDataDirPath()),Q=function(e){const t=e&&"object"==typeof e?e:{};return{historySeriesServiceEnabled:!1!==("boolean"==typeof t.historySeriesServiceEnabled?t.historySeriesServiceEnabled:void 0),registerAsHistoryApiProvider:!1!==("boolean"==typeof t.registerAsHistoryApiProvider?t.registerAsHistoryApiProvider:void 0),nodeSqliteAvailable:!1!==("boolean"==typeof t.nodeSqliteAvailable?t.nodeSqliteAvailable:void 0)}}(t),Q.nodeSqliteAvailable=await async function(){const e=start,t="function"==typeof e.getSqliteModule?e.getSqliteModule:defaultGetSqliteModule,r=await t();return r?r.DatabaseSync||r.Database?(S=null,!0):(S="node:sqlite module missing required exports",!1):(S=`node:sqlite requires Node ${f}+`,!1)}(),Q.nodeSqliteAvailable||e.error(`[KIP][RUNTIME] node:sqlite unavailable. ${S}`),d.setRuntimeAvailability(Q.nodeSqliteAvailable,S??void 0),function(){const t=`node@${process.version}`,r=Q&&Q.nodeSqliteAvailable?"available":"unavailable";e.debug(`[KIP][RUNTIME] ${t} node:sqlite=${r}`)}(),M("start-configured");if((Q.historySeriesServiceEnabled||Q.registerAsHistoryApiProvider)&&Q.nodeSqliteAvailable){d.setLogger({debug:t=>e.debug(t),error:t=>e.error(t)});const t=d.configure();e.debug(`[KIP][STORAGE] config engine=${t.engine} db=${t.databaseFile} flushMs=${t.flushIntervalMs}`),l.setSampleSink((e=>{d.enqueueSample(e)})),p=d.initialize(),p.then((r=>{if(e.debug(`[KIP][STORAGE] sqliteReady=${r}`),r&&d.isSqliteEnabled())return void(Q&&Q.historySeriesServiceEnabled?d.getSeriesDefinitions().then((r=>{r.length>0&&(l.reconcileSeries(r),X()),Z(t.flushIntervalMs),M("sqlite-ready"),e.setPluginStatus(`Providing: Remote Control${y?", History service":", No History service"}${r.length>0?`, ${r.length} Time-Series`:", No Time-Series"}.`)})).catch((r=>{e.error(`[SERIES STORAGE] failed to load persisted series: ${String(r.message||r)}`),Z(t.flushIntervalMs),M("sqlite-ready-series-load-failed"),e.setPluginStatus(`Providing: Remote Control${y?", History service":", No History service"}, No Time-Series.`)})):(l.reconcileSeries([]),W(),Z(t.flushIntervalMs),M("sqlite-ready-series-disabled"),e.setPluginStatus(`Providing: Remote Control${y?", History service":", No History service"}, No Time-Series.`)));c&&(clearInterval(c),c=null);const i=d.getLastInitError();i&&(e.setPluginError(`node:sqlite unavailable. ${i}`),M("sqlite-unavailable"),e.setPluginStatus(`Providing: Remote Control${y?", History service":", No History service"}, No Time-Series.`))})),u&&clearInterval(u),u=setInterval((()=>{try{if(d.isSqliteReady()){const t=d.getLifecycleToken();d.pruneExpiredSamples(Date.now(),t).then((r=>(r>0&&e.debug(`[KIP][RETENTION] pruneExpired removedRows=${r}`),d.pruneOrphanedSamples(t).then((t=>{t>0&&e.debug(`[KIP][RETENTION] pruneOrphaned removedRows=${t}`)}))))).catch((t=>{e.error(`[SERIES RETENTION] node:sqlite Prune failed: ${String(t.message||t)}`)}))}}catch(t){e.error(`[SERIES RETENTION] node:sqlite sweep failed: ${String(t.message||t)}`)}}),36e5),u.unref?.(),X()}else Q&&!Q.nodeSqliteAvailable&&(Q.historySeriesServiceEnabled||Q.registerAsHistoryApiProvider)&&e.setPluginStatus(h()),e.debug("[KIP][STORAGE] sqlite init skipped reason=config-disabled-or-runtime"),p=null,W();e.registerPutHandler&&(e.debug(`[KIP][COMMAND] registerPutHandlers context=${i}`),e.registerPutHandler(i,s,((t,r,i)=>(e.debug(`[KIP][COMMAND] putHandlerHit command=${s} path=${String(r)} context=${String(t)}`),L(i))),ee.id),e.registerPutHandler(i,n,((t,r,i)=>(e.debug(`[KIP][COMMAND] putHandlerHit command=${n} path=${String(r)} context=${String(t)}`),k(i,"screenIndex"))),ee.id),e.registerPutHandler(i,a,((t,r,i)=>(e.debug(`[KIP][COMMAND] putHandlerHit command=${a} path=${String(r)} context=${String(t)}`),k(i,"activeScreen"))),ee.id)),z(),M("post-provider-registration"),e.setPluginStatus("Starting...")},stop:()=>{e.debug("[KIP][LIFECYCLE] stop"),W(),u&&(clearInterval(u),u=null),c&&(clearInterval(c),c=null);const t=d.getLifecycleToken();d.flush(t).catch((()=>{})).then((()=>d.close(t))).catch((()=>{}));const r=e,i="function"==typeof r.unregisterHistoryApiProvider?r.unregisterHistoryApiProvider.bind(r):"function"==typeof r.history?.unregisterHistoryApiProvider?r.history.unregisterHistoryApiProvider.bind(r.history):null;i&&i(),y=!1,p=null;e.setPluginStatus("Stopped.")},schema:()=>{const e=JSON.parse(JSON.stringify(o));return e&&e.properties&&Q&&("boolean"==typeof Q.nodeSqliteAvailable&&(e.properties.nodeSqliteAvailable.default=Q.nodeSqliteAvailable),"boolean"==typeof Q.historySeriesServiceEnabled&&(e.properties.historySeriesServiceEnabled.default=Q.historySeriesServiceEnabled),"boolean"==typeof Q.registerAsHistoryApiProvider&&(e.properties.registerAsHistoryApiProvider.default=Q.registerAsHistoryApiProvider)),e},registerWithRouter(t){e.debug(`[KIP][ROUTES] register displays=${r.DISPLAYS} instance=${r.INSTANCE} screenIndex=${r.SCREEN_INDEX} activeScreen=${r.ACTIVATE_SCREEN}`),t.param("displayId",((t,r,i,s)=>{if(x(t,"router.param:displayId:entry"),null==s)return C(r,400,"Missing displayId parameter");try{let n=String(s);try{n=decodeURIComponent(n)}catch{}if(n.trim().startsWith("{"))try{const e=JSON.parse(n);if(!e||"string"!=typeof e.displayId)return C(r,400,"Invalid displayId format in JSON");n=e.displayId}catch{return C(r,400,"Invalid displayId JSON")}if(!/^[A-Za-z0-9-]+$/.test(n))return C(r,400,"Invalid displayId format");t.displayId=n,e.debug(`[KIP][AUTH] displayIdNormalized value=${n}`),i()}catch{return e.error(`[AUTH TRACE] router.param:displayId:failed rawDisplayId=${String(s)}`),C(r,400,"Missing or invalid displayId parameter")}})),t.put(`${r.INSTANCE}`,(async(t,i)=>{x(t,"route:PUT:INSTANCE:entry"),e.debug(`[KIP][ROUTE] method=PUT path=${r.INSTANCE} params=${JSON.stringify(t.params)} body=${JSON.stringify(t.body)}`);try{const e=t.displayId;if(!e)return C(i,400,"Missing displayId parameter");return G(i,L({displayId:e,display:t.body??null}))}catch(t){const r="HandleMessage failed with errors!";return e.setPluginError(r),e.error(`Error in HandleMessage: ${t}`),C(i,400,t.message)}})),t.put(`${r.SCREEN_INDEX}`,(async(t,i)=>{x(t,"route:PUT:SCREEN_INDEX:entry"),e.debug(`[KIP][ROUTE] method=PUT path=${r.SCREEN_INDEX} params=${JSON.stringify(t.params)} body=${JSON.stringify(t.body)}`);try{const e=t.displayId;if(!e)return C(i,400,"Missing displayId parameter");return G(i,k({displayId:e,screenIdx:void 0!==t.body?.screenIdx?t.body.screenIdx:null},"screenIndex"))}catch(t){const r="HandleMessage failed with errors!";return e.setPluginError(r),e.error(`Error in HandleMessage: ${t}`),C(i,400,t.message)}})),t.put(`${r.ACTIVATE_SCREEN}`,(async(t,i)=>{x(t,"route:PUT:ACTIVATE_SCREEN:entry"),e.debug(`[KIP][ROUTE] method=PUT path=${r.ACTIVATE_SCREEN} params=${JSON.stringify(t.params)} body=${JSON.stringify(t.body)}`);try{const e=t.displayId;if(!e)return C(i,400,"Missing displayId parameter");return G(i,k({displayId:e,screenIdx:void 0!==t.body?.screenIdx?t.body.screenIdx:null},"activeScreen"))}catch(t){const r="HandleMessage failed with errors!";return e.setPluginError(r),e.error(`Error in HandleMessage: ${t}`),C(i,400,t.message)}})),t.get(r.DISPLAYS,((t,i)=>{e.debug(`[KIP][ROUTE] method=GET path=${r.DISPLAYS} params=${JSON.stringify(t.params)}`);try{const t=function(){const t=e.getSelfPath("displays");return e.debug(`[KIP][DISPLAYS] resolved=${JSON.stringify(t)}`),"object"==typeof t&&null!==t?t:void 0}(),r=t&&"object"==typeof t?Object.entries(t).filter((([,e])=>e&&"object"==typeof e)).map((([e,t])=>({displayId:e,displayName:t?.value?.displayName??null}))):[];return e.debug(`[KIP][DISPLAYS] raw=${JSON.stringify(t)}`),e.debug(`[KIP][DISPLAYS] count=${r.length} items=${JSON.stringify(r)}`),i.status(200).json(r)}catch(t){return e.error(`Error reading displays: ${String(t.message||t)}`),C(i,400,t.message)}})),t.get(`${r.INSTANCE}`,((t,i)=>{e.debug(`[KIP][ROUTE] method=GET path=${r.INSTANCE} params=${JSON.stringify(t.params)}`);try{const e=t.displayId;if(!e)return C(i,400,"Missing displayId parameter");const r=T(e);if(void 0===r)return C(i,404,`Display ${e} not found`);return R(i,r?.value?.screens??null)}catch(r){return e.error(`Error reading display ${t.params?.displayId}: ${String(r.message||r)}`),C(i,400,r.message)}})),t.get(`${r.SCREEN_INDEX}`,((t,i)=>{e.debug(`[KIP][ROUTE] method=GET path=${r.SCREEN_INDEX} params=${JSON.stringify(t.params)}`);try{const e=t.displayId;if(!e)return C(i,400,"Missing displayId parameter");const r=T(e,"screenIndex");if(void 0===r)return C(i,404,`Active screen for display Id ${e} not found in path`);return R(i,r?.value??null)}catch(r){return e.error(`Error reading activeScreen for ${t.params?.displayId}: ${String(r.message||r)}`),C(i,400,r.message)}})),t.get(`${r.ACTIVATE_SCREEN}`,((t,i)=>{e.debug(`[KIP][ROUTE] method=GET path=${r.ACTIVATE_SCREEN} params=${JSON.stringify(t.params)}`);try{const e=t.displayId;if(!e)return C(i,400,"Missing displayId parameter");const r=T(e,"activeScreen");if(void 0===r)return C(i,404,`Change display screen Id ${e} not found in path`);return R(i,r?.value??null)}catch(r){return e.error(`Error reading activeScreen for ${t.params?.displayId}: ${String(r.message||r)}`),C(i,400,r.message)}})),t.get(r.SERIES,(async(t,i)=>{e.debug(`[KIP][ROUTE] method=GET path=${r.SERIES} params=${JSON.stringify(t.params)}`);try{if(!K(i))return;if(!await D(i))return;return R(i,l.listSeries())}catch(t){e.error(`Error reading series: ${String(t.message||t)}`);const r=_(t,"Failed to read series");return C(i,r.statusCode,r.message)}})),t.put(r.SERIES_INSTANCE,(async(t,i)=>{e.debug(`[KIP][ROUTE] method=PUT path=${r.SERIES_INSTANCE} params=${JSON.stringify(t.params)} body=${JSON.stringify(t.body)}`);try{if(!K(i))return;if(!await D(i))return;const e=String(t.params.seriesId??"").trim();if(!e)return C(i,400,"Missing seriesId parameter");const r=t.body??{},s=w(e),n=l.upsertSeries({...r,seriesId:e,datasetUuid:String(r.datasetUuid??e)});try{await d.upsertSeriesDefinition(n)}catch(t){throw s?l.upsertSeries(s):l.deleteSeries(e),t}return X(),R(i,n)}catch(t){e.error(`Error writing series: ${String(t.message||t)}`);const r=_(t,"Failed to write series");return C(i,r.statusCode,r.message)}})),t.delete(r.SERIES_INSTANCE,(async(t,i)=>{e.debug(`[KIP][ROUTE] method=DELETE path=${r.SERIES_INSTANCE} params=${JSON.stringify(t.params)}`);try{if(!K(i))return;if(!await D(i))return;const e=String(t.params.seriesId??"").trim();if(!e)return C(i,400,"Missing seriesId parameter");return w(e)?(await d.deleteSeriesDefinition(e),l.deleteSeries(e),X(),R(i,{state:"SUCCESS",statusCode:200})):C(i,404,`Series ${e} not found`)}catch(t){e.error(`Error deleting series: ${String(t.message||t)}`);const r=_(t,"Failed to delete series");return C(i,r.statusCode,r.message)}})),t.post(r.SERIES_RECONCILE,(async(t,i)=>{e.debug(`[KIP][ROUTE] method=POST path=${r.SERIES_RECONCILE} body=${JSON.stringify(t.body)}`);try{if(!K(i))return;if(!await D(i))return;const r=t.body;if(!Array.isArray(r))return C(i,400,"Body must be an array of series definitions");const s=new history_series_service_1.HistorySeriesService((()=>Date.now()),"string"==typeof e.selfId&&e.selfId.trim().length>0?`vessels.${e.selfId.trim()}`:null),n=P([...await d.getSeriesDefinitions(),...l.listSeries()]);n.forEach((e=>{s.upsertSeries(e)}));const a=r.map((e=>({...e}))),o=a.filter(history_series_service_1.isKipTemplateSeriesDefinition).flatMap((e=>{const t=v(e);if(!t)return[];if(b(e).length>0)return[];return 0===$(I[t]).length?A(e,t,n):[]})),u=P([...N(a,n),...o]),c=s.reconcileSeries(u),p=s.listSeries();return await d.replaceSeriesDefinitions(p),l.reconcileSeries(p),e.debug(`[KIP][SERIES_RECONCILE] created=${c.created} updated=${c.updated} deleted=${c.deleted} total=${c.total}`),X(),R(i,c)}catch(t){e.error(`Error reconciling series: ${String(t.message||t)}`);const r=_(t,"Failed to reconcile series");return C(i,r.statusCode,r.message)}})),t.stack&&t.stack.forEach((t=>{t.route&&t.route.path&&e.debug(`[KIP][ROUTES] registered method=${t.route.stack[0].method.toUpperCase()} path=${t.route.path}`)})),e.setPluginStatus("Providing remote display screen control and history series API")},getOpenApi:()=>t};return ee},startWithHooks=start;startWithHooks.getSqliteModule=defaultGetSqliteModule,module.exports=start;
//# sourceMappingURL=/sm/517e49336e924473d387033ec8d38753897480139e5a5d76d9e362b8f91ee90a.map