libshv-js 3.24.0 → 3.25.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/dist/index.d.ts CHANGED
@@ -5,7 +5,6 @@ export * from './cpon';
5
5
  export * from './json';
6
6
  export * from './rpcmessage';
7
7
  export * from './rpcvalue';
8
- export * from './vue-shv';
9
8
  export * from './ws-client';
10
9
  export * from './zod';
11
10
  export * from './zod-ws-client';
package/dist/index.js CHANGED
@@ -21,7 +21,6 @@ __exportStar(require("./cpon"), exports);
21
21
  __exportStar(require("./json"), exports);
22
22
  __exportStar(require("./rpcmessage"), exports);
23
23
  __exportStar(require("./rpcvalue"), exports);
24
- __exportStar(require("./vue-shv"), exports);
25
24
  __exportStar(require("./ws-client"), exports);
26
25
  __exportStar(require("./zod"), exports);
27
26
  __exportStar(require("./zod-ws-client"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libshv-js",
3
- "version": "3.24.0",
3
+ "version": "3.25.0",
4
4
  "description": "Typescript implementation of libshv",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -34,15 +34,11 @@
34
34
  "./rpcmessage": "./dist/rpcmessage.js",
35
35
  "./rpcvalue": "./dist/rpcvalue.js",
36
36
  "./utils": "./dist/utils.js",
37
- "./vue-shv": "./dist/vue-shv.js",
38
37
  "./ws-client": "./dist/ws-client.js",
39
38
  "./zod": "./dist/zod.js",
40
39
  "./zod-ws-client": "./dist/zod-ws-client.js"
41
40
  },
42
41
  "dependencies": {
43
- "@vueuse/core": "^13.5.0",
44
- "js-pkce": "^2.0.0",
45
- "vue": "^3.5.22",
46
42
  "zod": "^4.0.11"
47
43
  },
48
44
  "devDependencies": {
package/dist/vue-shv.d.ts DELETED
@@ -1,94 +0,0 @@
1
- import { ComputedRef, Ref } from 'vue';
2
- import { type WsClient, type WsClientOptionsLogin } from './ws-client';
3
- import PKCE from 'js-pkce';
4
- import * as z from './zod';
5
- import { type shvMapType } from './rpcvalue';
6
- import { RpcValue } from './rpcvalue';
7
- import { StringGetter } from './utils';
8
- import { ZodMethodHandler } from './zod-ws-client';
9
- type GlobalResourceOptions<ResourceType> = {
10
- shvPath: StringGetter;
11
- method: string;
12
- validator: z.ZodType<ResourceType>;
13
- signalName: string;
14
- signalHandler: (param: RpcValue, resource: Ref<ResourceType | undefined>, reinit: () => void) => void;
15
- };
16
- type VueShvOptions = {
17
- wsUri: StringGetter;
18
- onRequest: WsClientOptionsLogin<ZodMethodHandler>['onRequest'];
19
- azureCodeRedirect?: string;
20
- mountPoint?: string;
21
- };
22
- type ShvLocalStorage = {
23
- azureAccessToken?: string;
24
- azureRedirectTo?: string;
25
- };
26
- type ShvSessionStorage = {
27
- shvLoginUser?: string;
28
- shvLoginPassword?: string;
29
- azureWorkflow?: z.infer<typeof OAuth2AzureWorkflowZod>;
30
- };
31
- declare const OAuth2AzureWorkflowZod: z.ZodCustom<{
32
- type: "oauth2-azure";
33
- authorizeUrl: string;
34
- tokenUrl: string;
35
- clientId: string;
36
- scopes: string | string[];
37
- } & {
38
- [shvMapType]: "map";
39
- }, {
40
- type: "oauth2-azure";
41
- authorizeUrl: string;
42
- tokenUrl: string;
43
- clientId: string;
44
- scopes: string | string[];
45
- } & {
46
- [shvMapType]: "map";
47
- }>;
48
- export declare enum LoginFailureReason {
49
- NoCredentials = 0,
50
- AzureTimedOut = 1,
51
- AzureUnsupported = 2,
52
- CouldntLogin = 3,
53
- LoggedOut = 4
54
- }
55
- type LoginFailure = {
56
- reason: LoginFailureReason;
57
- message?: string;
58
- };
59
- declare const makePkce: (oauthOptions: {
60
- azureCodeRedirect: string;
61
- clientId: string;
62
- authorizeUrl: string;
63
- tokenUrl: string;
64
- scopes: string | string[];
65
- }) => PKCE;
66
- export { makePkce as azure };
67
- export declare function useShv(options: VueShvOptions): {
68
- azureAuth: (redirectTo: string) => Promise<void>;
69
- azureHandlerError: Ref<string, string>;
70
- connected: Ref<"connected" | "connecting" | "disconnected", "connected" | "connecting" | "disconnected">;
71
- displayEmail: Ref<string, string>;
72
- displayFullName: Ref<string, string>;
73
- displayName: Ref<string, string>;
74
- displayPhoto: Ref<string | undefined, string | undefined>;
75
- displayShortName: Ref<string, string>;
76
- getConnection: () => Promise<WsClient>;
77
- handleAzureCode: () => Promise<string | void>;
78
- logContents: Ref<string, string>;
79
- loginFailure: Ref<LoginFailure | undefined, LoginFailure | undefined>;
80
- makeGlobalResource: {
81
- <ResourceType>(options: GlobalResourceOptions<ResourceType>): () => Ref<ResourceType | undefined>;
82
- <ResourceType>(options: GlobalResourceOptions<ResourceType> & {
83
- default: ResourceType;
84
- }): () => ComputedRef<ResourceType>;
85
- };
86
- makeRpcCall: <ResultType>(shvPath: StringGetter, method: string, validator: z.ZodType<ResultType>) => () => Promise<Error | ResultType>;
87
- makeRpcCallParam: <ResultType, ParamType extends RpcValue>(shvPath: StringGetter, method: string, _paramType: z.ZodType<ParamType>, validator: z.ZodType<ResultType>) => (param: ParamType) => Promise<Error | ResultType>;
88
- rpcCall: (shvPath: StringGetter, method: string, params?: RpcValue) => Promise<Error | RpcValue>;
89
- setShvCredentials: (userName: string, password: string) => void;
90
- shvLocalStorage: import("@vueuse/shared").RemovableRef<ShvLocalStorage>;
91
- shvLogout: () => void;
92
- shvSessionStorage: import("@vueuse/shared").RemovableRef<ShvSessionStorage>;
93
- };
94
- export declare const fullReloadHandler: (_param: RpcValue, _resource: unknown, reinit: () => void) => void;
package/dist/vue-shv.js DELETED
@@ -1,441 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.fullReloadHandler = exports.azure = exports.LoginFailureReason = void 0;
40
- exports.useShv = useShv;
41
- const vue_1 = require("vue");
42
- const core_1 = require("@vueuse/core");
43
- const js_pkce_1 = __importDefault(require("js-pkce"));
44
- const z = __importStar(require("./zod"));
45
- const utils_1 = require("./utils");
46
- const zod_ws_client_1 = require("./zod-ws-client");
47
- const OAuth2AzureWorkflowZod = z.map({
48
- type: z.literal('oauth2-azure'),
49
- authorizeUrl: z.string(),
50
- tokenUrl: z.string(),
51
- clientId: z.string(),
52
- scopes: z.string().or(z.array(z.string())),
53
- });
54
- var LoginFailureReason;
55
- (function (LoginFailureReason) {
56
- LoginFailureReason[LoginFailureReason["NoCredentials"] = 0] = "NoCredentials";
57
- LoginFailureReason[LoginFailureReason["AzureTimedOut"] = 1] = "AzureTimedOut";
58
- LoginFailureReason[LoginFailureReason["AzureUnsupported"] = 2] = "AzureUnsupported";
59
- LoginFailureReason[LoginFailureReason["CouldntLogin"] = 3] = "CouldntLogin";
60
- LoginFailureReason[LoginFailureReason["LoggedOut"] = 4] = "LoggedOut";
61
- })(LoginFailureReason || (exports.LoginFailureReason = LoginFailureReason = {}));
62
- const makePkce = (oauthOptions) => {
63
- const pkce = new js_pkce_1.default({
64
- client_id: oauthOptions.clientId,
65
- redirect_uri: (() => {
66
- const url = new URL(globalThis.location.href);
67
- url.pathname = oauthOptions.azureCodeRedirect;
68
- url.search = '';
69
- return url.toString();
70
- })(),
71
- authorization_endpoint: oauthOptions.authorizeUrl,
72
- token_endpoint: oauthOptions.tokenUrl,
73
- requested_scopes: Array.isArray(oauthOptions.scopes) ? oauthOptions.scopes.join(' ') : oauthOptions.scopes,
74
- });
75
- return pkce;
76
- };
77
- exports.azure = makePkce;
78
- function useShv(options) {
79
- const shvLocalStorage = (0, core_1.useLocalStorage)('vue-shv', {});
80
- const shvSessionStorage = (0, core_1.useSessionStorage)('vue-shv', {});
81
- const displayName = (0, vue_1.ref)('Loading...');
82
- const displayShortName = (0, vue_1.ref)('');
83
- const displayFullName = (0, vue_1.ref)('');
84
- const displayEmail = (0, vue_1.ref)('');
85
- const displayPhoto = (0, vue_1.ref)();
86
- const state = {
87
- ws: undefined,
88
- reconnectService: undefined,
89
- };
90
- const waitingForSocket = [];
91
- const resetAzureToken = () => {
92
- shvLocalStorage.value.azureAccessToken = undefined;
93
- };
94
- const azureAvailable = async () => {
95
- const accessToken = shvLocalStorage.value.azureAccessToken;
96
- if (accessToken === undefined) {
97
- return LoginFailureReason.NoCredentials;
98
- }
99
- const resp = await fetch('https://graph.microsoft.com/v1.0/me', {
100
- headers: {
101
- Authorization: `Bearer ${accessToken}`,
102
- },
103
- });
104
- const json = await resp.json();
105
- if (typeof json === 'object' && json !== null) {
106
- if ('displayName' in json && typeof json.displayName === 'string') {
107
- displayName.value = json.displayName;
108
- }
109
- if ('givenName' in json && typeof json.givenName === 'string'
110
- && 'surname' in json && typeof json.surname === 'string') {
111
- const firstName = json.givenName;
112
- const lastname = json.surname;
113
- displayShortName.value = firstName.charAt(0) + lastname.charAt(0);
114
- displayFullName.value = firstName + ' ' + lastname;
115
- }
116
- if ('mail' in json && typeof json.mail === 'string') {
117
- displayEmail.value = json.mail;
118
- }
119
- }
120
- const photo = await fetch('https://graph.microsoft.com/v1.0/me/photos/48x48/$value', {
121
- headers: {
122
- Authorization: `Bearer ${accessToken}`,
123
- },
124
- });
125
- if (photo.ok) {
126
- displayPhoto.value = URL.createObjectURL(await photo.blob());
127
- }
128
- if (!resp.ok) {
129
- resetAzureToken();
130
- }
131
- return resp.ok ? 'azureAvailable' : LoginFailureReason.AzureTimedOut;
132
- };
133
- const debug = (...args) => {
134
- logContents.value = logContents.value + args.join(' ') + '\n';
135
- console.debug(...args);
136
- };
137
- const azureAuth = async (redirectTo) => {
138
- if (options.azureCodeRedirect === undefined) {
139
- throw new Error('Azure redirect URL not set');
140
- }
141
- const { azureCodeRedirect } = options;
142
- shvLocalStorage.value.azureRedirectTo = redirectTo;
143
- const noBrokerSupport = () => {
144
- loginFailure.value = {
145
- reason: LoginFailureReason.AzureUnsupported,
146
- message: 'Broker does not support Azure',
147
- };
148
- };
149
- state.ws = (0, zod_ws_client_1.createZodWsClient)({
150
- logDebug: debug,
151
- wsUri: await (0, utils_1.resolveString)(options.wsUri),
152
- onWorkflows(workflows) {
153
- if (!Array.isArray(workflows)) {
154
- noBrokerSupport();
155
- return;
156
- }
157
- for (const workflow of workflows) {
158
- const parsedWorkflow = OAuth2AzureWorkflowZod.safeParse(workflow);
159
- if (!parsedWorkflow.success) {
160
- continue;
161
- }
162
- shvSessionStorage.value.azureWorkflow = parsedWorkflow.data;
163
- globalThis.location.replace(makePkce({ ...parsedWorkflow.data, azureCodeRedirect }).authorizeUrl());
164
- }
165
- noBrokerSupport();
166
- },
167
- onWorkflowsFailed() {
168
- noBrokerSupport();
169
- },
170
- });
171
- };
172
- const setShvCredentials = (userName, password) => {
173
- shvLogout();
174
- shvSessionStorage.value.shvLoginUser = userName;
175
- shvSessionStorage.value.shvLoginPassword = password;
176
- };
177
- const rpcCall = async (shvPath, method, params) => {
178
- const shv = await getConnection();
179
- return shv.callRpcMethod(await (0, utils_1.resolveString)(shvPath), method, params);
180
- };
181
- const makeRpcCall = (shvPath, method, validator) => async () => {
182
- const resultOrError = await rpcCall(await (0, utils_1.resolveString)(shvPath), method);
183
- if (resultOrError instanceof Error) {
184
- return resultOrError;
185
- }
186
- const parsed = validator.safeParse(resultOrError);
187
- if (!parsed.success) {
188
- return new Error(parsed.error.message);
189
- }
190
- return parsed.data;
191
- };
192
- const makeRpcCallParam = (shvPath, method, _paramType, validator) => async (param) => {
193
- const resultOrError = await rpcCall(await (0, utils_1.resolveString)(shvPath), method, param);
194
- if (resultOrError instanceof Error) {
195
- return resultOrError;
196
- }
197
- const parsed = validator.safeParse(resultOrError);
198
- if (!parsed.success) {
199
- return new Error(parsed.error.message);
200
- }
201
- return parsed.data;
202
- };
203
- const connected = (0, vue_1.ref)('disconnected');
204
- const logContents = (0, vue_1.ref)('');
205
- const shvLogout = () => {
206
- resetAzureToken();
207
- shvSessionStorage.value.shvLoginUser = undefined;
208
- shvSessionStorage.value.shvLoginPassword = undefined;
209
- for (const waiter of waitingForSocket) {
210
- waiter.reject();
211
- }
212
- connected.value = 'disconnected';
213
- waitingForSocket.length = 0;
214
- state.ws?.close();
215
- displayName.value = 'Logged out';
216
- displayPhoto.value = undefined;
217
- state.ws = undefined;
218
- };
219
- const loginFailure = (0, vue_1.ref)();
220
- const getConnection = async () => {
221
- if (connected.value === 'connected') {
222
- return state.ws;
223
- }
224
- return new Promise((resolve, reject) => {
225
- waitingForSocket.push({ resolve, reject });
226
- if (connected.value === 'connecting') {
227
- // We should try to connect only once at the same time.
228
- return;
229
- }
230
- connected.value = 'connecting';
231
- const doConnect = async (user, password, loginType) => {
232
- const wsUri = await (0, utils_1.resolveString)(options.wsUri);
233
- console.log('Connecting to', wsUri);
234
- const makeLoginOptions = () => {
235
- switch (loginType) {
236
- case 'PLAIN':
237
- return {
238
- type: loginType,
239
- user,
240
- password,
241
- };
242
- case 'TOKEN':
243
- return {
244
- type: loginType,
245
- token: `oauth2-azure:${password}`,
246
- };
247
- }
248
- };
249
- state.ws = (0, zod_ws_client_1.createZodWsClient)({
250
- login: makeLoginOptions(),
251
- wsUri,
252
- timeout: 120_000,
253
- mountPoint: options.mountPoint,
254
- logDebug: debug,
255
- onConnected() {
256
- for (const waiter of waitingForSocket) {
257
- waiter.resolve(state.ws);
258
- }
259
- waitingForSocket.length = 0;
260
- console.log('Connected to', wsUri);
261
- connected.value = 'connected';
262
- },
263
- onConnectionFailure(error) {
264
- console.error(`Failed to connect to: ${wsUri}`, error);
265
- shvLogout();
266
- loginFailure.value = {
267
- reason: LoginFailureReason.CouldntLogin,
268
- message: error.message,
269
- };
270
- },
271
- onDisconnected() {
272
- connected.value = 'disconnected';
273
- const RECONNECT_INTERVAL = 3000;
274
- if (shvLocalStorage.value.azureAccessToken !== undefined) {
275
- console.log('Disconnected from', wsUri, 'reconnecting in', RECONNECT_INTERVAL, 'ms');
276
- state.reconnectService = globalThis.setTimeout(async () => {
277
- await getConnection();
278
- }, RECONNECT_INTERVAL);
279
- }
280
- },
281
- onRequest: options.onRequest,
282
- });
283
- };
284
- const shvUser = shvSessionStorage.value.shvLoginUser;
285
- const shvPassword = shvSessionStorage.value.shvLoginPassword;
286
- if (shvUser !== undefined && shvPassword !== undefined) {
287
- displayName.value = shvUser;
288
- displayShortName.value = shvUser[0];
289
- displayFullName.value = shvUser;
290
- doConnect(shvUser, shvPassword, 'PLAIN')
291
- .catch((error) => {
292
- console.error('Unexpected failure in doConnect:', error);
293
- });
294
- return;
295
- }
296
- azureAvailable().then(isAzureAvailable => {
297
- switch (isAzureAvailable) {
298
- case LoginFailureReason.NoCredentials:
299
- case LoginFailureReason.AzureTimedOut:
300
- shvLogout();
301
- loginFailure.value = {
302
- reason: isAzureAvailable,
303
- };
304
- return;
305
- case 'azureAvailable':
306
- break;
307
- }
308
- const accessToken = shvLocalStorage.value.azureAccessToken;
309
- if (accessToken !== undefined) {
310
- doConnect('', accessToken, 'TOKEN')
311
- .catch((error) => {
312
- console.error('Unexpected failure in doConnect:', error);
313
- });
314
- }
315
- }).catch((error) => {
316
- console.error('Failed to fetch verify azure info, redirecting to the login page in 3 seconds', error);
317
- setTimeout(() => {
318
- loginFailure.value = {
319
- reason: LoginFailureReason.CouldntLogin,
320
- message: 'Failed to fetch verify azure info',
321
- };
322
- }, 3000);
323
- });
324
- });
325
- };
326
- function makeGlobalResource(options) {
327
- const resource = (0, vue_1.ref)();
328
- const resourceCall = makeRpcCall(options.shvPath, options.method, options.validator);
329
- const refreshValue = async () => {
330
- const newResource = await resourceCall();
331
- if (newResource instanceof Error) {
332
- return;
333
- }
334
- resource.value = newResource;
335
- };
336
- const initialize = async () => {
337
- const shvPath = await (0, utils_1.resolveString)(options.shvPath);
338
- const resIdentifier = `${shvPath}:${options.method}`;
339
- try {
340
- await refreshValue();
341
- const connection = await getConnection();
342
- await connection.subscribe(`Global-${resIdentifier}:`, shvPath, options.signalName, (_path, _method, param) => {
343
- options.signalHandler(param, resource, async () => refreshValue().catch((error) => {
344
- console.error(`Failed to initialize ${resIdentifier}`, error);
345
- }));
346
- });
347
- }
348
- catch (error) {
349
- console.error(`Failed to initialize ${resIdentifier}`, error);
350
- }
351
- };
352
- let initialized = false;
353
- return () => {
354
- if (!initialized) {
355
- initialized = true;
356
- (0, vue_1.watchEffect)(async () => {
357
- (0, vue_1.onWatcherCleanup)(() => {
358
- initialized = false;
359
- resource.value = undefined;
360
- });
361
- if (connected.value !== 'connected') {
362
- return;
363
- }
364
- const shvPath = await (0, utils_1.resolveString)(options.shvPath);
365
- const resIdentifier = `${shvPath}:${options.method}`;
366
- initialize().catch((error) => {
367
- console.error(`Failed to initialize ${resIdentifier}`, error);
368
- });
369
- });
370
- }
371
- if ('default' in options) {
372
- const defaultValue = options.default;
373
- const withDefault = (0, vue_1.computed)(() => {
374
- if (resource.value === undefined) {
375
- return defaultValue;
376
- }
377
- return resource.value;
378
- });
379
- return withDefault;
380
- }
381
- return resource;
382
- };
383
- }
384
- const azureHandlerError = (0, vue_1.ref)('');
385
- const handleAzureCode = async () => {
386
- if (shvSessionStorage.value.azureWorkflow === undefined) {
387
- azureHandlerError.value = 'Azure error: no active login procedure';
388
- return;
389
- }
390
- if (options.azureCodeRedirect === undefined) {
391
- throw new Error('Azure redirect URL not set');
392
- }
393
- const { azureCodeRedirect } = options;
394
- return makePkce({ ...shvSessionStorage.value.azureWorkflow, azureCodeRedirect }).exchangeForAccessToken(globalThis.location.href).then(resp => {
395
- shvSessionStorage.value.azureWorkflow = undefined;
396
- const token = resp.access_token;
397
- if (token === undefined) {
398
- azureHandlerError.value = 'Couldn\'t authenticate to Azure: unable to exchange access token';
399
- return;
400
- }
401
- // Store the token and remove the code from the query params.
402
- shvLogout();
403
- shvLocalStorage.value.azureAccessToken = token;
404
- const redirectTo = shvLocalStorage.value.azureRedirectTo;
405
- if (redirectTo === undefined) {
406
- azureHandlerError.value = 'Couldn\'t authenticate to Azure: no redirect URL';
407
- return;
408
- }
409
- shvLocalStorage.value.azureRedirectTo = undefined;
410
- return redirectTo;
411
- }).catch((error) => {
412
- azureHandlerError.value = `Couldn't authenticate to Azure: ${JSON.stringify(error)}`;
413
- });
414
- };
415
- return {
416
- azureAuth,
417
- azureHandlerError,
418
- connected,
419
- displayEmail,
420
- displayFullName,
421
- displayName,
422
- displayPhoto,
423
- displayShortName,
424
- getConnection,
425
- handleAzureCode,
426
- logContents,
427
- loginFailure,
428
- makeGlobalResource,
429
- makeRpcCall,
430
- makeRpcCallParam,
431
- rpcCall,
432
- setShvCredentials,
433
- shvLocalStorage,
434
- shvLogout,
435
- shvSessionStorage,
436
- };
437
- }
438
- const fullReloadHandler = (_param, _resource, reinit) => {
439
- reinit();
440
- };
441
- exports.fullReloadHandler = fullReloadHandler;