@truenas/api-client 3.0.3 → 3.0.5

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.js CHANGED
@@ -367,766 +367,153 @@ var TrueNasApi = class {
367
367
  }
368
368
  };
369
369
 
370
- // src/enums/truenas-auth-mechanism.enum.ts
371
- var TrueNasAuthMechanism = /* @__PURE__ */ ((TrueNasAuthMechanism2) => {
372
- TrueNasAuthMechanism2["ApiKey"] = "API_KEY_PLAIN";
373
- TrueNasAuthMechanism2["Password"] = "PASSWORD_PLAIN";
374
- TrueNasAuthMechanism2["Otp"] = "OTP_TOKEN";
375
- TrueNasAuthMechanism2["Token"] = "TOKEN_PLAIN";
376
- return TrueNasAuthMechanism2;
377
- })(TrueNasAuthMechanism || {});
370
+ // src/generated/v25_10_0/index.ts
371
+ var v25_10_0_exports = {};
372
+ __export(v25_10_0_exports, {
373
+ ACLTemplateEntryAcltypeInput: () => ACLTemplateEntryAcltypeInput,
374
+ Aclmode: () => Aclmode,
375
+ Acltype: () => Acltype,
376
+ Action: () => Action,
377
+ Advpowermgmt: () => Advpowermgmt,
378
+ Algorithm: () => Algorithm,
379
+ AppContainerDetailsStateInput: () => AppContainerDetailsStateInput,
380
+ Atime: () => Atime,
381
+ Authenticator: () => Authenticator,
382
+ Authmethod: () => Authmethod,
383
+ Autotrim: () => Autotrim,
384
+ Basic: () => Basic,
385
+ Blocksize: () => Blocksize,
386
+ Bootloader: () => Bootloader,
387
+ Casesensitivity: () => Casesensitivity,
388
+ CloudBackupSnapshotItemType: () => CloudBackupSnapshotItemType,
389
+ CloudSyncCreateDirection: () => CloudSyncCreateDirection,
390
+ CloudSyncCreateDirectionInput: () => CloudSyncCreateDirectionInput,
391
+ CloudTaskAttributesEncryptionInput: () => CloudTaskAttributesEncryptionInput,
392
+ Code: () => Code,
393
+ Compression: () => Compression,
394
+ CorePingRemoteTypeInput: () => CorePingRemoteTypeInput,
395
+ Credentials: () => Credentials,
396
+ DeviceGetInfoOtherTypeInput: () => DeviceGetInfoOtherTypeInput,
397
+ DiskDetailsTypeInput: () => DiskDetailsTypeInput,
398
+ DiskWipeModeInput: () => DiskWipeModeInput,
399
+ DockerStatusInfoStatusInput: () => DockerStatusInfoStatusInput,
400
+ Enclosure2SetSlotStatusStatusInput: () => Enclosure2SetSlotStatusStatusInput,
401
+ Encryption: () => Encryption,
402
+ Endpoint: () => Endpoint,
403
+ Exec: () => Exec,
404
+ Feature: () => Feature,
405
+ FilesystemDirEntryType: () => FilesystemDirEntryType,
406
+ Function: () => Function,
407
+ GetDisplayDeviceType: () => GetDisplayDeviceType,
408
+ Hddstandby: () => Hddstandby,
409
+ InitShutdownScriptCreateType: () => InitShutdownScriptCreateType,
410
+ InitShutdownScriptCreateTypeInput: () => InitShutdownScriptCreateTypeInput,
411
+ InterfaceCreateAliasTypeInput: () => InterfaceCreateAliasTypeInput,
412
+ InterfaceCreateTypeInput: () => InterfaceCreateTypeInput,
413
+ Iotype: () => Iotype,
414
+ IpmiChassisIdentifyVerb: () => IpmiChassisIdentifyVerb,
415
+ IscsiExtentCreateType: () => IscsiExtentCreateType,
416
+ IscsiExtentCreateTypeInput: () => IscsiExtentCreateTypeInput,
417
+ IscsiTargetCreateMode: () => IscsiTargetCreateMode,
418
+ IscsiTargetCreateModeInput: () => IscsiTargetCreateModeInput,
419
+ KeychainCredentialEntryType: () => KeychainCredentialEntryType,
420
+ KeychainCredentialEntryTypeInput: () => KeychainCredentialEntryTypeInput,
421
+ Level: () => Level,
422
+ NFS4ACEType: () => NFS4ACEType,
423
+ NFS4ACETypeInput: () => NFS4ACETypeInput,
424
+ Name: () => Name,
425
+ Policy: () => Policy,
426
+ PoolCreateChecksum: () => PoolCreateChecksum,
427
+ PoolCreateDeduplication: () => PoolCreateDeduplication,
428
+ PoolCreateTopologyDataVdevDRAIDTypeInput: () => PoolCreateTopologyDataVdevDRAIDTypeInput,
429
+ PoolDatasetCreateFilesystemAcltypeInput: () => PoolDatasetCreateFilesystemAcltypeInput,
430
+ PoolDatasetCreateFilesystemChecksum: () => PoolDatasetCreateFilesystemChecksum,
431
+ PoolDatasetCreateFilesystemDeduplication: () => PoolDatasetCreateFilesystemDeduplication,
432
+ PoolDatasetCreateFilesystemReadonlyInput: () => PoolDatasetCreateFilesystemReadonlyInput,
433
+ PoolDatasetDeleteResult: () => PoolDatasetDeleteResult,
434
+ PoolScanStateInput: () => PoolScanStateInput,
435
+ Protocol: () => Protocol,
436
+ Purpose: () => Purpose,
437
+ Readonly: () => Readonly,
438
+ ReplicationCountEligibleManualSnapshotsTransportInput: () => ReplicationCountEligibleManualSnapshotsTransportInput,
439
+ ReplicationCreateReadonlyInput: () => ReplicationCreateReadonlyInput,
440
+ Resolution: () => Resolution,
441
+ Rpm: () => Rpm,
442
+ RsyncTaskCreateDirection: () => RsyncTaskCreateDirection,
443
+ RsyncTaskCreateDirectionInput: () => RsyncTaskCreateDirectionInput,
444
+ RsyncTaskCreateMode: () => RsyncTaskCreateMode,
445
+ RsyncTaskCreateModeInput: () => RsyncTaskCreateModeInput,
446
+ SMBEntryEncryptionInput: () => SMBEntryEncryptionInput,
447
+ STIGType: () => STIGType,
448
+ Schema: () => Schema,
449
+ Security: () => Security,
450
+ Serialspeed: () => Serialspeed,
451
+ ServiceControlVerb: () => ServiceControlVerb,
452
+ SharingSMBEntryPurposeInput: () => SharingSMBEntryPurposeInput,
453
+ SharingSMBEntryPurposeInput2: () => SharingSMBEntryPurposeInput2,
454
+ Shutdown: () => Shutdown,
455
+ Snapdev: () => Snapdev,
456
+ Snapdir: () => Snapdir,
457
+ Source: () => Source,
458
+ SourceInput: () => SourceInput,
459
+ State: () => State,
460
+ Status: () => Status,
461
+ SupportNewTicketCommunityTypeInput: () => SupportNewTicketCommunityTypeInput,
462
+ Sync: () => Sync,
463
+ SyslogServerTransportInput: () => SyslogServerTransportInput,
464
+ Sysloglevel: () => Sysloglevel,
465
+ SystemProductTypeResult: () => SystemProductTypeResult,
466
+ SystemStateResult: () => SystemStateResult,
467
+ Tag: () => Tag,
468
+ Target: () => Target,
469
+ Time: () => Time,
470
+ Transport: () => Transport,
471
+ TruecommandConfigChangedEventFieldsStatus: () => TruecommandConfigChangedEventFieldsStatus,
472
+ TruecommandConfigChangedEventFieldsStatusInput: () => TruecommandConfigChangedEventFieldsStatusInput,
473
+ TunableCreateType: () => TunableCreateType,
474
+ TunableCreateTypeInput: () => TunableCreateTypeInput,
475
+ UPSEntryMode: () => UPSEntryMode,
476
+ UPSEntryModeInput: () => UPSEntryModeInput,
477
+ Unixcharset: () => Unixcharset,
478
+ Username: () => Username,
479
+ VMDiskDeviceType: () => VMDiskDeviceType,
480
+ VMDiskDeviceTypeInput: () => VMDiskDeviceTypeInput,
481
+ VMWareEntryStateStateInput: () => VMWareEntryStateStateInput,
482
+ VMWareMatchDatastoresWithDatasetsResultFilesystemType: () => VMWareMatchDatastoresWithDatasetsResultFilesystemType,
483
+ Vendor: () => Vendor,
484
+ Volblocksize: () => Volblocksize,
485
+ When: () => When,
486
+ ZfsTierRewriteJobEntryStatusInput: () => ZfsTierRewriteJobEntryStatusInput
487
+ });
378
488
 
379
- // src/errors/auth.errors.ts
380
- var AuthErrorCode = /* @__PURE__ */ ((AuthErrorCode2) => {
381
- AuthErrorCode2["PasswordAuthFailed"] = "PASSWORD_AUTH_FAILED";
382
- AuthErrorCode2["OtpAuthFailed"] = "OTP_AUTH_FAILED";
383
- AuthErrorCode2["ApiKeyAuthFailed"] = "API_KEY_AUTH_FAILED";
384
- AuthErrorCode2["FullAdminRequired"] = "FULL_ADMIN_REQUIRED";
385
- return AuthErrorCode2;
386
- })(AuthErrorCode || {});
387
- var AuthError = class _AuthError extends Error {
388
- constructor(code, message) {
389
- super(message);
390
- this.code = code;
391
- this.name = "AuthError";
392
- Object.setPrototypeOf(this, _AuthError.prototype);
393
- }
489
+ // src/generated/v25_10_0/api-types.ts
490
+ var Aclmode = {
491
+ Passthrough: "PASSTHROUGH",
492
+ Restricted: "RESTRICTED",
493
+ Discard: "DISCARD",
494
+ Inherit: "INHERIT"
394
495
  };
395
-
396
- // src/auth/truenas-authenticator.ts
397
- var throwOnAuthenticationFailure = (code, message) => switchMap((response) => {
398
- if (response.response_type === "AUTH_ERR" /* AuthErr */) {
399
- return throwError(() => new AuthError(code, message));
400
- }
401
- return of(response);
402
- });
403
- var TrueNasAuthenticator = class _TrueNasAuthenticator {
404
- constructor(connection) {
405
- this.connection = connection;
406
- // in seconds (5 minutes)
407
- /**
408
- * whether or not the system is currently authenticated and accessible.
409
- * this is a `BehaviorSubject` instead of a signal, since we use its `getValue` method
410
- * throughout a lot of the codebase.
411
- */
412
- this.authenticated$ = new BehaviorSubject(false);
413
- /**
414
- * `true` when the system is currently being authenticated to, and `false` otherwise.
415
- * does not indicate whatsoever if authentication is successful or not, just whether the process
416
- * is ongoing.
417
- */
418
- this.authenticating$ = new BehaviorSubject(false);
419
- this.credentials = { username: "", password: "", key: "" };
420
- this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
421
- this.connection.opened.pipe(
422
- filter(
423
- (isOpen) => !!(isOpen && this.credentials?.username && (this.credentials.password || this.credentials.key))
424
- ),
425
- switchMap(() => {
426
- if (this.credentials.password) {
427
- return this.loginWithUserPass(
428
- this.credentials.username,
429
- this.credentials.password
430
- );
431
- }
432
- return this.loginWithApiKey({
433
- username: this.credentials.username,
434
- key: this.credentials.key
435
- });
436
- })
437
- ).subscribe();
438
- connection.closed.subscribe(() => {
439
- this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
440
- this.authenticated$.next(false);
441
- });
442
- }
443
- static {
444
- this.DefaultSessionLifetime = 300;
445
- }
446
- loginWithUserPass(username, password) {
447
- const message = createJsonRpcMessage("auth.login_ex", [
448
- {
449
- mechanism: "PASSWORD_PLAIN" /* Password */,
450
- username,
451
- password
452
- }
453
- ]);
454
- this.authenticating$.next(true);
455
- this.connection.send(message);
456
- const messageId = message.id ?? "";
457
- return this.connection.messages().pipe(
458
- withId(messageId),
459
- map((msg) => {
460
- if (msg.error) {
461
- const errorMessage = getApiErrorMessage(
462
- msg.error,
463
- "Authentication failed"
464
- );
465
- throw new Error(errorMessage);
466
- }
467
- return msg.result;
468
- }),
469
- throwOnAuthenticationFailure(
470
- "PASSWORD_AUTH_FAILED" /* PasswordAuthFailed */,
471
- "TrueNAS authentication failed. Please verify your TrueNAS user credentials and try again."
472
- ),
473
- tap((res) => {
474
- if (res.response_type === "SUCCESS" /* Success */) {
475
- if (res.user_info?.privilege.roles.$set.includes("FULL_ADMIN" /* FullAdmin */)) {
476
- this.credentials.username = username;
477
- this.credentials.password = password;
478
- this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
479
- this.authenticated$.next(true);
480
- } else {
481
- this.logout();
482
- this.authenticated$.next(false);
483
- throw new AuthError(
484
- "FULL_ADMIN_REQUIRED" /* FullAdminRequired */,
485
- "User account must have full admin privileges"
486
- );
487
- }
488
- }
489
- }),
490
- finalize(() => {
491
- this.authenticating$.next(false);
492
- }),
493
- take(1)
494
- );
495
- }
496
- loginWithOtp(code) {
497
- const message = createJsonRpcMessage("auth.login_ex", [
498
- {
499
- mechanism: "OTP_TOKEN" /* Otp */,
500
- otp_token: code
501
- }
502
- ]);
503
- this.authenticating$.next(true);
504
- this.connection.send(message);
505
- const messageId = message.id ?? "";
506
- return this.connection.messages().pipe(
507
- withId(messageId),
508
- map((msg) => {
509
- if (msg.error) {
510
- const errorMessage = getApiErrorMessage(
511
- msg.error,
512
- "Authentication failed"
513
- );
514
- throw new Error(errorMessage);
515
- }
516
- return msg.result;
517
- }),
518
- tap((res) => {
519
- if (res?.response_type === "SUCCESS" /* Success */) {
520
- this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
521
- this.authenticated$.next(true);
522
- }
523
- }),
524
- throwOnAuthenticationFailure(
525
- "OTP_AUTH_FAILED" /* OtpAuthFailed */,
526
- "TrueNAS authentication failed. Please verify your one-time passcode and try again."
527
- ),
528
- finalize(() => {
529
- this.authenticating$.next(false);
530
- }),
531
- take(1)
532
- );
533
- }
534
- loginWithApiKey(credentials) {
535
- const { username, key } = credentials;
536
- const message = createJsonRpcMessage("auth.login_ex", [
537
- {
538
- mechanism: "API_KEY_PLAIN" /* ApiKey */,
539
- username,
540
- api_key: key
541
- }
542
- ]);
543
- this.authenticating$.next(true);
544
- this.connection.send(message);
545
- const messageId = message.id ?? "";
546
- return this.connection.messages().pipe(
547
- withId(messageId),
548
- map((msg) => {
549
- if (msg.error) {
550
- const errorMessage = getApiErrorMessage(
551
- msg.error,
552
- "Authentication failed"
553
- );
554
- throw new Error(errorMessage);
555
- }
556
- return msg.result;
557
- }),
558
- throwOnAuthenticationFailure(
559
- "API_KEY_AUTH_FAILED" /* ApiKeyAuthFailed */,
560
- "TrueNAS authentication failed. Has the TrueNAS Connect API key been removed from your TrueNAS server?"
561
- ),
562
- tap((res) => {
563
- this.credentials.username = username;
564
- this.credentials.key = key;
565
- this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
566
- this.authenticated$.next(true);
567
- }),
568
- finalize(() => {
569
- this.authenticating$.next(false);
570
- }),
571
- take(1)
572
- );
573
- }
574
- newApiKey(username) {
575
- const message = createJsonRpcMessage("api_key.create", [
576
- { name: `tnc-${randomUUID()}`, username }
577
- ]);
578
- this.connection.send(message);
579
- const messageId = message.id ?? "";
580
- return this.connection.messages().pipe(
581
- withId(messageId),
582
- map((msg) => {
583
- if (msg.error) {
584
- const errorMessage = getApiErrorMessage(
585
- msg.error,
586
- "Failed to create API key"
587
- );
588
- throw new Error(errorMessage);
589
- }
590
- return msg.result;
591
- }),
592
- take(1)
593
- );
594
- }
595
- logout() {
596
- const message = createJsonRpcMessage("auth.logout");
597
- this.connection.send(message);
598
- const messageId = message.id ?? "";
599
- return this.connection.messages().pipe(
600
- withId(messageId),
601
- map((msg) => {
602
- if (msg.error) {
603
- return false;
604
- }
605
- return msg.result;
606
- }),
607
- tap((success) => {
608
- this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
609
- this.authenticated$.next(!success);
610
- }),
611
- take(1)
612
- );
613
- }
496
+ var ACLTemplateEntryAcltypeInput = {
497
+ Nfs4: "NFS4",
498
+ Posix1e: "POSIX1E"
614
499
  };
615
-
616
- // src/logger.ts
617
- var consoleLogger = {
618
- trace: (message, ...args) => console.trace(message, ...args),
619
- debug: (message, ...args) => console.debug(message, ...args),
620
- info: (message, ...args) => console.info(message, ...args),
621
- warn: (message, ...args) => console.warn(message, ...args),
622
- error: (message, ...args) => console.error(message, ...args)
500
+ var Acltype = {
501
+ Nfs4: "NFS4",
502
+ Posix1e: "POSIX1E"
623
503
  };
624
- var noop = () => void 0;
625
- var noopLogger = {
626
- trace: noop,
627
- debug: noop,
628
- info: noop,
629
- warn: noop,
630
- error: noop
504
+ var Action = {
505
+ Start: "START",
506
+ Stop: "STOP",
507
+ Pause: "PAUSE"
631
508
  };
632
-
633
- // src/utils/truenas-connection.utils.ts
634
- function isHttpStatusError(reason) {
635
- return ["404", "502", "503"].some((code) => reason.includes(code));
636
- }
637
- function getHttpError(reason) {
638
- if (reason.includes("404")) {
639
- return "API endpoint not found - System may not support versioned API";
640
- }
641
- if (reason.includes("502")) {
642
- return "Bad Gateway - System may be starting up";
643
- }
644
- if (reason.includes("503")) {
645
- return "Service Unavailable - System may be overloaded";
646
- }
647
- return "";
648
- }
649
- function getWebSocketError(code) {
650
- switch (code) {
651
- case 1e3:
652
- return "Connection closed normally";
653
- case 1001:
654
- return "Server is shutting down or restarting";
655
- case 1002:
656
- return "Protocol error - Invalid WebSocket communication";
657
- case 1003:
658
- return "Unsupported data format received";
659
- case 1006:
660
- return "Connection lost unexpectedly - Check network connectivity";
661
- case 1007:
662
- return "Invalid data received from server";
663
- case 1008:
664
- return "Connection terminated due to policy violation";
665
- case 1009:
666
- return "Message size exceeded server limits";
667
- case 1011:
668
- return "Server encountered an internal error";
669
- case 1012:
670
- return "Service is restarting";
671
- case 1013:
672
- return "Server temporarily overloaded - Try again later";
673
- case 1015:
674
- return "TLS/Certificate error - Certificate may be expired";
675
- default:
676
- return "Network connection failed - Check IP address and connectivity";
677
- }
678
- }
679
- var TrueNasSocket = class {
680
- constructor(config) {
681
- this.config = config;
682
- this.socket = webSocket(this.config);
683
- }
684
- messages() {
685
- return this.socket;
686
- }
687
- next(msg) {
688
- this.socket.next(msg);
689
- }
690
- complete() {
691
- this.socket.complete();
692
- }
693
- };
694
-
695
- // src/connection/truenas-connection.ts
696
- var tenSeconds = 10 * 1e3;
697
- var twentySeconds = 20 * 1e3;
698
- var TrueNasConnection = class {
699
- constructor(initialEnabled, hostnames, systemUuid, websocketPath, systemName, retryDelay = tenSeconds, maxRetry = 3, logger = noopLogger) {
700
- this.hostnames = hostnames;
701
- this.systemUuid = systemUuid;
702
- this.websocketPath = websocketPath;
703
- this.systemName = systemName;
704
- this.retryDelay = retryDelay;
705
- this.maxRetry = maxRetry;
706
- this.logger = logger;
707
- // compatibility properties
708
- this.opened = new BehaviorSubject(false);
709
- this.closed = new Subject();
710
- this.hostname = new BehaviorSubject("");
711
- this.connectionAttempts = new BehaviorSubject(0);
712
- this.lastErrorMessage = new BehaviorSubject(null);
713
- /**
714
- * emits when the connection is manually closed.
715
- */
716
- this.closeConnection = new Subject();
717
- /**
718
- * the connection only establishes a socket while this gate is `true`. consumers
719
- * flip it via `setEnabled()` (the app maps `SystemState.Active -> true`).
720
- */
721
- this.enabled$ = new BehaviorSubject(false);
722
- /**
723
- * observable which emits the current gate value and only emits again when it changes.
724
- */
725
- this.enabledChange$ = this.enabled$.pipe(distinctUntilChanged());
726
- /**
727
- * observable that handles the entire connection lifecycle.
728
- */
729
- this.connection$ = this.enabledChange$.pipe(
730
- switchMap((enabled) => {
731
- if (enabled) {
732
- return this.connect().pipe(
733
- map((conn) => makeActiveConnection(conn.ws, conn.hostname))
734
- );
735
- }
736
- return of(closedConnection);
737
- }),
738
- switchMap((connection) => {
739
- if (connection.state !== "active") {
740
- return of(connection);
741
- }
742
- const initMessage = createJsonRpcMessage("core.set_options", [
743
- { legacy_jobs: false }
744
- ]);
745
- connection.ws.next(initMessage);
746
- return connection.ws.messages().pipe(
747
- filter((msg) => msg.id === initMessage.id),
748
- take(1),
749
- map(() => connection)
750
- );
751
- }),
752
- // in the event of an error, do two things:
753
- // 1. emit an errored connection downstream to inform consumers that
754
- // the connection is dead.
755
- // 2. re-throw an error so the downstream `retry` will re-subscribe.
756
- catchError$1((err) => {
757
- this.logger.error("All connections failed - retrying", { message: err?.message, hostname: err?.hostname });
758
- return concat(
759
- of(makeConnectionError(err.message, err.hostname)),
760
- // since this error will immediately get caught by `retry` there's no reason to build a real error.
761
- throwError(() => null)
762
- );
763
- }),
764
- retry(),
765
- // start with a closed connection.
766
- startWith(closedConnection),
767
- // prevent multiple subscriptions from re-evaluating the entire pipeline.
768
- shareReplay$1({ bufferSize: 1, refCount: false }),
769
- takeUntil(this.closeConnection)
770
- );
771
- /**
772
- * observable which is either an instance of the current `TrueNasSocket` used for the connection
773
- * or `null` if the connection is closed or errored for any reason.
774
- */
775
- this.ws$ = this.connection$.pipe(
776
- map((conn) => conn.state === "active" ? conn.ws : null)
777
- );
778
- /**
779
- * current hostname we used to build the URL for this connection.
780
- */
781
- this.hostname$ = this.connection$.pipe(
782
- map((conn) => conn.state === "active" ? conn.hostname : null)
783
- );
784
- /**
785
- * emits error messages from the connection pipeline. this is used to derive the
786
- * corresponding compatibility property.
787
- */
788
- this.lastErrorMessage$ = this.connection$.pipe(
789
- map((conn) => conn.state === "error" ? conn.message : null)
790
- );
791
- /**
792
- * emits when the connection state *changes*, so it'll never emit `true` twice
793
- * in a row nor `false` twice in a row.
794
- */
795
- this.opened$ = this.connection$.pipe(
796
- map((conn) => conn.state),
797
- distinctUntilChanged(),
798
- map((state) => state === "active")
799
- );
800
- /**
801
- * emits when the connection state goes from open to closed.
802
- */
803
- this.closed$ = this.connection$.pipe(
804
- map((conn) => conn.state),
805
- distinctUntilChanged(),
806
- filter((state) => state === "closed" || state === "error"),
807
- map(() => {
808
- })
809
- );
810
- /**
811
- * whether to display a connection error to the user — the **live** signal.
812
- *
813
- * `true` only while `connection$` is currently a `ConnectionError`, meaning the entire race +
814
- * retry cycle has been exhausted for all hostnames right now; it flips back to `false` once a
815
- * connection is re-established. individual socket losses during a race are expected and not surfaced.
816
- *
817
- * NOTE: this is NOT the same as the `hasExhaustedRetries()` method, which is a **cumulative**
818
- * snapshot (see there). The two can disagree — prefer this observable for "is the connection
819
- * errored right now?".
820
- */
821
- this.hasConnectionError$ = this.connection$.pipe(
822
- map((conn) => conn.state === "error"),
823
- takeUntil(this.closeConnection)
824
- );
825
- /**
826
- * observable which always emits messages from the current socket.
827
- */
828
- this.messages$ = this.ws$.pipe(
829
- filter((ws) => ws !== null),
830
- switchMap((ws) => ws.messages().pipe(
831
- catchError$1(() => EMPTY)
832
- ))
833
- );
834
- combineLatest([
835
- interval(twentySeconds),
836
- this.ws$
837
- ]).pipe(
838
- takeUntil(this.closeConnection)
839
- ).subscribe(([, ws]) => {
840
- if (ws) {
841
- const pingMessage = createJsonRpcMessage("core.ping");
842
- ws.next(pingMessage);
843
- }
844
- });
845
- this.opened$.subscribe((val) => this.opened.next(val));
846
- this.closed$.subscribe(() => this.closed.next());
847
- this.hostname$.pipe(filter(Boolean)).subscribe((name) => this.hostname.next(name));
848
- this.ws$.pipe(filter(Boolean)).subscribe((ws) => this.ws = ws);
849
- this.lastErrorMessage$.subscribe((msg) => this.lastErrorMessage.next(msg));
850
- this.enabled$.next(initialEnabled);
851
- }
852
- /**
853
- * whether the connection has exhausted its retries — the **cumulative** snapshot, read
854
- * synchronously. (Formerly `hasConnectionError()`; renamed to disambiguate it from the
855
- * live `hasConnectionError$` observable, with which it can disagree.)
856
- *
857
- * `true` when the lifetime `connectionAttempts` count exceeds `hostnames.length * maxRetry`,
858
- * OR when an error message is currently set. Ported from the source (tncui) behavior.
859
- */
860
- hasExhaustedRetries() {
861
- const attemptsExhausted = this.connectionAttempts.value > this.hostnames.length * this.maxRetry;
862
- const hasErrorMessage = this.lastErrorMessage.value !== null;
863
- return attemptsExhausted || hasErrorMessage;
864
- }
865
- /**
866
- * enables or disables the connection gate. the app calls this when its `SystemState`
867
- * changes (mapping `SystemState.Active -> true`, everything else -> `false`).
868
- */
869
- setEnabled(enabled) {
870
- this.enabled$.next(enabled);
871
- }
872
- /**
873
- * compatibility method which just returns the public `messages$` observable.
874
- * this is used in a few places in the codebase that relied upon the old implementation.
875
- */
876
- messages() {
877
- return this.messages$;
878
- }
879
- /**
880
- * sends a message over the current websocket OR queues it to send once
881
- * the next websocket is opened. messages sent via `send` will not be lost until after
882
- * the next `closed$` emission.
883
- */
884
- send(message) {
885
- return this.ws$.pipe(
886
- filter((ws) => ws !== null),
887
- take(1)
888
- ).subscribe((ws) => ws.next(message));
889
- }
890
- /**
891
- * manually closes this connection and prevents it from retrying/opening any more.
892
- */
893
- close() {
894
- this.closeConnection.next();
895
- this.closeConnection.complete();
896
- }
897
- /**
898
- * helper method which creates an `Observable` which emits an `ActiveConnection`
899
- * after it establishes a connection to the given hostname. the observable will emit an
900
- * error if the connection is never established and will not complete until unsubscribed from or closed.
901
- */
902
- createSocket(hostname) {
903
- const url = `wss://${hostname}${this.websocketPath}`;
904
- let hasOpened = false;
905
- return new Observable((subscriber) => {
906
- const ws = new TrueNasSocket({
907
- url,
908
- openObserver: {
909
- next: () => {
910
- hasOpened = true;
911
- this.connectionAttempts.next(0);
912
- subscriber.next({ ws, hostname });
913
- }
914
- },
915
- closeObserver: {
916
- next: (event) => {
917
- const reason = event.reason || "";
918
- let errorMessage;
919
- if (isHttpStatusError(reason)) {
920
- errorMessage = getHttpError(reason);
921
- } else {
922
- errorMessage = getWebSocketError(event.code);
923
- }
924
- this.connectionAttempts.next(this.connectionAttempts.value + 1);
925
- subscriber.error(makeConnectionError(errorMessage, hostname));
926
- }
927
- }
928
- });
929
- const startupSub = ws.socket.subscribe({
930
- error: () => {
931
- }
932
- });
933
- return () => {
934
- startupSub.unsubscribe();
935
- ws.complete();
936
- };
937
- }).pipe(
938
- // retry logic:
939
- // * if a connection is not established in 10 seconds, consider that an error
940
- timeout({ first: tenSeconds }),
941
- retry({
942
- // * while still *establishing*: wait `retryDelay` before trying again, giving up
943
- // after `maxRetry` retries.
944
- count: this.maxRetry,
945
- // * we use a custom `delay` function here to ensure no retries are performed
946
- // once a socket is *opened*.
947
- // basically: a later death must propagate out rather than being retried
948
- // so it can be handled by the `connection$` observable.
949
- delay: (error) => {
950
- if (hasOpened) {
951
- return throwError(() => error);
952
- }
953
- return timer(this.retryDelay);
954
- }
955
- })
956
- );
957
- }
958
- /**
959
- * helper function which actually performs the parallel connection `race`.
960
- */
961
- connect() {
962
- return race(
963
- this.hostnames.map(this.createSocket.bind(this))
964
- ).pipe(
965
- tap((conn) => this.logger.debug(`TrueNas socket opened to ${conn.hostname}.`)),
966
- takeUntil(this.closeConnection)
967
- );
968
- }
969
- };
970
- var makeActiveConnection = (ws, hostname) => ({
971
- ws,
972
- hostname,
973
- state: "active"
974
- });
975
- var makeConnectionError = (message, hostname) => ({
976
- name: "ConnectionError",
977
- message,
978
- hostname,
979
- state: "error"
980
- });
981
- var closedConnection = { state: "closed" };
982
-
983
- // src/generated/v25_10_0/index.ts
984
- var v25_10_0_exports = {};
985
- __export(v25_10_0_exports, {
986
- ACLTemplateEntryAcltypeInput: () => ACLTemplateEntryAcltypeInput,
987
- Aclmode: () => Aclmode,
988
- Acltype: () => Acltype,
989
- Action: () => Action,
990
- Advpowermgmt: () => Advpowermgmt,
991
- Algorithm: () => Algorithm,
992
- AppContainerDetailsStateInput: () => AppContainerDetailsStateInput,
993
- Atime: () => Atime,
994
- Authenticator: () => Authenticator,
995
- Authmethod: () => Authmethod,
996
- Autotrim: () => Autotrim,
997
- Basic: () => Basic,
998
- Blocksize: () => Blocksize,
999
- Bootloader: () => Bootloader,
1000
- Casesensitivity: () => Casesensitivity,
1001
- CloudBackupSnapshotItemType: () => CloudBackupSnapshotItemType,
1002
- CloudSyncCreateDirection: () => CloudSyncCreateDirection,
1003
- CloudSyncCreateDirectionInput: () => CloudSyncCreateDirectionInput,
1004
- CloudTaskAttributesEncryptionInput: () => CloudTaskAttributesEncryptionInput,
1005
- Code: () => Code,
1006
- Compression: () => Compression,
1007
- CorePingRemoteTypeInput: () => CorePingRemoteTypeInput,
1008
- Credentials: () => Credentials,
1009
- DeviceGetInfoOtherTypeInput: () => DeviceGetInfoOtherTypeInput,
1010
- DiskDetailsTypeInput: () => DiskDetailsTypeInput,
1011
- DiskWipeModeInput: () => DiskWipeModeInput,
1012
- DockerStatusInfoStatusInput: () => DockerStatusInfoStatusInput,
1013
- Enclosure2SetSlotStatusStatusInput: () => Enclosure2SetSlotStatusStatusInput,
1014
- Encryption: () => Encryption,
1015
- Endpoint: () => Endpoint,
1016
- Exec: () => Exec,
1017
- Feature: () => Feature,
1018
- FilesystemDirEntryType: () => FilesystemDirEntryType,
1019
- Function: () => Function,
1020
- GetDisplayDeviceType: () => GetDisplayDeviceType,
1021
- Hddstandby: () => Hddstandby,
1022
- InitShutdownScriptCreateType: () => InitShutdownScriptCreateType,
1023
- InitShutdownScriptCreateTypeInput: () => InitShutdownScriptCreateTypeInput,
1024
- InterfaceCreateAliasTypeInput: () => InterfaceCreateAliasTypeInput,
1025
- InterfaceCreateTypeInput: () => InterfaceCreateTypeInput,
1026
- Iotype: () => Iotype,
1027
- IpmiChassisIdentifyVerb: () => IpmiChassisIdentifyVerb,
1028
- IscsiExtentCreateType: () => IscsiExtentCreateType,
1029
- IscsiExtentCreateTypeInput: () => IscsiExtentCreateTypeInput,
1030
- IscsiTargetCreateMode: () => IscsiTargetCreateMode,
1031
- IscsiTargetCreateModeInput: () => IscsiTargetCreateModeInput,
1032
- KeychainCredentialEntryType: () => KeychainCredentialEntryType,
1033
- KeychainCredentialEntryTypeInput: () => KeychainCredentialEntryTypeInput,
1034
- Level: () => Level,
1035
- NFS4ACEType: () => NFS4ACEType,
1036
- NFS4ACETypeInput: () => NFS4ACETypeInput,
1037
- Name: () => Name,
1038
- Policy: () => Policy,
1039
- PoolCreateChecksum: () => PoolCreateChecksum,
1040
- PoolCreateDeduplication: () => PoolCreateDeduplication,
1041
- PoolCreateTopologyDataVdevDRAIDTypeInput: () => PoolCreateTopologyDataVdevDRAIDTypeInput,
1042
- PoolDatasetCreateFilesystemAcltypeInput: () => PoolDatasetCreateFilesystemAcltypeInput,
1043
- PoolDatasetCreateFilesystemChecksum: () => PoolDatasetCreateFilesystemChecksum,
1044
- PoolDatasetCreateFilesystemDeduplication: () => PoolDatasetCreateFilesystemDeduplication,
1045
- PoolDatasetCreateFilesystemReadonlyInput: () => PoolDatasetCreateFilesystemReadonlyInput,
1046
- PoolDatasetDeleteResult: () => PoolDatasetDeleteResult,
1047
- PoolScanStateInput: () => PoolScanStateInput,
1048
- Protocol: () => Protocol,
1049
- Purpose: () => Purpose,
1050
- Readonly: () => Readonly,
1051
- ReplicationCountEligibleManualSnapshotsTransportInput: () => ReplicationCountEligibleManualSnapshotsTransportInput,
1052
- ReplicationCreateReadonlyInput: () => ReplicationCreateReadonlyInput,
1053
- Resolution: () => Resolution,
1054
- Rpm: () => Rpm,
1055
- RsyncTaskCreateDirection: () => RsyncTaskCreateDirection,
1056
- RsyncTaskCreateDirectionInput: () => RsyncTaskCreateDirectionInput,
1057
- RsyncTaskCreateMode: () => RsyncTaskCreateMode,
1058
- RsyncTaskCreateModeInput: () => RsyncTaskCreateModeInput,
1059
- SMBEntryEncryptionInput: () => SMBEntryEncryptionInput,
1060
- STIGType: () => STIGType,
1061
- Schema: () => Schema,
1062
- Security: () => Security,
1063
- Serialspeed: () => Serialspeed,
1064
- ServiceControlVerb: () => ServiceControlVerb,
1065
- SharingSMBEntryPurposeInput: () => SharingSMBEntryPurposeInput,
1066
- SharingSMBEntryPurposeInput2: () => SharingSMBEntryPurposeInput2,
1067
- Shutdown: () => Shutdown,
1068
- Snapdev: () => Snapdev,
1069
- Snapdir: () => Snapdir,
1070
- Source: () => Source,
1071
- SourceInput: () => SourceInput,
1072
- State: () => State,
1073
- Status: () => Status,
1074
- SupportNewTicketCommunityTypeInput: () => SupportNewTicketCommunityTypeInput,
1075
- Sync: () => Sync,
1076
- SyslogServerTransportInput: () => SyslogServerTransportInput,
1077
- Sysloglevel: () => Sysloglevel,
1078
- SystemProductTypeResult: () => SystemProductTypeResult,
1079
- SystemStateResult: () => SystemStateResult,
1080
- Tag: () => Tag,
1081
- Target: () => Target,
1082
- Time: () => Time,
1083
- Transport: () => Transport,
1084
- TruecommandConfigChangedEventFieldsStatus: () => TruecommandConfigChangedEventFieldsStatus,
1085
- TruecommandConfigChangedEventFieldsStatusInput: () => TruecommandConfigChangedEventFieldsStatusInput,
1086
- TunableCreateType: () => TunableCreateType,
1087
- TunableCreateTypeInput: () => TunableCreateTypeInput,
1088
- UPSEntryMode: () => UPSEntryMode,
1089
- UPSEntryModeInput: () => UPSEntryModeInput,
1090
- Unixcharset: () => Unixcharset,
1091
- Username: () => Username,
1092
- VMDiskDeviceType: () => VMDiskDeviceType,
1093
- VMDiskDeviceTypeInput: () => VMDiskDeviceTypeInput,
1094
- VMWareEntryStateStateInput: () => VMWareEntryStateStateInput,
1095
- VMWareMatchDatastoresWithDatasetsResultFilesystemType: () => VMWareMatchDatastoresWithDatasetsResultFilesystemType,
1096
- Vendor: () => Vendor,
1097
- Volblocksize: () => Volblocksize,
1098
- When: () => When,
1099
- ZfsTierRewriteJobEntryStatusInput: () => ZfsTierRewriteJobEntryStatusInput
1100
- });
1101
-
1102
- // src/generated/v25_10_0/api-types.ts
1103
- var Aclmode = {
1104
- Passthrough: "PASSTHROUGH",
1105
- Restricted: "RESTRICTED",
1106
- Discard: "DISCARD",
1107
- Inherit: "INHERIT"
1108
- };
1109
- var ACLTemplateEntryAcltypeInput = {
1110
- Nfs4: "NFS4",
1111
- Posix1e: "POSIX1E"
1112
- };
1113
- var Acltype = {
1114
- Nfs4: "NFS4",
1115
- Posix1e: "POSIX1E"
1116
- };
1117
- var Action = {
1118
- Start: "START",
1119
- Stop: "STOP",
1120
- Pause: "PAUSE"
1121
- };
1122
- var Advpowermgmt = {
1123
- Disabled: "DISABLED",
1124
- "1": "1",
1125
- "64": "64",
1126
- "127": "127",
1127
- "128": "128",
1128
- "192": "192",
1129
- "254": "254"
509
+ var Advpowermgmt = {
510
+ Disabled: "DISABLED",
511
+ "1": "1",
512
+ "64": "64",
513
+ "127": "127",
514
+ "128": "128",
515
+ "192": "192",
516
+ "254": "254"
1130
517
  };
1131
518
  var Algorithm = {
1132
519
  Aes128Ccm: "AES-128-CCM",
@@ -2861,151 +2248,882 @@ __export(v27_0_0_exports, {
2861
2248
  ZpoolScrubRunAction: () => ZpoolScrubRunAction
2862
2249
  });
2863
2250
 
2864
- // src/generated/index.ts
2865
- var SUPPORTED_API_VERSIONS = [
2866
- "v25.10.0",
2867
- "v25.10.1",
2868
- "v25.10.2",
2869
- "v25.10.3",
2870
- "v25.10.4",
2871
- "v25.10.5",
2872
- "v26.0.0",
2873
- "v27.0.0"
2874
- ];
2251
+ // src/generated/index.ts
2252
+ var SUPPORTED_API_VERSIONS = [
2253
+ "v25.10.0",
2254
+ "v25.10.1",
2255
+ "v25.10.2",
2256
+ "v25.10.3",
2257
+ "v25.10.4",
2258
+ "v25.10.5",
2259
+ "v26.0.0",
2260
+ "v27.0.0"
2261
+ ];
2262
+
2263
+ // src/config/api-version.config.ts
2264
+ var apiVersionConfig = {
2265
+ /**
2266
+ * Minimum supported API version. Systems below it are rejected.
2267
+ *
2268
+ * DERIVED, not declared. The client supports exactly the versions it ships
2269
+ * types for, so the oldest generated version *is* the minimum — there is no
2270
+ * second decision to make, and therefore nothing to keep in sync.
2271
+ *
2272
+ * To move the floor, change `--min-version` in the `generate:api` script in
2273
+ * package.json and regenerate; this follows on its own. Written as a literal
2274
+ * it would duplicate that value with nothing enforcing agreement, so raising
2275
+ * one and forgetting the other would silently keep generating types for
2276
+ * versions the client rejects.
2277
+ */
2278
+ MIN_SUPPORTED_VERSION: SUPPORTED_API_VERSIONS[0],
2279
+ /**
2280
+ * Maximum supported API version. Systems above it are rejected.
2281
+ *
2282
+ * NOT derived, deliberately — and for a different reason than it used to
2283
+ * lag. It sat at v26.0.0 while types for v27 already shipped, because
2284
+ * `CLIENT_BY_VERSION_KEY` had no `27` and a v27 system would have passed the
2285
+ * range check only to throw on client selection. `TrueNasApiClientV27` now
2286
+ * exists, so this moves up with it.
2287
+ *
2288
+ * What it must not become is `SUPPORTED_API_VERSIONS[length - 1]`, the mirror
2289
+ * of how MIN is derived. MIN is safe to derive because the oldest generated
2290
+ * version always has a client — it is the floor the clients were built from.
2291
+ * The ceiling is not symmetric: generating types for v28 does not write a v28
2292
+ * client, so deriving this would re-create the exact gap described above on
2293
+ * the next regeneration, silently. The real invariant is "the newest version
2294
+ * a client can be built for", which lives in `CLIENT_BY_VERSION_KEY`; a
2295
+ * factory test asserts the two agree, which is the check that keeps this
2296
+ * literal honest without importing the factory here.
2297
+ */
2298
+ MAX_SUPPORTED_VERSION: "v27.0.0",
2299
+ /**
2300
+ * Fallback version to use when version discovery fails due to CORS/network errors.
2301
+ * When /api/versions returns HTTP status 0 (CORS block, network down, etc.),
2302
+ * the system will attempt to connect using this version as a best-effort fallback.
2303
+ *
2304
+ * WARNING: Status 0 errors have multiple causes:
2305
+ * - CORS policy blocking the request
2306
+ * - Network disconnected
2307
+ * - DNS lookup failure
2308
+ * - Server unreachable
2309
+ *
2310
+ * Using this fallback means systems with genuine network issues will still
2311
+ * attempt connection (and fail during WebSocket handshake instead of immediately).
2312
+ */
2313
+ FALLBACK_VERSION: "v25.10.0"
2314
+ };
2315
+
2316
+ // src/types/api-version.type.ts
2317
+ var VersionCompatibility = /* @__PURE__ */ ((VersionCompatibility2) => {
2318
+ VersionCompatibility2["Compatible"] = "compatible";
2319
+ VersionCompatibility2["TooOld"] = "too-old";
2320
+ VersionCompatibility2["TooNew"] = "too-new";
2321
+ VersionCompatibility2["Invalid"] = "invalid";
2322
+ return VersionCompatibility2;
2323
+ })(VersionCompatibility || {});
2324
+
2325
+ // src/utils/api-version.utils.ts
2326
+ var legacyCutoffYear = 25;
2327
+ function parseApiVersion(versionString) {
2328
+ const regex = /^v(\d{2})\.(\d+)\.(\d+)$/;
2329
+ const match = versionString.match(regex);
2330
+ if (!match) {
2331
+ return null;
2332
+ }
2333
+ const [, yearStr, minorStr, patchStr] = match;
2334
+ const year = parseInt(yearStr, 10);
2335
+ const minor = parseInt(minorStr, 10);
2336
+ const patch = parseInt(patchStr, 10);
2337
+ if (year <= legacyCutoffYear) {
2338
+ if (minor < 1 || minor > 12) {
2339
+ return null;
2340
+ }
2341
+ } else if (year >= 26) {
2342
+ if (minor < 0 || minor > 99) {
2343
+ return null;
2344
+ }
2345
+ }
2346
+ return {
2347
+ version: versionString,
2348
+ year,
2349
+ minor,
2350
+ patch,
2351
+ websocketPath: `/api/${versionString}`
2352
+ };
2353
+ }
2354
+ function compareVersions(a, b) {
2355
+ if (a.year !== b.year) {
2356
+ return a.year - b.year;
2357
+ }
2358
+ if (a.minor !== b.minor) {
2359
+ return a.minor - b.minor;
2360
+ }
2361
+ return a.patch - b.patch;
2362
+ }
2363
+ function checkVersionCompatibility(version) {
2364
+ const minVersion = parseApiVersion(apiVersionConfig.MIN_SUPPORTED_VERSION);
2365
+ const maxVersion = parseApiVersion(apiVersionConfig.MAX_SUPPORTED_VERSION);
2366
+ if (!minVersion || !maxVersion) {
2367
+ return "invalid" /* Invalid */;
2368
+ }
2369
+ if (compareVersions(version, minVersion) < 0) {
2370
+ return "too-old" /* TooOld */;
2371
+ }
2372
+ if (compareVersions(version, maxVersion) > 0) {
2373
+ return "too-new" /* TooNew */;
2374
+ }
2375
+ return "compatible" /* Compatible */;
2376
+ }
2377
+ function isVersionSupported(version) {
2378
+ return checkVersionCompatibility(version) === "compatible" /* Compatible */;
2379
+ }
2380
+ function filterCompatibleVersions(versions) {
2381
+ return versions.filter(isVersionSupported);
2382
+ }
2383
+ function getWebSocketPath(version) {
2384
+ return version.websocketPath;
2385
+ }
2386
+
2387
+ // src/enums/truenas-auth-mechanism.enum.ts
2388
+ var TrueNasAuthMechanism = /* @__PURE__ */ ((TrueNasAuthMechanism2) => {
2389
+ TrueNasAuthMechanism2["ApiKey"] = "API_KEY_PLAIN";
2390
+ TrueNasAuthMechanism2["Password"] = "PASSWORD_PLAIN";
2391
+ TrueNasAuthMechanism2["Otp"] = "OTP_TOKEN";
2392
+ TrueNasAuthMechanism2["Token"] = "TOKEN_PLAIN";
2393
+ return TrueNasAuthMechanism2;
2394
+ })(TrueNasAuthMechanism || {});
2395
+
2396
+ // src/errors/auth.errors.ts
2397
+ var AuthErrorCode = /* @__PURE__ */ ((AuthErrorCode2) => {
2398
+ AuthErrorCode2["PasswordAuthFailed"] = "PASSWORD_AUTH_FAILED";
2399
+ AuthErrorCode2["OtpAuthFailed"] = "OTP_AUTH_FAILED";
2400
+ AuthErrorCode2["ApiKeyAuthFailed"] = "API_KEY_AUTH_FAILED";
2401
+ AuthErrorCode2["TokenAuthFailed"] = "TOKEN_AUTH_FAILED";
2402
+ AuthErrorCode2["FullAdminRequired"] = "FULL_ADMIN_REQUIRED";
2403
+ return AuthErrorCode2;
2404
+ })(AuthErrorCode || {});
2405
+ var AuthError = class _AuthError extends Error {
2406
+ constructor(code, message) {
2407
+ super(message);
2408
+ this.code = code;
2409
+ this.name = "AuthError";
2410
+ Object.setPrototypeOf(this, _AuthError.prototype);
2411
+ }
2412
+ };
2413
+
2414
+ // src/auth/truenas-authenticator.ts
2415
+ var throwOnAuthenticationFailure = (code, message) => switchMap((response) => {
2416
+ if (response.response_type === "AUTH_ERR" /* AuthErr */) {
2417
+ return throwError(() => new AuthError(code, message));
2418
+ }
2419
+ return of(response);
2420
+ });
2421
+ var TrueNasAuthenticator = class _TrueNasAuthenticator {
2422
+ constructor(connection, version) {
2423
+ this.connection = connection;
2424
+ this.version = version;
2425
+ // in seconds (5 minutes)
2426
+ /**
2427
+ * whether or not the system is currently authenticated and accessible.
2428
+ * this is a `BehaviorSubject` instead of a signal, since we use its `getValue` method
2429
+ * throughout a lot of the codebase.
2430
+ */
2431
+ this.authenticated$ = new BehaviorSubject(false);
2432
+ /**
2433
+ * `true` when the system is currently being authenticated to, and `false` otherwise.
2434
+ * does not indicate whatsoever if authentication is successful or not, just whether the process
2435
+ * is ongoing.
2436
+ */
2437
+ this.authenticating$ = new BehaviorSubject(false);
2438
+ this.credentials = { username: "", password: "", key: "" };
2439
+ this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
2440
+ this.connection.opened.pipe(
2441
+ filter(
2442
+ (isOpen) => !!(isOpen && this.credentials?.username && (this.credentials.password || this.credentials.key))
2443
+ ),
2444
+ switchMap(() => {
2445
+ if (this.credentials.password) {
2446
+ return this.loginWithUserPass(
2447
+ this.credentials.username,
2448
+ this.credentials.password
2449
+ );
2450
+ }
2451
+ return this.loginWithApiKey({
2452
+ username: this.credentials.username,
2453
+ key: this.credentials.key
2454
+ });
2455
+ })
2456
+ ).subscribe();
2457
+ connection.closed.subscribe(() => {
2458
+ this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
2459
+ this.authenticated$.next(false);
2460
+ });
2461
+ }
2462
+ static {
2463
+ this.DefaultSessionLifetime = 300;
2464
+ }
2465
+ /**
2466
+ * `login_options` asking for a reconnect token, when the server understands it.
2467
+ *
2468
+ * Omitted below v26. `AuthCommonOptions` is `additionalProperties: false`
2469
+ * there and has only `user_info`, so sending the member is a validation
2470
+ * error, not an ignored field — it would fail login outright on the oldest
2471
+ * version this client supports.
2472
+ */
2473
+ /**
2474
+ * Two things this does not do, both deliberate and both worth knowing.
2475
+ *
2476
+ * There is no way for a consumer to decline: every v26+ password login now
2477
+ * mints a single-use credential carrying that session's roles, whether or not
2478
+ * the caller wants one. And the auto-relogin in the constructor subscribes
2479
+ * with no observer, so the token it mints is dropped — a caller reconnecting
2480
+ * repeatedly holds an ageing token while the appliance mints fresh ones
2481
+ * nobody reads. Tokens are single-use with a 600s TTL, so that is the
2482
+ * reconnect case the feature is named for.
2483
+ */
2484
+ reconnectTokenOption() {
2485
+ if (!this.version || this.version.year <= legacyCutoffYear) return void 0;
2486
+ return { login_options: { reconnect_token: true } };
2487
+ }
2488
+ loginWithUserPass(username, password) {
2489
+ const message = createJsonRpcMessage("auth.login_ex", [
2490
+ {
2491
+ mechanism: "PASSWORD_PLAIN" /* Password */,
2492
+ username,
2493
+ password,
2494
+ ...this.reconnectTokenOption()
2495
+ }
2496
+ ]);
2497
+ this.authenticating$.next(true);
2498
+ this.connection.send(message);
2499
+ const messageId = message.id ?? "";
2500
+ return this.connection.messages().pipe(
2501
+ withId(messageId),
2502
+ map((msg) => {
2503
+ if (msg.error) {
2504
+ const errorMessage = getApiErrorMessage(
2505
+ msg.error,
2506
+ "Authentication failed"
2507
+ );
2508
+ throw new Error(errorMessage);
2509
+ }
2510
+ return msg.result;
2511
+ }),
2512
+ throwOnAuthenticationFailure(
2513
+ "PASSWORD_AUTH_FAILED" /* PasswordAuthFailed */,
2514
+ "TrueNAS authentication failed. Please verify your TrueNAS user credentials and try again."
2515
+ ),
2516
+ tap((res) => {
2517
+ if (res.response_type === "SUCCESS" /* Success */) {
2518
+ if (res.user_info?.privilege.roles.$set.includes("FULL_ADMIN" /* FullAdmin */)) {
2519
+ this.credentials.username = username;
2520
+ this.credentials.password = password;
2521
+ this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
2522
+ this.authenticated$.next(true);
2523
+ } else {
2524
+ this.logout();
2525
+ this.authenticated$.next(false);
2526
+ throw new AuthError(
2527
+ "FULL_ADMIN_REQUIRED" /* FullAdminRequired */,
2528
+ "User account must have full admin privileges"
2529
+ );
2530
+ }
2531
+ }
2532
+ }),
2533
+ finalize(() => {
2534
+ this.authenticating$.next(false);
2535
+ }),
2536
+ take(1)
2537
+ );
2538
+ }
2539
+ loginWithOtp(code) {
2540
+ const message = createJsonRpcMessage("auth.login_ex", [
2541
+ {
2542
+ mechanism: "OTP_TOKEN" /* Otp */,
2543
+ otp_token: code
2544
+ }
2545
+ ]);
2546
+ this.authenticating$.next(true);
2547
+ this.connection.send(message);
2548
+ const messageId = message.id ?? "";
2549
+ return this.connection.messages().pipe(
2550
+ withId(messageId),
2551
+ map((msg) => {
2552
+ if (msg.error) {
2553
+ const errorMessage = getApiErrorMessage(
2554
+ msg.error,
2555
+ "Authentication failed"
2556
+ );
2557
+ throw new Error(errorMessage);
2558
+ }
2559
+ return msg.result;
2560
+ }),
2561
+ tap((res) => {
2562
+ if (res?.response_type === "SUCCESS" /* Success */) {
2563
+ this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
2564
+ this.authenticated$.next(true);
2565
+ }
2566
+ }),
2567
+ throwOnAuthenticationFailure(
2568
+ "OTP_AUTH_FAILED" /* OtpAuthFailed */,
2569
+ "TrueNAS authentication failed. Please verify your one-time passcode and try again."
2570
+ ),
2571
+ finalize(() => {
2572
+ this.authenticating$.next(false);
2573
+ }),
2574
+ take(1)
2575
+ );
2576
+ }
2577
+ /**
2578
+ * Re-authenticate with a token from a previous login's `reconnect_token`.
2579
+ *
2580
+ * This is what lets a second connection to the same appliance authenticate
2581
+ * without asking the user for a password again — middleware sessions are
2582
+ * per-connection, so a second socket has its own to establish.
2583
+ *
2584
+ * The token is single-use and short-lived. On v26+ a successful login mints
2585
+ * another on the response, so a caller keeping a session alive across
2586
+ * reconnects stores the newest each time; below v26 nothing is minted and
2587
+ * there is no chain to keep.
2588
+ *
2589
+ * Re-login is the caller's to drive. A token session is not covered by the
2590
+ * automatic reconnect this class does for password and api-key sessions,
2591
+ * which is deliberate — the token is single-use — but it means a dropped
2592
+ * socket needs the stored token spending explicitly. Middleware holds tokens
2593
+ * in memory, so a `middlewared` restart voids them, and that is a common
2594
+ * reason the socket dropped in the first place.
2595
+ */
2596
+ loginWithToken(token) {
2597
+ const message = createJsonRpcMessage("auth.login_ex", [
2598
+ {
2599
+ mechanism: "TOKEN_PLAIN" /* Token */,
2600
+ token,
2601
+ ...this.reconnectTokenOption()
2602
+ }
2603
+ ]);
2604
+ this.authenticating$.next(true);
2605
+ this.connection.send(message);
2606
+ const messageId = message.id ?? "";
2607
+ return this.connection.messages().pipe(
2608
+ withId(messageId),
2609
+ map((msg) => {
2610
+ if (msg.error) {
2611
+ const errorMessage = getApiErrorMessage(
2612
+ msg.error,
2613
+ "Authentication failed"
2614
+ );
2615
+ throw new Error(errorMessage);
2616
+ }
2617
+ return msg.result;
2618
+ }),
2619
+ // Password login lets non-`AUTH_ERR` answers through because it has to
2620
+ // hand `OTP_REQUIRED` back to the caller. Token login has no such case:
2621
+ // middleware answers `EXPIRED` for an account locked or expired between
2622
+ // minting and spending, and `DENIED` for a permission refusal, so letting
2623
+ // those reach `next` would report a failed login as a successful one.
2624
+ map((res) => {
2625
+ if (res.response_type !== "SUCCESS" /* Success */) {
2626
+ throw new AuthError(
2627
+ "TOKEN_AUTH_FAILED" /* TokenAuthFailed */,
2628
+ `TrueNAS token authentication failed (${res.response_type}). The token may have expired or been used, or the account may no longer be permitted to log in.`
2629
+ );
2630
+ }
2631
+ return res;
2632
+ }),
2633
+ tap((res) => {
2634
+ if (res.response_type === "SUCCESS" /* Success */) {
2635
+ if (res.user_info?.privilege.roles.$set.includes("FULL_ADMIN" /* FullAdmin */)) {
2636
+ this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
2637
+ this.authenticated$.next(true);
2638
+ } else {
2639
+ this.logout();
2640
+ this.authenticated$.next(false);
2641
+ throw new AuthError(
2642
+ "FULL_ADMIN_REQUIRED" /* FullAdminRequired */,
2643
+ "User account must have full admin privileges"
2644
+ );
2645
+ }
2646
+ }
2647
+ }),
2648
+ finalize(() => {
2649
+ this.authenticating$.next(false);
2650
+ }),
2651
+ take(1)
2652
+ );
2653
+ }
2654
+ /**
2655
+ * No reconnect token is requested here, though v26+ would mint one: an
2656
+ * api-key session already reconnects without a prompt, since the key is held
2657
+ * and replayed. The token exists for the credential that cannot be.
2658
+ */
2659
+ loginWithApiKey(credentials) {
2660
+ const { username, key } = credentials;
2661
+ const message = createJsonRpcMessage("auth.login_ex", [
2662
+ {
2663
+ mechanism: "API_KEY_PLAIN" /* ApiKey */,
2664
+ username,
2665
+ api_key: key
2666
+ }
2667
+ ]);
2668
+ this.authenticating$.next(true);
2669
+ this.connection.send(message);
2670
+ const messageId = message.id ?? "";
2671
+ return this.connection.messages().pipe(
2672
+ withId(messageId),
2673
+ map((msg) => {
2674
+ if (msg.error) {
2675
+ const errorMessage = getApiErrorMessage(
2676
+ msg.error,
2677
+ "Authentication failed"
2678
+ );
2679
+ throw new Error(errorMessage);
2680
+ }
2681
+ return msg.result;
2682
+ }),
2683
+ throwOnAuthenticationFailure(
2684
+ "API_KEY_AUTH_FAILED" /* ApiKeyAuthFailed */,
2685
+ "TrueNAS authentication failed. Has the TrueNAS Connect API key been removed from your TrueNAS server?"
2686
+ ),
2687
+ tap((res) => {
2688
+ this.credentials.username = username;
2689
+ this.credentials.key = key;
2690
+ this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
2691
+ this.authenticated$.next(true);
2692
+ }),
2693
+ finalize(() => {
2694
+ this.authenticating$.next(false);
2695
+ }),
2696
+ take(1)
2697
+ );
2698
+ }
2699
+ newApiKey(username) {
2700
+ const message = createJsonRpcMessage("api_key.create", [
2701
+ { name: `tnc-${randomUUID()}`, username }
2702
+ ]);
2703
+ this.connection.send(message);
2704
+ const messageId = message.id ?? "";
2705
+ return this.connection.messages().pipe(
2706
+ withId(messageId),
2707
+ map((msg) => {
2708
+ if (msg.error) {
2709
+ const errorMessage = getApiErrorMessage(
2710
+ msg.error,
2711
+ "Failed to create API key"
2712
+ );
2713
+ throw new Error(errorMessage);
2714
+ }
2715
+ return msg.result;
2716
+ }),
2717
+ take(1)
2718
+ );
2719
+ }
2720
+ logout() {
2721
+ const message = createJsonRpcMessage("auth.logout");
2722
+ this.connection.send(message);
2723
+ const messageId = message.id ?? "";
2724
+ return this.connection.messages().pipe(
2725
+ withId(messageId),
2726
+ map((msg) => {
2727
+ if (msg.error) {
2728
+ return false;
2729
+ }
2730
+ return msg.result;
2731
+ }),
2732
+ tap((success) => {
2733
+ this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
2734
+ this.authenticated$.next(!success);
2735
+ }),
2736
+ take(1)
2737
+ );
2738
+ }
2739
+ };
2740
+
2741
+ // src/logger.ts
2742
+ var consoleLogger = {
2743
+ trace: (message, ...args) => console.trace(message, ...args),
2744
+ debug: (message, ...args) => console.debug(message, ...args),
2745
+ info: (message, ...args) => console.info(message, ...args),
2746
+ warn: (message, ...args) => console.warn(message, ...args),
2747
+ error: (message, ...args) => console.error(message, ...args)
2748
+ };
2749
+ var noop = () => void 0;
2750
+ var noopLogger = {
2751
+ trace: noop,
2752
+ debug: noop,
2753
+ info: noop,
2754
+ warn: noop,
2755
+ error: noop
2756
+ };
2875
2757
 
2876
- // src/config/api-version.config.ts
2877
- var apiVersionConfig = {
2758
+ // src/utils/truenas-connection.utils.ts
2759
+ function isHttpStatusError(reason) {
2760
+ return ["404", "502", "503"].some((code) => reason.includes(code));
2761
+ }
2762
+ function getHttpError(reason) {
2763
+ if (reason.includes("404")) {
2764
+ return "API endpoint not found - System may not support versioned API";
2765
+ }
2766
+ if (reason.includes("502")) {
2767
+ return "Bad Gateway - System may be starting up";
2768
+ }
2769
+ if (reason.includes("503")) {
2770
+ return "Service Unavailable - System may be overloaded";
2771
+ }
2772
+ return "";
2773
+ }
2774
+ function getWebSocketError(code) {
2775
+ switch (code) {
2776
+ case 1e3:
2777
+ return "Connection closed normally";
2778
+ case 1001:
2779
+ return "Server is shutting down or restarting";
2780
+ case 1002:
2781
+ return "Protocol error - Invalid WebSocket communication";
2782
+ case 1003:
2783
+ return "Unsupported data format received";
2784
+ case 1006:
2785
+ return "Connection lost unexpectedly - Check network connectivity";
2786
+ case 1007:
2787
+ return "Invalid data received from server";
2788
+ case 1008:
2789
+ return "Connection terminated due to policy violation";
2790
+ case 1009:
2791
+ return "Message size exceeded server limits";
2792
+ case 1011:
2793
+ return "Server encountered an internal error";
2794
+ case 1012:
2795
+ return "Service is restarting";
2796
+ case 1013:
2797
+ return "Server temporarily overloaded - Try again later";
2798
+ case 1015:
2799
+ return "TLS/Certificate error - Certificate may be expired";
2800
+ default:
2801
+ return "Network connection failed - Check IP address and connectivity";
2802
+ }
2803
+ }
2804
+ var TrueNasSocket = class {
2805
+ constructor(config) {
2806
+ this.config = config;
2807
+ this.socket = webSocket(this.config);
2808
+ }
2809
+ messages() {
2810
+ return this.socket;
2811
+ }
2812
+ next(msg) {
2813
+ this.socket.next(msg);
2814
+ }
2815
+ complete() {
2816
+ this.socket.complete();
2817
+ }
2818
+ };
2819
+
2820
+ // src/types/transport.type.ts
2821
+ function httpScheme(protocol) {
2822
+ return protocol === "http:" ? "http:" : "https:";
2823
+ }
2824
+ function socketScheme(protocol) {
2825
+ return protocol === "http:" ? "ws:" : "wss:";
2826
+ }
2827
+
2828
+ // src/connection/truenas-connection.ts
2829
+ var tenSeconds = 10 * 1e3;
2830
+ var twentySeconds = 20 * 1e3;
2831
+ var TrueNasConnection = class {
2832
+ constructor(initialEnabled, hostnames, systemUuid, websocketPath, systemName, retryDelay = tenSeconds, maxRetry = 3, logger = noopLogger, protocol = "https:") {
2833
+ this.hostnames = hostnames;
2834
+ this.systemUuid = systemUuid;
2835
+ this.websocketPath = websocketPath;
2836
+ this.systemName = systemName;
2837
+ this.retryDelay = retryDelay;
2838
+ this.maxRetry = maxRetry;
2839
+ this.logger = logger;
2840
+ this.protocol = protocol;
2841
+ // compatibility properties
2842
+ this.opened = new BehaviorSubject(false);
2843
+ this.closed = new Subject();
2844
+ this.hostname = new BehaviorSubject("");
2845
+ this.connectionAttempts = new BehaviorSubject(0);
2846
+ this.lastErrorMessage = new BehaviorSubject(null);
2847
+ /**
2848
+ * emits when the connection is manually closed.
2849
+ */
2850
+ this.closeConnection = new Subject();
2851
+ /**
2852
+ * the connection only establishes a socket while this gate is `true`. consumers
2853
+ * flip it via `setEnabled()` (the app maps `SystemState.Active -> true`).
2854
+ */
2855
+ this.enabled$ = new BehaviorSubject(false);
2856
+ /**
2857
+ * observable which emits the current gate value and only emits again when it changes.
2858
+ */
2859
+ this.enabledChange$ = this.enabled$.pipe(distinctUntilChanged());
2860
+ /**
2861
+ * observable that handles the entire connection lifecycle.
2862
+ */
2863
+ this.connection$ = this.enabledChange$.pipe(
2864
+ switchMap((enabled) => {
2865
+ if (enabled) {
2866
+ return this.connect().pipe(
2867
+ map((conn) => makeActiveConnection(conn.ws, conn.hostname))
2868
+ );
2869
+ }
2870
+ return of(closedConnection);
2871
+ }),
2872
+ switchMap((connection) => {
2873
+ if (connection.state !== "active") {
2874
+ return of(connection);
2875
+ }
2876
+ const initMessage = createJsonRpcMessage("core.set_options", [
2877
+ { legacy_jobs: false }
2878
+ ]);
2879
+ connection.ws.next(initMessage);
2880
+ return connection.ws.messages().pipe(
2881
+ filter((msg) => msg.id === initMessage.id),
2882
+ take(1),
2883
+ map(() => connection)
2884
+ );
2885
+ }),
2886
+ // in the event of an error, do two things:
2887
+ // 1. emit an errored connection downstream to inform consumers that
2888
+ // the connection is dead.
2889
+ // 2. re-throw an error so the downstream `retry` will re-subscribe.
2890
+ catchError$1((err) => {
2891
+ this.logger.error("All connections failed - retrying", { message: err?.message, hostname: err?.hostname });
2892
+ return concat(
2893
+ of(makeConnectionError(err.message, err.hostname)),
2894
+ // since this error will immediately get caught by `retry` there's no reason to build a real error.
2895
+ throwError(() => null)
2896
+ );
2897
+ }),
2898
+ retry(),
2899
+ // start with a closed connection.
2900
+ startWith(closedConnection),
2901
+ // prevent multiple subscriptions from re-evaluating the entire pipeline.
2902
+ shareReplay$1({ bufferSize: 1, refCount: false }),
2903
+ takeUntil(this.closeConnection)
2904
+ );
2905
+ /**
2906
+ * observable which is either an instance of the current `TrueNasSocket` used for the connection
2907
+ * or `null` if the connection is closed or errored for any reason.
2908
+ */
2909
+ this.ws$ = this.connection$.pipe(
2910
+ map((conn) => conn.state === "active" ? conn.ws : null)
2911
+ );
2912
+ /**
2913
+ * current hostname we used to build the URL for this connection.
2914
+ */
2915
+ this.hostname$ = this.connection$.pipe(
2916
+ map((conn) => conn.state === "active" ? conn.hostname : null)
2917
+ );
2918
+ /**
2919
+ * emits error messages from the connection pipeline. this is used to derive the
2920
+ * corresponding compatibility property.
2921
+ */
2922
+ this.lastErrorMessage$ = this.connection$.pipe(
2923
+ map((conn) => conn.state === "error" ? conn.message : null)
2924
+ );
2925
+ /**
2926
+ * emits when the connection state *changes*, so it'll never emit `true` twice
2927
+ * in a row nor `false` twice in a row.
2928
+ */
2929
+ this.opened$ = this.connection$.pipe(
2930
+ map((conn) => conn.state),
2931
+ distinctUntilChanged(),
2932
+ map((state) => state === "active")
2933
+ );
2934
+ /**
2935
+ * emits when the connection state goes from open to closed.
2936
+ */
2937
+ this.closed$ = this.connection$.pipe(
2938
+ map((conn) => conn.state),
2939
+ distinctUntilChanged(),
2940
+ filter((state) => state === "closed" || state === "error"),
2941
+ map(() => {
2942
+ })
2943
+ );
2944
+ /**
2945
+ * whether to display a connection error to the user — the **live** signal.
2946
+ *
2947
+ * `true` only while `connection$` is currently a `ConnectionError`, meaning the entire race +
2948
+ * retry cycle has been exhausted for all hostnames right now; it flips back to `false` once a
2949
+ * connection is re-established. individual socket losses during a race are expected and not surfaced.
2950
+ *
2951
+ * NOTE: this is NOT the same as the `hasExhaustedRetries()` method, which is a **cumulative**
2952
+ * snapshot (see there). The two can disagree — prefer this observable for "is the connection
2953
+ * errored right now?".
2954
+ */
2955
+ this.hasConnectionError$ = this.connection$.pipe(
2956
+ map((conn) => conn.state === "error"),
2957
+ takeUntil(this.closeConnection)
2958
+ );
2959
+ /**
2960
+ * observable which always emits messages from the current socket.
2961
+ */
2962
+ this.messages$ = this.ws$.pipe(
2963
+ filter((ws) => ws !== null),
2964
+ switchMap((ws) => ws.messages().pipe(
2965
+ catchError$1(() => EMPTY)
2966
+ ))
2967
+ );
2968
+ combineLatest([
2969
+ interval(twentySeconds),
2970
+ this.ws$
2971
+ ]).pipe(
2972
+ takeUntil(this.closeConnection)
2973
+ ).subscribe(([, ws]) => {
2974
+ if (ws) {
2975
+ const pingMessage = createJsonRpcMessage("core.ping");
2976
+ ws.next(pingMessage);
2977
+ }
2978
+ });
2979
+ this.opened$.subscribe((val) => this.opened.next(val));
2980
+ this.closed$.subscribe(() => this.closed.next());
2981
+ this.hostname$.pipe(filter(Boolean)).subscribe((name) => this.hostname.next(name));
2982
+ this.ws$.pipe(filter(Boolean)).subscribe((ws) => this.ws = ws);
2983
+ this.lastErrorMessage$.subscribe((msg) => this.lastErrorMessage.next(msg));
2984
+ this.enabled$.next(initialEnabled);
2985
+ }
2878
2986
  /**
2879
- * Minimum supported API version. Systems below it are rejected.
2880
- *
2881
- * DERIVED, not declared. The client supports exactly the versions it ships
2882
- * types for, so the oldest generated version *is* the minimum — there is no
2883
- * second decision to make, and therefore nothing to keep in sync.
2987
+ * whether the connection has exhausted its retries the **cumulative** snapshot, read
2988
+ * synchronously. (Formerly `hasConnectionError()`; renamed to disambiguate it from the
2989
+ * live `hasConnectionError$` observable, with which it can disagree.)
2884
2990
  *
2885
- * To move the floor, change `--min-version` in the `generate:api` script in
2886
- * package.json and regenerate; this follows on its own. Written as a literal
2887
- * it would duplicate that value with nothing enforcing agreement, so raising
2888
- * one and forgetting the other would silently keep generating types for
2889
- * versions the client rejects.
2991
+ * `true` when the lifetime `connectionAttempts` count exceeds `hostnames.length * maxRetry`,
2992
+ * OR when an error message is currently set. Ported from the source (tncui) behavior.
2890
2993
  */
2891
- MIN_SUPPORTED_VERSION: SUPPORTED_API_VERSIONS[0],
2994
+ hasExhaustedRetries() {
2995
+ const attemptsExhausted = this.connectionAttempts.value > this.hostnames.length * this.maxRetry;
2996
+ const hasErrorMessage = this.lastErrorMessage.value !== null;
2997
+ return attemptsExhausted || hasErrorMessage;
2998
+ }
2892
2999
  /**
2893
- * Maximum supported API version. Systems above it are rejected.
2894
- *
2895
- * NOT derived, deliberately — and for a different reason than it used to
2896
- * lag. It sat at v26.0.0 while types for v27 already shipped, because
2897
- * `CLIENT_BY_VERSION_KEY` had no `27` and a v27 system would have passed the
2898
- * range check only to throw on client selection. `TrueNasApiClientV27` now
2899
- * exists, so this moves up with it.
2900
- *
2901
- * What it must not become is `SUPPORTED_API_VERSIONS[length - 1]`, the mirror
2902
- * of how MIN is derived. MIN is safe to derive because the oldest generated
2903
- * version always has a client — it is the floor the clients were built from.
2904
- * The ceiling is not symmetric: generating types for v28 does not write a v28
2905
- * client, so deriving this would re-create the exact gap described above on
2906
- * the next regeneration, silently. The real invariant is "the newest version
2907
- * a client can be built for", which lives in `CLIENT_BY_VERSION_KEY`; a
2908
- * factory test asserts the two agree, which is the check that keeps this
2909
- * literal honest without importing the factory here.
3000
+ * enables or disables the connection gate. the app calls this when its `SystemState`
3001
+ * changes (mapping `SystemState.Active -> true`, everything else -> `false`).
2910
3002
  */
2911
- MAX_SUPPORTED_VERSION: "v27.0.0",
3003
+ setEnabled(enabled) {
3004
+ this.enabled$.next(enabled);
3005
+ }
2912
3006
  /**
2913
- * Fallback version to use when version discovery fails due to CORS/network errors.
2914
- * When /api/versions returns HTTP status 0 (CORS block, network down, etc.),
2915
- * the system will attempt to connect using this version as a best-effort fallback.
2916
- *
2917
- * WARNING: Status 0 errors have multiple causes:
2918
- * - CORS policy blocking the request
2919
- * - Network disconnected
2920
- * - DNS lookup failure
2921
- * - Server unreachable
2922
- *
2923
- * Using this fallback means systems with genuine network issues will still
2924
- * attempt connection (and fail during WebSocket handshake instead of immediately).
3007
+ * compatibility method which just returns the public `messages$` observable.
3008
+ * this is used in a few places in the codebase that relied upon the old implementation.
2925
3009
  */
2926
- FALLBACK_VERSION: "v25.10.0"
2927
- };
2928
-
2929
- // src/types/api-version.type.ts
2930
- var VersionCompatibility = /* @__PURE__ */ ((VersionCompatibility2) => {
2931
- VersionCompatibility2["Compatible"] = "compatible";
2932
- VersionCompatibility2["TooOld"] = "too-old";
2933
- VersionCompatibility2["TooNew"] = "too-new";
2934
- VersionCompatibility2["Invalid"] = "invalid";
2935
- return VersionCompatibility2;
2936
- })(VersionCompatibility || {});
2937
-
2938
- // src/utils/api-version.utils.ts
2939
- var legacyCutoffYear = 25;
2940
- function parseApiVersion(versionString) {
2941
- const regex = /^v(\d{2})\.(\d+)\.(\d+)$/;
2942
- const match = versionString.match(regex);
2943
- if (!match) {
2944
- return null;
2945
- }
2946
- const [, yearStr, minorStr, patchStr] = match;
2947
- const year = parseInt(yearStr, 10);
2948
- const minor = parseInt(minorStr, 10);
2949
- const patch = parseInt(patchStr, 10);
2950
- if (year <= legacyCutoffYear) {
2951
- if (minor < 1 || minor > 12) {
2952
- return null;
2953
- }
2954
- } else if (year >= 26) {
2955
- if (minor < 0 || minor > 99) {
2956
- return null;
2957
- }
2958
- }
2959
- return {
2960
- version: versionString,
2961
- year,
2962
- minor,
2963
- patch,
2964
- websocketPath: `/api/${versionString}`
2965
- };
2966
- }
2967
- function compareVersions(a, b) {
2968
- if (a.year !== b.year) {
2969
- return a.year - b.year;
3010
+ messages() {
3011
+ return this.messages$;
2970
3012
  }
2971
- if (a.minor !== b.minor) {
2972
- return a.minor - b.minor;
3013
+ /**
3014
+ * sends a message over the current websocket OR queues it to send once
3015
+ * the next websocket is opened. messages sent via `send` will not be lost until after
3016
+ * the next `closed$` emission.
3017
+ */
3018
+ send(message) {
3019
+ return this.ws$.pipe(
3020
+ filter((ws) => ws !== null),
3021
+ take(1)
3022
+ ).subscribe((ws) => ws.next(message));
2973
3023
  }
2974
- return a.patch - b.patch;
2975
- }
2976
- function checkVersionCompatibility(version) {
2977
- const minVersion = parseApiVersion(apiVersionConfig.MIN_SUPPORTED_VERSION);
2978
- const maxVersion = parseApiVersion(apiVersionConfig.MAX_SUPPORTED_VERSION);
2979
- if (!minVersion || !maxVersion) {
2980
- return "invalid" /* Invalid */;
3024
+ /**
3025
+ * manually closes this connection and prevents it from retrying/opening any more.
3026
+ */
3027
+ close() {
3028
+ this.closeConnection.next();
3029
+ this.closeConnection.complete();
2981
3030
  }
2982
- if (compareVersions(version, minVersion) < 0) {
2983
- return "too-old" /* TooOld */;
3031
+ /**
3032
+ * helper method which creates an `Observable` which emits an `ActiveConnection`
3033
+ * after it establishes a connection to the given hostname. the observable will emit an
3034
+ * error if the connection is never established and will not complete until unsubscribed from or closed.
3035
+ */
3036
+ createSocket(hostname) {
3037
+ const url = `${socketScheme(this.protocol)}//${hostname}${this.websocketPath}`;
3038
+ let hasOpened = false;
3039
+ return new Observable((subscriber) => {
3040
+ const ws = new TrueNasSocket({
3041
+ url,
3042
+ openObserver: {
3043
+ next: () => {
3044
+ hasOpened = true;
3045
+ this.connectionAttempts.next(0);
3046
+ subscriber.next({ ws, hostname });
3047
+ }
3048
+ },
3049
+ closeObserver: {
3050
+ next: (event) => {
3051
+ const reason = event.reason || "";
3052
+ let errorMessage;
3053
+ if (isHttpStatusError(reason)) {
3054
+ errorMessage = getHttpError(reason);
3055
+ } else {
3056
+ errorMessage = getWebSocketError(event.code);
3057
+ }
3058
+ this.connectionAttempts.next(this.connectionAttempts.value + 1);
3059
+ subscriber.error(makeConnectionError(errorMessage, hostname));
3060
+ }
3061
+ }
3062
+ });
3063
+ const startupSub = ws.socket.subscribe({
3064
+ error: () => {
3065
+ }
3066
+ });
3067
+ return () => {
3068
+ startupSub.unsubscribe();
3069
+ ws.complete();
3070
+ };
3071
+ }).pipe(
3072
+ // retry logic:
3073
+ // * if a connection is not established in 10 seconds, consider that an error
3074
+ timeout({ first: tenSeconds }),
3075
+ retry({
3076
+ // * while still *establishing*: wait `retryDelay` before trying again, giving up
3077
+ // after `maxRetry` retries.
3078
+ count: this.maxRetry,
3079
+ // * we use a custom `delay` function here to ensure no retries are performed
3080
+ // once a socket is *opened*.
3081
+ // basically: a later death must propagate out rather than being retried
3082
+ // so it can be handled by the `connection$` observable.
3083
+ delay: (error) => {
3084
+ if (hasOpened) {
3085
+ return throwError(() => error);
3086
+ }
3087
+ return timer(this.retryDelay);
3088
+ }
3089
+ })
3090
+ );
2984
3091
  }
2985
- if (compareVersions(version, maxVersion) > 0) {
2986
- return "too-new" /* TooNew */;
3092
+ /**
3093
+ * helper function which actually performs the parallel connection `race`.
3094
+ */
3095
+ connect() {
3096
+ return race(
3097
+ this.hostnames.map(this.createSocket.bind(this))
3098
+ ).pipe(
3099
+ tap((conn) => this.logger.debug(`TrueNas socket opened to ${conn.hostname}.`)),
3100
+ takeUntil(this.closeConnection)
3101
+ );
2987
3102
  }
2988
- return "compatible" /* Compatible */;
2989
- }
2990
- function isVersionSupported(version) {
2991
- return checkVersionCompatibility(version) === "compatible" /* Compatible */;
2992
- }
2993
- function filterCompatibleVersions(versions) {
2994
- return versions.filter(isVersionSupported);
2995
- }
2996
- function getWebSocketPath(version) {
2997
- return version.websocketPath;
2998
- }
3103
+ };
3104
+ var makeActiveConnection = (ws, hostname) => ({
3105
+ ws,
3106
+ hostname,
3107
+ state: "active"
3108
+ });
3109
+ var makeConnectionError = (message, hostname) => ({
3110
+ name: "ConnectionError",
3111
+ message,
3112
+ hostname,
3113
+ state: "error"
3114
+ });
3115
+ var closedConnection = { state: "closed" };
2999
3116
 
3000
3117
  // src/client/truenas-api-client.ts
3001
3118
  var TrueNasApiClient = class {
3002
- constructor(uuid, hostnames, version, enabled, systemName, logger = noopLogger) {
3119
+ constructor(uuid, hostnames, version, enabled, systemName, logger = noopLogger, protocol = "https:") {
3003
3120
  this.uuid = uuid;
3004
3121
  this.hostnames = hostnames;
3005
3122
  this.version = version;
3006
3123
  this.enabled = enabled;
3007
3124
  this.systemName = systemName;
3008
3125
  this.logger = logger;
3126
+ this.protocol = protocol;
3009
3127
  this.connection = this.createConnection();
3010
3128
  this.authenticator = this.createAuthenticator();
3011
3129
  this.api = this.createApi();
@@ -3048,7 +3166,8 @@ var TrueNasApiClient = class {
3048
3166
  // retryDelay (use default)
3049
3167
  void 0,
3050
3168
  // maxRetry (use default)
3051
- this.logger
3169
+ this.logger,
3170
+ this.protocol
3052
3171
  );
3053
3172
  }
3054
3173
  /**
@@ -3063,7 +3182,7 @@ var TrueNasApiClient = class {
3063
3182
  * Override in subclasses to provide version-specific authentication.
3064
3183
  */
3065
3184
  createAuthenticator() {
3066
- return new TrueNasAuthenticator(this.connection);
3185
+ return new TrueNasAuthenticator(this.connection, this.version);
3067
3186
  }
3068
3187
  };
3069
3188
 
@@ -3442,14 +3561,18 @@ function hasErrorName(error, expected) {
3442
3561
  return typeof error === "object" && error !== null && "name" in error && error.name === expected;
3443
3562
  }
3444
3563
  var VersionDiscovery = class {
3445
- constructor(logger = noopLogger) {
3564
+ constructor(logger = noopLogger, protocol = "https:") {
3446
3565
  this.logger = logger;
3566
+ this.protocol = protocol;
3447
3567
  this.versionCache = /* @__PURE__ */ new Map();
3448
3568
  }
3569
+ versionsUrl(hostname) {
3570
+ return `${httpScheme(this.protocol)}//${hostname}/api/versions`;
3571
+ }
3449
3572
  /**
3450
3573
  * Discovers the API version for a given hostname.
3451
3574
  *
3452
- * Makes a GET request to `https://{hostname}/api/versions` and returns the latest
3575
+ * Makes a GET request to `{protocol}//{hostname}/api/versions` and returns the latest
3453
3576
  * compatible version. Results are cached per hostname; the cache entry is removed
3454
3577
  * on failure so the next call retries.
3455
3578
  *
@@ -3463,8 +3586,10 @@ var VersionDiscovery = class {
3463
3586
  this.logger.info("Version discovery cache hit", { hostname });
3464
3587
  return cached;
3465
3588
  }
3466
- const url = `https://${hostname}/api/versions`;
3467
- this.logger.info("Starting version discovery", { hostname, url });
3589
+ this.logger.info("Starting version discovery", {
3590
+ hostname,
3591
+ url: this.versionsUrl(hostname)
3592
+ });
3468
3593
  const discovery$ = defer(() => from(this.fetchVersions(hostname))).pipe(
3469
3594
  map$1((versionStrings) => this.selectVersion(hostname, versionStrings)),
3470
3595
  catchError((error) => {
@@ -3502,7 +3627,7 @@ var VersionDiscovery = class {
3502
3627
  * misfile as a network error. Validating here keeps it an `InvalidVersionResponseError`.
3503
3628
  */
3504
3629
  async fetchVersions(hostname) {
3505
- const url = `https://${hostname}/api/versions`;
3630
+ const url = this.versionsUrl(hostname);
3506
3631
  const controller = new AbortController();
3507
3632
  const timer2 = setTimeout(() => controller.abort(), discoveryTimeoutMs);
3508
3633
  try {
@@ -3675,7 +3800,7 @@ async function createTrueNasClient(opts) {
3675
3800
  });
3676
3801
  return instantiateClientForVersion(known, opts, logger);
3677
3802
  }
3678
- const versionDiscovery = new VersionDiscovery(logger);
3803
+ const versionDiscovery = new VersionDiscovery(logger, opts.protocol);
3679
3804
  let version;
3680
3805
  try {
3681
3806
  const winner = await discoverVersionFromAnyHostname(
@@ -3784,7 +3909,8 @@ function instantiateClientForVersion(version, opts, logger) {
3784
3909
  version,
3785
3910
  enabled,
3786
3911
  systemName,
3787
- logger
3912
+ logger,
3913
+ opts.protocol
3788
3914
  );
3789
3915
  }
3790
3916
  function errorMessageOrDefault(error, fallback) {