@homelib/core 0.0.0-wip.01265bf1cc90

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.
Files changed (140) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +11 -0
  3. package/bld/exports/mobx.d.ts +1 -0
  4. package/bld/exports/mobx.js +2 -0
  5. package/bld/exports/mobx.js.map +1 -0
  6. package/bld/library/@lifecycle.d.ts +4 -0
  7. package/bld/library/@lifecycle.js +23 -0
  8. package/bld/library/@lifecycle.js.map +1 -0
  9. package/bld/library/atomics/index.d.ts +1 -0
  10. package/bld/library/atomics/index.js +2 -0
  11. package/bld/library/atomics/index.js.map +1 -0
  12. package/bld/library/atomics/temperature.d.ts +13 -0
  13. package/bld/library/atomics/temperature.js +53 -0
  14. package/bld/library/atomics/temperature.js.map +1 -0
  15. package/bld/library/command.d.ts +12 -0
  16. package/bld/library/command.js +21 -0
  17. package/bld/library/command.js.map +1 -0
  18. package/bld/library/device/index.d.ts +1 -0
  19. package/bld/library/device/index.js +2 -0
  20. package/bld/library/device/index.js.map +1 -0
  21. package/bld/library/device/sensor.d.ts +8 -0
  22. package/bld/library/device/sensor.js +2 -0
  23. package/bld/library/device/sensor.js.map +1 -0
  24. package/bld/library/device-namespace.d.ts +13 -0
  25. package/bld/library/device-namespace.js +11 -0
  26. package/bld/library/device-namespace.js.map +1 -0
  27. package/bld/library/device.d.ts +23 -0
  28. package/bld/library/device.js +92 -0
  29. package/bld/library/device.js.map +1 -0
  30. package/bld/library/devices/air-conditioner.d.ts +72 -0
  31. package/bld/library/devices/air-conditioner.js +246 -0
  32. package/bld/library/devices/air-conditioner.js.map +1 -0
  33. package/bld/library/devices/dehumidifier.d.ts +62 -0
  34. package/bld/library/devices/dehumidifier.js +211 -0
  35. package/bld/library/devices/dehumidifier.js.map +1 -0
  36. package/bld/library/devices/fan.d.ts +70 -0
  37. package/bld/library/devices/fan.js +229 -0
  38. package/bld/library/devices/fan.js.map +1 -0
  39. package/bld/library/devices/index.d.ts +6 -0
  40. package/bld/library/devices/index.js +7 -0
  41. package/bld/library/devices/index.js.map +1 -0
  42. package/bld/library/devices/light.d.ts +59 -0
  43. package/bld/library/devices/light.js +197 -0
  44. package/bld/library/devices/light.js.map +1 -0
  45. package/bld/library/devices/pet-feeder.d.ts +36 -0
  46. package/bld/library/devices/pet-feeder.js +115 -0
  47. package/bld/library/devices/pet-feeder.js.map +1 -0
  48. package/bld/library/devices/temperature-humidity-sensor.d.ts +18 -0
  49. package/bld/library/devices/temperature-humidity-sensor.js +86 -0
  50. package/bld/library/devices/temperature-humidity-sensor.js.map +1 -0
  51. package/bld/library/endpoint.d.ts +100 -0
  52. package/bld/library/endpoint.js +431 -0
  53. package/bld/library/endpoint.js.map +1 -0
  54. package/bld/library/home.d.ts +4 -0
  55. package/bld/library/home.js +11 -0
  56. package/bld/library/home.js.map +1 -0
  57. package/bld/library/index.d.ts +16 -0
  58. package/bld/library/index.js +17 -0
  59. package/bld/library/index.js.map +1 -0
  60. package/bld/library/log.d.ts +43 -0
  61. package/bld/library/log.js +78 -0
  62. package/bld/library/log.js.map +1 -0
  63. package/bld/library/provider.d.ts +26 -0
  64. package/bld/library/provider.js +18 -0
  65. package/bld/library/provider.js.map +1 -0
  66. package/bld/library/registry.d.ts +19 -0
  67. package/bld/library/registry.js +65 -0
  68. package/bld/library/registry.js.map +1 -0
  69. package/bld/library/runtime/@binding-creation.d.ts +4 -0
  70. package/bld/library/runtime/@binding-creation.js +19 -0
  71. package/bld/library/runtime/@binding-creation.js.map +1 -0
  72. package/bld/library/runtime/binding.d.ts +50 -0
  73. package/bld/library/runtime/binding.js +108 -0
  74. package/bld/library/runtime/binding.js.map +1 -0
  75. package/bld/library/runtime/bootstrap-frontend.d.ts +48 -0
  76. package/bld/library/runtime/bootstrap-frontend.js +96 -0
  77. package/bld/library/runtime/bootstrap-frontend.js.map +1 -0
  78. package/bld/library/runtime/bootstrap.d.ts +9 -0
  79. package/bld/library/runtime/bootstrap.js +165 -0
  80. package/bld/library/runtime/bootstrap.js.map +1 -0
  81. package/bld/library/runtime/environment.d.ts +1 -0
  82. package/bld/library/runtime/environment.js +7 -0
  83. package/bld/library/runtime/environment.js.map +1 -0
  84. package/bld/library/runtime/index.d.ts +4 -0
  85. package/bld/library/runtime/index.js +5 -0
  86. package/bld/library/runtime/index.js.map +1 -0
  87. package/bld/library/scope.d.ts +41 -0
  88. package/bld/library/scope.js +132 -0
  89. package/bld/library/scope.js.map +1 -0
  90. package/bld/library/types.d.ts +17 -0
  91. package/bld/library/types.js +8 -0
  92. package/bld/library/types.js.map +1 -0
  93. package/bld/library/utils/backoff.d.ts +10 -0
  94. package/bld/library/utils/backoff.js +63 -0
  95. package/bld/library/utils/backoff.js.map +1 -0
  96. package/bld/library/utils/constructor.d.ts +21 -0
  97. package/bld/library/utils/constructor.js +30 -0
  98. package/bld/library/utils/constructor.js.map +1 -0
  99. package/bld/library/utils/index.d.ts +2 -0
  100. package/bld/library/utils/index.js +3 -0
  101. package/bld/library/utils/index.js.map +1 -0
  102. package/bld/library/x-data-medium.d.ts +12 -0
  103. package/bld/library/x-data-medium.js +3 -0
  104. package/bld/library/x-data-medium.js.map +1 -0
  105. package/package.json +27 -0
  106. package/src/exports/mobx.ts +1 -0
  107. package/src/library/@lifecycle.ts +30 -0
  108. package/src/library/atomics/index.ts +1 -0
  109. package/src/library/atomics/temperature.ts +60 -0
  110. package/src/library/command.ts +25 -0
  111. package/src/library/device/index.ts +1 -0
  112. package/src/library/device/sensor.ts +10 -0
  113. package/src/library/device-namespace.ts +32 -0
  114. package/src/library/device.ts +91 -0
  115. package/src/library/devices/air-conditioner.ts +234 -0
  116. package/src/library/devices/dehumidifier.ts +200 -0
  117. package/src/library/devices/fan.ts +204 -0
  118. package/src/library/devices/index.ts +6 -0
  119. package/src/library/devices/light.ts +177 -0
  120. package/src/library/devices/pet-feeder.ts +98 -0
  121. package/src/library/devices/temperature-humidity-sensor.ts +67 -0
  122. package/src/library/endpoint.ts +610 -0
  123. package/src/library/home.ts +11 -0
  124. package/src/library/index.ts +16 -0
  125. package/src/library/log.ts +163 -0
  126. package/src/library/provider.ts +66 -0
  127. package/src/library/registry.ts +129 -0
  128. package/src/library/runtime/@binding-creation.ts +48 -0
  129. package/src/library/runtime/binding.ts +165 -0
  130. package/src/library/runtime/bootstrap-frontend.ts +243 -0
  131. package/src/library/runtime/bootstrap.ts +286 -0
  132. package/src/library/runtime/environment.ts +6 -0
  133. package/src/library/runtime/index.ts +4 -0
  134. package/src/library/scope.ts +193 -0
  135. package/src/library/types/global.d.ts +8 -0
  136. package/src/library/types.ts +26 -0
  137. package/src/library/utils/backoff.ts +65 -0
  138. package/src/library/utils/constructor.ts +89 -0
  139. package/src/library/utils/index.ts +2 -0
  140. package/src/library/x-data-medium.ts +16 -0
@@ -0,0 +1,163 @@
1
+ import type {Command} from './command.js';
2
+ import type {EndpointLogState} from './endpoint.js';
3
+
4
+ const endpointLogTargetMap = new WeakMap<object, EndpointLogTarget>();
5
+ const logListenerSet = new Set<LogListener>();
6
+
7
+ export type EndpointLogTarget = {
8
+ readonly scopePath: readonly string[];
9
+ readonly deviceName: string;
10
+ readonly endpointName: string;
11
+ };
12
+
13
+ export type LogEvent =
14
+ EndpointCommandLogEvent | EndpointStateLogEvent | ErrorLogEvent;
15
+
16
+ export type EndpointCommandLogEvent = {
17
+ readonly type: 'endpoint-command';
18
+ /** Unix timestamp in milliseconds. */
19
+ readonly timestamp: number;
20
+ /** The execution decision made by Core. */
21
+ readonly action: 'execute' | 'skip';
22
+ readonly target: EndpointLogTarget;
23
+ readonly connectionDescription: string | undefined;
24
+ readonly commandDescription: string;
25
+ };
26
+
27
+ export type EndpointStateLogEvent = {
28
+ readonly type: 'endpoint-state';
29
+ /** Unix timestamp in milliseconds. */
30
+ readonly timestamp: number;
31
+ readonly target: EndpointLogTarget;
32
+ readonly connectionDescription: string | undefined;
33
+ readonly state: EndpointLogState;
34
+ readonly previousState: EndpointLogState | undefined;
35
+ };
36
+
37
+ export type ErrorLogEvent = {
38
+ readonly type: 'error';
39
+ /** Unix timestamp in milliseconds. */
40
+ readonly timestamp: number;
41
+ readonly error: unknown;
42
+ };
43
+
44
+ export type LogListener = (event: LogEvent) => void;
45
+
46
+ export function addLogListener(listener: LogListener): () => void {
47
+ logListenerSet.add(listener);
48
+
49
+ return () => {
50
+ logListenerSet.delete(listener);
51
+ };
52
+ }
53
+
54
+ export function setEndpointLogTarget(
55
+ endpoint: object,
56
+ target: EndpointLogTarget,
57
+ ): void {
58
+ endpointLogTargetMap.set(endpoint, target);
59
+ }
60
+
61
+ export function hasEndpointLogTarget(endpoint: object): boolean {
62
+ return endpointLogTargetMap.has(endpoint);
63
+ }
64
+
65
+ export function logEndpointCommand(
66
+ endpoint: object,
67
+ connection: Loggable,
68
+ command: Command,
69
+ action: EndpointCommandLogEvent['action'],
70
+ execution: Loggable | undefined = undefined,
71
+ ): void {
72
+ try {
73
+ const target = endpointLogTargetMap.get(endpoint);
74
+
75
+ if (target !== undefined) {
76
+ emitLogEvent({
77
+ type: 'endpoint-command',
78
+ action,
79
+ target,
80
+ connectionDescription: safeLogString(
81
+ connection,
82
+ connection.constructor.name,
83
+ ),
84
+ commandDescription:
85
+ safeLogString(execution) ??
86
+ safeLogString(command) ??
87
+ command.constructor.name,
88
+ });
89
+ }
90
+ } catch {
91
+ // Logging must never affect command processing.
92
+ }
93
+ }
94
+
95
+ export function logEndpointState(
96
+ endpoint: object,
97
+ connection: Loggable,
98
+ state: EndpointLogState,
99
+ previousState: EndpointLogState | undefined,
100
+ ): void {
101
+ try {
102
+ const target = endpointLogTargetMap.get(endpoint);
103
+
104
+ if (target !== undefined) {
105
+ emitLogEvent({
106
+ type: 'endpoint-state',
107
+ target,
108
+ connectionDescription: safeLogString(
109
+ connection,
110
+ connection.constructor.name,
111
+ ),
112
+ state,
113
+ previousState,
114
+ });
115
+ }
116
+ } catch {
117
+ // Logging must never affect state propagation.
118
+ }
119
+ }
120
+
121
+ export function logEndpointError(error: unknown): void {
122
+ emitLogEvent({type: 'error', error});
123
+ }
124
+
125
+ function emitLogEvent(event: LogEventWithoutTimestamp): void {
126
+ const timestampedEvent = {...event, timestamp: Date.now()} as LogEvent;
127
+
128
+ for (const listener of logListenerSet) {
129
+ try {
130
+ listener(timestampedEvent);
131
+ } catch {
132
+ // A log listener must never affect another listener or homelib itself.
133
+ }
134
+ }
135
+ }
136
+
137
+ function safeLogString(
138
+ value: Loggable | undefined,
139
+ errorFallback: string | undefined = undefined,
140
+ ): string | undefined {
141
+ if (value === undefined) {
142
+ return undefined;
143
+ }
144
+
145
+ try {
146
+ const {toLogString} = value;
147
+
148
+ return typeof toLogString === 'function'
149
+ ? String(toLogString.call(value))
150
+ : undefined;
151
+ } catch {
152
+ return errorFallback;
153
+ }
154
+ }
155
+
156
+ export type Loggable = {
157
+ readonly toLogString?: () => string;
158
+ };
159
+
160
+ type LogEventWithoutTimestamp =
161
+ | Omit<EndpointCommandLogEvent, 'timestamp'>
162
+ | Omit<EndpointStateLogEvent, 'timestamp'>
163
+ | Omit<ErrorLogEvent, 'timestamp'>;
@@ -0,0 +1,66 @@
1
+ import * as x from 'x-value';
2
+
3
+ import type {Device, DeviceConstructor} from './device.js';
4
+ import type {
5
+ EndpointConnection,
6
+ EndpointConnectionBinding,
7
+ EndpointConnectionMetadata,
8
+ EndpointReference,
9
+ } from './endpoint.js';
10
+ import type {NamedObject, types} from './types.js';
11
+
12
+ export const ProviderName = x.string.nominal<'provider name'>();
13
+
14
+ export type ProviderName = x.TypeOf<typeof ProviderName>;
15
+
16
+ export abstract class Provider<
17
+ TMetadata extends EndpointConnectionMetadata = EndpointConnectionMetadata,
18
+ > implements NamedObject<ProviderName> {
19
+ declare [types]: {name: ProviderName};
20
+
21
+ readonly name: ProviderName;
22
+
23
+ abstract readonly EndpointConnectionMetadata: x.XTypeOfValue<TMetadata>;
24
+
25
+ constructor(name: string) {
26
+ this.name = name as ProviderName;
27
+ }
28
+
29
+ abstract get endpointConnections(): readonly EndpointConnection<never>[];
30
+
31
+ createEndpointConnectionBindingPlan(
32
+ endpoint: EndpointReference,
33
+ deviceConstructors: readonly DeviceConstructor<Device>[],
34
+ metadata: unknown,
35
+ ): EndpointConnectionBindingPlan {
36
+ const validatedMetadata =
37
+ this.EndpointConnectionMetadata.satisfies(metadata);
38
+
39
+ return this.createEndpointConnectionBindingPlanFromMetadata(
40
+ endpoint,
41
+ deviceConstructors,
42
+ validatedMetadata,
43
+ );
44
+ }
45
+
46
+ protected abstract createEndpointConnectionBindingPlanFromMetadata(
47
+ endpoint: EndpointReference,
48
+ deviceConstructors: readonly DeviceConstructor<Device>[],
49
+ metadata: TMetadata,
50
+ ): EndpointConnectionBindingPlan;
51
+ }
52
+
53
+ export type EndpointConnectionBindingPlan = {
54
+ readonly resourceKeys: readonly string[];
55
+ create(): PromiseLike<EndpointConnectionBinding>;
56
+ };
57
+
58
+ export type RuntimeProvider = {
59
+ readonly name: ProviderName;
60
+ readonly endpointConnections: readonly EndpointConnection<never>[];
61
+ createEndpointConnectionBindingPlan(
62
+ endpoint: EndpointReference,
63
+ deviceConstructors: readonly DeviceConstructor<Device>[],
64
+ metadata: unknown,
65
+ ): EndpointConnectionBindingPlan;
66
+ };
@@ -0,0 +1,129 @@
1
+ import {assertDeclaring} from './@lifecycle.js';
2
+ import type {Device, DeviceConstructor} from './device.js';
3
+ import type {EndpointConnectionMetadata} from './endpoint.js';
4
+ import {Provider, type RuntimeProvider} from './provider.js';
5
+ import type {Scope} from './scope.js';
6
+
7
+ const PROVIDER_MAP = new Map<string, Map<string, RuntimeProvider>>();
8
+ const DEVICE_CONSTRUCTOR_MAP = new Map<string, DeviceConstructor<Device>>();
9
+ const PROVIDER_NAMESPACE_DEVICE_CONSTRUCTOR_MAP = new Map<
10
+ string,
11
+ Map<string, DeviceConstructor<Device>>
12
+ >();
13
+ const ROOT_SCOPE_SET = new Set<Scope>();
14
+
15
+ export function register<TMetadata extends EndpointConnectionMetadata>(
16
+ providerNamespace: Extract<keyof Home.ProviderNamespaces, string>,
17
+ provider: Provider<TMetadata>,
18
+ ): void;
19
+ export function register(
20
+ constructors: DeviceConstructors<Home.DeviceConstructors>,
21
+ ): void;
22
+ export function register<
23
+ TProviderNamespace extends Extract<keyof Home.ProviderNamespaces, string>,
24
+ >(
25
+ providerNamespace: TProviderNamespace,
26
+ constructors: ProviderNamespaceDeviceConstructors<
27
+ Home.ProviderNamespaces[TProviderNamespace]
28
+ >,
29
+ ): void;
30
+ export function register(
31
+ objectOrProviderNamespace:
32
+ | Record<string, DeviceConstructor<Device>>
33
+ | Extract<keyof Home.ProviderNamespaces, string>,
34
+ providerOrConstructors?:
35
+ RuntimeProvider | Record<string, DeviceConstructor<Device>>,
36
+ ): void {
37
+ assertDeclaring();
38
+
39
+ if (typeof objectOrProviderNamespace === 'string') {
40
+ if (providerOrConstructors instanceof Provider) {
41
+ registerProvider(objectOrProviderNamespace, providerOrConstructors);
42
+ } else if (providerOrConstructors === undefined) {
43
+ throw new TypeError('Expecting a provider or device constructors.');
44
+ } else {
45
+ PROVIDER_NAMESPACE_DEVICE_CONSTRUCTOR_MAP.set(
46
+ objectOrProviderNamespace,
47
+ new Map(Object.entries(providerOrConstructors)),
48
+ );
49
+ }
50
+ } else {
51
+ for (const [deviceType, Constructor] of Object.entries(
52
+ objectOrProviderNamespace,
53
+ )) {
54
+ DEVICE_CONSTRUCTOR_MAP.set(deviceType, Constructor);
55
+ }
56
+ }
57
+ }
58
+
59
+ export function registerRootScope(scope: Scope): void {
60
+ assertDeclaring();
61
+ ROOT_SCOPE_SET.add(scope);
62
+ }
63
+
64
+ export function* getProviderEntries(): IterableIterator<
65
+ readonly [namespace: string, provider: RuntimeProvider]
66
+ > {
67
+ for (const [namespace, providerNameMap] of PROVIDER_MAP) {
68
+ for (const provider of providerNameMap.values()) {
69
+ yield [namespace, provider];
70
+ }
71
+ }
72
+ }
73
+
74
+ export function getProvider(
75
+ providerNamespace: string,
76
+ providerName: string,
77
+ ): RuntimeProvider | undefined {
78
+ return PROVIDER_MAP.get(providerNamespace)?.get(providerName);
79
+ }
80
+
81
+ export function getDeviceConstructor(
82
+ deviceType: string,
83
+ ): DeviceConstructor<Device> | undefined {
84
+ return DEVICE_CONSTRUCTOR_MAP.get(deviceType);
85
+ }
86
+
87
+ export function hasProviderNamespace(providerNamespace: string): boolean {
88
+ return PROVIDER_NAMESPACE_DEVICE_CONSTRUCTOR_MAP.has(providerNamespace);
89
+ }
90
+
91
+ export function getProviderNamespaceDeviceConstructor(
92
+ providerNamespace: string,
93
+ deviceType: string,
94
+ ): DeviceConstructor<Device> | undefined {
95
+ return PROVIDER_NAMESPACE_DEVICE_CONSTRUCTOR_MAP.get(providerNamespace)?.get(
96
+ deviceType,
97
+ );
98
+ }
99
+
100
+ export function getRootScopes(): IterableIterator<Scope> {
101
+ return ROOT_SCOPE_SET.values();
102
+ }
103
+
104
+ type DeviceConstructors<TDevices> = {
105
+ [TKey in Extract<keyof TDevices, string>]: DeviceConstructor<
106
+ TDevices[TKey] & Device
107
+ >;
108
+ };
109
+
110
+ type ProviderNamespaceDeviceConstructors<TDevices> =
111
+ DeviceConstructors<TDevices>;
112
+
113
+ function registerProvider(
114
+ providerNamespace: string,
115
+ provider: RuntimeProvider,
116
+ ): void {
117
+ let providerNameMap = PROVIDER_MAP.get(providerNamespace);
118
+
119
+ if (providerNameMap === undefined) {
120
+ providerNameMap = new Map();
121
+ PROVIDER_MAP.set(providerNamespace, providerNameMap);
122
+ }
123
+
124
+ if (providerNameMap.has(provider.name)) {
125
+ throw new TypeError(`Duplicate provider: ${provider.name}.`);
126
+ }
127
+
128
+ providerNameMap.set(provider.name, provider);
129
+ }
@@ -0,0 +1,48 @@
1
+ import type {EndpointConnectionBinding} from '../endpoint.js';
2
+ import type {EndpointConnectionBindingPlan} from '../provider.js';
3
+
4
+ export async function createEndpointConnectionBindings(
5
+ plans: readonly EndpointConnectionBindingPlan[],
6
+ ): Promise<readonly EndpointConnectionBinding[]> {
7
+ const results = await Promise.allSettled(
8
+ plans.map(async plan => plan.create()),
9
+ );
10
+ const creationErrors = results.flatMap(result =>
11
+ result.status === 'rejected' ? [result.reason] : [],
12
+ );
13
+
14
+ if (creationErrors.length === 0) {
15
+ return results.flatMap(result =>
16
+ result.status === 'fulfilled' ? [result.value] : [],
17
+ );
18
+ }
19
+
20
+ const disposalErrors = await disposeEndpointConnectionBindings(
21
+ results.flatMap(result =>
22
+ result.status === 'fulfilled' ? [result.value] : [],
23
+ ),
24
+ );
25
+ const errors = [...creationErrors, ...disposalErrors];
26
+ const [error] = errors;
27
+
28
+ if (errors.length === 1 && error !== undefined) {
29
+ throw error;
30
+ }
31
+
32
+ throw new AggregateError(
33
+ errors,
34
+ 'Failed to create endpoint connection bindings.',
35
+ );
36
+ }
37
+
38
+ export async function disposeEndpointConnectionBindings(
39
+ bindings: readonly EndpointConnectionBinding[],
40
+ ): Promise<readonly unknown[]> {
41
+ const results = await Promise.allSettled(
42
+ bindings.map(async binding => binding.dispose()),
43
+ );
44
+
45
+ return results.flatMap(result =>
46
+ result.status === 'rejected' ? [result.reason] : [],
47
+ );
48
+ }
@@ -0,0 +1,165 @@
1
+ import {randomUUID} from 'node:crypto';
2
+ import {mkdir, open, readFile, rename, rm} from 'node:fs/promises';
3
+ import {dirname, join} from 'node:path';
4
+
5
+ import * as x from 'x-value';
6
+
7
+ import type {DeviceEntry} from '../device.js';
8
+ import type {EndpointReference} from '../endpoint.js';
9
+ import {ProviderName} from '../provider.js';
10
+ import {type Scope, ScopePath} from '../scope.js';
11
+
12
+ import {getEnvironmentDirectory} from './environment.js';
13
+
14
+ export const EndpointPath = x.object({
15
+ scopePath: ScopePath,
16
+ deviceName: x.string,
17
+ endpointName: x.string,
18
+ });
19
+
20
+ export type EndpointPath = Readonly<x.TypeOf<typeof EndpointPath>>;
21
+
22
+ export const ProviderReference = x.object({
23
+ namespace: x.string,
24
+ name: ProviderName,
25
+ });
26
+
27
+ export type ProviderReference = Readonly<x.TypeOf<typeof ProviderReference>>;
28
+
29
+ export const EndpointBinding = x.object({
30
+ endpoint: EndpointPath,
31
+ provider: ProviderReference,
32
+ metadata: x.unknown,
33
+ });
34
+
35
+ export type EndpointBinding = Readonly<x.TypeOf<typeof EndpointBinding>>;
36
+
37
+ export const BindingFile = x.object({
38
+ version: x.literal(0),
39
+ bindings: x.array(EndpointBinding),
40
+ });
41
+
42
+ export type BindingFile = Readonly<x.TypeOf<typeof BindingFile>>;
43
+
44
+ export async function readBindingFile(): Promise<BindingFile> {
45
+ const path = getBindingFilePath();
46
+ let source: string;
47
+
48
+ try {
49
+ source = await readFile(path, 'utf8');
50
+ } catch (error) {
51
+ if (isFileNotFoundError(error)) {
52
+ return {version: 0, bindings: []};
53
+ }
54
+
55
+ throw error;
56
+ }
57
+
58
+ return BindingFile.satisfies(JSON.parse(source));
59
+ }
60
+
61
+ export async function writeBindingFile(file: BindingFile): Promise<void> {
62
+ const validatedFile = BindingFile.satisfies(file);
63
+ const path = getBindingFilePath();
64
+ const temporaryPath = `${path}.${randomUUID()}.tmp`;
65
+
66
+ await mkdir(dirname(path), {recursive: true, mode: 0o700});
67
+
68
+ try {
69
+ const handle = await open(temporaryPath, 'wx', 0o600);
70
+
71
+ try {
72
+ await handle.writeFile(
73
+ `${JSON.stringify(validatedFile, undefined, 2)}\n`,
74
+ );
75
+ await handle.sync();
76
+ } finally {
77
+ await handle.close();
78
+ }
79
+
80
+ await rename(temporaryPath, path);
81
+ } finally {
82
+ await rm(temporaryPath, {force: true});
83
+ }
84
+ }
85
+
86
+ export function upsertEndpointBinding(
87
+ file: BindingFile,
88
+ binding: EndpointBinding,
89
+ ): BindingFile {
90
+ const validatedBinding = EndpointBinding.satisfies(binding);
91
+ const bindings = file.bindings.filter(
92
+ item => !endpointPathsEqual(item.endpoint, validatedBinding.endpoint),
93
+ );
94
+
95
+ bindings.push(validatedBinding);
96
+ bindings.sort(compareEndpointBindings);
97
+
98
+ return {version: 0, bindings};
99
+ }
100
+
101
+ export function removeEndpointBinding(
102
+ file: BindingFile,
103
+ endpoint: EndpointPath,
104
+ ): BindingFile {
105
+ const validatedEndpoint = EndpointPath.satisfies(endpoint);
106
+
107
+ return {
108
+ version: 0,
109
+ bindings: file.bindings.filter(
110
+ binding => !endpointPathsEqual(binding.endpoint, validatedEndpoint),
111
+ ),
112
+ };
113
+ }
114
+
115
+ export function getEndpointPathKey(path: EndpointPath): string {
116
+ return JSON.stringify([path.scopePath, path.deviceName, path.endpointName]);
117
+ }
118
+
119
+ export function getEndpointPath(
120
+ scope: Scope,
121
+ deviceEntry: DeviceEntry,
122
+ endpoint: EndpointReference,
123
+ ): EndpointPath {
124
+ return {
125
+ scopePath: scope.path,
126
+ deviceName: deviceEntry.name,
127
+ endpointName: endpoint.name,
128
+ };
129
+ }
130
+
131
+ function isFileNotFoundError(error: unknown): boolean {
132
+ if (typeof error !== 'object' || error === null || !('code' in error)) {
133
+ return false;
134
+ }
135
+
136
+ return error.code === 'ENOENT';
137
+ }
138
+
139
+ function getBindingFilePath(): string {
140
+ return join(getEnvironmentDirectory(), 'bindings.json');
141
+ }
142
+
143
+ function endpointPathsEqual(left: EndpointPath, right: EndpointPath): boolean {
144
+ return getEndpointPathKey(left) === getEndpointPathKey(right);
145
+ }
146
+
147
+ function compareEndpointBindings(
148
+ left: EndpointBinding,
149
+ right: EndpointBinding,
150
+ ): number {
151
+ return compareStrings(
152
+ getEndpointPathKey(left.endpoint),
153
+ getEndpointPathKey(right.endpoint),
154
+ );
155
+ }
156
+
157
+ function compareStrings(left: string, right: string): number {
158
+ if (left < right) {
159
+ return -1;
160
+ } else if (left > right) {
161
+ return 1;
162
+ }
163
+
164
+ return 0;
165
+ }