@kitsuned/webos-service 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrey Smirnov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,10 @@
1
+ export declare class IdleTimer {
2
+ private readonly idleTimeout;
3
+ private readonly onQuit;
4
+ private counter;
5
+ private timer;
6
+ constructor(idleTimeout?: number | null, onQuit?: (() => void) | null);
7
+ acquire(): void;
8
+ release(): void;
9
+ private tick;
10
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IdleTimer = void 0;
4
+ class IdleTimer {
5
+ idleTimeout;
6
+ onQuit;
7
+ counter = 0;
8
+ timer = null;
9
+ constructor(idleTimeout = null, onQuit = null) {
10
+ this.idleTimeout = idleTimeout;
11
+ this.onQuit = onQuit;
12
+ if (idleTimeout) {
13
+ this.timer = setTimeout(this.tick.bind(this), idleTimeout * 1000);
14
+ }
15
+ else {
16
+ // keep process alive by resuming stdin stream
17
+ process.stdin.resume();
18
+ }
19
+ }
20
+ acquire() {
21
+ this.counter++;
22
+ if (this.timer !== null) {
23
+ clearTimeout(this.timer);
24
+ }
25
+ }
26
+ release() {
27
+ this.counter--;
28
+ if (this.idleTimeout && this.counter === 0) {
29
+ this.timer = setTimeout(this.tick.bind(this), this.idleTimeout * 1000);
30
+ }
31
+ }
32
+ tick() {
33
+ this.onQuit?.();
34
+ }
35
+ }
36
+ exports.IdleTimer = IdleTimer;
@@ -0,0 +1,38 @@
1
+ import { Message } from './message';
2
+ type AnyRecord = Record<string, any>;
3
+ export type LunaErrorResponse = {
4
+ returnValue: false;
5
+ errorCode?: number;
6
+ errorText: string;
7
+ };
8
+ export type LunaSuccessResponse<T> = {
9
+ returnValue?: true;
10
+ } & T;
11
+ export type LunaResponse<T extends AnyRecord> = LunaSuccessResponse<T> | LunaErrorResponse;
12
+ export type Executor<TReq extends AnyRecord, TResp extends AnyRecord | void, TNext extends AnyRecord> = (payload: TReq, message: Message<TReq>) => AsyncGenerator<TNext, TResp> | Promise<TResp> | TResp;
13
+ export type Client = Pick<Service, 'oneshot' | 'subscribe' | 'stream'> & {
14
+ id: string | null;
15
+ };
16
+ export declare const isLegacyBus: boolean;
17
+ export declare class Service {
18
+ readonly id: string;
19
+ private readonly handleOutbound;
20
+ private readonly handlePublic;
21
+ private readonly handlePrivate;
22
+ private readonly idleTimer;
23
+ private readonly methods;
24
+ private readonly pending;
25
+ constructor(serviceId?: string, idleTimeout?: number | null, publicBus?: boolean);
26
+ register<TReq extends AnyRecord, TResp extends AnyRecord | void = AnyRecord | void, TNext extends AnyRecord = AnyRecord>(method: string, executor: Executor<TReq, TResp, TNext>, { bus }?: {
27
+ bus?: 'public' | 'private' | 'both';
28
+ }): void;
29
+ subscribe<T extends AnyRecord>(uri: string, params: AnyRecord, callback: (response: LunaResponse<T>) => void): () => void;
30
+ stream<T extends AnyRecord>(uri: string, params?: AnyRecord): AsyncGenerator<LunaResponse<T>, void>;
31
+ oneshot<T extends AnyRecord>(uri: string, params?: AnyRecord): Promise<LunaResponse<T>>;
32
+ unregister(): void;
33
+ private drainExecutor;
34
+ private handleRequest;
35
+ private handleCancel;
36
+ private handleQuit;
37
+ }
38
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Service = exports.isLegacyBus = void 0;
7
+ const palmbus_1 = __importDefault(require("palmbus"));
8
+ const fs_1 = require("fs");
9
+ const path_1 = require("path");
10
+ const async_utils_1 = require("@kitsuned/async-utils");
11
+ const message_1 = require("./message");
12
+ const idle_timer_1 = require("./idle-timer");
13
+ function extractMethodPath(path) {
14
+ const lastSlashIndex = path.lastIndexOf('/');
15
+ if (lastSlashIndex <= 0) {
16
+ return ['/', path.slice(1)];
17
+ }
18
+ return [path.slice(0, lastSlashIndex), path.slice(lastSlashIndex + 1)];
19
+ }
20
+ function readServiceIdFromConfig() {
21
+ const path = (0, path_1.join)(process.cwd(), './services.json');
22
+ let config;
23
+ try {
24
+ config = JSON.parse((0, fs_1.readFileSync)(path, 'utf8'));
25
+ }
26
+ catch {
27
+ throw new Error('Failed to read "services.json" to get Service ID');
28
+ }
29
+ if (!config.id) {
30
+ throw new Error('Service ID is missing in "services.json"');
31
+ }
32
+ return config.id;
33
+ }
34
+ exports.isLegacyBus = (0, fs_1.existsSync)('/var/run/ls2/ls-hubd.private.pid');
35
+ class Service {
36
+ id;
37
+ handleOutbound;
38
+ handlePublic;
39
+ handlePrivate;
40
+ idleTimer;
41
+ methods = new Map();
42
+ pending = new Map();
43
+ constructor(serviceId, idleTimeout = null, publicBus = true) {
44
+ this.idleTimer = new idle_timer_1.IdleTimer(idleTimeout, this.handleQuit.bind(this));
45
+ this.id = serviceId ?? readServiceIdFromConfig();
46
+ if (exports.isLegacyBus) {
47
+ this.handlePublic = new palmbus_1.default.Handle(this.id, true);
48
+ this.handlePublic.addListener('request', this.handleRequest.bind(this));
49
+ this.handlePublic.addListener('cancel', this.handleCancel.bind(this));
50
+ this.handlePrivate = new palmbus_1.default.Handle(this.id, false);
51
+ this.handlePrivate.addListener('request', this.handleRequest.bind(this));
52
+ this.handlePrivate.addListener('cancel', this.handleCancel.bind(this));
53
+ }
54
+ else {
55
+ const handle = new palmbus_1.default.Handle(this.id);
56
+ handle.addListener('request', this.handleRequest.bind(this));
57
+ handle.addListener('cancel', this.handleCancel.bind(this));
58
+ this.handlePublic = handle;
59
+ this.handlePrivate = handle;
60
+ }
61
+ this.handleOutbound = publicBus ? this.handlePublic : this.handlePrivate;
62
+ }
63
+ register(method, executor, { bus = 'both' } = {}) {
64
+ if (bus === 'public') {
65
+ this.handlePublic.registerMethod(...extractMethodPath(method));
66
+ }
67
+ else if (bus === 'private') {
68
+ this.handlePrivate.registerMethod(...extractMethodPath(method));
69
+ }
70
+ else if (bus === 'both') {
71
+ if (this.handlePublic !== this.handlePrivate) {
72
+ this.handlePublic.registerMethod(...extractMethodPath(method));
73
+ }
74
+ this.handlePrivate.registerMethod(...extractMethodPath(method));
75
+ }
76
+ this.methods.set(method, executor);
77
+ }
78
+ subscribe(uri, params, callback) {
79
+ const subscription = this.handleOutbound.subscribe(uri, JSON.stringify(params));
80
+ subscription.addListener('response', pMessage => {
81
+ const message = message_1.Message.fromPalmMessage(pMessage);
82
+ callback(message.payload);
83
+ });
84
+ return () => subscription.cancel();
85
+ }
86
+ async *stream(uri, params = { subscribe: true }) {
87
+ const sink = new async_utils_1.AsyncSink();
88
+ const cancel = this.subscribe(uri, params, payload => sink.push(payload));
89
+ try {
90
+ yield* sink;
91
+ }
92
+ finally {
93
+ cancel();
94
+ }
95
+ }
96
+ async oneshot(uri, params = {}) {
97
+ const generator = this.stream(uri, params);
98
+ const { value } = await generator.next();
99
+ await generator.return();
100
+ return value;
101
+ }
102
+ unregister() {
103
+ this.pending.clear();
104
+ this.handleOutbound.unregister();
105
+ }
106
+ async drainExecutor(executor, message) {
107
+ if (typeof executor !== 'object') {
108
+ executor = {};
109
+ }
110
+ if (Symbol.asyncIterator in executor) {
111
+ const isSubscription = message.payload.subscribe === true;
112
+ let it;
113
+ do {
114
+ if (message.cancelled) {
115
+ await executor.throw(new Error('Subscription cancelled'));
116
+ break;
117
+ }
118
+ it = await executor.next();
119
+ if (it.done) {
120
+ message.respond({ returnValue: true, ...it.value });
121
+ }
122
+ else if (isSubscription && it.value) {
123
+ message.respond(it.value);
124
+ }
125
+ } while (!it.done);
126
+ return;
127
+ }
128
+ if ('then' in executor) {
129
+ message.respond({ returnValue: true, ...await executor });
130
+ return;
131
+ }
132
+ message.respond({ returnValue: true, ...executor });
133
+ }
134
+ handleRequest(pMessage) {
135
+ const message = message_1.Message.fromPalmMessage(pMessage);
136
+ // essential to receive 'cancel' event
137
+ if (pMessage.isSubscription()) {
138
+ this.handleOutbound.subscriptionAdd(pMessage.uniqueToken(), pMessage);
139
+ this.pending.set(pMessage.uniqueToken(), message);
140
+ }
141
+ Promise.resolve(message)
142
+ .then(async (message) => {
143
+ // Luna won't allow calls to unregistered methods
144
+ const impl = this.methods.get(message.method);
145
+ this.idleTimer.acquire();
146
+ return this.drainExecutor(impl(message.payload, message), message);
147
+ })
148
+ .catch(e => {
149
+ console.error('webos-service: handleRequest:', e);
150
+ message.respond({
151
+ returnValue: false,
152
+ errorCode: -1,
153
+ errorText: e instanceof Error ? e.message : String(e),
154
+ errorStack: 'stack' in e.stack ? String(e.stack) : null,
155
+ });
156
+ })
157
+ .finally(() => {
158
+ this.pending.delete(pMessage.uniqueToken());
159
+ this.idleTimer.release();
160
+ });
161
+ }
162
+ handleCancel(pMessage) {
163
+ const token = pMessage.uniqueToken();
164
+ const message = this.pending.get(token);
165
+ if (message) {
166
+ message.cancelled = true;
167
+ }
168
+ }
169
+ handleQuit() {
170
+ this.handleOutbound.unregister();
171
+ process.nextTick(() => process.exit(0));
172
+ }
173
+ }
174
+ exports.Service = Service;
@@ -0,0 +1,18 @@
1
+ export interface PalmMessage {
2
+ category(): string;
3
+ method(): string;
4
+ isSubscription(): boolean;
5
+ uniqueToken(): string;
6
+ token(): string;
7
+ payload(): string;
8
+ respond(serialized: string): string;
9
+ }
10
+ export declare class Message<T extends Record<string, any>> {
11
+ readonly ls2Message: PalmMessage;
12
+ readonly method: string;
13
+ readonly payload: T;
14
+ cancelled: boolean;
15
+ protected constructor(ls2Message: PalmMessage);
16
+ respond(message: Record<string, any>): void;
17
+ static fromPalmMessage<T extends Record<string, any> = Record<string, any>>(pMessage: PalmMessage): Message<T>;
18
+ }
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Message = void 0;
4
+ function joinCategoryWithMethod(pMessage) {
5
+ let category = pMessage.category();
6
+ // keep / as is; normalize /example -> /example/
7
+ if (!category.endsWith('/')) {
8
+ category += '/';
9
+ }
10
+ return category + pMessage.method();
11
+ }
12
+ class Message {
13
+ ls2Message;
14
+ method;
15
+ payload;
16
+ cancelled = false;
17
+ constructor(ls2Message) {
18
+ this.ls2Message = ls2Message;
19
+ this.method = joinCategoryWithMethod(ls2Message);
20
+ this.payload = JSON.parse(ls2Message.payload());
21
+ }
22
+ respond(message) {
23
+ this.ls2Message.respond(JSON.stringify(message));
24
+ }
25
+ static fromPalmMessage(pMessage) {
26
+ return new Message(pMessage);
27
+ }
28
+ }
29
+ exports.Message = Message;
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@kitsuned/webos-service",
3
+ "version": "1.0.7",
4
+ "license": "MIT",
5
+ "scripts": {
6
+ "build": "tsc"
7
+ },
8
+ "type": "commonjs",
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ "node": "./dist/index.js",
13
+ "types": "./dist/index.d.ts"
14
+ },
15
+ "dependencies": {
16
+ "@kitsuned/async-utils": "^1.0.0"
17
+ },
18
+ "devDependencies": {
19
+ "@types/node": "25.4.0",
20
+ "typescript": "5.9.3"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "LICENSE",
25
+ "README.md",
26
+ "package.json"
27
+ ],
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/kitsuned/webos-service.git"
31
+ },
32
+ "packageManager": "yarn@4.13.0"
33
+ }