@kemu-io/hs 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cjs/service.d.ts +96 -0
- package/cjs/service.js +1 -1
- package/cjs/types/kemuCore.js +4 -0
- package/mjs/service.d.ts +96 -0
- package/mjs/service.js +1 -1
- package/mjs/types/kemuCore.js +4 -0
- package/package.json +1 -1
package/cjs/service.d.ts
CHANGED
|
@@ -201,6 +201,7 @@ export type RecipeContextInfo = {
|
|
|
201
201
|
/** the id of the author of the recipe */
|
|
202
202
|
authorId: string;
|
|
203
203
|
};
|
|
204
|
+
export type GlobalVariableControlType = "number" | "slider" | "text" | "multilineText" | "dropdown" | "image" | "binaryFile" | "checkbox" | "multiSelect" | "anything";
|
|
204
205
|
export type ValidEventContextValue = {
|
|
205
206
|
[key: string]: ValidEventContextValue | string | number | boolean | null;
|
|
206
207
|
};
|
|
@@ -268,6 +269,12 @@ export type WidgetContext<T extends WidgetState = WidgetState> = SerializableWid
|
|
|
268
269
|
* This will be available to any child widget down the line that is a variant of the current widget.
|
|
269
270
|
*/
|
|
270
271
|
eventContext?: ValidEventContextValue;
|
|
272
|
+
/**
|
|
273
|
+
* The id of the event to forward if this event is the continuation of a previous invocation.
|
|
274
|
+
* By default the last event id is used. Set to `null` signal a brand new execution path, this has implications on child
|
|
275
|
+
* widgets that rely on the event id to access the context of parent widgets of the same service type.
|
|
276
|
+
*/
|
|
277
|
+
eventId?: number | null;
|
|
271
278
|
}) => Promise<void>;
|
|
272
279
|
};
|
|
273
280
|
export type PortEventInfo = {
|
|
@@ -406,6 +413,41 @@ export type WidgetSecretConfig = {
|
|
|
406
413
|
*/
|
|
407
414
|
sharedAcrossInstances?: boolean;
|
|
408
415
|
};
|
|
416
|
+
/**
|
|
417
|
+
* Configuration for a global variable.
|
|
418
|
+
*/
|
|
419
|
+
export type GlobalVariableConfig = {
|
|
420
|
+
/**
|
|
421
|
+
* The name of the global variable to set.
|
|
422
|
+
*/
|
|
423
|
+
name: string;
|
|
424
|
+
/**
|
|
425
|
+
* The value of the global variable to set.
|
|
426
|
+
*/
|
|
427
|
+
value: SupportedTypes | null;
|
|
428
|
+
/**
|
|
429
|
+
* The control type of the global variable to set.
|
|
430
|
+
* This will override the control type of the global variable if it already exists.
|
|
431
|
+
* Defaults to 'Anything' if the variable does not exist and is created.
|
|
432
|
+
**/
|
|
433
|
+
controlType?: GlobalVariableControlType;
|
|
434
|
+
/** optional control settings for the global variable */
|
|
435
|
+
controlSettings?: Record<string, any>;
|
|
436
|
+
/** whether to notify other widgets about the change. Defaults to true. */
|
|
437
|
+
emitChangeEvent?: boolean;
|
|
438
|
+
/** optional help text for the global variable */
|
|
439
|
+
helpText?: string;
|
|
440
|
+
/** optional order to display the global variable in the variables panel */
|
|
441
|
+
order?: number;
|
|
442
|
+
/**
|
|
443
|
+
* If true, the global variable will not be overridden if it already exists. Defaults to false.
|
|
444
|
+
*/
|
|
445
|
+
doNotOverrideExisting?: boolean;
|
|
446
|
+
/**
|
|
447
|
+
* whether to emit an event if the variable did not exist and is set by this widget for the first time. Default is true.
|
|
448
|
+
**/
|
|
449
|
+
emitDefineEvent?: boolean;
|
|
450
|
+
};
|
|
409
451
|
export type InitializeContext<T extends WidgetState = WidgetState> = {
|
|
410
452
|
/** @deprecated use `recipe.poolId` instead */
|
|
411
453
|
recipeId: string;
|
|
@@ -429,6 +471,14 @@ export type InitializeContext<T extends WidgetState = WidgetState> = {
|
|
|
429
471
|
**/
|
|
430
472
|
requestAccess: (names: WidgetSecretConfig[] | string[]) => void;
|
|
431
473
|
};
|
|
474
|
+
globalVars: {
|
|
475
|
+
/**
|
|
476
|
+
* Allows you to declare or update a global variable with a specified configuration during initialization.
|
|
477
|
+
* This helper method functions like `service.globalVars.setValues`, but is intended for use within the 'initialize' callback only.
|
|
478
|
+
* You may call this method multiple times during the 'initialize' callback; all declared values will be set once the function completes.
|
|
479
|
+
*/
|
|
480
|
+
declare: (config: GlobalVariableConfig) => void;
|
|
481
|
+
};
|
|
432
482
|
};
|
|
433
483
|
export type InitializeServiceHandler<T extends WidgetState = WidgetState> = (context: InitializeContext<T>) => Promise<T | null | void | undefined>;
|
|
434
484
|
export type TerminateServiceHandler<T extends WidgetState = WidgetState> = (context: TerminateContext<T>) => Promise<void>;
|
|
@@ -473,6 +523,10 @@ export type ServiceBroadcastConfig = {
|
|
|
473
523
|
*/
|
|
474
524
|
eventId?: number;
|
|
475
525
|
};
|
|
526
|
+
export type CommonServiceToServiceArgs = {
|
|
527
|
+
/** the id of the widget instance performing the request */
|
|
528
|
+
widgetId: string;
|
|
529
|
+
};
|
|
476
530
|
/**
|
|
477
531
|
* Instance of a Kemu Widget library. Used by Widget services to integrate with the Kemu Hub.
|
|
478
532
|
*/
|
|
@@ -616,6 +670,48 @@ export type KemuService<T extends Record<string, any> = Record<string, any>> = {
|
|
|
616
670
|
*/
|
|
617
671
|
add: (secret: AddSecretConfig | AddSecretConfig[]) => Promise<void>;
|
|
618
672
|
};
|
|
673
|
+
globalVars: {
|
|
674
|
+
getNames: (config: CommonServiceToServiceArgs & {
|
|
675
|
+
/** optional filter for variable types. If provided, only variables of the given types will be returned. */
|
|
676
|
+
filterTypes?: GlobalVariableControlType[];
|
|
677
|
+
}) => Promise<{
|
|
678
|
+
name: string;
|
|
679
|
+
type: GlobalVariableControlType;
|
|
680
|
+
}[]>;
|
|
681
|
+
getValues: (config: CommonServiceToServiceArgs & {
|
|
682
|
+
/** the names of the variables to get the values of */
|
|
683
|
+
names: string[];
|
|
684
|
+
}) => Promise<{
|
|
685
|
+
name: string;
|
|
686
|
+
value: SupportedTypes | null;
|
|
687
|
+
}[]>;
|
|
688
|
+
setValues: (config: CommonServiceToServiceArgs & {
|
|
689
|
+
/** the values to set for the variables */
|
|
690
|
+
values: GlobalVariableConfig[];
|
|
691
|
+
}) => Promise<void>;
|
|
692
|
+
};
|
|
693
|
+
helpers: {
|
|
694
|
+
/**
|
|
695
|
+
* Parses the given expressions using kemu's expressions engine, which provides access to helper methods and global vars
|
|
696
|
+
* @returns a list of parsed expressions.text values in the same order they were provided.
|
|
697
|
+
**/
|
|
698
|
+
parseExpressions: (config: CommonServiceToServiceArgs & {
|
|
699
|
+
/** a list of expressions to parse */
|
|
700
|
+
expressions: {
|
|
701
|
+
/** the expression to parse */
|
|
702
|
+
text: string;
|
|
703
|
+
/** optional context to use when parsing the expression */
|
|
704
|
+
context?: Record<string, any>;
|
|
705
|
+
}[];
|
|
706
|
+
}) => Promise<string[]>;
|
|
707
|
+
/** simplified form of `parseStringExpressions` that parses a single text expression */
|
|
708
|
+
parseExpression: (config: CommonServiceToServiceArgs & {
|
|
709
|
+
/** the expression to parse */
|
|
710
|
+
text: string;
|
|
711
|
+
/** optional context to use when parsing the expression */
|
|
712
|
+
context?: Record<string, any>;
|
|
713
|
+
}) => Promise<string>;
|
|
714
|
+
};
|
|
619
715
|
};
|
|
620
716
|
export type AddSecretConfig = {
|
|
621
717
|
/**
|
package/cjs/service.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("fs/promises"),t=require("minimist"),r=require("path"),n=require("node-ipc"),o=require("debug");function a(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var i,s={},c={},d={};var u,l={};var f,g={};var p,m={};var y,S={};var v,b={};var I,h,L={};function w(){return h||(h=1,e=c,A=c&&c.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),H=c&&c.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||A(t,e,r)},Object.defineProperty(e,"__esModule",{value:!0}),H((i||(i=1,Object.defineProperty(d,"__esModule",{value:!0}),d.DataTypeStr=d.DataType=d.RecipeType=void 0,function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(t||(d.RecipeType=t={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(r||(d.DataType=r={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(n||(d.DataTypeStr=n={}))),d),e),H((u||(u=1,Object.defineProperty(l,"__esModule",{value:!0})),l),e),H((f||(f=1,Object.defineProperty(g,"__esModule",{value:!0})),g),e),H((p||(p=1,Object.defineProperty(m,"__esModule",{value:!0}),m.ProcessorType=void 0,function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(o||(m.ProcessorType=o={}))),m),e),H((y||(y=1,Object.defineProperty(S,"__esModule",{value:!0}),S.Transport=S.ServiceToServiceFunctions=S.KemuHubFunctions=S.KemuHubCommand=void 0,function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(a||(S.KemuHubCommand=a={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.AddServiceSecret="addServiceSecret",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.SendToRecipe="sendToRecipe",e.KemuComposerDisconnected="kemu-composer-disconnected",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.SaveRecipeToFile="saveRecipeToFile",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey",e.GetHubConfig="getHubConfig",e.GetRecipeDecryptedSecretsValues="getRecipeDecryptedSecretsValues",e.GetRecipeSecretMappings="getRecipeSecretMappings",e.AddRecipeSecretMapping="addRecipeSecretMapping",e.DeleteRecipeSecretMapping="deleteRecipeSecretMapping",e.GetHubSecrets="getHubSecrets",e.AddHubSecrets="addHubSecrets",e.DeleteHubSecret="deleteHubSecret"}(s||(S.KemuHubFunctions=s={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(w||(S.ServiceToServiceFunctions=w={})),function(e){e.IPC="ipc",e.WS="ws"}(P||(S.Transport=P={}))),S),e),H((v||(v=1,Object.defineProperty(b,"__esModule",{value:!0})),b),e),H((I||(I=1,Object.defineProperty(L,"__esModule",{value:!0})),L),e)),c;var e,t,r,n,o,a,s,w,P,A,H}var P,A={};var H,K={};function C(){if(H)return K;H=1,Object.defineProperty(K,"__esModule",{value:!0}),K.onAssumeSession=K.buildIpcAckResponse=K.isBrowser=K.onSendManifestCommand=K.onEndBroadcastCommand=K.onStartBroadcastCommand=K.onAckResponse=K.onAckRequest=K.buildSocketAckRequest=K.buildIpcAckRequest=K.buildAckResponse=K.safeJsonParse=void 0;const e=w();K.safeJsonParse=e=>{try{return JSON.parse(e)}catch(e){return null}};K.buildAckResponse=t=>`${e.KemuHubCommand.AcknowledgeResponse}${t}`;K.buildIpcAckResponse=(t,r)=>`${e.KemuHubCommand.AcknowledgeResponse}${t}:${r||""}`;K.buildIpcAckRequest=()=>`${e.KemuHubCommand.IpcAcknowledge}`;K.buildSocketAckRequest=t=>`${e.KemuHubCommand.SocketAcknowledge}${t}`;K.onAssumeSession=(t,r)=>{if(t.startsWith(e.KemuHubCommand.AssumeSession)){const n=t.split(e.KemuHubCommand.AssumeSession);return r(parseInt(n[1])),!0}return!1};K.onAckResponse=(t,r)=>{if(t.startsWith(e.KemuHubCommand.AcknowledgeResponse)){const n=t.split(e.KemuHubCommand.AcknowledgeResponse),o=parseInt(n[1]);return r&&r(o),o}return null};K.onAckRequest=(t,r)=>{const n=e.KemuHubCommand.SocketAcknowledge,o=e.KemuHubCommand.IpcAcknowledge,a=t.startsWith(n),i=t.startsWith(o);if(a||i){const e=t.split(a?n:o),i=parseInt(e[1]);return r&&r(i),i}return null};K.onStartBroadcastCommand=(t,r)=>t===e.KemuHubCommand.BroadcastStart&&(r(),!0);K.onEndBroadcastCommand=(t,r)=>t===e.KemuHubCommand.BroadcastEnd&&(r(),!0);K.onSendManifestCommand=(t,r)=>t===e.KemuHubCommand.SendManifest&&(r(),!0);const t="undefined"!=typeof window;return K.isBrowser=t,K}var B,E={};var _,D={},j={};var k,M={},z={},U={};function O(){return k||(k=1,e=U,Object.defineProperty(e,"__esModule",{value:!0}),e.KLCmdHeaderSize=e.KLHeaderSize=e.KLCmdProtocolHeaderSize=e.KLProtocolHeadersSize=void 0,e.KLProtocolHeadersSize={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},e.KLCmdProtocolHeaderSize={protocolPrefix:4,txtLength:4},e.KLHeaderSize=Object.values(e.KLProtocolHeadersSize).reduce(((e,t)=>e+t),0),e.KLCmdHeaderSize=Object.values(e.KLCmdProtocolHeaderSize).reduce(((e,t)=>e+t),0)),U;var e}var R,F={};function T(){if(R)return F;R=1,Object.defineProperty(F,"__esModule",{value:!0}),F.setNestedProperty=F.decodeMap=F.isSupportedBinaryType=F.getEncodedMap=void 0;const e=["width","height","colorSpace"],t=e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,r=e instanceof ArrayBuffer,n=e instanceof Uint8ClampedArray,o=e instanceof Uint8Array,a=e instanceof Int8Array;return t?"Buffer":r?"ArrayBuffer":n?"Uint8ClampedArray":o?"Uint8Array":a?"Int8Array":null};F.isSupportedBinaryType=t;F.getEncodedMap=(r,n)=>{const o={},a=[];let i=0,s=Array.isArray(r)?[]:{};const c=(r,s)=>{const d=t(r);if(!d){if(Array.isArray(r)){const e=[];for(let t=0;t<r.length;t++)e[t]=c(r[t],`${s}[${t}]`);return e}if("object"==typeof r){const t={},n=(e=>{const t=e instanceof Int16Array,r=e instanceof Uint16Array,n=e instanceof Int32Array,o=e instanceof Uint32Array,a=e instanceof Float32Array,i=e instanceof Float64Array,s=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":r?"Uint16Array":n?"Int32Array":o?"Uint32Array":a?"Float32Array":i?"Float64Array":s?"BigInt64Array":c?"BigUint64Array":null})(r);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in r)Object.hasOwn(r,n)||e.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=c(r[n],`${s.length?`${s}.`:""}${n}`);return t}return r}o[s]={index:i,length:r.byteLength,binaryType:d},"Buffer"===n?a.push(Buffer.from(r)):"ArrayBuffer"===d?a.push(r):a.push(r.buffer),i+=r.byteLength};s=c(r,"");let d=null;if(a.length>1)if("ArrayBuffer"===n){const e=a.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let r=0;for(let e=0;e<a.length;e++)t.set(new Uint8Array(a[e]),r),r+=a[e].byteLength;d=t.buffer}else{d=Buffer.concat(a)}else 1===a.length&&(d=a[0]);return d?{map:o,combinedData:d,sourceCopy:s}:null};const r=(e,t,r,n)=>{const o=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let a=e;for(let e=0;e<o.length;e++){let t=o[e];const i=t.startsWith("[")&&t.endsWith("]"),s=e===o.length-1;if(i){t=t.slice(1,-1);const i=parseInt(t,10);if(!Array.isArray(a))throw new Error(`Expected an array at key "${o.slice(0,e).join(".")}" but found an object.`);s?n?a.splice(i,1):a[i]=r:(a[i]||(a[i]=o[e+1].startsWith("[")?[]:{}),a=a[i])}else s?n?delete a[t]:a[t]=r:(a[t]||(a[t]=o[e+1].startsWith("[")?[]:{}),a=a[t])}return e};F.setNestedProperty=r;return F.decodeMap=(e,t,n)=>{const o="undefined"!=typeof Buffer,a=t instanceof Uint8Array;for(const i in n)if(Object.hasOwn(n,i)){const{index:s,length:c,binaryType:d}=n[i];let u=null;if(o&&t instanceof Buffer)switch(d){case"Buffer":u=t.subarray(s,s+c);break;case"ArrayBuffer":u=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+c);break;case"Uint8Array":u=new Uint8Array(t.subarray(s,s+c));break;case"Uint8ClampedArray":u=new Uint8ClampedArray(t.subarray(s,s+c));break;case"Int8Array":u=new Int8Array(t.subarray(s,s+c))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(d){case"Buffer":if(o){u=Buffer.from(t.slice(s,s+c));break}case"ArrayBuffer":u=a?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+c):t.slice(s,s+c);break;case"Uint8Array":u=a?t.slice(s,s+c):new Uint8Array(t.slice(s,s+c));break;case"Uint8ClampedArray":u=new Uint8ClampedArray(t.slice(s,s+c));break;case"Int8Array":u=new Int8Array(t.slice(s,s+c))}u&&r(e,i,u)}return e},F}var x,$,N={};function G(){if(x)return N;x=1;var e=N&&N.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(N,"__esModule",{value:!0}),N.createLogger=void 0;const t=e(o);return N.createLogger=e=>(0,t.default)(e),N}function V(){if($)return z;$=1,Object.defineProperty(z,"__esModule",{value:!0});const e=C(),t=O(),r=T(),n=G(),o="KMSG",a="KCMD",i=(0,n.createLogger)("klProtocol");return z.default={encode:(e,n,a)=>{const i={json:e.json},s=(0,r.getEncodedMap)(i.json,"Buffer"),c=s?.combinedData;s&&(i.jsonBinaryMap=s.map,i.json=s.sourceCopy);const d=c?c.byteLength:0,u=JSON.stringify(i),l=Buffer.from(u),f=l.byteLength,g=t.KLProtocolHeadersSize.protocolPrefix+t.KLProtocolHeadersSize.protocolVersion+t.KLProtocolHeadersSize.jsonLength+t.KLProtocolHeadersSize.binaryLength+t.KLProtocolHeadersSize.fromServiceId+t.KLProtocolHeadersSize.toServiceId+t.KLProtocolHeadersSize.sentAt+f+d,p=Buffer.alloc(g),m=Date.now();let y=0;return p.write(o,y),y+=t.KLProtocolHeadersSize.protocolPrefix,p.writeUInt8(1,y),y+=t.KLProtocolHeadersSize.protocolVersion,p.writeUInt32LE(f,y),y+=t.KLProtocolHeadersSize.jsonLength,p.writeUInt32LE(d,y),y+=t.KLProtocolHeadersSize.binaryLength,p.writeUInt32LE(n,y),y+=t.KLProtocolHeadersSize.fromServiceId,p.writeUInt32LE(a,y),y+=t.KLProtocolHeadersSize.toServiceId,p.writeBigInt64LE(BigInt(m),y),y+=t.KLProtocolHeadersSize.sentAt,l.copy(p,y),y+=f,c&&d&&c.copy(p,y),p},decodeHeader:e=>{let r=0;const n=e.toString("utf-8",r,t.KLProtocolHeadersSize.protocolPrefix);if(r+=t.KLProtocolHeadersSize.protocolPrefix,n!==o)return null;if(e.byteLength<t.KLHeaderSize)return i(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const a=e.readUInt8(r);r+=t.KLProtocolHeadersSize.protocolVersion;const s=e.readUInt32LE(r);r+=t.KLProtocolHeadersSize.jsonLength;const c=e.readUInt32LE(r);r+=t.KLProtocolHeadersSize.binaryLength;const d=e.readUInt32LE(r);r+=t.KLProtocolHeadersSize.fromServiceId;const u=e.readUInt32LE(r);r+=t.KLProtocolHeadersSize.toServiceId;const l=e.readBigInt64LE(r);r+=t.KLProtocolHeadersSize.sentAt;const f=s+c,g=e.subarray(r,r+f),p=e.subarray(0,t.KLHeaderSize);let m=null;return e.byteLength-t.KLHeaderSize-s-c>0&&(m=e.subarray(t.KLHeaderSize+s+c)),{header:{protocolVersion:a,jsonLength:s,binaryLength:c,fromServiceId:d,toServiceId:u,sentAt:new Date(Number(l)),packages:[g],headerPackage:p},remaining:m}},decodeFullKlMessage:n=>{const o=Buffer.concat(n.packages),a=o.subarray(0,n.jsonLength).toString(),s=o.subarray(n.jsonLength,n.jsonLength+n.binaryLength),c=(0,e.safeJsonParse)(a);if(!c?.json)return i("Invalid JSON in KL message"),null;c.jsonBinaryMap&&s.byteLength&&(0,r.decodeMap)(c.json,s,c.jsonBinaryMap);const d=Buffer.concat([n.headerPackage,o]);let u=d,l=null;const f=t.KLHeaderSize+n.jsonLength+n.binaryLength;return d.byteLength>f&&(l=d.subarray(f),u=d.subarray(0,f)),{message:{json:c.json,rawMessage:u},remaining:l}},patchEncodedHeader:(e,r)=>{if(null==r.fromServiceId&&void 0===r.toServiceId)return e;if(e.byteLength<t.KLHeaderSize)return i("Invalid Header Size"),e;let n=0;return n+=t.KLProtocolHeadersSize.protocolPrefix,n+=t.KLProtocolHeadersSize.protocolVersion,n+=t.KLProtocolHeadersSize.jsonLength,n+=t.KLProtocolHeadersSize.binaryLength,void 0!==r.fromServiceId&&e.writeUInt32LE(r.fromServiceId,n),n+=t.KLProtocolHeadersSize.fromServiceId,void 0!==r.toServiceId&&e.writeUInt32LE(r.toServiceId,n),e},encodeCommand:e=>{let r=0;const n=Buffer.from(e),o=n.byteLength,i=t.KLCmdHeaderSize+o,s=Buffer.alloc(i);return s.write(a,r),r+=t.KLCmdProtocolHeaderSize.protocolPrefix,s.writeUint32LE(o,r),r+=t.KLCmdProtocolHeaderSize.txtLength,n.copy(s,r),s},decodeCommand:e=>{let r=0;if(e.byteLength<t.KLCmdHeaderSize)return{command:null};const n=e.toString("utf-8",r,t.KLCmdProtocolHeaderSize.protocolPrefix);if(r+=t.KLCmdProtocolHeaderSize.protocolPrefix,n!==a)return{command:null};const o=e.readUInt32LE(r);r+=t.KLCmdProtocolHeaderSize.txtLength;const i=e.toString("utf-8",r,r+o),s=e.byteLength-t.KLCmdHeaderSize-o;let c=null;s>0&&(c=e.subarray(t.KLCmdHeaderSize+o));let d=0;return s<0&&(d=Math.abs(s)),{command:i,remainingData:c,missing:d}}},z}var W,q,J={};function Q(){if(W)return J;W=1,Object.defineProperty(J,"__esModule",{value:!0});const e=O(),t=G(),r=T(),n=C(),o="KMSG",a="KCMD",i=(0,t.createLogger)("klProtocol"),s=new TextEncoder;return J.default={encode:(t,n,a)=>{const i={json:t.json},c=(0,r.getEncodedMap)(t.json,"ArrayBuffer"),d=c?.combinedData;c&&(i.jsonBinaryMap=c.map,i.json=c.sourceCopy);const u=d?d.byteLength:0,l=JSON.stringify(i),f=s.encode(l),g=f.byteLength,p=e.KLProtocolHeadersSize.protocolPrefix+e.KLProtocolHeadersSize.protocolVersion+e.KLProtocolHeadersSize.jsonLength+e.KLProtocolHeadersSize.binaryLength+e.KLProtocolHeadersSize.fromServiceId+e.KLProtocolHeadersSize.toServiceId+e.KLProtocolHeadersSize.sentAt+g+u,m=new ArrayBuffer(p),y=new DataView(m),S=new Uint8Array(m),v=Date.now();let b=0;for(let e=0;e<4;++e)S[b++]=o.charCodeAt(e);return y.setUint8(b,1),b+=e.KLProtocolHeadersSize.protocolVersion,y.setUint32(b,g,!0),b+=e.KLProtocolHeadersSize.jsonLength,y.setUint32(b,u,!0),b+=e.KLProtocolHeadersSize.binaryLength,y.setUint32(b,n,!0),b+=e.KLProtocolHeadersSize.fromServiceId,y.setUint32(b,a,!0),b+=e.KLProtocolHeadersSize.toServiceId,y.setBigInt64(b,BigInt(v),!0),b+=e.KLProtocolHeadersSize.sentAt,S.set(f,b),b+=g,d&&u&&S.set(new Uint8Array(d),b),m},decodeHeader:t=>{const r=new DataView(t);let n=0,a="";for(let t=0;t<e.KLProtocolHeadersSize.protocolPrefix;++t)a+=String.fromCharCode(r.getUint8(n++));if(a!==o)return null;if(t.byteLength<e.KLHeaderSize)return i.log(`Received a Partial Header with ${t.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const s=r.getUint8(n);n+=e.KLProtocolHeadersSize.protocolVersion;const c=r.getUint32(n,!0);n+=e.KLProtocolHeadersSize.jsonLength;const d=r.getUint32(n,!0);n+=e.KLProtocolHeadersSize.binaryLength;const u=r.getUint32(n,!0);n+=e.KLProtocolHeadersSize.fromServiceId;const l=r.getUint32(n,!0);n+=e.KLProtocolHeadersSize.toServiceId;const f=r.getBigInt64(n,!0);n+=e.KLProtocolHeadersSize.sentAt;const g=c+d,p=t.slice(n,n+g),m=new Uint8Array(t,0,e.KLHeaderSize);let y=null;if(t.byteLength-e.KLHeaderSize-c-d>0){y=new Uint8Array(t,e.KLHeaderSize+c+d).slice().buffer}return{header:{protocolVersion:s,jsonLength:c,binaryLength:d,fromServiceId:u,toServiceId:l,sentAt:new Date(Number(f)),packages:[p],headerPackage:m.slice().buffer},remaining:y}},decodeFullKlMessage:t=>{const o=t.packages.reduce(((e,t)=>e+t.byteLength),0),a=new Uint8Array(o);let s,c=0;for(const e of t.packages)s=new Uint8Array(e),a.set(s,c),c+=s.byteLength;const d=(new TextDecoder).decode(a.subarray(0,t.jsonLength)),u=a.subarray(t.jsonLength,t.jsonLength+t.binaryLength),l=(0,n.safeJsonParse)(d);if(!l?.json)return i.log("Invalid JSON in KL message"),null;l.jsonBinaryMap&&u.byteLength&&(0,r.decodeMap)(l.json,u,l.jsonBinaryMap);const f=new Uint8Array(t.headerPackage.byteLength+a.byteLength);f.set(new Uint8Array(t.headerPackage),0),f.set(a,t.headerPackage.byteLength);let g=f,p=null;const m=e.KLHeaderSize+t.jsonLength+t.binaryLength;return f.byteLength>m&&(p=f.subarray(m),g=f.subarray(0,m)),{message:{json:l.json,...u.length?{binaryData:u.buffer}:{},rawMessage:g.buffer},remaining:p?.buffer??null}},patchEncodedHeader:(t,r)=>{if(null==r.fromServiceId&&void 0===r.toServiceId)return t;if(t.byteLength<e.KLHeaderSize)return i("Invalid Header Size"),t;let n=0;n+=e.KLProtocolHeadersSize.protocolPrefix,n+=e.KLProtocolHeadersSize.protocolVersion,n+=e.KLProtocolHeadersSize.jsonLength,n+=e.KLProtocolHeadersSize.binaryLength;const o=new DataView(t);return void 0!==r.fromServiceId&&o.setUint32(n,r.fromServiceId,!0),n+=e.KLProtocolHeadersSize.fromServiceId,void 0!==r.toServiceId&&o.setUint32(n,r.toServiceId,!0),t},encodeCommand:t=>{let r=0;const n=s.encode(t),o=n.byteLength,i=e.KLCmdHeaderSize+o,c=new ArrayBuffer(i),d=new DataView(c),u=new Uint8Array(c);for(let e=0;e<4;++e)u[r++]=a.charCodeAt(e);return d.setUint32(r,o,!0),r+=e.KLCmdProtocolHeaderSize.txtLength,u.set(n,r),c},decodeCommand:t=>{const r=new DataView(t);let n=0;if(t.byteLength<e.KLCmdHeaderSize)return{command:null};let o="";for(let t=0;t<e.KLCmdProtocolHeaderSize.protocolPrefix;++t)o+=String.fromCharCode(r.getUint8(n++));if(o!==a)return{command:null};const i=r.getUint32(n,!0);n+=e.KLCmdProtocolHeaderSize.txtLength;const s=t.byteLength-e.KLCmdHeaderSize-i,c=new Uint8Array(t,n,Math.min(i,t.byteLength-e.KLCmdHeaderSize)),d=(new TextDecoder).decode(c);let u=null;s>0&&(u=t.slice(e.KLCmdHeaderSize+i));let l=0;return s<0&&(l=Math.abs(s)),{command:d,remainingData:u,missing:l}}},J}function X(){if(q)return M;q=1;var e=M&&M.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(M,"__esModule",{value:!0}),M.createTransmissionManager=void 0;const t=e(V()),r=e(Q()),n=(0,G().createLogger)("klTransmissionManager");return M.createTransmissionManager=()=>{const e=(o,a,i,s)=>{let c=a,d=null;const u=o instanceof ArrayBuffer;if(n(`RAW: ${o.toString()}`),!c||c.partialHeaderData){let l;if(u?(l=c?.partialHeaderData?new Uint8Array([...new Uint8Array(c.partialHeaderData),...new Uint8Array(o)]).buffer:o,d=r.default.decodeHeader(l)):(l=c?.partialHeaderData?Buffer.concat([c.partialHeaderData,o]):o,d=t.default.decodeHeader(l)),!d){const{command:o,missing:c,remainingData:d}=u?r.default.decodeCommand(l):t.default.decodeCommand(l);return o?s({command:o,complete:!0,rawMessage:l}):n(c?`ERROR: Missing ${c} bytes to complete the command. This partial command will be aborted.`:`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${l.byteLength} bytes`),d?(n(`${d.byteLength} bytes remain after processing command. Re-analyzing...`),e(d,a,i,s)):void 0}if(d.partialHeader)return c={firstPackageAt:Date.now(),partialHeaderData:l},i(c);if(!d.header)return n(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${l.byteLength} bytes`);const f=d.header;c={firstPackageAt:Date.now(),header:{...f,totalBytesReceived:f.packages[0].byteLength,totalBytesExpected:f.binaryLength+f.jsonLength,remaining:d.remaining}},i(c)}else c.header&&c.header.totalBytesReceived<c.header.totalBytesExpected&&(c.header.packages.push(o),c.header.totalBytesReceived+=o.byteLength,i(c));if(c.header&&c.header.totalBytesReceived>=c.header.totalBytesExpected){const o=Date.now()-c.header.sentAt.getTime(),a=Date.now()-c.firstPackageAt;n(`Received ${c.header.totalBytesReceived} of ${c.header.totalBytesExpected} expected in ${o} ms, elapsed since first package: ${a}ms`);const d=u?r.default.decodeFullKlMessage(c.header):t.default.decodeFullKlMessage(c.header),l=c.header.totalBytesReceived,f=c.header.remaining;i(null),d&&s({klMessage:d.message,complete:!0,sourceServiceId:c.header.fromServiceId,targetServiceId:c.header.toServiceId,rawMessage:d.message.rawMessage});let g=f;if(d?.remaining&&(g=u?f?((e,t)=>{const r=e.byteLength+t.byteLength,n=new ArrayBuffer(r),o=new Uint8Array(e),a=new Uint8Array(t),i=new Uint8Array(n);return i.set(o),i.set(a,o.length),n})(f,d.remaining):d.remaining:f?Buffer.concat([f,d.remaining]):d.remaining),g)return n(`${g.byteLength} bytes remaining after processing message with ${l} bytes of data. Re-analyzing...`),e(g,null,i,s)}};return e},M}var Y,Z,ee={};function te(){if(Y)return ee;Y=1;var e=ee&&ee.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ee,"__esModule",{value:!0});const t=e(V()),r=e(Q()),n=C();let o=t.default;return n.isBrowser&&(o=r.default),ee.default=o,ee}function re(){if(Z)return D;Z=1;var e=D&&D.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(D,"__esModule",{value:!0});const t=e(n),r=e((_||(_=1,Object.defineProperty(j,"__esModule",{value:!0}),j.default={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"}),j)),o=X(),a=G(),i=e(te());let s,c,d,u,l=null;const f=(0,o.createTransmissionManager)(),g=(0,a.createLogger)("ipcClient"),p=e=>{const n=r.default.id;t.default.of[n].emit(e)};return D.default={connect:e=>{r.default.id=e?.id||r.default.id,r.default.appspace=e?.appSpace||r.default.appspace,t.default.config={...t.default.config,...r.default};const n=r.default.id;t.default.connectTo(n,(()=>{t.default.of[n].on("connect",(()=>{g("Connected to server"),l=null,c&&c()})),t.default.of[n].on("data",(e=>{f(e,l,(e=>l=e),(e=>{if(e.complete)return e.command?(g(`Received command: ${e.command}`),void(s&&s(e.command))):void(e.klMessage&&d&&d({send:p,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json}))}))})),t.default.of[n].on("disconnect",(()=>{g(`Disconnected from ${n}`),l=null,u&&u()}))}))},sendCommand:e=>{const n=r.default.id,o=i.default.encodeCommand(e);t.default.of[n].emit(o)},sendBuffer:p,onCommand:e=>s=e,onMessageReceived:e=>d=e,onClientConnected:e=>c=e,onClientDisconnected:e=>u=e},D}var ne,oe,ae,ie={},se={};function ce(){return oe||(oe=1,function(e){var t=ie&&ie.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=ie&&ie.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)},n=ie&&ie.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0});const o=n(te()),a=C();var i;r((ne||(ne=1,Object.defineProperty(se,"__esModule",{value:!0}),se.RemoveInvokeError=void 0,function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(i||(se.RemoveInvokeError=i={}))),se),e);let s=Math.ceil(Date.now()/1e3);e.default=function(e){const t={};let r,n=console.log;const i={};let c=e||String(Date.now());const d={},u=e=>!d[e],l=(e,t,r,n,i,s)=>{let c=a.isBrowser?new ArrayBuffer(0):Buffer.alloc(0);const d={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return u(n)&&(c=o.default.encode(d,r,n)),i(c,{msg:d,sourceServiceId:r,targetServiceId:n})};return{setLogger:e=>{n=e},processMessage:(e,o,a,s)=>{if(!s)return!1;const c=s;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=i[c.functionName];if(t){const i=e=>{l(c.functionName,c.messageId,a.targetServiceId,a.sourceServiceId,o,e)};if(!(!r||r({args:c.args,functionName:c.functionName,transport:e,messageId:c.messageId,sourceServiceId:a.sourceServiceId,reply:i,send:o})))return n&&n(`Function "${c.functionName}" not allowed to be invoked by client [${a.sourceServiceId}]`),i({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;t({transport:e,args:c.args,reply:i,messageId:c.messageId,sourceServiceId:a.sourceServiceId,send:o})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),l(c.functionName,c.messageId,a.targetServiceId,a.sourceServiceId,o,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,i,d,l,f)=>{if(!i){const e="No send buffer function provided.";throw n&&n(e),e}s+=1;const g=`${c}-${s}-exec-${e.substring(0,10)}`,p={messageId:g,functionName:e,send:i,sourceServiceId:d,targetServiceId:l,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};p.promise=new Promise(((e,t)=>{p.resolve=e,p.reject=t}));let m=a.isBrowser?new ArrayBuffer(0):Buffer.alloc(0);const y={json:{functionName:e,args:r,messageId:g,type:"execute"}};u(l)&&(m=o.default.encode(y,d,l)),t[g]=p,n&&n(`Calling remote function "${e}" with message id "${g}"`);const S="true"===process.env.NO_INVOKE_TIMEOUT;return f?.async?(p.fulfilled=!0,p.resolve([void 0]),delete t[g]):0===f?.timeout||S||(p.timer=setTimeout((()=>{n&&n(`Remote function ${g} timed out`);const r=t[g];r&&!r.fulfilled&&(r.fulfilled=!0,p.reject(`Function ${e} Timed out`)),delete t[g]}),f?.timeout||3e4)),i(m,{sourceServiceId:d,targetServiceId:l,msg:y}),p.promise},sendResponse:l,registerFunction:(e,t)=>{i[e]=t},registerFunctionsMiddleware:e=>{r=e},unregisterAllFunctions:()=>{Object.keys(i).forEach((e=>{delete i[e]}))},getTransportSendFunction:e=>{const r=t[e];return r?r.send:null},setServiceName:e=>{c=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((r=>{const n=t[r];n&&!n.fulfilled&&(clearTimeout(n.timer),n.fulfilled=!0,n.reject(e),delete t[r])}))},broadcast:(e,t,r,i)=>{s+=1;const d=`${c}-${s}-multicast-${e.substring(0,10)}`;let l=a.isBrowser?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:e,args:t,messageId:d,type:"execute"}};let g=u(r[0].serviceId);g&&(l=o.default.encode(f,i,r[0].serviceId));for(let t=0;t<r.length;t++)try{const a=r[t];n&&n(`Broadcasting function "${e}" with message id "${d}" to client [${a.serviceId}]`),0!==t&&(g=u(a.serviceId),g&&(l=o.default.patchEncodedHeader(l,{toServiceId:a.serviceId}))),a.sendFn(l,{msg:f,sourceServiceId:i,targetServiceId:a.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{d[e]=t}}}}(ie)),ie}var de=a((ae||(ae=1,function(n){var o=s&&s.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.createImageDataLike=n.KemuHubServiceId=n.DataType=void 0;const a=w();Object.defineProperty(n,"DataType",{enumerable:!0,get:function(){return a.DataType}});const i=e,c=o(t),d=o(r),u=(P||(P=1,Object.defineProperty(A,"__esModule",{value:!0}),A.KemuComposerGuestServiceId=A.KemuHubServiceId=void 0,A.KemuHubServiceId=0,A.KemuComposerGuestServiceId=1),A);Object.defineProperty(n,"KemuHubServiceId",{enumerable:!0,get:function(){return u.KemuHubServiceId}});const l=C(),f=function(){if(B)return E;B=1,Object.defineProperty(E,"__esModule",{value:!0}),E.preProcessManifest=E.portStrToWidgetPort=E.createImageDataLike=void 0;const e=w();return E.createImageDataLike=(t,r,n,o="srgb")=>{let a;return a=t instanceof Uint8ClampedArray?t:new Uint8ClampedArray(t),{data:a,width:r,height:n,colorSpace:o,_kemuType:e.DataType.ImageData}},E.portStrToWidgetPort=t=>({...t,type:e.DataType[t.type]}),E.preProcessManifest=(e,t,r)=>({...e,path:t,...e.widgetUI&&r?.widgetUIContents?{widgetUIContents:r.widgetUIContents}:{}}),E}();Object.defineProperty(n,"createImageDataLike",{enumerable:!0,get:function(){return f.createImageDataLike}});const g=o(re()),p=G(),m=o(ce()),y=(0,p.createLogger)("kemuWidgetService"),S=(0,c.default)(process.argv.slice(2));n.default=function(e){const t={},r=process.env.KEMU_WIDGET_SESSION_ID;let n,o,s,c,p=!1;const v={};let b,I,h,L,w,P,A,H,K=null;const C=new m.default;C.setLogger(y),t.start=async(t,c)=>{const u=t||d.default.resolve(d.default.dirname(process.argv[1]),"manifest.json");s=d.default.dirname(u);const m=await(0,i.readFile)(u,"utf-8"),v=(0,l.safeJsonParse)(m);if(!v)throw new Error("Error parsing manifest file.");let b;if(v.inputs||(v.inputs=[]),v.outputs||(v.outputs=[]),v.widgetUI)try{b=await(0,i.readFile)(d.default.join(s,"widgetUI.js"))}catch(e){y(`Error loading widgetUI file ${v.name}: ${e}`)}if(v.svgIcon)try{const e=await(0,i.readFile)(d.default.join(s,v.svgIcon),"utf-8");v.svgIcon=e}catch(e){y(`Error loading icon for service ${v.name}: ${e}`)}o=(0,f.preProcessManifest)(v,s,{widgetUIContents:b}),p=o.name.startsWith("test."),o.path=s,o.internal=S.internal||!1,p?y("Starting Kemu Service in Dev mode"):((e=>{const t=e||S.sessionId||r;if(!t)throw new Error("Missing sessionId. Expected service to be launched with a sessionId as first argument, or the KEMU_WIDGET_SESSION_ID environment variable to be set.");n=parseInt(String(t))})(c),y(`Starting Kemu Service with session id: ${n}`)),C.setServiceName(`${o.name}_${o.version}`),g.default.onCommand(B),g.default.onMessageReceived((({json:e,transmission:t})=>C.processMessage(a.Transport.IPC,g.default.sendBuffer,t,e))),C.registerFunction(a.KemuHubFunctions.OnParentEvent,_),C.registerFunction(a.KemuHubFunctions.GetDefaultState,E),C.registerFunction(a.KemuHubFunctions.UIEvent,M),C.registerFunction(a.KemuHubFunctions.InitializeInstance,D),C.registerFunction(a.KemuHubFunctions.TerminateInstance,j),C.registerFunction(a.KemuHubFunctions.KemuComposerDisconnected,k),g.default.onClientConnected((()=>{H&&H()})),g.default.onClientDisconnected((()=>{p&&(n=void 0)})),g.default.connect({appSpace:S.ipcSpace||e?.ipc?.appSpace,id:S.ipcId||e?.ipc?.id})};const B=e=>{(0,l.onAckRequest)(e,(e=>{g.default.sendCommand((0,l.buildIpcAckResponse)(e,n||void 0)),!n&&p&&(y("Dev mode detected, assuming service session id from ack request:",e),n=e)})),(0,l.onStartBroadcastCommand)(e,(()=>{h&&h()})),(0,l.onEndBroadcastCommand)(e,(()=>{L&&L()})),(0,l.onSendManifestCommand)(e,(()=>{y("Sending manifest to hub"),n?C.execute(a.KemuHubFunctions.ServiceManifest,[{...o,devMode:p}],g.default.sendBuffer,n,u.KemuHubServiceId,{async:!0}):y("Service session id is not set. Cannot send manifest.")})),(0,l.onAssumeSession)(e,(e=>{n=e,y(`Assumed session id ${e}`)}))},E=async e=>{if(I){const t=await I();return e.reply({success:[t]})}return e.reply({success:[{}]})},_=async e=>{if(!b)return y("No onParentEvent callback defined. Skipping parent event."),e.reply({success:[]});const t=e.args[0],{source:r,target:o,data:i,recipe:s,currentState:c,targetVariantId:d,eventContext:u,currentPath:l,eventId:f}=t;if(!n)return void y("Service session id is not set. Cannot process parent event.");if(!r||!o||!i)return e.reply({error:"Invalid arguments, expected [source, target, data, context]"});const p=g.default.sendBuffer,m=async t=>C.execute(a.KemuHubFunctions.SetOutputs,[t],p,n,e.sourceServiceId,{timeout:0}),S={currentState:c,type:o.widgetType,widgetId:o.widgetId,variantId:d,recipeId:s.poolId,recipeName:s.name,recipe:s,setState:async t=>{const r={widgetId:o.widgetId,variantId:d,recipeId:s.poolId,newState:t};return C.execute(a.KemuHubFunctions.SetState,[r],p,n,e.sourceServiceId)},setOutputs:async(e,t)=>{const r={widgetId:o.widgetId,recipeId:s.poolId,outputs:e,finalState:t,currentPath:l};await m(r)},setOutputsWithContext:async e=>{const t={...e,widgetId:o.widgetId,recipeId:s.poolId,currentPath:l};await m(t)}};y(`Invoking user-defined onParentEvent callback for event id "${e.messageId}"`),await b({data:i,source:r,target:o,eventContext:u,currentPath:l,eventId:f},S).then((()=>{y(`Replying SUCCESS to event id "${e.messageId}"`),e.reply({success:[]})})).catch((t=>{const r="string"==typeof t?t:t.message||t;y(`Error invoking onParentEvent callback: ${r}`),e.reply({error:r,errCode:"PARENT_EVENT_CALLBACK_ERROR"})}))},D=async e=>{const[{currentState:t,widgetId:r,variantId:n,recipeType:o,currentDependencies:a,kemuApiKey:i,recipe:s}]=e.args;if(i&&(c=i),v[r]={currentRecipeId:s.poolId,variantId:n,currentSourceServiceId:e.sourceServiceId},w){const c=[],d={currentState:t,recipeId:s.poolId,recipeName:s.name,recipe:{uuid:s.uuid,poolId:s.poolId,name:s.name,type:s.type,version:s.version,authorId:s.authorId,dbId:s.dbId},widgetId:r,variantId:n,recipeType:o,currentDependencies:a||{},kemuApiKey:i,secrets:{requestAccess:e=>{for(const t of e)"string"==typeof t?c.push({name:t}):c.push(t)}}},u=[await w(d)||null,c.length>0?c:null];e.reply({success:u})}else e.reply({error:"Not implemented",errCode:"FNC_NOT_FOUND"})},j=async e=>{if(P){const[{currentState:t,recipe:r,widgetId:n,variantId:o}]=e.args,a={currentState:t,recipeId:r.poolId,recipe:r,widgetId:n,variantId:o};await P(a),delete v[n]}e.reply({success:[]})},k=async e=>{if(console.log("Kemu Composer disconnected event: ",e),e.reply({success:[]}),A){const[t]=e.args;t.recipe&&await A(t)}},M=async e=>{if(K)try{const t=await K.apply(void 0,e.args);return e.reply({success:[t]})}catch(t){const r="string"==typeof t?t:JSON.stringify(t);return y(`Error invoking UI Event handler: ${r}`),e.reply({error:r})}e.reply({error:"UI Events are not supported in this service."})},z=async e=>{if(!o.eventEmitter)throw new Error("This service does not support broadcasting events. Please set `eventEmitter` to true in your manifest file.");if(n)return C.execute(a.KemuHubFunctions.BroadcastEvent,e,g.default.sendBuffer,n,u.KemuHubServiceId,{async:!0});y("Service session id is not set. Cannot broadcast event.")};t.broadcast=async(e,t)=>{const r=[{outputs:e,variantId:t,currentPath:[]}];await z(r)},t.broadcastEvent=async e=>{const t=[{outputs:e.outputs,variantId:e.variantId,eventContext:e.eventContext,targetRecipeId:e.targetRecipeId,targetRecipePoolId:e.targetRecipePoolId,targetWidgetId:e.targetWidgetId,currentPath:e.currentPath||[],eventId:e.eventId}];await z(t)},t.addDependencyPath=async(e,t,r)=>{if(!n)throw new Error("Not yet registered with the Hub");const o=v[r];if(!o.currentSourceServiceId||!o.currentRecipeId)throw new Error("Cannot invoke this method before initialization");const i={key:e,path:t,recipeId:o.currentRecipeId,widgetId:r};y(`Adding dependency path for key "${e}" with path "${t}"`),await C.execute(a.ServiceToServiceFunctions.SetDependencyPath,[i],g.default.sendBuffer,n,o.currentSourceServiceId)},t.getDependencyPath=async(e,t)=>{if(!n)throw new Error("Not yet registered with the Hub");const r=v[t];if(!r.currentSourceServiceId||!r.currentRecipeId)throw new Error("Cannot invoke this method before initialization");y("Getting dependency path for key:",e);const o={key:e,recipeId:r.currentRecipeId,widgetId:t},[i]=await C.execute(a.ServiceToServiceFunctions.GetDependencyPath,[o],g.default.sendBuffer,n,r.currentSourceServiceId);return y("Dependency path response:",i),i},t.getUniqueId=async()=>{if(!n)throw new Error("Not yet registered with the Hub");const[e]=await C.execute(a.KemuHubFunctions.GetUniqueId,[],g.default.sendBuffer,n,u.KemuHubServiceId);return e},t.resolveRuntimeDependencyPath=e=>{if(!S.recipePath)throw new Error("Cannot resolve runtime dependency without a recipe path. Missing [--recipePath] argument.");return d.default.resolve(S.recipePath,e)},t.onGetDefaultState=e=>{I=e},t.onParentEvent=e=>{b=e},t.onTerminate=e=>{P=e},t.onKemuComposerDisconnected=e=>{A=e},t.onInitialize=e=>{w=e},t.onConnected=e=>{H=e},t.onStartBroadcast=e=>{h=e},t.onStopBroadcast=e=>{L=e},t.onUIEvent=e=>{K=e},t.secrets={add:async e=>{if(!n)throw new Error("Service session id is not set. Cannot add secret.");const t=Array.isArray(e)?e:[e],r=[{hubServiceName:o.name,secrets:t}];await C.execute(a.KemuHubFunctions.AddServiceSecret,r,g.default.sendBuffer,n,u.KemuHubServiceId)},read:async e=>{if(!n)throw new Error("Service session id is not set. Cannot read secret.");const t=[{recipeUuid:e.recipeUuid,secretNames:e.names,serviceName:o.name}],[r]=await C.execute(a.KemuHubFunctions.GetRecipeDecryptedSecretsValues,t,g.default.sendBuffer,n,u.KemuHubServiceId);return r?.secrets||{}}},S.internal&&(t.executeHubFunction=async(e,t,r)=>{if(n)return C.execute(e,t,g.default.sendBuffer,n,u.KemuHubServiceId,r);y("Service session id is not set. Cannot execute hub function.")});const U=t;return U._getRemoteInvoker=()=>C,U.getHubConfig=async()=>{if(!n)throw new Error("Service session id is not set. Cannot execute hub function.");const e=await C.execute(a.KemuHubFunctions.GetHubConfig,[],g.default.sendBuffer,n,u.KemuHubServiceId);return e?.[0]&&!e[0].kemuApiKey&&c&&(e[0].kemuApiKey=c),e?.[0]},U.getEdgeApiKey=async()=>{if(p)return void console.warn("This method [getEdgeApiKey] is NOT available in dev mode");if(!n)throw new Error("Service session id is not set. Cannot execute hub function.");const e=await C.execute(a.KemuHubFunctions.GetDecryptedEdgeApiKey,[],g.default.sendBuffer,n,u.KemuHubServiceId);return e?.[0]},t}}(s)),s));module.exports=de;
|
|
1
|
+
"use strict";var e=require("fs/promises"),t=require("minimist"),r=require("path"),n=require("node-ipc"),o=require("debug");function a(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var i,s={},c={},d={};var u,l={};var f,p={};var g,m={};var y,S={};var v,I={};var b,h,w={};function L(){return h||(h=1,e=c,A=c&&c.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),H=c&&c.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||A(t,e,r)},Object.defineProperty(e,"__esModule",{value:!0}),H((i||(i=1,Object.defineProperty(d,"__esModule",{value:!0}),d.DataTypeStr=d.DataType=d.RecipeType=void 0,function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(t||(d.RecipeType=t={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(r||(d.DataType=r={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(n||(d.DataTypeStr=n={}))),d),e),H((u||(u=1,Object.defineProperty(l,"__esModule",{value:!0})),l),e),H((f||(f=1,Object.defineProperty(p,"__esModule",{value:!0})),p),e),H((g||(g=1,Object.defineProperty(m,"__esModule",{value:!0}),m.ProcessorType=void 0,function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(o||(m.ProcessorType=o={}))),m),e),H((y||(y=1,Object.defineProperty(S,"__esModule",{value:!0}),S.Transport=S.ServiceToServiceFunctions=S.KemuHubFunctions=S.KemuHubCommand=void 0,function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(a||(S.KemuHubCommand=a={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.AddServiceSecret="addServiceSecret",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.SendToRecipe="sendToRecipe",e.KemuComposerDisconnected="kemu-composer-disconnected",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.SaveRecipeToFile="saveRecipeToFile",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey",e.GetHubConfig="getHubConfig",e.GetRecipeDecryptedSecretsValues="getRecipeDecryptedSecretsValues",e.GetRecipeSecretMappings="getRecipeSecretMappings",e.AddRecipeSecretMapping="addRecipeSecretMapping",e.DeleteRecipeSecretMapping="deleteRecipeSecretMapping",e.GetHubSecrets="getHubSecrets",e.AddHubSecrets="addHubSecrets",e.DeleteHubSecret="deleteHubSecret"}(s||(S.KemuHubFunctions=s={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath",e.ParseStringExpression="parseStringExpression",e.GetGlobalVariableNames="getGlobalVariableNames",e.GetGlobalVariableValues="getGlobalVariableValues",e.SetGlobalVariableValues="setGlobalVariableValues"}(L||(S.ServiceToServiceFunctions=L={})),function(e){e.IPC="ipc",e.WS="ws"}(P||(S.Transport=P={}))),S),e),H((v||(v=1,Object.defineProperty(I,"__esModule",{value:!0})),I),e),H((b||(b=1,Object.defineProperty(w,"__esModule",{value:!0})),w),e)),c;var e,t,r,n,o,a,s,L,P,A,H}var P,A={};var H,K={};var C,B={};function E(){if(C)return B;C=1,Object.defineProperty(B,"__esModule",{value:!0}),B.onAssumeSession=B.buildIpcAckResponse=B.isBrowser=B.onSendManifestCommand=B.onEndBroadcastCommand=B.onStartBroadcastCommand=B.onAckResponse=B.onAckRequest=B.buildSocketAckRequest=B.buildIpcAckRequest=B.buildAckResponse=B.safeJsonParse=void 0;const e=L();B.safeJsonParse=e=>{try{return JSON.parse(e)}catch(e){return null}};B.buildAckResponse=t=>`${e.KemuHubCommand.AcknowledgeResponse}${t}`;B.buildIpcAckResponse=(t,r)=>`${e.KemuHubCommand.AcknowledgeResponse}${t}:${r||""}`;B.buildIpcAckRequest=()=>`${e.KemuHubCommand.IpcAcknowledge}`;B.buildSocketAckRequest=t=>`${e.KemuHubCommand.SocketAcknowledge}${t}`;B.onAssumeSession=(t,r)=>{if(t.startsWith(e.KemuHubCommand.AssumeSession)){const n=t.split(e.KemuHubCommand.AssumeSession);return r(parseInt(n[1])),!0}return!1};B.onAckResponse=(t,r)=>{if(t.startsWith(e.KemuHubCommand.AcknowledgeResponse)){const n=t.split(e.KemuHubCommand.AcknowledgeResponse),o=parseInt(n[1]);return r&&r(o),o}return null};B.onAckRequest=(t,r)=>{const n=e.KemuHubCommand.SocketAcknowledge,o=e.KemuHubCommand.IpcAcknowledge,a=t.startsWith(n),i=t.startsWith(o);if(a||i){const e=t.split(a?n:o),i=parseInt(e[1]);return r&&r(i),i}return null};B.onStartBroadcastCommand=(t,r)=>t===e.KemuHubCommand.BroadcastStart&&(r(),!0);B.onEndBroadcastCommand=(t,r)=>t===e.KemuHubCommand.BroadcastEnd&&(r(),!0);B.onSendManifestCommand=(t,r)=>t===e.KemuHubCommand.SendManifest&&(r(),!0);const t="undefined"!=typeof window;return B.isBrowser=t,B}var _,D={};var j,k={},M={};var z,x={},U={},O={};function R(){return z||(z=1,e=O,Object.defineProperty(e,"__esModule",{value:!0}),e.KLCmdHeaderSize=e.KLHeaderSize=e.KLCmdProtocolHeaderSize=e.KLProtocolHeadersSize=void 0,e.KLProtocolHeadersSize={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},e.KLCmdProtocolHeaderSize={protocolPrefix:4,txtLength:4},e.KLHeaderSize=Object.values(e.KLProtocolHeadersSize).reduce(((e,t)=>e+t),0),e.KLCmdHeaderSize=Object.values(e.KLCmdProtocolHeaderSize).reduce(((e,t)=>e+t),0)),O;var e}var T,F={};function N(){if(T)return F;T=1,Object.defineProperty(F,"__esModule",{value:!0}),F.setNestedProperty=F.decodeMap=F.isSupportedBinaryType=F.getEncodedMap=void 0;const e=["width","height","colorSpace"],t=e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,r=e instanceof ArrayBuffer,n=e instanceof Uint8ClampedArray,o=e instanceof Uint8Array,a=e instanceof Int8Array;return t?"Buffer":r?"ArrayBuffer":n?"Uint8ClampedArray":o?"Uint8Array":a?"Int8Array":null};F.isSupportedBinaryType=t;F.getEncodedMap=(r,n)=>{const o={},a=[];let i=0,s=Array.isArray(r)?[]:{};const c=(r,s)=>{const d=t(r);if(!d){if(Array.isArray(r)){const e=[];for(let t=0;t<r.length;t++)e[t]=c(r[t],`${s}[${t}]`);return e}if("object"==typeof r){const t={},n=(e=>{const t=e instanceof Int16Array,r=e instanceof Uint16Array,n=e instanceof Int32Array,o=e instanceof Uint32Array,a=e instanceof Float32Array,i=e instanceof Float64Array,s=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":r?"Uint16Array":n?"Int32Array":o?"Uint32Array":a?"Float32Array":i?"Float64Array":s?"BigInt64Array":c?"BigUint64Array":null})(r);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in r)Object.hasOwn(r,n)||e.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=c(r[n],`${s.length?`${s}.`:""}${n}`);return t}return r}o[s]={index:i,length:r.byteLength,binaryType:d},"Buffer"===n?a.push(Buffer.from(r)):"ArrayBuffer"===d?a.push(r):a.push(r.buffer),i+=r.byteLength};s=c(r,"");let d=null;if(a.length>1)if("ArrayBuffer"===n){const e=a.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let r=0;for(let e=0;e<a.length;e++)t.set(new Uint8Array(a[e]),r),r+=a[e].byteLength;d=t.buffer}else{d=Buffer.concat(a)}else 1===a.length&&(d=a[0]);return d?{map:o,combinedData:d,sourceCopy:s}:null};const r=(e,t,r,n)=>{const o=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let a=e;for(let e=0;e<o.length;e++){let t=o[e];const i=t.startsWith("[")&&t.endsWith("]"),s=e===o.length-1;if(i){t=t.slice(1,-1);const i=parseInt(t,10);if(!Array.isArray(a))throw new Error(`Expected an array at key "${o.slice(0,e).join(".")}" but found an object.`);s?n?a.splice(i,1):a[i]=r:(a[i]||(a[i]=o[e+1].startsWith("[")?[]:{}),a=a[i])}else s?n?delete a[t]:a[t]=r:(a[t]||(a[t]=o[e+1].startsWith("[")?[]:{}),a=a[t])}return e};F.setNestedProperty=r;return F.decodeMap=(e,t,n)=>{const o="undefined"!=typeof Buffer,a=t instanceof Uint8Array;for(const i in n)if(Object.hasOwn(n,i)){const{index:s,length:c,binaryType:d}=n[i];let u=null;if(o&&t instanceof Buffer)switch(d){case"Buffer":u=t.subarray(s,s+c);break;case"ArrayBuffer":u=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+c);break;case"Uint8Array":u=new Uint8Array(t.subarray(s,s+c));break;case"Uint8ClampedArray":u=new Uint8ClampedArray(t.subarray(s,s+c));break;case"Int8Array":u=new Int8Array(t.subarray(s,s+c))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(d){case"Buffer":if(o){u=Buffer.from(t.slice(s,s+c));break}case"ArrayBuffer":u=a?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+c):t.slice(s,s+c);break;case"Uint8Array":u=a?t.slice(s,s+c):new Uint8Array(t.slice(s,s+c));break;case"Uint8ClampedArray":u=new Uint8ClampedArray(t.slice(s,s+c));break;case"Int8Array":u=new Int8Array(t.slice(s,s+c))}u&&r(e,i,u)}return e},F}var $,G,V={};function W(){if($)return V;$=1;var e=V&&V.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(V,"__esModule",{value:!0}),V.createLogger=void 0;const t=e(o);return V.createLogger=e=>(0,t.default)(e),V}function q(){if(G)return U;G=1,Object.defineProperty(U,"__esModule",{value:!0});const e=E(),t=R(),r=N(),n=W(),o="KMSG",a="KCMD",i=(0,n.createLogger)("klProtocol");return U.default={encode:(e,n,a)=>{const i={json:e.json},s=(0,r.getEncodedMap)(i.json,"Buffer"),c=s?.combinedData;s&&(i.jsonBinaryMap=s.map,i.json=s.sourceCopy);const d=c?c.byteLength:0,u=JSON.stringify(i),l=Buffer.from(u),f=l.byteLength,p=t.KLProtocolHeadersSize.protocolPrefix+t.KLProtocolHeadersSize.protocolVersion+t.KLProtocolHeadersSize.jsonLength+t.KLProtocolHeadersSize.binaryLength+t.KLProtocolHeadersSize.fromServiceId+t.KLProtocolHeadersSize.toServiceId+t.KLProtocolHeadersSize.sentAt+f+d,g=Buffer.alloc(p),m=Date.now();let y=0;return g.write(o,y),y+=t.KLProtocolHeadersSize.protocolPrefix,g.writeUInt8(1,y),y+=t.KLProtocolHeadersSize.protocolVersion,g.writeUInt32LE(f,y),y+=t.KLProtocolHeadersSize.jsonLength,g.writeUInt32LE(d,y),y+=t.KLProtocolHeadersSize.binaryLength,g.writeUInt32LE(n,y),y+=t.KLProtocolHeadersSize.fromServiceId,g.writeUInt32LE(a,y),y+=t.KLProtocolHeadersSize.toServiceId,g.writeBigInt64LE(BigInt(m),y),y+=t.KLProtocolHeadersSize.sentAt,l.copy(g,y),y+=f,c&&d&&c.copy(g,y),g},decodeHeader:e=>{let r=0;const n=e.toString("utf-8",r,t.KLProtocolHeadersSize.protocolPrefix);if(r+=t.KLProtocolHeadersSize.protocolPrefix,n!==o)return null;if(e.byteLength<t.KLHeaderSize)return i(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const a=e.readUInt8(r);r+=t.KLProtocolHeadersSize.protocolVersion;const s=e.readUInt32LE(r);r+=t.KLProtocolHeadersSize.jsonLength;const c=e.readUInt32LE(r);r+=t.KLProtocolHeadersSize.binaryLength;const d=e.readUInt32LE(r);r+=t.KLProtocolHeadersSize.fromServiceId;const u=e.readUInt32LE(r);r+=t.KLProtocolHeadersSize.toServiceId;const l=e.readBigInt64LE(r);r+=t.KLProtocolHeadersSize.sentAt;const f=s+c,p=e.subarray(r,r+f),g=e.subarray(0,t.KLHeaderSize);let m=null;return e.byteLength-t.KLHeaderSize-s-c>0&&(m=e.subarray(t.KLHeaderSize+s+c)),{header:{protocolVersion:a,jsonLength:s,binaryLength:c,fromServiceId:d,toServiceId:u,sentAt:new Date(Number(l)),packages:[p],headerPackage:g},remaining:m}},decodeFullKlMessage:n=>{const o=Buffer.concat(n.packages),a=o.subarray(0,n.jsonLength).toString(),s=o.subarray(n.jsonLength,n.jsonLength+n.binaryLength),c=(0,e.safeJsonParse)(a);if(!c?.json)return i("Invalid JSON in KL message"),null;c.jsonBinaryMap&&s.byteLength&&(0,r.decodeMap)(c.json,s,c.jsonBinaryMap);const d=Buffer.concat([n.headerPackage,o]);let u=d,l=null;const f=t.KLHeaderSize+n.jsonLength+n.binaryLength;return d.byteLength>f&&(l=d.subarray(f),u=d.subarray(0,f)),{message:{json:c.json,rawMessage:u},remaining:l}},patchEncodedHeader:(e,r)=>{if(null==r.fromServiceId&&void 0===r.toServiceId)return e;if(e.byteLength<t.KLHeaderSize)return i("Invalid Header Size"),e;let n=0;return n+=t.KLProtocolHeadersSize.protocolPrefix,n+=t.KLProtocolHeadersSize.protocolVersion,n+=t.KLProtocolHeadersSize.jsonLength,n+=t.KLProtocolHeadersSize.binaryLength,void 0!==r.fromServiceId&&e.writeUInt32LE(r.fromServiceId,n),n+=t.KLProtocolHeadersSize.fromServiceId,void 0!==r.toServiceId&&e.writeUInt32LE(r.toServiceId,n),e},encodeCommand:e=>{let r=0;const n=Buffer.from(e),o=n.byteLength,i=t.KLCmdHeaderSize+o,s=Buffer.alloc(i);return s.write(a,r),r+=t.KLCmdProtocolHeaderSize.protocolPrefix,s.writeUint32LE(o,r),r+=t.KLCmdProtocolHeaderSize.txtLength,n.copy(s,r),s},decodeCommand:e=>{let r=0;if(e.byteLength<t.KLCmdHeaderSize)return{command:null};const n=e.toString("utf-8",r,t.KLCmdProtocolHeaderSize.protocolPrefix);if(r+=t.KLCmdProtocolHeaderSize.protocolPrefix,n!==a)return{command:null};const o=e.readUInt32LE(r);r+=t.KLCmdProtocolHeaderSize.txtLength;const i=e.toString("utf-8",r,r+o),s=e.byteLength-t.KLCmdHeaderSize-o;let c=null;s>0&&(c=e.subarray(t.KLCmdHeaderSize+o));let d=0;return s<0&&(d=Math.abs(s)),{command:i,remainingData:c,missing:d}}},U}var J,Q,X={};function Y(){if(J)return X;J=1,Object.defineProperty(X,"__esModule",{value:!0});const e=R(),t=W(),r=N(),n=E(),o="KMSG",a="KCMD",i=(0,t.createLogger)("klProtocol"),s=new TextEncoder;return X.default={encode:(t,n,a)=>{const i={json:t.json},c=(0,r.getEncodedMap)(t.json,"ArrayBuffer"),d=c?.combinedData;c&&(i.jsonBinaryMap=c.map,i.json=c.sourceCopy);const u=d?d.byteLength:0,l=JSON.stringify(i),f=s.encode(l),p=f.byteLength,g=e.KLProtocolHeadersSize.protocolPrefix+e.KLProtocolHeadersSize.protocolVersion+e.KLProtocolHeadersSize.jsonLength+e.KLProtocolHeadersSize.binaryLength+e.KLProtocolHeadersSize.fromServiceId+e.KLProtocolHeadersSize.toServiceId+e.KLProtocolHeadersSize.sentAt+p+u,m=new ArrayBuffer(g),y=new DataView(m),S=new Uint8Array(m),v=Date.now();let I=0;for(let e=0;e<4;++e)S[I++]=o.charCodeAt(e);return y.setUint8(I,1),I+=e.KLProtocolHeadersSize.protocolVersion,y.setUint32(I,p,!0),I+=e.KLProtocolHeadersSize.jsonLength,y.setUint32(I,u,!0),I+=e.KLProtocolHeadersSize.binaryLength,y.setUint32(I,n,!0),I+=e.KLProtocolHeadersSize.fromServiceId,y.setUint32(I,a,!0),I+=e.KLProtocolHeadersSize.toServiceId,y.setBigInt64(I,BigInt(v),!0),I+=e.KLProtocolHeadersSize.sentAt,S.set(f,I),I+=p,d&&u&&S.set(new Uint8Array(d),I),m},decodeHeader:t=>{const r=new DataView(t);let n=0,a="";for(let t=0;t<e.KLProtocolHeadersSize.protocolPrefix;++t)a+=String.fromCharCode(r.getUint8(n++));if(a!==o)return null;if(t.byteLength<e.KLHeaderSize)return i.log(`Received a Partial Header with ${t.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const s=r.getUint8(n);n+=e.KLProtocolHeadersSize.protocolVersion;const c=r.getUint32(n,!0);n+=e.KLProtocolHeadersSize.jsonLength;const d=r.getUint32(n,!0);n+=e.KLProtocolHeadersSize.binaryLength;const u=r.getUint32(n,!0);n+=e.KLProtocolHeadersSize.fromServiceId;const l=r.getUint32(n,!0);n+=e.KLProtocolHeadersSize.toServiceId;const f=r.getBigInt64(n,!0);n+=e.KLProtocolHeadersSize.sentAt;const p=c+d,g=t.slice(n,n+p),m=new Uint8Array(t,0,e.KLHeaderSize);let y=null;if(t.byteLength-e.KLHeaderSize-c-d>0){y=new Uint8Array(t,e.KLHeaderSize+c+d).slice().buffer}return{header:{protocolVersion:s,jsonLength:c,binaryLength:d,fromServiceId:u,toServiceId:l,sentAt:new Date(Number(f)),packages:[g],headerPackage:m.slice().buffer},remaining:y}},decodeFullKlMessage:t=>{const o=t.packages.reduce(((e,t)=>e+t.byteLength),0),a=new Uint8Array(o);let s,c=0;for(const e of t.packages)s=new Uint8Array(e),a.set(s,c),c+=s.byteLength;const d=(new TextDecoder).decode(a.subarray(0,t.jsonLength)),u=a.subarray(t.jsonLength,t.jsonLength+t.binaryLength),l=(0,n.safeJsonParse)(d);if(!l?.json)return i.log("Invalid JSON in KL message"),null;l.jsonBinaryMap&&u.byteLength&&(0,r.decodeMap)(l.json,u,l.jsonBinaryMap);const f=new Uint8Array(t.headerPackage.byteLength+a.byteLength);f.set(new Uint8Array(t.headerPackage),0),f.set(a,t.headerPackage.byteLength);let p=f,g=null;const m=e.KLHeaderSize+t.jsonLength+t.binaryLength;return f.byteLength>m&&(g=f.subarray(m),p=f.subarray(0,m)),{message:{json:l.json,...u.length?{binaryData:u.buffer}:{},rawMessage:p.buffer},remaining:g?.buffer??null}},patchEncodedHeader:(t,r)=>{if(null==r.fromServiceId&&void 0===r.toServiceId)return t;if(t.byteLength<e.KLHeaderSize)return i("Invalid Header Size"),t;let n=0;n+=e.KLProtocolHeadersSize.protocolPrefix,n+=e.KLProtocolHeadersSize.protocolVersion,n+=e.KLProtocolHeadersSize.jsonLength,n+=e.KLProtocolHeadersSize.binaryLength;const o=new DataView(t);return void 0!==r.fromServiceId&&o.setUint32(n,r.fromServiceId,!0),n+=e.KLProtocolHeadersSize.fromServiceId,void 0!==r.toServiceId&&o.setUint32(n,r.toServiceId,!0),t},encodeCommand:t=>{let r=0;const n=s.encode(t),o=n.byteLength,i=e.KLCmdHeaderSize+o,c=new ArrayBuffer(i),d=new DataView(c),u=new Uint8Array(c);for(let e=0;e<4;++e)u[r++]=a.charCodeAt(e);return d.setUint32(r,o,!0),r+=e.KLCmdProtocolHeaderSize.txtLength,u.set(n,r),c},decodeCommand:t=>{const r=new DataView(t);let n=0;if(t.byteLength<e.KLCmdHeaderSize)return{command:null};let o="";for(let t=0;t<e.KLCmdProtocolHeaderSize.protocolPrefix;++t)o+=String.fromCharCode(r.getUint8(n++));if(o!==a)return{command:null};const i=r.getUint32(n,!0);n+=e.KLCmdProtocolHeaderSize.txtLength;const s=t.byteLength-e.KLCmdHeaderSize-i,c=new Uint8Array(t,n,Math.min(i,t.byteLength-e.KLCmdHeaderSize)),d=(new TextDecoder).decode(c);let u=null;s>0&&(u=t.slice(e.KLCmdHeaderSize+i));let l=0;return s<0&&(l=Math.abs(s)),{command:d,remainingData:u,missing:l}}},X}function Z(){if(Q)return x;Q=1;var e=x&&x.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(x,"__esModule",{value:!0}),x.createTransmissionManager=void 0;const t=e(q()),r=e(Y()),n=(0,W().createLogger)("klTransmissionManager");return x.createTransmissionManager=()=>{const e=(o,a,i,s)=>{let c=a,d=null;const u=o instanceof ArrayBuffer;if(n(`RAW: ${o.toString()}`),!c||c.partialHeaderData){let l;if(u?(l=c?.partialHeaderData?new Uint8Array([...new Uint8Array(c.partialHeaderData),...new Uint8Array(o)]).buffer:o,d=r.default.decodeHeader(l)):(l=c?.partialHeaderData?Buffer.concat([c.partialHeaderData,o]):o,d=t.default.decodeHeader(l)),!d){const{command:o,missing:c,remainingData:d}=u?r.default.decodeCommand(l):t.default.decodeCommand(l);return o?s({command:o,complete:!0,rawMessage:l}):n(c?`ERROR: Missing ${c} bytes to complete the command. This partial command will be aborted.`:`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${l.byteLength} bytes`),d?(n(`${d.byteLength} bytes remain after processing command. Re-analyzing...`),e(d,a,i,s)):void 0}if(d.partialHeader)return c={firstPackageAt:Date.now(),partialHeaderData:l},i(c);if(!d.header)return n(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${l.byteLength} bytes`);const f=d.header;c={firstPackageAt:Date.now(),header:{...f,totalBytesReceived:f.packages[0].byteLength,totalBytesExpected:f.binaryLength+f.jsonLength,remaining:d.remaining}},i(c)}else c.header&&c.header.totalBytesReceived<c.header.totalBytesExpected&&(c.header.packages.push(o),c.header.totalBytesReceived+=o.byteLength,i(c));if(c.header&&c.header.totalBytesReceived>=c.header.totalBytesExpected){const o=Date.now()-c.header.sentAt.getTime(),a=Date.now()-c.firstPackageAt;n(`Received ${c.header.totalBytesReceived} of ${c.header.totalBytesExpected} expected in ${o} ms, elapsed since first package: ${a}ms`);const d=u?r.default.decodeFullKlMessage(c.header):t.default.decodeFullKlMessage(c.header),l=c.header.totalBytesReceived,f=c.header.remaining;i(null),d&&s({klMessage:d.message,complete:!0,sourceServiceId:c.header.fromServiceId,targetServiceId:c.header.toServiceId,rawMessage:d.message.rawMessage});let p=f;if(d?.remaining&&(p=u?f?((e,t)=>{const r=e.byteLength+t.byteLength,n=new ArrayBuffer(r),o=new Uint8Array(e),a=new Uint8Array(t),i=new Uint8Array(n);return i.set(o),i.set(a,o.length),n})(f,d.remaining):d.remaining:f?Buffer.concat([f,d.remaining]):d.remaining),p)return n(`${p.byteLength} bytes remaining after processing message with ${l} bytes of data. Re-analyzing...`),e(p,null,i,s)}};return e},x}var ee,te,re={};function ne(){if(ee)return re;ee=1;var e=re&&re.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(re,"__esModule",{value:!0});const t=e(q()),r=e(Y()),n=E();let o=t.default;return n.isBrowser&&(o=r.default),re.default=o,re}function oe(){if(te)return k;te=1;var e=k&&k.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(k,"__esModule",{value:!0});const t=e(n),r=e((j||(j=1,Object.defineProperty(M,"__esModule",{value:!0}),M.default={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"}),M)),o=Z(),a=W(),i=e(ne());let s,c,d,u,l=null;const f=(0,o.createTransmissionManager)(),p=(0,a.createLogger)("ipcClient"),g=e=>{const n=r.default.id;t.default.of[n].emit(e)};return k.default={connect:e=>{r.default.id=e?.id||r.default.id,r.default.appspace=e?.appSpace||r.default.appspace,t.default.config={...t.default.config,...r.default};const n=r.default.id;t.default.connectTo(n,(()=>{t.default.of[n].on("connect",(()=>{p("Connected to server"),l=null,c&&c()})),t.default.of[n].on("data",(e=>{f(e,l,(e=>l=e),(e=>{if(e.complete)return e.command?(p(`Received command: ${e.command}`),void(s&&s(e.command))):void(e.klMessage&&d&&d({send:g,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json}))}))})),t.default.of[n].on("disconnect",(()=>{p(`Disconnected from ${n}`),l=null,u&&u()}))}))},sendCommand:e=>{const n=r.default.id,o=i.default.encodeCommand(e);t.default.of[n].emit(o)},sendBuffer:g,onCommand:e=>s=e,onMessageReceived:e=>d=e,onClientConnected:e=>c=e,onClientDisconnected:e=>u=e},k}var ae,ie,se,ce={},de={};function ue(){return ie||(ie=1,function(e){var t=ce&&ce.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=ce&&ce.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)},n=ce&&ce.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0});const o=n(ne()),a=E();var i;r((ae||(ae=1,Object.defineProperty(de,"__esModule",{value:!0}),de.RemoveInvokeError=void 0,function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(i||(de.RemoveInvokeError=i={}))),de),e);let s=Math.ceil(Date.now()/1e3);e.default=function(e){const t={};let r,n=console.log;const i={};let c=e||String(Date.now());const d={},u=e=>!d[e],l=(e,t,r,n,i,s)=>{let c=a.isBrowser?new ArrayBuffer(0):Buffer.alloc(0);const d={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return u(n)&&(c=o.default.encode(d,r,n)),i(c,{msg:d,sourceServiceId:r,targetServiceId:n})};return{setLogger:e=>{n=e},processMessage:(e,o,a,s)=>{if(!s)return!1;const c=s;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=i[c.functionName];if(t){const i=e=>{l(c.functionName,c.messageId,a.targetServiceId,a.sourceServiceId,o,e)};if(!(!r||r({args:c.args,functionName:c.functionName,transport:e,messageId:c.messageId,sourceServiceId:a.sourceServiceId,reply:i,send:o})))return n&&n(`Function "${c.functionName}" not allowed to be invoked by client [${a.sourceServiceId}]`),i({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;t({transport:e,args:c.args,reply:i,messageId:c.messageId,sourceServiceId:a.sourceServiceId,send:o})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),l(c.functionName,c.messageId,a.targetServiceId,a.sourceServiceId,o,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,i,d,l,f)=>{if(!i){const e="No send buffer function provided.";throw n&&n(e),e}s+=1;const p=`${c}-${s}-exec-${e.substring(0,10)}`,g={messageId:p,functionName:e,send:i,sourceServiceId:d,targetServiceId:l,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};g.promise=new Promise(((e,t)=>{g.resolve=e,g.reject=t}));let m=a.isBrowser?new ArrayBuffer(0):Buffer.alloc(0);const y={json:{functionName:e,args:r,messageId:p,type:"execute"}};u(l)&&(m=o.default.encode(y,d,l)),t[p]=g,n&&n(`Calling remote function "${e}" with message id "${p}"`);const S="true"===process.env.NO_INVOKE_TIMEOUT;return f?.async?(g.fulfilled=!0,g.resolve([void 0]),delete t[p]):0===f?.timeout||S||(g.timer=setTimeout((()=>{n&&n(`Remote function ${p} timed out`);const r=t[p];r&&!r.fulfilled&&(r.fulfilled=!0,g.reject(`Function ${e} Timed out`)),delete t[p]}),f?.timeout||3e4)),i(m,{sourceServiceId:d,targetServiceId:l,msg:y}),g.promise},sendResponse:l,registerFunction:(e,t)=>{i[e]=t},registerFunctionsMiddleware:e=>{r=e},unregisterAllFunctions:()=>{Object.keys(i).forEach((e=>{delete i[e]}))},getTransportSendFunction:e=>{const r=t[e];return r?r.send:null},setServiceName:e=>{c=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((r=>{const n=t[r];n&&!n.fulfilled&&(clearTimeout(n.timer),n.fulfilled=!0,n.reject(e),delete t[r])}))},broadcast:(e,t,r,i)=>{s+=1;const d=`${c}-${s}-multicast-${e.substring(0,10)}`;let l=a.isBrowser?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:e,args:t,messageId:d,type:"execute"}};let p=u(r[0].serviceId);p&&(l=o.default.encode(f,i,r[0].serviceId));for(let t=0;t<r.length;t++)try{const a=r[t];n&&n(`Broadcasting function "${e}" with message id "${d}" to client [${a.serviceId}]`),0!==t&&(p=u(a.serviceId),p&&(l=o.default.patchEncodedHeader(l,{toServiceId:a.serviceId}))),a.sendFn(l,{msg:f,sourceServiceId:i,targetServiceId:a.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{d[e]=t}}}}(ce)),ce}var le=a((se||(se=1,function(n){var o=s&&s.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(n,"__esModule",{value:!0}),n.createImageDataLike=n.KemuHubServiceId=n.DataType=void 0;const a=L();Object.defineProperty(n,"DataType",{enumerable:!0,get:function(){return a.DataType}});const i=e,c=o(t),d=o(r),u=(P||(P=1,Object.defineProperty(A,"__esModule",{value:!0}),A.KemuComposerGuestServiceId=A.KemuHubServiceId=void 0,A.KemuHubServiceId=0,A.KemuComposerGuestServiceId=1),A);Object.defineProperty(n,"KemuHubServiceId",{enumerable:!0,get:function(){return u.KemuHubServiceId}});const l=(H||(H=1,Object.defineProperty(K,"__esModule",{value:!0}),K.hasExpressionPatterns=void 0,K.hasExpressionPatterns=e=>{if("string"!=typeof e)return!1;const t=/\{\{\{\s*[^{}\s][^{}]*\s*\}\}\}/g;return!!/\{\{\s*[^{}\s][^{}]*\s*\}\}/g.test(e)||(t.lastIndex=0,!!t.test(e))}),K),f=E(),p=function(){if(_)return D;_=1,Object.defineProperty(D,"__esModule",{value:!0}),D.preProcessManifest=D.portStrToWidgetPort=D.createImageDataLike=void 0;const e=L();return D.createImageDataLike=(t,r,n,o="srgb")=>{let a;return a=t instanceof Uint8ClampedArray?t:new Uint8ClampedArray(t),{data:a,width:r,height:n,colorSpace:o,_kemuType:e.DataType.ImageData}},D.portStrToWidgetPort=t=>({...t,type:e.DataType[t.type]}),D.preProcessManifest=(e,t,r)=>({...e,path:t,...e.widgetUI&&r?.widgetUIContents?{widgetUIContents:r.widgetUIContents}:{}}),D}();Object.defineProperty(n,"createImageDataLike",{enumerable:!0,get:function(){return p.createImageDataLike}});const g=o(oe()),m=W(),y=o(ue()),S=(0,m.createLogger)("kemuWidgetService"),v=(0,c.default)(process.argv.slice(2));n.default=function(e){const t={},r=process.env.KEMU_WIDGET_SESSION_ID;let n,o,s,c,m=!1;const I={};let b,h,w,L,P,A,H,K,C=null;const B=new y.default;B.setLogger(S),t.start=async(t,c)=>{const u=t||d.default.resolve(d.default.dirname(process.argv[1]),"manifest.json");s=d.default.dirname(u);const l=await(0,i.readFile)(u,"utf-8"),y=(0,f.safeJsonParse)(l);if(!y)throw new Error("Error parsing manifest file.");let I;if(y.inputs||(y.inputs=[]),y.outputs||(y.outputs=[]),y.widgetUI)try{I=await(0,i.readFile)(d.default.join(s,"widgetUI.js"))}catch(e){S(`Error loading widgetUI file ${y.name}: ${e}`)}if(y.svgIcon)try{const e=await(0,i.readFile)(d.default.join(s,y.svgIcon),"utf-8");y.svgIcon=e}catch(e){S(`Error loading icon for service ${y.name}: ${e}`)}o=(0,p.preProcessManifest)(y,s,{widgetUIContents:I}),m=o.name.startsWith("test."),o.path=s,o.internal=v.internal||!1,m?S("Starting Kemu Service in Dev mode"):((e=>{const t=e||v.sessionId||r;if(!t)throw new Error("Missing sessionId. Expected service to be launched with a sessionId as first argument, or the KEMU_WIDGET_SESSION_ID environment variable to be set.");n=parseInt(String(t))})(c),S(`Starting Kemu Service with session id: ${n}`)),B.setServiceName(`${o.name}_${o.version}`),g.default.onCommand(E),g.default.onMessageReceived((({json:e,transmission:t})=>B.processMessage(a.Transport.IPC,g.default.sendBuffer,t,e))),B.registerFunction(a.KemuHubFunctions.OnParentEvent,D),B.registerFunction(a.KemuHubFunctions.GetDefaultState,_),B.registerFunction(a.KemuHubFunctions.UIEvent,z),B.registerFunction(a.KemuHubFunctions.InitializeInstance,j),B.registerFunction(a.KemuHubFunctions.TerminateInstance,k),B.registerFunction(a.KemuHubFunctions.KemuComposerDisconnected,M),g.default.onClientConnected((()=>{K&&K()})),g.default.onClientDisconnected((()=>{m&&(n=void 0)})),g.default.connect({appSpace:v.ipcSpace||e?.ipc?.appSpace,id:v.ipcId||e?.ipc?.id})};const E=e=>{(0,f.onAckRequest)(e,(e=>{g.default.sendCommand((0,f.buildIpcAckResponse)(e,n||void 0)),!n&&m&&(S("Dev mode detected, assuming service session id from ack request:",e),n=e)})),(0,f.onStartBroadcastCommand)(e,(()=>{w&&w()})),(0,f.onEndBroadcastCommand)(e,(()=>{L&&L()})),(0,f.onSendManifestCommand)(e,(()=>{S("Sending manifest to hub"),n?B.execute(a.KemuHubFunctions.ServiceManifest,[{...o,devMode:m}],g.default.sendBuffer,n,u.KemuHubServiceId,{async:!0}):S("Service session id is not set. Cannot send manifest.")})),(0,f.onAssumeSession)(e,(e=>{n=e,S(`Assumed session id ${e}`)}))},_=async e=>{if(h){const t=await h();return e.reply({success:[t]})}return e.reply({success:[{}]})},D=async e=>{if(!b)return S("No onParentEvent callback defined. Skipping parent event."),e.reply({success:[]});const t=e.args[0],{source:r,target:o,data:i,recipe:s,currentState:c,targetVariantId:d,eventContext:u,currentPath:l,eventId:f}=t;if(!n)return void S("Service session id is not set. Cannot process parent event.");if(!r||!o||!i)return e.reply({error:"Invalid arguments, expected [source, target, data, context]"});const p=g.default.sendBuffer,m=async t=>B.execute(a.KemuHubFunctions.SetOutputs,[t],p,n,e.sourceServiceId,{timeout:0}),y={currentState:c,type:o.widgetType,widgetId:o.widgetId,variantId:d,recipeId:s.poolId,recipeName:s.name,recipe:s,setState:async t=>{const r={widgetId:o.widgetId,variantId:d,recipeId:s.poolId,newState:t};return B.execute(a.KemuHubFunctions.SetState,[r],p,n,e.sourceServiceId)},setOutputs:async(e,t)=>{const r={widgetId:o.widgetId,recipeId:s.poolId,outputs:e,finalState:t,currentPath:l};await m(r)},setOutputsWithContext:async e=>{const t={...e,eventId:f,widgetId:o.widgetId,recipeId:s.poolId,currentPath:l};null===e.eventId&&delete t.eventId,await m(t)}};S(`Invoking user-defined onParentEvent callback for event id "${e.messageId}"`),await b({data:i,source:r,target:o,eventContext:u,currentPath:l,eventId:f},y).then((()=>{S(`Replying SUCCESS to event id "${e.messageId}"`),e.reply({success:[]})})).catch((t=>{const r="string"==typeof t?t:t.message||t;S(`Error invoking onParentEvent callback: ${r}`),e.reply({error:r,errCode:"PARENT_EVENT_CALLBACK_ERROR"})}))},j=async e=>{const[{currentState:t,widgetId:r,variantId:n,recipeType:o,currentDependencies:a,kemuApiKey:i,recipe:s}]=e.args;if(i&&(c=i),I[r]={currentRecipeId:s.poolId,variantId:n,currentSourceServiceId:e.sourceServiceId},P){const c=[],d=[],u={currentState:t,recipeId:s.poolId,recipeName:s.name,recipe:{uuid:s.uuid,poolId:s.poolId,name:s.name,type:s.type,version:s.version,authorId:s.authorId,dbId:s.dbId},widgetId:r,variantId:n,recipeType:o,currentDependencies:a||{},kemuApiKey:i,globalVars:{declare:e=>{d.push(e)}},secrets:{requestAccess:e=>{for(const t of e)"string"==typeof t?c.push({name:t}):c.push(t)}}},l=[await P(u)||null,c.length>0?c:null,d.length>0?d:null];e.reply({success:l})}else e.reply({error:"Not implemented",errCode:"FNC_NOT_FOUND"})},k=async e=>{if(A){const[{currentState:t,recipe:r,widgetId:n,variantId:o}]=e.args,a={currentState:t,recipeId:r.poolId,recipe:r,widgetId:n,variantId:o};await A(a),delete I[n]}e.reply({success:[]})},M=async e=>{if(console.log("Kemu Composer disconnected event: ",e),e.reply({success:[]}),H){const[t]=e.args;t.recipe&&await H(t)}},z=async e=>{if(C)try{const t=await C.apply(void 0,e.args);return e.reply({success:[t]})}catch(t){const r="string"==typeof t?t:JSON.stringify(t);return S(`Error invoking UI Event handler: ${r}`),e.reply({error:r})}e.reply({error:"UI Events are not supported in this service."})},x=async e=>{if(!o.eventEmitter)throw new Error("This service does not support broadcasting events. Please set `eventEmitter` to true in your manifest file.");if(n)return B.execute(a.KemuHubFunctions.BroadcastEvent,e,g.default.sendBuffer,n,u.KemuHubServiceId,{async:!0});S("Service session id is not set. Cannot broadcast event.")};t.broadcast=async(e,t)=>{const r=[{outputs:e,variantId:t,currentPath:[]}];await x(r)},t.broadcastEvent=async e=>{const t=[{outputs:e.outputs,variantId:e.variantId,eventContext:e.eventContext,targetRecipeId:e.targetRecipeId,targetRecipePoolId:e.targetRecipePoolId,targetWidgetId:e.targetWidgetId,currentPath:e.currentPath||[],eventId:e.eventId}];await x(t)},t.addDependencyPath=async(e,t,r)=>{if(!n)throw new Error("Not yet registered with the Hub");const o=I[r];if(!o.currentSourceServiceId||!o.currentRecipeId)throw new Error("Cannot invoke this method before initialization");const i={key:e,path:t,recipeId:o.currentRecipeId,widgetId:r};S(`Adding dependency path for key "${e}" with path "${t}"`),await B.execute(a.ServiceToServiceFunctions.SetDependencyPath,[i],g.default.sendBuffer,n,o.currentSourceServiceId)},t.getDependencyPath=async(e,t)=>{if(!n)throw new Error("Not yet registered with the Hub");const r=I[t];if(!r.currentSourceServiceId||!r.currentRecipeId)throw new Error("Cannot invoke this method before initialization");S("Getting dependency path for key:",e);const o={key:e,recipeId:r.currentRecipeId,widgetId:t},[i]=await B.execute(a.ServiceToServiceFunctions.GetDependencyPath,[o],g.default.sendBuffer,n,r.currentSourceServiceId);return S("Dependency path response:",i),i},t.getUniqueId=async()=>{if(!n)throw new Error("Not yet registered with the Hub");const[e]=await B.execute(a.KemuHubFunctions.GetUniqueId,[],g.default.sendBuffer,n,u.KemuHubServiceId);return e},t.resolveRuntimeDependencyPath=e=>{if(!v.recipePath)throw new Error("Cannot resolve runtime dependency without a recipe path. Missing [--recipePath] argument.");return d.default.resolve(v.recipePath,e)},t.onGetDefaultState=e=>{h=e},t.onParentEvent=e=>{b=e},t.onTerminate=e=>{A=e},t.onKemuComposerDisconnected=e=>{H=e},t.onInitialize=e=>{P=e},t.onConnected=e=>{K=e},t.onStartBroadcast=e=>{w=e},t.onStopBroadcast=e=>{L=e},t.onUIEvent=e=>{C=e},t.secrets={add:async e=>{if(!n)throw new Error("Service session id is not set. Cannot add secret.");const t=Array.isArray(e)?e:[e],r=[{hubServiceName:o.name,secrets:t}];await B.execute(a.KemuHubFunctions.AddServiceSecret,r,g.default.sendBuffer,n,u.KemuHubServiceId)},read:async e=>{if(!n)throw new Error("Service session id is not set. Cannot read secret.");const t=[{recipeUuid:e.recipeUuid,secretNames:e.names,serviceName:o.name}],[r]=await B.execute(a.KemuHubFunctions.GetRecipeDecryptedSecretsValues,t,g.default.sendBuffer,n,u.KemuHubServiceId);return r?.secrets||{}}};const U=()=>{if(!n)throw new Error("Service session id is not set.");return n},O=e=>{const t=I[e];if(!t.currentSourceServiceId||!t.currentRecipeId)throw new Error("Cannot invoke this method before initialization");return{sourceServiceId:t.currentSourceServiceId,recipePoolId:t.currentRecipeId}};t.globalVars={getNames:async e=>{const t=U(),{sourceServiceId:r,recipePoolId:n}=O(e.widgetId),o=[{filterTypes:e.filterTypes,recipePoolId:n,widgetId:e.widgetId}],[i]=await B.execute(a.ServiceToServiceFunctions.GetGlobalVariableNames,o,g.default.sendBuffer,t,r);return i.variables},getValues:async e=>{const t=U(),{sourceServiceId:r,recipePoolId:n}=O(e.widgetId),o=[{names:e.names,recipePoolId:n,widgetId:e.widgetId}],[i]=await B.execute(a.ServiceToServiceFunctions.GetGlobalVariableValues,o,g.default.sendBuffer,t,r);return i.values},setValues:async e=>{const t=U(),{sourceServiceId:r,recipePoolId:n}=O(e.widgetId),o=[{values:e.values,recipePoolId:n,widgetId:e.widgetId}];await B.execute(a.ServiceToServiceFunctions.SetGlobalVariableValues,o,g.default.sendBuffer,t,r)}},t.helpers={parseExpressions:async e=>{const{expressions:t,widgetId:r}=e;if(!Array.isArray(t))throw new Error("expressions must be an array");if(!e.expressions.some((e=>(0,l.hasExpressionPatterns)(e.text))))return e.expressions.map((e=>e.text));const n=U(),{sourceServiceId:o,recipePoolId:i}=O(r),s=[{expressions:t,recipePoolId:i,widgetId:r}],[c]=await B.execute(a.ServiceToServiceFunctions.ParseStringExpression,s,g.default.sendBuffer,n,o);return c.expressions},parseExpression:async e=>{const{text:t,widgetId:r,context:n}=e;if(!(0,l.hasExpressionPatterns)(t))return t;const o=U(),{sourceServiceId:i,recipePoolId:s}=O(r),c=[{expressions:[{text:t,context:n}],recipePoolId:s,widgetId:r}],[d]=await B.execute(a.ServiceToServiceFunctions.ParseStringExpression,c,g.default.sendBuffer,o,i);return d.expressions[0]}},v.internal&&(t.executeHubFunction=async(e,t,r)=>{if(n)return B.execute(e,t,g.default.sendBuffer,n,u.KemuHubServiceId,r);S("Service session id is not set. Cannot execute hub function.")});const R=t;return R._getRemoteInvoker=()=>B,R.getHubConfig=async()=>{if(!n)throw new Error("Service session id is not set. Cannot execute hub function.");const e=await B.execute(a.KemuHubFunctions.GetHubConfig,[],g.default.sendBuffer,n,u.KemuHubServiceId);return e?.[0]&&!e[0].kemuApiKey&&c&&(e[0].kemuApiKey=c),e?.[0]},R.getEdgeApiKey=async()=>{if(m)return void console.warn("This method [getEdgeApiKey] is NOT available in dev mode");if(!n)throw new Error("Service session id is not set. Cannot execute hub function.");const e=await B.execute(a.KemuHubFunctions.GetDecryptedEdgeApiKey,[],g.default.sendBuffer,n,u.KemuHubServiceId);return e?.[0]},t}}(s)),s));module.exports=le;
|
package/cjs/types/kemuCore.js
CHANGED
|
@@ -164,6 +164,10 @@ function requireKemuHub_t () {
|
|
|
164
164
|
(function (ServiceToServiceFunctions) {
|
|
165
165
|
ServiceToServiceFunctions["SetDependencyPath"] = "setDependencyPath";
|
|
166
166
|
ServiceToServiceFunctions["GetDependencyPath"] = "getDependencyPath";
|
|
167
|
+
ServiceToServiceFunctions["ParseStringExpression"] = "parseStringExpression";
|
|
168
|
+
ServiceToServiceFunctions["GetGlobalVariableNames"] = "getGlobalVariableNames";
|
|
169
|
+
ServiceToServiceFunctions["GetGlobalVariableValues"] = "getGlobalVariableValues";
|
|
170
|
+
ServiceToServiceFunctions["SetGlobalVariableValues"] = "setGlobalVariableValues";
|
|
167
171
|
})(ServiceToServiceFunctions || (kemuHub_t.ServiceToServiceFunctions = ServiceToServiceFunctions = {}));
|
|
168
172
|
var Transport;
|
|
169
173
|
(function (Transport) {
|
package/mjs/service.d.ts
CHANGED
|
@@ -201,6 +201,7 @@ export type RecipeContextInfo = {
|
|
|
201
201
|
/** the id of the author of the recipe */
|
|
202
202
|
authorId: string;
|
|
203
203
|
};
|
|
204
|
+
export type GlobalVariableControlType = "number" | "slider" | "text" | "multilineText" | "dropdown" | "image" | "binaryFile" | "checkbox" | "multiSelect" | "anything";
|
|
204
205
|
export type ValidEventContextValue = {
|
|
205
206
|
[key: string]: ValidEventContextValue | string | number | boolean | null;
|
|
206
207
|
};
|
|
@@ -268,6 +269,12 @@ export type WidgetContext<T extends WidgetState = WidgetState> = SerializableWid
|
|
|
268
269
|
* This will be available to any child widget down the line that is a variant of the current widget.
|
|
269
270
|
*/
|
|
270
271
|
eventContext?: ValidEventContextValue;
|
|
272
|
+
/**
|
|
273
|
+
* The id of the event to forward if this event is the continuation of a previous invocation.
|
|
274
|
+
* By default the last event id is used. Set to `null` signal a brand new execution path, this has implications on child
|
|
275
|
+
* widgets that rely on the event id to access the context of parent widgets of the same service type.
|
|
276
|
+
*/
|
|
277
|
+
eventId?: number | null;
|
|
271
278
|
}) => Promise<void>;
|
|
272
279
|
};
|
|
273
280
|
export type PortEventInfo = {
|
|
@@ -406,6 +413,41 @@ export type WidgetSecretConfig = {
|
|
|
406
413
|
*/
|
|
407
414
|
sharedAcrossInstances?: boolean;
|
|
408
415
|
};
|
|
416
|
+
/**
|
|
417
|
+
* Configuration for a global variable.
|
|
418
|
+
*/
|
|
419
|
+
export type GlobalVariableConfig = {
|
|
420
|
+
/**
|
|
421
|
+
* The name of the global variable to set.
|
|
422
|
+
*/
|
|
423
|
+
name: string;
|
|
424
|
+
/**
|
|
425
|
+
* The value of the global variable to set.
|
|
426
|
+
*/
|
|
427
|
+
value: SupportedTypes | null;
|
|
428
|
+
/**
|
|
429
|
+
* The control type of the global variable to set.
|
|
430
|
+
* This will override the control type of the global variable if it already exists.
|
|
431
|
+
* Defaults to 'Anything' if the variable does not exist and is created.
|
|
432
|
+
**/
|
|
433
|
+
controlType?: GlobalVariableControlType;
|
|
434
|
+
/** optional control settings for the global variable */
|
|
435
|
+
controlSettings?: Record<string, any>;
|
|
436
|
+
/** whether to notify other widgets about the change. Defaults to true. */
|
|
437
|
+
emitChangeEvent?: boolean;
|
|
438
|
+
/** optional help text for the global variable */
|
|
439
|
+
helpText?: string;
|
|
440
|
+
/** optional order to display the global variable in the variables panel */
|
|
441
|
+
order?: number;
|
|
442
|
+
/**
|
|
443
|
+
* If true, the global variable will not be overridden if it already exists. Defaults to false.
|
|
444
|
+
*/
|
|
445
|
+
doNotOverrideExisting?: boolean;
|
|
446
|
+
/**
|
|
447
|
+
* whether to emit an event if the variable did not exist and is set by this widget for the first time. Default is true.
|
|
448
|
+
**/
|
|
449
|
+
emitDefineEvent?: boolean;
|
|
450
|
+
};
|
|
409
451
|
export type InitializeContext<T extends WidgetState = WidgetState> = {
|
|
410
452
|
/** @deprecated use `recipe.poolId` instead */
|
|
411
453
|
recipeId: string;
|
|
@@ -429,6 +471,14 @@ export type InitializeContext<T extends WidgetState = WidgetState> = {
|
|
|
429
471
|
**/
|
|
430
472
|
requestAccess: (names: WidgetSecretConfig[] | string[]) => void;
|
|
431
473
|
};
|
|
474
|
+
globalVars: {
|
|
475
|
+
/**
|
|
476
|
+
* Allows you to declare or update a global variable with a specified configuration during initialization.
|
|
477
|
+
* This helper method functions like `service.globalVars.setValues`, but is intended for use within the 'initialize' callback only.
|
|
478
|
+
* You may call this method multiple times during the 'initialize' callback; all declared values will be set once the function completes.
|
|
479
|
+
*/
|
|
480
|
+
declare: (config: GlobalVariableConfig) => void;
|
|
481
|
+
};
|
|
432
482
|
};
|
|
433
483
|
export type InitializeServiceHandler<T extends WidgetState = WidgetState> = (context: InitializeContext<T>) => Promise<T | null | void | undefined>;
|
|
434
484
|
export type TerminateServiceHandler<T extends WidgetState = WidgetState> = (context: TerminateContext<T>) => Promise<void>;
|
|
@@ -473,6 +523,10 @@ export type ServiceBroadcastConfig = {
|
|
|
473
523
|
*/
|
|
474
524
|
eventId?: number;
|
|
475
525
|
};
|
|
526
|
+
export type CommonServiceToServiceArgs = {
|
|
527
|
+
/** the id of the widget instance performing the request */
|
|
528
|
+
widgetId: string;
|
|
529
|
+
};
|
|
476
530
|
/**
|
|
477
531
|
* Instance of a Kemu Widget library. Used by Widget services to integrate with the Kemu Hub.
|
|
478
532
|
*/
|
|
@@ -616,6 +670,48 @@ export type KemuService<T extends Record<string, any> = Record<string, any>> = {
|
|
|
616
670
|
*/
|
|
617
671
|
add: (secret: AddSecretConfig | AddSecretConfig[]) => Promise<void>;
|
|
618
672
|
};
|
|
673
|
+
globalVars: {
|
|
674
|
+
getNames: (config: CommonServiceToServiceArgs & {
|
|
675
|
+
/** optional filter for variable types. If provided, only variables of the given types will be returned. */
|
|
676
|
+
filterTypes?: GlobalVariableControlType[];
|
|
677
|
+
}) => Promise<{
|
|
678
|
+
name: string;
|
|
679
|
+
type: GlobalVariableControlType;
|
|
680
|
+
}[]>;
|
|
681
|
+
getValues: (config: CommonServiceToServiceArgs & {
|
|
682
|
+
/** the names of the variables to get the values of */
|
|
683
|
+
names: string[];
|
|
684
|
+
}) => Promise<{
|
|
685
|
+
name: string;
|
|
686
|
+
value: SupportedTypes | null;
|
|
687
|
+
}[]>;
|
|
688
|
+
setValues: (config: CommonServiceToServiceArgs & {
|
|
689
|
+
/** the values to set for the variables */
|
|
690
|
+
values: GlobalVariableConfig[];
|
|
691
|
+
}) => Promise<void>;
|
|
692
|
+
};
|
|
693
|
+
helpers: {
|
|
694
|
+
/**
|
|
695
|
+
* Parses the given expressions using kemu's expressions engine, which provides access to helper methods and global vars
|
|
696
|
+
* @returns a list of parsed expressions.text values in the same order they were provided.
|
|
697
|
+
**/
|
|
698
|
+
parseExpressions: (config: CommonServiceToServiceArgs & {
|
|
699
|
+
/** a list of expressions to parse */
|
|
700
|
+
expressions: {
|
|
701
|
+
/** the expression to parse */
|
|
702
|
+
text: string;
|
|
703
|
+
/** optional context to use when parsing the expression */
|
|
704
|
+
context?: Record<string, any>;
|
|
705
|
+
}[];
|
|
706
|
+
}) => Promise<string[]>;
|
|
707
|
+
/** simplified form of `parseStringExpressions` that parses a single text expression */
|
|
708
|
+
parseExpression: (config: CommonServiceToServiceArgs & {
|
|
709
|
+
/** the expression to parse */
|
|
710
|
+
text: string;
|
|
711
|
+
/** optional context to use when parsing the expression */
|
|
712
|
+
context?: Record<string, any>;
|
|
713
|
+
}) => Promise<string>;
|
|
714
|
+
};
|
|
619
715
|
};
|
|
620
716
|
export type AddSecretConfig = {
|
|
621
717
|
/**
|
package/mjs/service.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile as e}from"fs/promises";import t from"minimist";import n from"path";import r from"node-ipc";import a from"debug";var i,o,s,c,d,u,l,f;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(i||(i={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(o||(o={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(s||(s={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(c||(c={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(d||(d={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.AddServiceSecret="addServiceSecret",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.SendToRecipe="sendToRecipe",e.KemuComposerDisconnected="kemu-composer-disconnected",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.SaveRecipeToFile="saveRecipeToFile",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey",e.GetHubConfig="getHubConfig",e.GetRecipeDecryptedSecretsValues="getRecipeDecryptedSecretsValues",e.GetRecipeSecretMappings="getRecipeSecretMappings",e.AddRecipeSecretMapping="addRecipeSecretMapping",e.DeleteRecipeSecretMapping="deleteRecipeSecretMapping",e.GetHubSecrets="getHubSecrets",e.AddHubSecrets="addHubSecrets",e.DeleteHubSecret="deleteHubSecret"}(u||(u={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(l||(l={})),function(e){e.IPC="ipc",e.WS="ws"}(f||(f={}));const g=0,p=e=>{try{return JSON.parse(e)}catch(e){return null}},y="undefined"!=typeof window,m=(e,t,n,r="srgb")=>{let a;return a=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:a,width:t,height:n,colorSpace:r,_kemuType:o.ImageData}};var h={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const I={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},v={protocolPrefix:4,txtLength:4},S=Object.values(I).reduce(((e,t)=>e+t),0),b=Object.values(v).reduce(((e,t)=>e+t),0),w=["width","height","colorSpace"],A=(e,t)=>{const n={},r=[];let a=0,i=Array.isArray(e)?[]:{};const o=(e,i)=>{const s=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,a=e instanceof Uint8Array,i=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":a?"Uint8Array":i?"Int8Array":null})(e);if(!s){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${i}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,a=e instanceof Uint32Array,i=e instanceof Float32Array,o=e instanceof Float64Array,s=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":a?"Uint32Array":i?"Float32Array":o?"Float64Array":s?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${i}"`);for(const n in e)Object.hasOwn(e,n)||w.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${i}`),t[n]=o(e[n],`${i.length?`${i}.`:""}${n}`);return t}return e}n[i]={index:a,length:e.byteLength,binaryType:s},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===s?r.push(e):r.push(e.buffer),a+=e.byteLength};i=o(e,"");let s=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;s=t.buffer}else{s=Buffer.concat(r)}else 1===r.length&&(s=r[0]);return s?{map:n,combinedData:s,sourceCopy:i}:null},B=(e,t,n,r)=>{const a=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<a.length;e++){let t=a[e];const r=t.startsWith("[")&&t.endsWith("]"),o=e===a.length-1;if(r){t=t.slice(1,-1);const r=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${a.slice(0,e).join(".")}" but found an object.`);o?i[r]=n:(i[r]||(i[r]=a[e+1].startsWith("[")?[]:{}),i=i[r])}else o?i[t]=n:(i[t]||(i[t]=a[e+1].startsWith("[")?[]:{}),i=i[t])}return e},L=(e,t,n)=>{const r="undefined"!=typeof Buffer,a=t instanceof Uint8Array;for(const i in n)if(Object.hasOwn(n,i)){const{index:o,length:s,binaryType:c}=n[i];let d=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":d=t.subarray(o,o+s);break;case"ArrayBuffer":d=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+s);break;case"Uint8Array":d=new Uint8Array(t.subarray(o,o+s));break;case"Uint8ClampedArray":d=new Uint8ClampedArray(t.subarray(o,o+s));break;case"Int8Array":d=new Int8Array(t.subarray(o,o+s))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){d=Buffer.from(t.slice(o,o+s));break}case"ArrayBuffer":d=a?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+s):t.slice(o,o+s);break;case"Uint8Array":d=a?t.slice(o,o+s):new Uint8Array(t.slice(o,o+s));break;case"Uint8ClampedArray":d=new Uint8ClampedArray(t.slice(o,o+s));break;case"Int8Array":d=new Int8Array(t.slice(o,o+s))}d&&B(e,i,d)}return e},E=e=>a(e),U="KMSG",C="KCMD",D=E("klProtocol");var k={encode:(e,t,n)=>{const r={json:e.json},a=A(r.json,"Buffer"),i=a?.combinedData;a&&(r.jsonBinaryMap=a.map,r.json=a.sourceCopy);const o=i?i.byteLength:0,s=JSON.stringify(r),c=Buffer.from(s),d=c.byteLength,u=I.protocolPrefix+I.protocolVersion+I.jsonLength+I.binaryLength+I.fromServiceId+I.toServiceId+I.sentAt+d+o,l=Buffer.alloc(u),f=Date.now();let g=0;return l.write(U,g),g+=I.protocolPrefix,l.writeUInt8(1,g),g+=I.protocolVersion,l.writeUInt32LE(d,g),g+=I.jsonLength,l.writeUInt32LE(o,g),g+=I.binaryLength,l.writeUInt32LE(t,g),g+=I.fromServiceId,l.writeUInt32LE(n,g),g+=I.toServiceId,l.writeBigInt64LE(BigInt(f),g),g+=I.sentAt,c.copy(l,g),g+=d,i&&o&&i.copy(l,g),l},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,I.protocolPrefix);if(t+=I.protocolPrefix,n!==U)return null;if(e.byteLength<S)return D(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=I.protocolVersion;const a=e.readUInt32LE(t);t+=I.jsonLength;const i=e.readUInt32LE(t);t+=I.binaryLength;const o=e.readUInt32LE(t);t+=I.fromServiceId;const s=e.readUInt32LE(t);t+=I.toServiceId;const c=e.readBigInt64LE(t);t+=I.sentAt;const d=a+i,u=e.subarray(t,t+d),l=e.subarray(0,S);let f=null;return e.byteLength-S-a-i>0&&(f=e.subarray(S+a+i)),{header:{protocolVersion:r,jsonLength:a,binaryLength:i,fromServiceId:o,toServiceId:s,sentAt:new Date(Number(c)),packages:[u],headerPackage:l},remaining:f}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=p(n);if(!a?.json)return D("Invalid JSON in KL message"),null;a.jsonBinaryMap&&r.byteLength&&L(a.json,r,a.jsonBinaryMap);const i=Buffer.concat([e.headerPackage,t]);let o=i,s=null;const c=S+e.jsonLength+e.binaryLength;return i.byteLength>c&&(s=i.subarray(c),o=i.subarray(0,c)),{message:{json:a.json,rawMessage:o},remaining:s}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<S)return D("Invalid Header Size"),e;let n=0;return n+=I.protocolPrefix,n+=I.protocolVersion,n+=I.jsonLength,n+=I.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=I.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,a=b+r,i=Buffer.alloc(a);return i.write(C,t),t+=v.protocolPrefix,i.writeUint32LE(r,t),t+=v.txtLength,n.copy(i,t),i},decodeCommand:e=>{let t=0;if(e.byteLength<b)return{command:null};const n=e.toString("utf-8",t,v.protocolPrefix);if(t+=v.protocolPrefix,n!==C)return{command:null};const r=e.readUInt32LE(t);t+=v.txtLength;const a=e.toString("utf-8",t,t+r),i=e.byteLength-b-r;let o=null;i>0&&(o=e.subarray(b+r));let s=0;return i<0&&(s=Math.abs(i)),{command:a,remainingData:o,missing:s}}};const j="KMSG",x="KCMD",P=E("klProtocol"),R=new TextEncoder;var N={encode:(e,t,n)=>{const r={json:e.json},a=A(e.json,"ArrayBuffer"),i=a?.combinedData;a&&(r.jsonBinaryMap=a.map,r.json=a.sourceCopy);const o=i?i.byteLength:0,s=JSON.stringify(r),c=R.encode(s),d=c.byteLength,u=new ArrayBuffer(I.protocolPrefix+I.protocolVersion+I.jsonLength+I.binaryLength+I.fromServiceId+I.toServiceId+I.sentAt+d+o),l=new DataView(u),f=new Uint8Array(u),g=Date.now();let p=0;for(let e=0;e<4;++e)f[p++]=j.charCodeAt(e);return l.setUint8(p,1),p+=I.protocolVersion,l.setUint32(p,d,!0),p+=I.jsonLength,l.setUint32(p,o,!0),p+=I.binaryLength,l.setUint32(p,t,!0),p+=I.fromServiceId,l.setUint32(p,n,!0),p+=I.toServiceId,l.setBigInt64(p,BigInt(g),!0),p+=I.sentAt,f.set(c,p),p+=d,i&&o&&f.set(new Uint8Array(i),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<I.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==j)return null;if(e.byteLength<S)return P.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const a=t.getUint8(n);n+=I.protocolVersion;const i=t.getUint32(n,!0);n+=I.jsonLength;const o=t.getUint32(n,!0);n+=I.binaryLength;const s=t.getUint32(n,!0);n+=I.fromServiceId;const c=t.getUint32(n,!0);n+=I.toServiceId;const d=t.getBigInt64(n,!0);n+=I.sentAt;const u=i+o,l=e.slice(n,n+u),f=new Uint8Array(e,0,S);let g=null;if(e.byteLength-S-i-o>0){g=new Uint8Array(e,S+i+o).slice().buffer}return{header:{protocolVersion:a,jsonLength:i,binaryLength:o,fromServiceId:s,toServiceId:c,sentAt:new Date(Number(d)),packages:[l],headerPackage:f.slice().buffer},remaining:g}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,a=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,a),a+=r.byteLength;const i=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),s=p(i);if(!s?.json)return P.log("Invalid JSON in KL message"),null;s.jsonBinaryMap&&o.byteLength&&L(s.json,o,s.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let d=c,u=null;const l=S+e.jsonLength+e.binaryLength;return c.byteLength>l&&(u=c.subarray(l),d=c.subarray(0,l)),{message:{json:s.json,...o.length?{binaryData:o.buffer}:{},rawMessage:d.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<S)return P("Invalid Header Size"),e;let n=0;n+=I.protocolPrefix,n+=I.protocolVersion,n+=I.jsonLength,n+=I.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=I.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=R.encode(e),r=n.byteLength,a=new ArrayBuffer(b+r),i=new DataView(a),o=new Uint8Array(a);for(let e=0;e<4;++e)o[t++]=x.charCodeAt(e);return i.setUint32(t,r,!0),t+=v.txtLength,o.set(n,t),a},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<b)return{command:null};let r="";for(let e=0;e<v.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==x)return{command:null};const a=t.getUint32(n,!0);n+=v.txtLength;const i=e.byteLength-b-a,o=new Uint8Array(e,n,Math.min(a,e.byteLength-b)),s=(new TextDecoder).decode(o);let c=null;i>0&&(c=e.slice(b+a));let d=0;return i<0&&(d=Math.abs(i)),{command:s,remainingData:c,missing:d}}};const $=E("klTransmissionManager");let M=k;y&&(M=N);var O=M;let F,T,H,K,G=null;const _=(()=>{const e=(t,n,r,a)=>{let i=n,o=null;const s=t instanceof ArrayBuffer;if($(`RAW: ${t.toString()}`),!i||i.partialHeaderData){let c;if(s?(c=i?.partialHeaderData?new Uint8Array([...new Uint8Array(i.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=N.decodeHeader(c)):(c=i?.partialHeaderData?Buffer.concat([i.partialHeaderData,t]):t,o=k.decodeHeader(c)),!o){const{command:t,missing:i,remainingData:o}=s?N.decodeCommand(c):k.decodeCommand(c);return t?a({command:t,complete:!0,rawMessage:c}):$(i?`ERROR: Missing ${i} bytes to complete the command. This partial command will be aborted.`:`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`),o?($(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,n,r,a)):void 0}if(o.partialHeader)return i={firstPackageAt:Date.now(),partialHeaderData:c},r(i);if(!o.header)return $(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const d=o.header;i={firstPackageAt:Date.now(),header:{...d,totalBytesReceived:d.packages[0].byteLength,totalBytesExpected:d.binaryLength+d.jsonLength,remaining:o.remaining}},r(i)}else i.header&&i.header.totalBytesReceived<i.header.totalBytesExpected&&(i.header.packages.push(t),i.header.totalBytesReceived+=t.byteLength,r(i));if(i.header&&i.header.totalBytesReceived>=i.header.totalBytesExpected){const t=Date.now()-i.header.sentAt.getTime(),n=Date.now()-i.firstPackageAt;$(`Received ${i.header.totalBytesReceived} of ${i.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=s?N.decodeFullKlMessage(i.header):k.decodeFullKlMessage(i.header),c=i.header.totalBytesReceived,d=i.header.remaining;r(null),o&&a({klMessage:o.message,complete:!0,sourceServiceId:i.header.fromServiceId,targetServiceId:i.header.toServiceId,rawMessage:o.message.rawMessage});let u=d;if(o?.remaining&&(u=s?d?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),a=new Uint8Array(e),i=new Uint8Array(t),o=new Uint8Array(r);return o.set(a),o.set(i,a.length),r})(d,o.remaining):o.remaining:d?Buffer.concat([d,o.remaining]):o.remaining),u)return $(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,a)}};return e})(),V=E("ipcClient"),W=e=>{const t=h.id;r.of[t].emit(e)};var J,z={connect:e=>{h.id=e?.id||h.id,h.appspace=e?.appSpace||h.appspace,r.config={...r.config,...h};const t=h.id;r.connectTo(t,(()=>{r.of[t].on("connect",(()=>{V("Connected to server"),G=null,T&&T()})),r.of[t].on("data",(e=>{_(e,G,(e=>G=e),(e=>{if(e.complete)return e.command?(V(`Received command: ${e.command}`),void(F&&F(e.command))):void(e.klMessage&&H&&H({send:W,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json}))}))})),r.of[t].on("disconnect",(()=>{V(`Disconnected from ${t}`),G=null,K&&K()}))}))},sendCommand:e=>{const t=h.id,n=O.encodeCommand(e);r.of[t].emit(n)},sendBuffer:W,onCommand:e=>F=e,onMessageReceived:e=>H=e,onClientConnected:e=>T=e,onClientDisconnected:e=>K=e};!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(J||(J={}));const q=3e4;let Q=Math.ceil(Date.now()/1e3);function X(e){const t={};let n,r=console.log;const a={};let i=e||String(Date.now());const o={},s=e=>!o[e],c=(e,t,n,r,a,i)=>{let o=y?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:i.success?i.success:[i],messageId:t,type:i.success?"response":"error"}};return s(r)&&(o=O.encode(c,n,r)),a(o,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{r=e},processMessage:(e,i,o,s)=>{if(!s)return!1;const d=s;if(t[d.messageId]){const e=t[d.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===d.type?e.resolve(d.args):"error"===d.type&&e.reject(d.args[0])),delete t[d.messageId]),!0}if("execute"!==d.type&&r&&r(`No pending execution found for message id "${d.messageId}"`),"execute"===d.type){const t=a[d.functionName];if(t){const a=e=>{c(d.functionName,d.messageId,o.targetServiceId,o.sourceServiceId,i,e)};if(!(!n||n({args:d.args,functionName:d.functionName,transport:e,messageId:d.messageId,sourceServiceId:o.sourceServiceId,reply:a,send:i})))return r&&r(`Function "${d.functionName}" not allowed to be invoked by client [${o.sourceServiceId}]`),a({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;t({transport:e,args:d.args,reply:a,messageId:d.messageId,sourceServiceId:o.sourceServiceId,send:i})}else{const e=`Function "${d.functionName}" not found.`;r&&r(e),c(d.functionName,d.messageId,o.targetServiceId,o.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,n,a,o,c,d)=>{if(!a){const e="No send buffer function provided.";throw r&&r(e),e}Q+=1;const u=`${i}-${Q}-exec-${e.substring(0,10)}`,l={messageId:u,functionName:e,send:a,sourceServiceId:o,targetServiceId:c,args:n||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};l.promise=new Promise(((e,t)=>{l.resolve=e,l.reject=t}));let f=y?new ArrayBuffer(0):Buffer.alloc(0);const g={json:{functionName:e,args:n,messageId:u,type:"execute"}};s(c)&&(f=O.encode(g,o,c)),t[u]=l,r&&r(`Calling remote function "${e}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return d?.async?(l.fulfilled=!0,l.resolve([void 0]),delete t[u]):0===d?.timeout||p||(l.timer=setTimeout((()=>{r&&r(`Remote function ${u} timed out`);const n=t[u];n&&!n.fulfilled&&(n.fulfilled=!0,l.reject(`Function ${e} Timed out`)),delete t[u]}),d?.timeout||q)),a(f,{sourceServiceId:o,targetServiceId:c,msg:g}),l.promise},sendResponse:c,registerFunction:(e,t)=>{a[e]=t},registerFunctionsMiddleware:e=>{n=e},unregisterAllFunctions:()=>{Object.keys(a).forEach((e=>{delete a[e]}))},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,n,a)=>{Q+=1;const o=`${i}-${Q}-multicast-${e.substring(0,10)}`;let c=y?new ArrayBuffer(0):Buffer.alloc(0);const d={json:{functionName:e,args:t,messageId:o,type:"execute"}};let u=s(n[0].serviceId);u&&(c=O.encode(d,a,n[0].serviceId));for(let t=0;t<n.length;t++)try{const i=n[t];r&&r(`Broadcasting function "${e}" with message id "${o}" to client [${i.serviceId}]`),0!==t&&(u=s(i.serviceId),u&&(c=O.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:d,sourceServiceId:a,targetServiceId:i.serviceId})}catch(e){r&&r(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{o[e]=t}}}const Y=E("kemuWidgetService"),Z=t(process.argv.slice(2));function ee(t){const r={},a=process.env.KEMU_WIDGET_SESSION_ID;let i,o,s,c,g=!1;const y={};let m,h,I,v,S,b,w,A,B=null;const L=new X;L.setLogger(Y);r.start=async(r,c)=>{const d=r||n.resolve(n.dirname(process.argv[1]),"manifest.json");s=n.dirname(d);const l=await e(d,"utf-8"),y=p(l);if(!y)throw new Error("Error parsing manifest file.");let m;if(y.inputs||(y.inputs=[]),y.outputs||(y.outputs=[]),y.widgetUI)try{m=await e(n.join(s,"widgetUI.js"))}catch(e){Y(`Error loading widgetUI file ${y.name}: ${e}`)}if(y.svgIcon)try{const t=await e(n.join(s,y.svgIcon),"utf-8");y.svgIcon=t}catch(e){Y(`Error loading icon for service ${y.name}: ${e}`)}o=((e,t,n)=>({...e,path:t,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}}))(y,s,{widgetUIContents:m}),g=o.name.startsWith("test."),o.path=s,o.internal=Z.internal||!1,g?Y("Starting Kemu Service in Dev mode"):((e=>{const t=e||Z.sessionId||a;if(!t)throw new Error("Missing sessionId. Expected service to be launched with a sessionId as first argument, or the KEMU_WIDGET_SESSION_ID environment variable to be set.");i=parseInt(String(t))})(c),Y(`Starting Kemu Service with session id: ${i}`)),L.setServiceName(`${o.name}_${o.version}`),z.onCommand(E),z.onMessageReceived((({json:e,transmission:t})=>L.processMessage(f.IPC,z.sendBuffer,t,e))),L.registerFunction(u.OnParentEvent,C),L.registerFunction(u.GetDefaultState,U),L.registerFunction(u.UIEvent,x),L.registerFunction(u.InitializeInstance,D),L.registerFunction(u.TerminateInstance,k),L.registerFunction(u.KemuComposerDisconnected,j),z.onClientConnected((()=>{A&&A()})),z.onClientDisconnected((()=>{g&&(i=void 0)})),z.connect({appSpace:Z.ipcSpace||t?.ipc?.appSpace,id:Z.ipcId||t?.ipc?.id})};const E=e=>{((e,t)=>{const n=d.SocketAcknowledge,r=d.IpcAcknowledge,a=e.startsWith(n),i=e.startsWith(r);if(a||i){const i=e.split(a?n:r),o=parseInt(i[1]);return t&&t(o),o}})(e,(e=>{z.sendCommand(((e,t)=>`${d.AcknowledgeResponse}${e}:${t||""}`)(e,i||void 0)),!i&&g&&(Y("Dev mode detected, assuming service session id from ack request:",e),i=e)})),((e,t)=>{e===d.BroadcastStart&&t()})(e,(()=>{I&&I()})),((e,t)=>{e===d.BroadcastEnd&&t()})(e,(()=>{v&&v()})),((e,t)=>{e===d.SendManifest&&t()})(e,(()=>{Y("Sending manifest to hub"),i?L.execute(u.ServiceManifest,[{...o,devMode:g}],z.sendBuffer,i,0,{async:!0}):Y("Service session id is not set. Cannot send manifest.")})),((e,t)=>{if(e.startsWith(d.AssumeSession)){const n=e.split(d.AssumeSession);return t(parseInt(n[1])),!0}})(e,(e=>{i=e,Y(`Assumed session id ${e}`)}))},U=async e=>{if(h){const t=await h();return e.reply({success:[t]})}return e.reply({success:[{}]})},C=async e=>{if(!m)return Y("No onParentEvent callback defined. Skipping parent event."),e.reply({success:[]});const t=e.args[0],{source:n,target:r,data:a,recipe:o,currentState:s,targetVariantId:c,eventContext:d,currentPath:l,eventId:f}=t;if(!i)return void Y("Service session id is not set. Cannot process parent event.");if(!n||!r||!a)return e.reply({error:"Invalid arguments, expected [source, target, data, context]"});const g=z.sendBuffer,p=async t=>L.execute(u.SetOutputs,[t],g,i,e.sourceServiceId,{timeout:0}),y={currentState:s,type:r.widgetType,widgetId:r.widgetId,variantId:c,recipeId:o.poolId,recipeName:o.name,recipe:o,setState:async t=>{const n={widgetId:r.widgetId,variantId:c,recipeId:o.poolId,newState:t};return L.execute(u.SetState,[n],g,i,e.sourceServiceId)},setOutputs:async(e,t)=>{const n={widgetId:r.widgetId,recipeId:o.poolId,outputs:e,finalState:t,currentPath:l};await p(n)},setOutputsWithContext:async e=>{const t={...e,widgetId:r.widgetId,recipeId:o.poolId,currentPath:l};await p(t)}};Y(`Invoking user-defined onParentEvent callback for event id "${e.messageId}"`),await m({data:a,source:n,target:r,eventContext:d,currentPath:l,eventId:f},y).then((()=>{Y(`Replying SUCCESS to event id "${e.messageId}"`),e.reply({success:[]})})).catch((t=>{const n="string"==typeof t?t:t.message||t;Y(`Error invoking onParentEvent callback: ${n}`),e.reply({error:n,errCode:"PARENT_EVENT_CALLBACK_ERROR"})}))},D=async e=>{const[{currentState:t,widgetId:n,variantId:r,recipeType:a,currentDependencies:i,kemuApiKey:o,recipe:s}]=e.args;if(o&&(c=o),y[n]={currentRecipeId:s.poolId,variantId:r,currentSourceServiceId:e.sourceServiceId},S){const c=[],d={currentState:t,recipeId:s.poolId,recipeName:s.name,recipe:{uuid:s.uuid,poolId:s.poolId,name:s.name,type:s.type,version:s.version,authorId:s.authorId,dbId:s.dbId},widgetId:n,variantId:r,recipeType:a,currentDependencies:i||{},kemuApiKey:o,secrets:{requestAccess:e=>{for(const t of e)"string"==typeof t?c.push({name:t}):c.push(t)}}},u=[await S(d)||null,c.length>0?c:null];e.reply({success:u})}else e.reply({error:"Not implemented",errCode:"FNC_NOT_FOUND"})},k=async e=>{if(b){const[{currentState:t,recipe:n,widgetId:r,variantId:a}]=e.args,i={currentState:t,recipeId:n.poolId,recipe:n,widgetId:r,variantId:a};await b(i),delete y[r]}e.reply({success:[]})},j=async e=>{if(console.log("Kemu Composer disconnected event: ",e),e.reply({success:[]}),w){const[t]=e.args;t.recipe&&await w(t)}},x=async e=>{if(B)try{const t=await B.apply(void 0,e.args);return e.reply({success:[t]})}catch(t){const n="string"==typeof t?t:JSON.stringify(t);return Y(`Error invoking UI Event handler: ${n}`),e.reply({error:n})}e.reply({error:"UI Events are not supported in this service."})},P=async e=>{if(!o.eventEmitter)throw new Error("This service does not support broadcasting events. Please set `eventEmitter` to true in your manifest file.");if(i)return L.execute(u.BroadcastEvent,e,z.sendBuffer,i,0,{async:!0});Y("Service session id is not set. Cannot broadcast event.")};r.broadcast=async(e,t)=>{const n=[{outputs:e,variantId:t,currentPath:[]}];await P(n)},r.broadcastEvent=async e=>{const t=[{outputs:e.outputs,variantId:e.variantId,eventContext:e.eventContext,targetRecipeId:e.targetRecipeId,targetRecipePoolId:e.targetRecipePoolId,targetWidgetId:e.targetWidgetId,currentPath:e.currentPath||[],eventId:e.eventId}];await P(t)},r.addDependencyPath=async(e,t,n)=>{if(!i)throw new Error("Not yet registered with the Hub");const r=y[n];if(!r.currentSourceServiceId||!r.currentRecipeId)throw new Error("Cannot invoke this method before initialization");const a={key:e,path:t,recipeId:r.currentRecipeId,widgetId:n};Y(`Adding dependency path for key "${e}" with path "${t}"`),await L.execute(l.SetDependencyPath,[a],z.sendBuffer,i,r.currentSourceServiceId)},r.getDependencyPath=async(e,t)=>{if(!i)throw new Error("Not yet registered with the Hub");const n=y[t];if(!n.currentSourceServiceId||!n.currentRecipeId)throw new Error("Cannot invoke this method before initialization");Y("Getting dependency path for key:",e);const r={key:e,recipeId:n.currentRecipeId,widgetId:t},[a]=await L.execute(l.GetDependencyPath,[r],z.sendBuffer,i,n.currentSourceServiceId);return Y("Dependency path response:",a),a},r.getUniqueId=async()=>{if(!i)throw new Error("Not yet registered with the Hub");const[e]=await L.execute(u.GetUniqueId,[],z.sendBuffer,i,0);return e},r.resolveRuntimeDependencyPath=e=>{if(!Z.recipePath)throw new Error("Cannot resolve runtime dependency without a recipe path. Missing [--recipePath] argument.");return n.resolve(Z.recipePath,e)},r.onGetDefaultState=e=>{h=e},r.onParentEvent=e=>{m=e},r.onTerminate=e=>{b=e},r.onKemuComposerDisconnected=e=>{w=e},r.onInitialize=e=>{S=e},r.onConnected=e=>{A=e},r.onStartBroadcast=e=>{I=e},r.onStopBroadcast=e=>{v=e},r.onUIEvent=e=>{B=e},r.secrets={add:async e=>{if(!i)throw new Error("Service session id is not set. Cannot add secret.");const t=Array.isArray(e)?e:[e],n=[{hubServiceName:o.name,secrets:t}];await L.execute(u.AddServiceSecret,n,z.sendBuffer,i,0)},read:async e=>{if(!i)throw new Error("Service session id is not set. Cannot read secret.");const t=[{recipeUuid:e.recipeUuid,secretNames:e.names,serviceName:o.name}],[n]=await L.execute(u.GetRecipeDecryptedSecretsValues,t,z.sendBuffer,i,0);return n?.secrets||{}}},Z.internal&&(r.executeHubFunction=async(e,t,n)=>{if(i)return L.execute(e,t,z.sendBuffer,i,0,n);Y("Service session id is not set. Cannot execute hub function.")});const R=r;return R._getRemoteInvoker=()=>L,R.getHubConfig=async()=>{if(!i)throw new Error("Service session id is not set. Cannot execute hub function.");const e=await L.execute(u.GetHubConfig,[],z.sendBuffer,i,0);return e?.[0]&&!e[0].kemuApiKey&&c&&(e[0].kemuApiKey=c),e?.[0]},R.getEdgeApiKey=async()=>{if(g)return void console.warn("This method [getEdgeApiKey] is NOT available in dev mode");if(!i)throw new Error("Service session id is not set. Cannot execute hub function.");const e=await L.execute(u.GetDecryptedEdgeApiKey,[],z.sendBuffer,i,0);return e?.[0]},r}export{o as DataType,g as KemuHubServiceId,m as createImageDataLike,ee as default};
|
|
1
|
+
import{readFile as e}from"fs/promises";import t from"minimist";import r from"path";import n from"node-ipc";import a from"debug";var i,o,s,c,d,u,l,g;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(i||(i={})),function(e){e[e.Number=0]="Number",e[e.String=1]="String",e[e.ArrayBuffer=2]="ArrayBuffer",e[e.Array=3]="Array",e[e.Boolean=4]="Boolean",e[e.JsonObj=5]="JsonObj",e[e.Anything=6]="Anything",e[e.ImageData=7]="ImageData",e[e.AudioBuffer=8]="AudioBuffer",e[e.Rect=9]="Rect",e[e.Point=10]="Point",e[e.ImageBitmap=11]="ImageBitmap",e[e.BinaryFile=12]="BinaryFile"}(o||(o={})),function(e){e.Number="Number",e.String="String",e.ArrayBuffer="ArrayBuffer",e.Array="Array",e.Boolean="Boolean",e.JsonObj="JsonObj",e.Anything="Anything",e.ImageData="ImageData",e.AudioBuffer="AudioBuffer",e.Rect="Rect",e.Point="Point",e.ImageBitmap="ImageBitmap",e.BinaryFile="BinaryFile"}(s||(s={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(c||(c={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(d||(d={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.AddServiceSecret="addServiceSecret",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.SendToRecipe="sendToRecipe",e.KemuComposerDisconnected="kemu-composer-disconnected",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.SaveRecipeToFile="saveRecipeToFile",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey",e.GetHubConfig="getHubConfig",e.GetRecipeDecryptedSecretsValues="getRecipeDecryptedSecretsValues",e.GetRecipeSecretMappings="getRecipeSecretMappings",e.AddRecipeSecretMapping="addRecipeSecretMapping",e.DeleteRecipeSecretMapping="deleteRecipeSecretMapping",e.GetHubSecrets="getHubSecrets",e.AddHubSecrets="addHubSecrets",e.DeleteHubSecret="deleteHubSecret"}(u||(u={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath",e.ParseStringExpression="parseStringExpression",e.GetGlobalVariableNames="getGlobalVariableNames",e.GetGlobalVariableValues="getGlobalVariableValues",e.SetGlobalVariableValues="setGlobalVariableValues"}(l||(l={})),function(e){e.IPC="ipc",e.WS="ws"}(g||(g={}));const f=0,p=e=>{if("string"!=typeof e)return!1;const t=/\{\{\{\s*[^{}\s][^{}]*\s*\}\}\}/g;return!!/\{\{\s*[^{}\s][^{}]*\s*\}\}/g.test(e)||(t.lastIndex=0,!!t.test(e))},y=e=>{try{return JSON.parse(e)}catch(e){return null}},m="undefined"!=typeof window,I=(e,t,r,n="srgb")=>{let a;return a=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:a,width:t,height:r,colorSpace:n,_kemuType:o.ImageData}};var h={id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const v={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},S={protocolPrefix:4,txtLength:4},b=Object.values(v).reduce(((e,t)=>e+t),0),w=Object.values(S).reduce(((e,t)=>e+t),0),A=["width","height","colorSpace"],B=(e,t)=>{const r={},n=[];let a=0,i=Array.isArray(e)?[]:{};const o=(e,i)=>{const s=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,r=e instanceof ArrayBuffer,n=e instanceof Uint8ClampedArray,a=e instanceof Uint8Array,i=e instanceof Int8Array;return t?"Buffer":r?"ArrayBuffer":n?"Uint8ClampedArray":a?"Uint8Array":i?"Int8Array":null})(e);if(!s){if(Array.isArray(e)){const t=[];for(let r=0;r<e.length;r++)t[r]=o(e[r],`${i}[${r}]`);return t}if("object"==typeof e){const t={},r=(e=>{const t=e instanceof Int16Array,r=e instanceof Uint16Array,n=e instanceof Int32Array,a=e instanceof Uint32Array,i=e instanceof Float32Array,o=e instanceof Float64Array,s=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":r?"Uint16Array":n?"Int32Array":a?"Uint32Array":i?"Float32Array":o?"Float64Array":s?"BigInt64Array":c?"BigUint64Array":null})(e);if(r)throw new Error(`Unsupported binary type [${r}] at path "${i}"`);for(const r in e)Object.hasOwn(e,r)||A.includes(r)||console.warn(`Allowing inherited property: ${r} from path: ${i}`),t[r]=o(e[r],`${i.length?`${i}.`:""}${r}`);return t}return e}r[i]={index:a,length:e.byteLength,binaryType:s},"Buffer"===t?n.push(Buffer.from(e)):"ArrayBuffer"===s?n.push(e):n.push(e.buffer),a+=e.byteLength};i=o(e,"");let s=null;if(n.length>1)if("ArrayBuffer"===t){const e=n.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let r=0;for(let e=0;e<n.length;e++)t.set(new Uint8Array(n[e]),r),r+=n[e].byteLength;s=t.buffer}else{s=Buffer.concat(n)}else 1===n.length&&(s=n[0]);return s?{map:r,combinedData:s,sourceCopy:i}:null},E=(e,t,r,n)=>{const a=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<a.length;e++){let t=a[e];const n=t.startsWith("[")&&t.endsWith("]"),o=e===a.length-1;if(n){t=t.slice(1,-1);const n=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${a.slice(0,e).join(".")}" but found an object.`);o?i[n]=r:(i[n]||(i[n]=a[e+1].startsWith("[")?[]:{}),i=i[n])}else o?i[t]=r:(i[t]||(i[t]=a[e+1].startsWith("[")?[]:{}),i=i[t])}return e},L=(e,t,r)=>{const n="undefined"!=typeof Buffer,a=t instanceof Uint8Array;for(const i in r)if(Object.hasOwn(r,i)){const{index:o,length:s,binaryType:c}=r[i];let d=null;if(n&&t instanceof Buffer)switch(c){case"Buffer":d=t.subarray(o,o+s);break;case"ArrayBuffer":d=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+s);break;case"Uint8Array":d=new Uint8Array(t.subarray(o,o+s));break;case"Uint8ClampedArray":d=new Uint8ClampedArray(t.subarray(o,o+s));break;case"Int8Array":d=new Int8Array(t.subarray(o,o+s))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(n){d=Buffer.from(t.slice(o,o+s));break}case"ArrayBuffer":d=a?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+s):t.slice(o,o+s);break;case"Uint8Array":d=a?t.slice(o,o+s):new Uint8Array(t.slice(o,o+s));break;case"Uint8ClampedArray":d=new Uint8ClampedArray(t.slice(o,o+s));break;case"Int8Array":d=new Int8Array(t.slice(o,o+s))}d&&E(e,i,d)}return e},C=e=>a(e),U="KMSG",x="KCMD",D=C("klProtocol");var P={encode:(e,t,r)=>{const n={json:e.json},a=B(n.json,"Buffer"),i=a?.combinedData;a&&(n.jsonBinaryMap=a.map,n.json=a.sourceCopy);const o=i?i.byteLength:0,s=JSON.stringify(n),c=Buffer.from(s),d=c.byteLength,u=v.protocolPrefix+v.protocolVersion+v.jsonLength+v.binaryLength+v.fromServiceId+v.toServiceId+v.sentAt+d+o,l=Buffer.alloc(u),g=Date.now();let f=0;return l.write(U,f),f+=v.protocolPrefix,l.writeUInt8(1,f),f+=v.protocolVersion,l.writeUInt32LE(d,f),f+=v.jsonLength,l.writeUInt32LE(o,f),f+=v.binaryLength,l.writeUInt32LE(t,f),f+=v.fromServiceId,l.writeUInt32LE(r,f),f+=v.toServiceId,l.writeBigInt64LE(BigInt(g),f),f+=v.sentAt,c.copy(l,f),f+=d,i&&o&&i.copy(l,f),l},decodeHeader:e=>{let t=0;const r=e.toString("utf-8",t,v.protocolPrefix);if(t+=v.protocolPrefix,r!==U)return null;if(e.byteLength<b)return D(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const n=e.readUInt8(t);t+=v.protocolVersion;const a=e.readUInt32LE(t);t+=v.jsonLength;const i=e.readUInt32LE(t);t+=v.binaryLength;const o=e.readUInt32LE(t);t+=v.fromServiceId;const s=e.readUInt32LE(t);t+=v.toServiceId;const c=e.readBigInt64LE(t);t+=v.sentAt;const d=a+i,u=e.subarray(t,t+d),l=e.subarray(0,b);let g=null;return e.byteLength-b-a-i>0&&(g=e.subarray(b+a+i)),{header:{protocolVersion:n,jsonLength:a,binaryLength:i,fromServiceId:o,toServiceId:s,sentAt:new Date(Number(c)),packages:[u],headerPackage:l},remaining:g}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),r=t.subarray(0,e.jsonLength).toString(),n=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=y(r);if(!a?.json)return D("Invalid JSON in KL message"),null;a.jsonBinaryMap&&n.byteLength&&L(a.json,n,a.jsonBinaryMap);const i=Buffer.concat([e.headerPackage,t]);let o=i,s=null;const c=b+e.jsonLength+e.binaryLength;return i.byteLength>c&&(s=i.subarray(c),o=i.subarray(0,c)),{message:{json:a.json,rawMessage:o},remaining:s}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<b)return D("Invalid Header Size"),e;let r=0;return r+=v.protocolPrefix,r+=v.protocolVersion,r+=v.jsonLength,r+=v.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,r),r+=v.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,r),e},encodeCommand:e=>{let t=0;const r=Buffer.from(e),n=r.byteLength,a=w+n,i=Buffer.alloc(a);return i.write(x,t),t+=S.protocolPrefix,i.writeUint32LE(n,t),t+=S.txtLength,r.copy(i,t),i},decodeCommand:e=>{let t=0;if(e.byteLength<w)return{command:null};const r=e.toString("utf-8",t,S.protocolPrefix);if(t+=S.protocolPrefix,r!==x)return{command:null};const n=e.readUInt32LE(t);t+=S.txtLength;const a=e.toString("utf-8",t,t+n),i=e.byteLength-w-n;let o=null;i>0&&(o=e.subarray(w+n));let s=0;return i<0&&(s=Math.abs(i)),{command:a,remainingData:o,missing:s}}};const k="KMSG",j="KCMD",R=C("klProtocol"),N=new TextEncoder;var $={encode:(e,t,r)=>{const n={json:e.json},a=B(e.json,"ArrayBuffer"),i=a?.combinedData;a&&(n.jsonBinaryMap=a.map,n.json=a.sourceCopy);const o=i?i.byteLength:0,s=JSON.stringify(n),c=N.encode(s),d=c.byteLength,u=new ArrayBuffer(v.protocolPrefix+v.protocolVersion+v.jsonLength+v.binaryLength+v.fromServiceId+v.toServiceId+v.sentAt+d+o),l=new DataView(u),g=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)g[p++]=k.charCodeAt(e);return l.setUint8(p,1),p+=v.protocolVersion,l.setUint32(p,d,!0),p+=v.jsonLength,l.setUint32(p,o,!0),p+=v.binaryLength,l.setUint32(p,t,!0),p+=v.fromServiceId,l.setUint32(p,r,!0),p+=v.toServiceId,l.setBigInt64(p,BigInt(f),!0),p+=v.sentAt,g.set(c,p),p+=d,i&&o&&g.set(new Uint8Array(i),p),u},decodeHeader:e=>{const t=new DataView(e);let r=0,n="";for(let e=0;e<v.protocolPrefix;++e)n+=String.fromCharCode(t.getUint8(r++));if(n!==k)return null;if(e.byteLength<b)return R.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const a=t.getUint8(r);r+=v.protocolVersion;const i=t.getUint32(r,!0);r+=v.jsonLength;const o=t.getUint32(r,!0);r+=v.binaryLength;const s=t.getUint32(r,!0);r+=v.fromServiceId;const c=t.getUint32(r,!0);r+=v.toServiceId;const d=t.getBigInt64(r,!0);r+=v.sentAt;const u=i+o,l=e.slice(r,r+u),g=new Uint8Array(e,0,b);let f=null;if(e.byteLength-b-i-o>0){f=new Uint8Array(e,b+i+o).slice().buffer}return{header:{protocolVersion:a,jsonLength:i,binaryLength:o,fromServiceId:s,toServiceId:c,sentAt:new Date(Number(d)),packages:[l],headerPackage:g.slice().buffer},remaining:f}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),r=new Uint8Array(t);let n,a=0;for(const t of e.packages)n=new Uint8Array(t),r.set(n,a),a+=n.byteLength;const i=(new TextDecoder).decode(r.subarray(0,e.jsonLength)),o=r.subarray(e.jsonLength,e.jsonLength+e.binaryLength),s=y(i);if(!s?.json)return R.log("Invalid JSON in KL message"),null;s.jsonBinaryMap&&o.byteLength&&L(s.json,o,s.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+r.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(r,e.headerPackage.byteLength);let d=c,u=null;const l=b+e.jsonLength+e.binaryLength;return c.byteLength>l&&(u=c.subarray(l),d=c.subarray(0,l)),{message:{json:s.json,...o.length?{binaryData:o.buffer}:{},rawMessage:d.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<b)return R("Invalid Header Size"),e;let r=0;r+=v.protocolPrefix,r+=v.protocolVersion,r+=v.jsonLength,r+=v.binaryLength;const n=new DataView(e);return void 0!==t.fromServiceId&&n.setUint32(r,t.fromServiceId,!0),r+=v.fromServiceId,void 0!==t.toServiceId&&n.setUint32(r,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const r=N.encode(e),n=r.byteLength,a=new ArrayBuffer(w+n),i=new DataView(a),o=new Uint8Array(a);for(let e=0;e<4;++e)o[t++]=j.charCodeAt(e);return i.setUint32(t,n,!0),t+=S.txtLength,o.set(r,t),a},decodeCommand:e=>{const t=new DataView(e);let r=0;if(e.byteLength<w)return{command:null};let n="";for(let e=0;e<S.protocolPrefix;++e)n+=String.fromCharCode(t.getUint8(r++));if(n!==j)return{command:null};const a=t.getUint32(r,!0);r+=S.txtLength;const i=e.byteLength-w-a,o=new Uint8Array(e,r,Math.min(a,e.byteLength-w)),s=(new TextDecoder).decode(o);let c=null;i>0&&(c=e.slice(w+a));let d=0;return i<0&&(d=Math.abs(i)),{command:s,remainingData:c,missing:d}}};const M=C("klTransmissionManager");let O=P;m&&(O=$);var F=O;let T,V,G,H,K=null;const _=(()=>{const e=(t,r,n,a)=>{let i=r,o=null;const s=t instanceof ArrayBuffer;if(M(`RAW: ${t.toString()}`),!i||i.partialHeaderData){let c;if(s?(c=i?.partialHeaderData?new Uint8Array([...new Uint8Array(i.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=$.decodeHeader(c)):(c=i?.partialHeaderData?Buffer.concat([i.partialHeaderData,t]):t,o=P.decodeHeader(c)),!o){const{command:t,missing:i,remainingData:o}=s?$.decodeCommand(c):P.decodeCommand(c);return t?a({command:t,complete:!0,rawMessage:c}):M(i?`ERROR: Missing ${i} bytes to complete the command. This partial command will be aborted.`:`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`),o?(M(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,r,n,a)):void 0}if(o.partialHeader)return i={firstPackageAt:Date.now(),partialHeaderData:c},n(i);if(!o.header)return M(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const d=o.header;i={firstPackageAt:Date.now(),header:{...d,totalBytesReceived:d.packages[0].byteLength,totalBytesExpected:d.binaryLength+d.jsonLength,remaining:o.remaining}},n(i)}else i.header&&i.header.totalBytesReceived<i.header.totalBytesExpected&&(i.header.packages.push(t),i.header.totalBytesReceived+=t.byteLength,n(i));if(i.header&&i.header.totalBytesReceived>=i.header.totalBytesExpected){const t=Date.now()-i.header.sentAt.getTime(),r=Date.now()-i.firstPackageAt;M(`Received ${i.header.totalBytesReceived} of ${i.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${r}ms`);const o=s?$.decodeFullKlMessage(i.header):P.decodeFullKlMessage(i.header),c=i.header.totalBytesReceived,d=i.header.remaining;n(null),o&&a({klMessage:o.message,complete:!0,sourceServiceId:i.header.fromServiceId,targetServiceId:i.header.toServiceId,rawMessage:o.message.rawMessage});let u=d;if(o?.remaining&&(u=s?d?((e,t)=>{const r=e.byteLength+t.byteLength,n=new ArrayBuffer(r),a=new Uint8Array(e),i=new Uint8Array(t),o=new Uint8Array(n);return o.set(a),o.set(i,a.length),n})(d,o.remaining):o.remaining:d?Buffer.concat([d,o.remaining]):o.remaining),u)return M(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,n,a)}};return e})(),W=C("ipcClient"),z=e=>{const t=h.id;n.of[t].emit(e)};var J,q={connect:e=>{h.id=e?.id||h.id,h.appspace=e?.appSpace||h.appspace,n.config={...n.config,...h};const t=h.id;n.connectTo(t,(()=>{n.of[t].on("connect",(()=>{W("Connected to server"),K=null,V&&V()})),n.of[t].on("data",(e=>{_(e,K,(e=>K=e),(e=>{if(e.complete)return e.command?(W(`Received command: ${e.command}`),void(T&&T(e.command))):void(e.klMessage&&G&&G({send:z,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json}))}))})),n.of[t].on("disconnect",(()=>{W(`Disconnected from ${t}`),K=null,H&&H()}))}))},sendCommand:e=>{const t=h.id,r=F.encodeCommand(e);n.of[t].emit(r)},sendBuffer:z,onCommand:e=>T=e,onMessageReceived:e=>G=e,onClientConnected:e=>V=e,onClientDisconnected:e=>H=e};!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(J||(J={}));const Q=3e4;let X=Math.ceil(Date.now()/1e3);function Y(e){const t={};let r,n=console.log;const a={};let i=e||String(Date.now());const o={},s=e=>!o[e],c=(e,t,r,n,a,i)=>{let o=m?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:i.success?i.success:[i],messageId:t,type:i.success?"response":"error"}};return s(n)&&(o=F.encode(c,r,n)),a(o,{msg:c,sourceServiceId:r,targetServiceId:n})};return{setLogger:e=>{n=e},processMessage:(e,i,o,s)=>{if(!s)return!1;const d=s;if(t[d.messageId]){const e=t[d.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===d.type?e.resolve(d.args):"error"===d.type&&e.reject(d.args[0])),delete t[d.messageId]),!0}if("execute"!==d.type&&n&&n(`No pending execution found for message id "${d.messageId}"`),"execute"===d.type){const t=a[d.functionName];if(t){const a=e=>{c(d.functionName,d.messageId,o.targetServiceId,o.sourceServiceId,i,e)};if(!(!r||r({args:d.args,functionName:d.functionName,transport:e,messageId:d.messageId,sourceServiceId:o.sourceServiceId,reply:a,send:i})))return n&&n(`Function "${d.functionName}" not allowed to be invoked by client [${o.sourceServiceId}]`),a({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;t({transport:e,args:d.args,reply:a,messageId:d.messageId,sourceServiceId:o.sourceServiceId,send:i})}else{const e=`Function "${d.functionName}" not found.`;n&&n(e),c(d.functionName,d.messageId,o.targetServiceId,o.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,a,o,c,d)=>{if(!a){const e="No send buffer function provided.";throw n&&n(e),e}X+=1;const u=`${i}-${X}-exec-${e.substring(0,10)}`,l={messageId:u,functionName:e,send:a,sourceServiceId:o,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};l.promise=new Promise(((e,t)=>{l.resolve=e,l.reject=t}));let g=m?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:e,args:r,messageId:u,type:"execute"}};s(c)&&(g=F.encode(f,o,c)),t[u]=l,n&&n(`Calling remote function "${e}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return d?.async?(l.fulfilled=!0,l.resolve([void 0]),delete t[u]):0===d?.timeout||p||(l.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=t[u];r&&!r.fulfilled&&(r.fulfilled=!0,l.reject(`Function ${e} Timed out`)),delete t[u]}),d?.timeout||Q)),a(g,{sourceServiceId:o,targetServiceId:c,msg:f}),l.promise},sendResponse:c,registerFunction:(e,t)=>{a[e]=t},registerFunctionsMiddleware:e=>{r=e},unregisterAllFunctions:()=>{Object.keys(a).forEach((e=>{delete a[e]}))},getTransportSendFunction:e=>{const r=t[e];return r?r.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((r=>{const n=t[r];n&&!n.fulfilled&&(clearTimeout(n.timer),n.fulfilled=!0,n.reject(e),delete t[r])}))},broadcast:(e,t,r,a)=>{X+=1;const o=`${i}-${X}-multicast-${e.substring(0,10)}`;let c=m?new ArrayBuffer(0):Buffer.alloc(0);const d={json:{functionName:e,args:t,messageId:o,type:"execute"}};let u=s(r[0].serviceId);u&&(c=F.encode(d,a,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${o}" to client [${i.serviceId}]`),0!==t&&(u=s(i.serviceId),u&&(c=F.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:d,sourceServiceId:a,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{o[e]=t}}}const Z=C("kemuWidgetService"),ee=t(process.argv.slice(2));function te(t){const n={},a=process.env.KEMU_WIDGET_SESSION_ID;let i,o,s,c,f=!1;const m={};let I,h,v,S,b,w,A,B,E=null;const L=new Y;L.setLogger(Z);n.start=async(n,c)=>{const d=n||r.resolve(r.dirname(process.argv[1]),"manifest.json");s=r.dirname(d);const l=await e(d,"utf-8"),p=y(l);if(!p)throw new Error("Error parsing manifest file.");let m;if(p.inputs||(p.inputs=[]),p.outputs||(p.outputs=[]),p.widgetUI)try{m=await e(r.join(s,"widgetUI.js"))}catch(e){Z(`Error loading widgetUI file ${p.name}: ${e}`)}if(p.svgIcon)try{const t=await e(r.join(s,p.svgIcon),"utf-8");p.svgIcon=t}catch(e){Z(`Error loading icon for service ${p.name}: ${e}`)}o=((e,t,r)=>({...e,path:t,...e.widgetUI&&r?.widgetUIContents?{widgetUIContents:r.widgetUIContents}:{}}))(p,s,{widgetUIContents:m}),f=o.name.startsWith("test."),o.path=s,o.internal=ee.internal||!1,f?Z("Starting Kemu Service in Dev mode"):((e=>{const t=e||ee.sessionId||a;if(!t)throw new Error("Missing sessionId. Expected service to be launched with a sessionId as first argument, or the KEMU_WIDGET_SESSION_ID environment variable to be set.");i=parseInt(String(t))})(c),Z(`Starting Kemu Service with session id: ${i}`)),L.setServiceName(`${o.name}_${o.version}`),q.onCommand(C),q.onMessageReceived((({json:e,transmission:t})=>L.processMessage(g.IPC,q.sendBuffer,t,e))),L.registerFunction(u.OnParentEvent,x),L.registerFunction(u.GetDefaultState,U),L.registerFunction(u.UIEvent,j),L.registerFunction(u.InitializeInstance,D),L.registerFunction(u.TerminateInstance,P),L.registerFunction(u.KemuComposerDisconnected,k),q.onClientConnected((()=>{B&&B()})),q.onClientDisconnected((()=>{f&&(i=void 0)})),q.connect({appSpace:ee.ipcSpace||t?.ipc?.appSpace,id:ee.ipcId||t?.ipc?.id})};const C=e=>{((e,t)=>{const r=d.SocketAcknowledge,n=d.IpcAcknowledge,a=e.startsWith(r),i=e.startsWith(n);if(a||i){const i=e.split(a?r:n),o=parseInt(i[1]);return t&&t(o),o}})(e,(e=>{q.sendCommand(((e,t)=>`${d.AcknowledgeResponse}${e}:${t||""}`)(e,i||void 0)),!i&&f&&(Z("Dev mode detected, assuming service session id from ack request:",e),i=e)})),((e,t)=>{e===d.BroadcastStart&&t()})(e,(()=>{v&&v()})),((e,t)=>{e===d.BroadcastEnd&&t()})(e,(()=>{S&&S()})),((e,t)=>{e===d.SendManifest&&t()})(e,(()=>{Z("Sending manifest to hub"),i?L.execute(u.ServiceManifest,[{...o,devMode:f}],q.sendBuffer,i,0,{async:!0}):Z("Service session id is not set. Cannot send manifest.")})),((e,t)=>{if(e.startsWith(d.AssumeSession)){const r=e.split(d.AssumeSession);return t(parseInt(r[1])),!0}})(e,(e=>{i=e,Z(`Assumed session id ${e}`)}))},U=async e=>{if(h){const t=await h();return e.reply({success:[t]})}return e.reply({success:[{}]})},x=async e=>{if(!I)return Z("No onParentEvent callback defined. Skipping parent event."),e.reply({success:[]});const t=e.args[0],{source:r,target:n,data:a,recipe:o,currentState:s,targetVariantId:c,eventContext:d,currentPath:l,eventId:g}=t;if(!i)return void Z("Service session id is not set. Cannot process parent event.");if(!r||!n||!a)return e.reply({error:"Invalid arguments, expected [source, target, data, context]"});const f=q.sendBuffer,p=async t=>L.execute(u.SetOutputs,[t],f,i,e.sourceServiceId,{timeout:0}),y={currentState:s,type:n.widgetType,widgetId:n.widgetId,variantId:c,recipeId:o.poolId,recipeName:o.name,recipe:o,setState:async t=>{const r={widgetId:n.widgetId,variantId:c,recipeId:o.poolId,newState:t};return L.execute(u.SetState,[r],f,i,e.sourceServiceId)},setOutputs:async(e,t)=>{const r={widgetId:n.widgetId,recipeId:o.poolId,outputs:e,finalState:t,currentPath:l};await p(r)},setOutputsWithContext:async e=>{const t={...e,eventId:g,widgetId:n.widgetId,recipeId:o.poolId,currentPath:l};null===e.eventId&&delete t.eventId,await p(t)}};Z(`Invoking user-defined onParentEvent callback for event id "${e.messageId}"`),await I({data:a,source:r,target:n,eventContext:d,currentPath:l,eventId:g},y).then((()=>{Z(`Replying SUCCESS to event id "${e.messageId}"`),e.reply({success:[]})})).catch((t=>{const r="string"==typeof t?t:t.message||t;Z(`Error invoking onParentEvent callback: ${r}`),e.reply({error:r,errCode:"PARENT_EVENT_CALLBACK_ERROR"})}))},D=async e=>{const[{currentState:t,widgetId:r,variantId:n,recipeType:a,currentDependencies:i,kemuApiKey:o,recipe:s}]=e.args;if(o&&(c=o),m[r]={currentRecipeId:s.poolId,variantId:n,currentSourceServiceId:e.sourceServiceId},b){const c=[],d=[],u={currentState:t,recipeId:s.poolId,recipeName:s.name,recipe:{uuid:s.uuid,poolId:s.poolId,name:s.name,type:s.type,version:s.version,authorId:s.authorId,dbId:s.dbId},widgetId:r,variantId:n,recipeType:a,currentDependencies:i||{},kemuApiKey:o,globalVars:{declare:e=>{d.push(e)}},secrets:{requestAccess:e=>{for(const t of e)"string"==typeof t?c.push({name:t}):c.push(t)}}},l=[await b(u)||null,c.length>0?c:null,d.length>0?d:null];e.reply({success:l})}else e.reply({error:"Not implemented",errCode:"FNC_NOT_FOUND"})},P=async e=>{if(w){const[{currentState:t,recipe:r,widgetId:n,variantId:a}]=e.args,i={currentState:t,recipeId:r.poolId,recipe:r,widgetId:n,variantId:a};await w(i),delete m[n]}e.reply({success:[]})},k=async e=>{if(console.log("Kemu Composer disconnected event: ",e),e.reply({success:[]}),A){const[t]=e.args;t.recipe&&await A(t)}},j=async e=>{if(E)try{const t=await E.apply(void 0,e.args);return e.reply({success:[t]})}catch(t){const r="string"==typeof t?t:JSON.stringify(t);return Z(`Error invoking UI Event handler: ${r}`),e.reply({error:r})}e.reply({error:"UI Events are not supported in this service."})},R=async e=>{if(!o.eventEmitter)throw new Error("This service does not support broadcasting events. Please set `eventEmitter` to true in your manifest file.");if(i)return L.execute(u.BroadcastEvent,e,q.sendBuffer,i,0,{async:!0});Z("Service session id is not set. Cannot broadcast event.")};n.broadcast=async(e,t)=>{const r=[{outputs:e,variantId:t,currentPath:[]}];await R(r)},n.broadcastEvent=async e=>{const t=[{outputs:e.outputs,variantId:e.variantId,eventContext:e.eventContext,targetRecipeId:e.targetRecipeId,targetRecipePoolId:e.targetRecipePoolId,targetWidgetId:e.targetWidgetId,currentPath:e.currentPath||[],eventId:e.eventId}];await R(t)},n.addDependencyPath=async(e,t,r)=>{if(!i)throw new Error("Not yet registered with the Hub");const n=m[r];if(!n.currentSourceServiceId||!n.currentRecipeId)throw new Error("Cannot invoke this method before initialization");const a={key:e,path:t,recipeId:n.currentRecipeId,widgetId:r};Z(`Adding dependency path for key "${e}" with path "${t}"`),await L.execute(l.SetDependencyPath,[a],q.sendBuffer,i,n.currentSourceServiceId)},n.getDependencyPath=async(e,t)=>{if(!i)throw new Error("Not yet registered with the Hub");const r=m[t];if(!r.currentSourceServiceId||!r.currentRecipeId)throw new Error("Cannot invoke this method before initialization");Z("Getting dependency path for key:",e);const n={key:e,recipeId:r.currentRecipeId,widgetId:t},[a]=await L.execute(l.GetDependencyPath,[n],q.sendBuffer,i,r.currentSourceServiceId);return Z("Dependency path response:",a),a},n.getUniqueId=async()=>{if(!i)throw new Error("Not yet registered with the Hub");const[e]=await L.execute(u.GetUniqueId,[],q.sendBuffer,i,0);return e},n.resolveRuntimeDependencyPath=e=>{if(!ee.recipePath)throw new Error("Cannot resolve runtime dependency without a recipe path. Missing [--recipePath] argument.");return r.resolve(ee.recipePath,e)},n.onGetDefaultState=e=>{h=e},n.onParentEvent=e=>{I=e},n.onTerminate=e=>{w=e},n.onKemuComposerDisconnected=e=>{A=e},n.onInitialize=e=>{b=e},n.onConnected=e=>{B=e},n.onStartBroadcast=e=>{v=e},n.onStopBroadcast=e=>{S=e},n.onUIEvent=e=>{E=e},n.secrets={add:async e=>{if(!i)throw new Error("Service session id is not set. Cannot add secret.");const t=Array.isArray(e)?e:[e],r=[{hubServiceName:o.name,secrets:t}];await L.execute(u.AddServiceSecret,r,q.sendBuffer,i,0)},read:async e=>{if(!i)throw new Error("Service session id is not set. Cannot read secret.");const t=[{recipeUuid:e.recipeUuid,secretNames:e.names,serviceName:o.name}],[r]=await L.execute(u.GetRecipeDecryptedSecretsValues,t,q.sendBuffer,i,0);return r?.secrets||{}}};const N=()=>{if(!i)throw new Error("Service session id is not set.");return i},$=e=>{const t=m[e];if(!t.currentSourceServiceId||!t.currentRecipeId)throw new Error("Cannot invoke this method before initialization");return{sourceServiceId:t.currentSourceServiceId,recipePoolId:t.currentRecipeId}};n.globalVars={getNames:async e=>{const t=N(),{sourceServiceId:r,recipePoolId:n}=$(e.widgetId),a=[{filterTypes:e.filterTypes,recipePoolId:n,widgetId:e.widgetId}],[i]=await L.execute(l.GetGlobalVariableNames,a,q.sendBuffer,t,r);return i.variables},getValues:async e=>{const t=N(),{sourceServiceId:r,recipePoolId:n}=$(e.widgetId),a=[{names:e.names,recipePoolId:n,widgetId:e.widgetId}],[i]=await L.execute(l.GetGlobalVariableValues,a,q.sendBuffer,t,r);return i.values},setValues:async e=>{const t=N(),{sourceServiceId:r,recipePoolId:n}=$(e.widgetId),a=[{values:e.values,recipePoolId:n,widgetId:e.widgetId}];await L.execute(l.SetGlobalVariableValues,a,q.sendBuffer,t,r)}},n.helpers={parseExpressions:async e=>{const{expressions:t,widgetId:r}=e;if(!Array.isArray(t))throw new Error("expressions must be an array");if(!e.expressions.some((e=>p(e.text))))return e.expressions.map((e=>e.text));const n=N(),{sourceServiceId:a,recipePoolId:i}=$(r),o=[{expressions:t,recipePoolId:i,widgetId:r}],[s]=await L.execute(l.ParseStringExpression,o,q.sendBuffer,n,a);return s.expressions},parseExpression:async e=>{const{text:t,widgetId:r,context:n}=e;if(!p(t))return t;const a=N(),{sourceServiceId:i,recipePoolId:o}=$(r),s=[{expressions:[{text:t,context:n}],recipePoolId:o,widgetId:r}],[c]=await L.execute(l.ParseStringExpression,s,q.sendBuffer,a,i);return c.expressions[0]}},ee.internal&&(n.executeHubFunction=async(e,t,r)=>{if(i)return L.execute(e,t,q.sendBuffer,i,0,r);Z("Service session id is not set. Cannot execute hub function.")});const M=n;return M._getRemoteInvoker=()=>L,M.getHubConfig=async()=>{if(!i)throw new Error("Service session id is not set. Cannot execute hub function.");const e=await L.execute(u.GetHubConfig,[],q.sendBuffer,i,0);return e?.[0]&&!e[0].kemuApiKey&&c&&(e[0].kemuApiKey=c),e?.[0]},M.getEdgeApiKey=async()=>{if(f)return void console.warn("This method [getEdgeApiKey] is NOT available in dev mode");if(!i)throw new Error("Service session id is not set. Cannot execute hub function.");const e=await L.execute(u.GetDecryptedEdgeApiKey,[],q.sendBuffer,i,0);return e?.[0]},n}export{o as DataType,f as KemuHubServiceId,I as createImageDataLike,te as default};
|
package/mjs/types/kemuCore.js
CHANGED
|
@@ -101,6 +101,10 @@ var ServiceToServiceFunctions;
|
|
|
101
101
|
(function (ServiceToServiceFunctions) {
|
|
102
102
|
ServiceToServiceFunctions["SetDependencyPath"] = "setDependencyPath";
|
|
103
103
|
ServiceToServiceFunctions["GetDependencyPath"] = "getDependencyPath";
|
|
104
|
+
ServiceToServiceFunctions["ParseStringExpression"] = "parseStringExpression";
|
|
105
|
+
ServiceToServiceFunctions["GetGlobalVariableNames"] = "getGlobalVariableNames";
|
|
106
|
+
ServiceToServiceFunctions["GetGlobalVariableValues"] = "getGlobalVariableValues";
|
|
107
|
+
ServiceToServiceFunctions["SetGlobalVariableValues"] = "setGlobalVariableValues";
|
|
104
108
|
})(ServiceToServiceFunctions || (ServiceToServiceFunctions = {}));
|
|
105
109
|
var Transport;
|
|
106
110
|
(function (Transport) {
|