@camstack/develop 0.1.44 → 0.1.45
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/CHANGELOG.md +6 -0
- package/dist/examples/catalogue.d.ts.map +1 -1
- package/dist/examples/catalogue.js +76 -0
- package/dist/examples/find.js +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/scaffold/addon.d.ts.map +1 -1
- package/dist/scaffold/addon.js +104 -10
- package/dist/scaffold/extend.js +5 -4
- package/dist/scaffold/integration-device.d.ts +10 -0
- package/dist/scaffold/integration-device.d.ts.map +1 -0
- package/dist/scaffold/integration-device.js +438 -0
- package/dist/scaffold/integration-exporter.d.ts +9 -0
- package/dist/scaffold/integration-exporter.d.ts.map +1 -0
- package/dist/scaffold/integration-exporter.js +267 -0
- package/dist/scaffold/integration-service.d.ts +7 -0
- package/dist/scaffold/integration-service.d.ts.map +1 -0
- package/dist/scaffold/integration-service.js +153 -0
- package/dist/types.d.ts +9 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +16 -1
- package/package.json +1 -1
- package/skills/camstack-addon.md +36 -1
- package/skills/camstack-capability.md +2 -2
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Templates of the `device-integration` scaffold (D1007, D996, D865): an addon whose integration
|
|
3
|
+
* is a typed instance record (connection + secret + test) and which brings devices. The
|
|
4
|
+
* integration's Gateway device is a SIBLING of the devices it brings, never their parent.
|
|
5
|
+
*/
|
|
6
|
+
export const DEVICE_INSTANCES_TS = `/**
|
|
7
|
+
* <%= displayName %> integrations as \`integration-instances\` (D1007): one \`connections\` record per
|
|
8
|
+
* integration, keyed by the registry id, holding the connection to ONE <%= displayName %> system. The
|
|
9
|
+
* token is a secret by TYPE; the records door keeps it in the keychain. The Gateway device is not
|
|
10
|
+
* part of the record: it is a device OF the integration, adopted from it.
|
|
11
|
+
*/
|
|
12
|
+
import {
|
|
13
|
+
type ConfigUISchema,
|
|
14
|
+
defineEntryKind,
|
|
15
|
+
entryBody,
|
|
16
|
+
type IntegrationTestConnectionResult,
|
|
17
|
+
RecordIntegrationInstances,
|
|
18
|
+
type RecordsAccess,
|
|
19
|
+
} from '@camstack/types'
|
|
20
|
+
import { z } from 'zod'
|
|
21
|
+
|
|
22
|
+
export const <%= className %>ConnectionsKind = defineEntryKind('connections', {
|
|
23
|
+
title: '<%= displayName %> integrations',
|
|
24
|
+
schema: entryBody({
|
|
25
|
+
host: z.string().optional(),
|
|
26
|
+
token: z.string().optional().meta({ secret: true }),
|
|
27
|
+
}),
|
|
28
|
+
writeTrigger: 'an operator adds, edits or removes a <%= displayName %> integration',
|
|
29
|
+
})
|
|
30
|
+
export type <%= className %>ConnectionBody = z.infer<typeof <%= className %>ConnectionsKind.schema>
|
|
31
|
+
|
|
32
|
+
/** Every record kind this addon declares, keyed by its name. */
|
|
33
|
+
export const <%= className %>RecordKinds = { connections: <%= className %>ConnectionsKind } as const
|
|
34
|
+
|
|
35
|
+
export function build<%= className %>ConnectionForm(): ConfigUISchema {
|
|
36
|
+
return {
|
|
37
|
+
sections: [
|
|
38
|
+
{
|
|
39
|
+
id: 'connection',
|
|
40
|
+
title: 'Connection',
|
|
41
|
+
columns: 1,
|
|
42
|
+
fields: [
|
|
43
|
+
{ type: 'text', key: 'name', label: 'Name' },
|
|
44
|
+
{ type: 'text', key: 'host', label: 'Host' },
|
|
45
|
+
{ type: 'password', key: 'token', label: 'Token', showToggle: true },
|
|
46
|
+
],
|
|
47
|
+
},
|
|
48
|
+
],
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface <%= className %>InstanceDeps {
|
|
53
|
+
/** Re-apply the runtime from the records after a create, update, enable or delete. */
|
|
54
|
+
readonly onChanged: () => Promise<void>
|
|
55
|
+
/** Probe the remote with the (possibly unsaved) values; a failed probe is not a pass. */
|
|
56
|
+
readonly probe: (values: Readonly<Record<string, unknown>>) => Promise<IntegrationTestConnectionResult>
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function build<%= className %>Instances(
|
|
60
|
+
records: Pick<RecordsAccess, 'kind' | 'owner'>,
|
|
61
|
+
deps: <%= className %>InstanceDeps,
|
|
62
|
+
): RecordIntegrationInstances<<%= className %>ConnectionBody> {
|
|
63
|
+
return new RecordIntegrationInstances<<%= className %>ConnectionBody>(
|
|
64
|
+
records,
|
|
65
|
+
<%= className %>ConnectionsKind,
|
|
66
|
+
{
|
|
67
|
+
description: {
|
|
68
|
+
role: 'devices',
|
|
69
|
+
discovery: { mode: 'account', scopedToInstance: true },
|
|
70
|
+
instanceMode: 'multiple',
|
|
71
|
+
kind: 'server',
|
|
72
|
+
canTest: true,
|
|
73
|
+
},
|
|
74
|
+
formSchema: () => build<%= className %>ConnectionForm(),
|
|
75
|
+
initialBody: (name): <%= className %>ConnectionBody => ({ name }),
|
|
76
|
+
configured: (body) => (body.host ?? '').length > 0,
|
|
77
|
+
onChanged: () => deps.onChanged(),
|
|
78
|
+
test: ({ values }) => deps.probe(values),
|
|
79
|
+
},
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
`;
|
|
83
|
+
export const DEVICE_DEVICES_TS = `/**
|
|
84
|
+
* The devices of an integration. Every one carries its \`integrationId\` in its persisted config, so
|
|
85
|
+
* a cascade can find what an integration owns. The Gateway is the integration's own presence in the
|
|
86
|
+
* device list and a SIBLING of the sensors: nothing is its child.
|
|
87
|
+
*
|
|
88
|
+
* Per-device configuration lives ONLY in \`ctx.settings.*DeviceStore\`, never in a field of the
|
|
89
|
+
* addon's own storage (D865).
|
|
90
|
+
*/
|
|
91
|
+
import { BaseDevice, type DeviceContext, type DeviceFeature, DeviceType } from '@camstack/types'
|
|
92
|
+
import { z } from 'zod'
|
|
93
|
+
|
|
94
|
+
export const <%= className %>_SYSTEM = '<%= fileName %>'
|
|
95
|
+
export const <%= className %>_GATEWAY_ID = 'gateway'
|
|
96
|
+
|
|
97
|
+
export const <%= className %>GatewaySchema = z.object({
|
|
98
|
+
equipment: z.literal(<%= className %>_GATEWAY_ID),
|
|
99
|
+
integrationId: z.string().min(1).describe('Owning integration'),
|
|
100
|
+
system: z.literal(<%= className %>_SYSTEM).optional(),
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
export class <%= className %>GatewayDevice extends BaseDevice<typeof <%= className %>GatewaySchema> {
|
|
104
|
+
readonly features: readonly DeviceFeature[] = []
|
|
105
|
+
|
|
106
|
+
constructor(ctx: DeviceContext) {
|
|
107
|
+
<%= className %>GatewaySchema.parse(ctx.persistedConfig ?? {})
|
|
108
|
+
super(ctx, <%= className %>GatewaySchema, { type: DeviceType.Gateway })
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export const <%= className %>SensorSchema = z.object({
|
|
113
|
+
equipment: z.string().min(1).describe('Remote id of the sensor'),
|
|
114
|
+
integrationId: z.string().min(1).describe('Owning integration'),
|
|
115
|
+
system: z.literal(<%= className %>_SYSTEM).optional(),
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
export class <%= className %>SensorDevice extends BaseDevice<typeof <%= className %>SensorSchema> {
|
|
119
|
+
readonly features: readonly DeviceFeature[] = []
|
|
120
|
+
|
|
121
|
+
constructor(ctx: DeviceContext) {
|
|
122
|
+
<%= className %>SensorSchema.parse(ctx.persistedConfig ?? {})
|
|
123
|
+
super(ctx, <%= className %>SensorSchema, { type: DeviceType.Sensor })
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
`;
|
|
127
|
+
export const DEVICE_ADOPTION_TS = `/**
|
|
128
|
+
* Discovery and adoption for <%= displayName %>. The Gateway and every sensor are offered as
|
|
129
|
+
* SIBLING candidates (the Gateway is never the parent of the sensors); adopting one creates a
|
|
130
|
+
* top-level device carrying the integration id. Replace \`discover\` with a real read of the remote.
|
|
131
|
+
*/
|
|
132
|
+
import {
|
|
133
|
+
DeviceType,
|
|
134
|
+
type DiscoveredChildDevice,
|
|
135
|
+
errMsg,
|
|
136
|
+
type IDeviceAdoptionProvider,
|
|
137
|
+
type IScopedLogger,
|
|
138
|
+
} from '@camstack/types'
|
|
139
|
+
import { <%= className %>_GATEWAY_ID } from './<%= fileName %>-devices.js'
|
|
140
|
+
|
|
141
|
+
export interface RemoteSensor {
|
|
142
|
+
readonly id: string
|
|
143
|
+
readonly name: string
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export interface <%= className %>AdoptionDeps {
|
|
147
|
+
readonly hasIntegration: (integrationId: string) => Promise<boolean>
|
|
148
|
+
readonly listIntegrations: () => Promise<readonly string[]>
|
|
149
|
+
/** What the remote reports for the integration, or null while it is unreachable. */
|
|
150
|
+
readonly discover: (integrationId: string) => Promise<readonly RemoteSensor[] | null>
|
|
151
|
+
/** Remote ids of the devices already adopted for the integration, with their device id. */
|
|
152
|
+
readonly adopted: (integrationId: string) => Promise<ReadonlyMap<string, number>>
|
|
153
|
+
readonly create: (input: {
|
|
154
|
+
readonly integrationId: string
|
|
155
|
+
readonly equipment: string
|
|
156
|
+
readonly type: DeviceType.Gateway | DeviceType.Sensor
|
|
157
|
+
readonly name: string
|
|
158
|
+
}) => Promise<number>
|
|
159
|
+
readonly remove: (deviceId: number) => Promise<void>
|
|
160
|
+
readonly logger: IScopedLogger
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function build<%= className %>AdoptionProvider(
|
|
164
|
+
deps: <%= className %>AdoptionDeps,
|
|
165
|
+
): IDeviceAdoptionProvider {
|
|
166
|
+
async function candidates(integrationId: string): Promise<readonly DiscoveredChildDevice[]> {
|
|
167
|
+
const sensors = await deps.discover(integrationId)
|
|
168
|
+
const adopted = await deps.adopted(integrationId)
|
|
169
|
+
const offered: DiscoveredChildDevice[] = [
|
|
170
|
+
{
|
|
171
|
+
childNativeId: <%= className %>_GATEWAY_ID,
|
|
172
|
+
name: '<%= displayName %>',
|
|
173
|
+
type: DeviceType.Gateway,
|
|
174
|
+
status: sensors === null ? 'offline' : 'online',
|
|
175
|
+
metadata: {},
|
|
176
|
+
alreadyAdopted: adopted.has(<%= className %>_GATEWAY_ID),
|
|
177
|
+
adoptedDeviceId: adopted.get(<%= className %>_GATEWAY_ID) ?? null,
|
|
178
|
+
capabilities: [],
|
|
179
|
+
},
|
|
180
|
+
]
|
|
181
|
+
for (const sensor of sensors ?? []) {
|
|
182
|
+
offered.push({
|
|
183
|
+
childNativeId: sensor.id,
|
|
184
|
+
name: sensor.name,
|
|
185
|
+
type: DeviceType.Sensor,
|
|
186
|
+
status: 'online',
|
|
187
|
+
metadata: {},
|
|
188
|
+
alreadyAdopted: adopted.has(sensor.id),
|
|
189
|
+
adoptedDeviceId: adopted.get(sensor.id) ?? null,
|
|
190
|
+
capabilities: [],
|
|
191
|
+
})
|
|
192
|
+
}
|
|
193
|
+
return offered
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function status(integrationId: string) {
|
|
197
|
+
const all = await candidates(integrationId)
|
|
198
|
+
return {
|
|
199
|
+
lastDiscoveryAt: Date.now(),
|
|
200
|
+
candidateCount: all.length,
|
|
201
|
+
adoptedCount: all.filter((c) => c.alreadyAdopted).length,
|
|
202
|
+
lastError: null,
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
listCandidateFilters: async () => ({
|
|
208
|
+
filters: [{ id: 'devices', label: 'Devices', isDefault: true }],
|
|
209
|
+
}),
|
|
210
|
+
listCandidates: async ({ integrationId, page, pageSize }) => {
|
|
211
|
+
const all = await candidates(integrationId)
|
|
212
|
+
const start = (page - 1) * pageSize
|
|
213
|
+
return {
|
|
214
|
+
candidates: all.slice(start, start + pageSize),
|
|
215
|
+
totalCount: all.length,
|
|
216
|
+
page,
|
|
217
|
+
pageSize,
|
|
218
|
+
}
|
|
219
|
+
},
|
|
220
|
+
getCandidate: async ({ integrationId, childNativeId }) =>
|
|
221
|
+
(await candidates(integrationId)).find((c) => c.childNativeId === childNativeId) ?? null,
|
|
222
|
+
getStatus: async () => {
|
|
223
|
+
try {
|
|
224
|
+
let candidateCount = 0
|
|
225
|
+
let adoptedCount = 0
|
|
226
|
+
for (const integrationId of await deps.listIntegrations()) {
|
|
227
|
+
const s = await status(integrationId)
|
|
228
|
+
candidateCount += s.candidateCount
|
|
229
|
+
adoptedCount += s.adoptedCount
|
|
230
|
+
}
|
|
231
|
+
return { lastDiscoveryAt: Date.now(), candidateCount, adoptedCount, lastError: null }
|
|
232
|
+
} catch (err: unknown) {
|
|
233
|
+
return { lastDiscoveryAt: null, candidateCount: 0, adoptedCount: 0, lastError: errMsg(err) }
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
refresh: async ({ integrationId }) => status(integrationId),
|
|
237
|
+
adopt: async ({ integrationId, childNativeIds, perCandidate }) => {
|
|
238
|
+
if (!(await deps.hasIntegration(integrationId))) {
|
|
239
|
+
throw new Error('<%= fileName %> adopt: integration ' + integrationId + ' not found')
|
|
240
|
+
}
|
|
241
|
+
const offered = await candidates(integrationId)
|
|
242
|
+
const adopted: Array<{
|
|
243
|
+
readonly childNativeId: string
|
|
244
|
+
readonly parentDeviceId: number
|
|
245
|
+
readonly accessoryDeviceIds: readonly number[]
|
|
246
|
+
}> = []
|
|
247
|
+
for (const childNativeId of childNativeIds) {
|
|
248
|
+
const candidate = offered.find((c) => c.childNativeId === childNativeId)
|
|
249
|
+
if (candidate === undefined) {
|
|
250
|
+
deps.logger.warn('<%= fileName %> adopt: the remote reports nothing for this id', {
|
|
251
|
+
meta: { childNativeId, integrationId },
|
|
252
|
+
})
|
|
253
|
+
continue
|
|
254
|
+
}
|
|
255
|
+
const deviceId = await deps.create({
|
|
256
|
+
integrationId,
|
|
257
|
+
equipment: childNativeId,
|
|
258
|
+
type: candidate.type === DeviceType.Gateway ? DeviceType.Gateway : DeviceType.Sensor,
|
|
259
|
+
name: perCandidate?.[childNativeId]?.name ?? candidate.name,
|
|
260
|
+
})
|
|
261
|
+
adopted.push({ childNativeId, parentDeviceId: deviceId, accessoryDeviceIds: [] })
|
|
262
|
+
}
|
|
263
|
+
if (adopted.length === 0) throw new Error('<%= fileName %> adopt: nothing was adopted')
|
|
264
|
+
return { adopted }
|
|
265
|
+
},
|
|
266
|
+
release: async ({ camDeviceId }) => {
|
|
267
|
+
await deps.remove(camDeviceId)
|
|
268
|
+
},
|
|
269
|
+
resync: async () => ({ changed: false, rebuiltChildren: 0 }),
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
`;
|
|
273
|
+
export const DEVICE_ADDON_TS = `/**
|
|
274
|
+
* <%= displayName %> — a device integration (role \`devices\`, D996). An integration is one typed
|
|
275
|
+
* connection record (secret + test) served through \`integration-instances\`; the devices it brings
|
|
276
|
+
* are adopted from it and carry its \`integrationId\`. There is no addon-level settings page and no
|
|
277
|
+
* legacy settings row: if the operator can configure it, it is an instance.
|
|
278
|
+
*
|
|
279
|
+
* Deleting a device is learned through \`device-removal-hook\` (a tombstone, D865), never from the
|
|
280
|
+
* device missing from a list. A failed read of the remote changes nothing (D49).
|
|
281
|
+
*/
|
|
282
|
+
import {
|
|
283
|
+
type AddonInitResult,
|
|
284
|
+
BaseDeviceProvider,
|
|
285
|
+
type ConfigUISchema,
|
|
286
|
+
type CreateDeviceSpec,
|
|
287
|
+
type DeviceConstructor,
|
|
288
|
+
DeviceType,
|
|
289
|
+
deviceAdoptionCapability,
|
|
290
|
+
deviceRemovalHookCapability,
|
|
291
|
+
type IDevice,
|
|
292
|
+
type IntegrationTestConnectionResult,
|
|
293
|
+
integrationInstancesCapability,
|
|
294
|
+
type RecordIntegrationInstances,
|
|
295
|
+
} from '@camstack/types'
|
|
296
|
+
import { build<%= className %>AdoptionProvider } from './<%= fileName %>-adoption.js'
|
|
297
|
+
import {
|
|
298
|
+
<%= className %>_SYSTEM,
|
|
299
|
+
<%= className %>GatewayDevice,
|
|
300
|
+
<%= className %>SensorDevice,
|
|
301
|
+
} from './<%= fileName %>-devices.js'
|
|
302
|
+
import {
|
|
303
|
+
build<%= className %>Instances,
|
|
304
|
+
<%= className %>RecordKinds,
|
|
305
|
+
type <%= className %>ConnectionBody,
|
|
306
|
+
} from './<%= fileName %>-instances.js'
|
|
307
|
+
|
|
308
|
+
export class <%= className %>Addon extends BaseDeviceProvider {
|
|
309
|
+
protected readonly addonId = '<%= fileName %>'
|
|
310
|
+
protected readonly providerName = '<%= displayName %>'
|
|
311
|
+
// The Gateway and the sensors are siblings: both are restored as top-level devices.
|
|
312
|
+
protected readonly deviceClasses: Partial<Record<DeviceType, DeviceConstructor<IDevice>>> = {
|
|
313
|
+
[DeviceType.Gateway]: <%= className %>GatewayDevice,
|
|
314
|
+
[DeviceType.Sensor]: <%= className %>SensorDevice,
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
constructor() {
|
|
318
|
+
super({})
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
protected override async onInitialize(): Promise<AddonInitResult> {
|
|
322
|
+
const regs = this.providerRegistrationsFromSuper(await super.onInitialize())
|
|
323
|
+
const records = this.ctx.records
|
|
324
|
+
if (records === undefined) {
|
|
325
|
+
throw new Error('<%= fileName %>: ctx.records is required (hub-only addon)')
|
|
326
|
+
}
|
|
327
|
+
await records.declare(<%= className %>RecordKinds)
|
|
328
|
+
const instances = build<%= className %>Instances(records, {
|
|
329
|
+
onChanged: async () => {
|
|
330
|
+
this.ctx.logger.info('<%= displayName %> integrations changed')
|
|
331
|
+
},
|
|
332
|
+
probe: (values) => this.probe(values),
|
|
333
|
+
})
|
|
334
|
+
return {
|
|
335
|
+
providers: [
|
|
336
|
+
...regs,
|
|
337
|
+
{ capability: deviceAdoptionCapability, provider: this.buildAdoptionProvider(instances) },
|
|
338
|
+
{ capability: integrationInstancesCapability, provider: instances.toProvider() },
|
|
339
|
+
{
|
|
340
|
+
capability: deviceRemovalHookCapability,
|
|
341
|
+
// Device DATA only (footage, history, rows). Settings are cleared centrally. Idempotent.
|
|
342
|
+
provider: {
|
|
343
|
+
onDeviceRemoved: async () => ({ counts: {} }),
|
|
344
|
+
listDeviceData: async () => [],
|
|
345
|
+
},
|
|
346
|
+
},
|
|
347
|
+
],
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Replace with a real call to the remote; \`rejected\` is a definite no, \`inconclusive\` is "could not tell". */
|
|
352
|
+
private async probe(
|
|
353
|
+
values: Readonly<Record<string, unknown>>,
|
|
354
|
+
): Promise<IntegrationTestConnectionResult> {
|
|
355
|
+
const host = values['host']
|
|
356
|
+
if (typeof host !== 'string' || host.length === 0) {
|
|
357
|
+
return { success: false, status: 'rejected', error: 'Host is required' }
|
|
358
|
+
}
|
|
359
|
+
return { success: true, status: 'validated' }
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private buildAdoptionProvider(
|
|
363
|
+
instances: RecordIntegrationInstances<<%= className %>ConnectionBody>,
|
|
364
|
+
) {
|
|
365
|
+
return build<%= className %>AdoptionProvider({
|
|
366
|
+
hasIntegration: async (integrationId) => (await instances.readResolved(integrationId)) !== null,
|
|
367
|
+
listIntegrations: async () => (await instances.listResolved()).map((read) => read.id),
|
|
368
|
+
discover: async (integrationId) => {
|
|
369
|
+
const read = await instances.readResolved(integrationId)
|
|
370
|
+
if (read === null) return null
|
|
371
|
+
// Replace with a real read of the remote using read.body (host, token).
|
|
372
|
+
return []
|
|
373
|
+
},
|
|
374
|
+
adopted: async (integrationId) => {
|
|
375
|
+
const reg = this.ctx.kernel.deviceRegistry
|
|
376
|
+
const devices = this.ctx.kernel.devices
|
|
377
|
+
const out = new Map<string, number>()
|
|
378
|
+
if (!reg || !devices) return out
|
|
379
|
+
for (const d of reg.getAllForAddon(this.addonId)) {
|
|
380
|
+
const config = await devices.loadConfig(d.id).catch((): Record<string, unknown> => ({}))
|
|
381
|
+
if (config['integrationId'] !== integrationId) continue
|
|
382
|
+
const equipment = config['equipment']
|
|
383
|
+
if (typeof equipment === 'string') out.set(equipment, d.id)
|
|
384
|
+
}
|
|
385
|
+
return out
|
|
386
|
+
},
|
|
387
|
+
create: async ({ integrationId, equipment, type, name }) => {
|
|
388
|
+
const devices = this.ctx.kernel.devices
|
|
389
|
+
if (!devices) throw new Error('<%= fileName %> adopt: kernel.devices unavailable')
|
|
390
|
+
const config = { equipment, integrationId, system: <%= className %>_SYSTEM }
|
|
391
|
+
const stableId = this.generateStableId(type, config)
|
|
392
|
+
const meta = { type, name, integrationId }
|
|
393
|
+
const device =
|
|
394
|
+
type === DeviceType.Gateway
|
|
395
|
+
? await devices.create(stableId, <%= className %>GatewayDevice, config, null, meta)
|
|
396
|
+
: await devices.create(stableId, <%= className %>SensorDevice, config, null, meta)
|
|
397
|
+
return device.id
|
|
398
|
+
},
|
|
399
|
+
remove: async (id) => {
|
|
400
|
+
await this.ctx.kernel.devices?.remove(id)
|
|
401
|
+
},
|
|
402
|
+
logger: this.ctx.logger,
|
|
403
|
+
})
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
protected override generateStableId(
|
|
407
|
+
_type: DeviceType,
|
|
408
|
+
config?: Record<string, unknown>,
|
|
409
|
+
): string {
|
|
410
|
+
const integrationId = config?.['integrationId']
|
|
411
|
+
const equipment = config?.['equipment']
|
|
412
|
+
if (typeof integrationId !== 'string' || integrationId.length === 0) {
|
|
413
|
+
throw new Error('<%= fileName %> generateStableId: integrationId required')
|
|
414
|
+
}
|
|
415
|
+
if (typeof equipment !== 'string' || equipment.length === 0) {
|
|
416
|
+
throw new Error('<%= fileName %> generateStableId: equipment required')
|
|
417
|
+
}
|
|
418
|
+
return '<%= fileName %>:' + integrationId + ':' + equipment
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
override async supportsManualCreation(): Promise<boolean> {
|
|
422
|
+
return false
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
protected async onGetCreationSchema(_type: DeviceType): Promise<ConfigUISchema | null> {
|
|
426
|
+
return null
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
protected async onCreateDevice(
|
|
430
|
+
_type: DeviceType,
|
|
431
|
+
_config: Record<string, unknown>,
|
|
432
|
+
): Promise<CreateDeviceSpec> {
|
|
433
|
+
throw new Error('<%= displayName %> devices are adopted from the integration')
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export default <%= className %>Addon
|
|
438
|
+
`;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Templates of the `exporter` scaffold (D1009, D996): every exporter is multi-instance. An export
|
|
3
|
+
* target is an integration INSTANCE (role `services`, `instanceMode: 'multiple'`), its id is MINTED,
|
|
4
|
+
* and what is exposed is keyed by that instance id. A target's actions are \`addon-action-button\`
|
|
5
|
+
* fields of its own form. Pattern: the Home Assistant export targets.
|
|
6
|
+
*/
|
|
7
|
+
export declare const EXPORTER_INSTANCES_TS = "/**\n * <%= displayName %> export targets as `integration-instances` (D1009): one `targets` record per\n * target, with a MINTED id (`<%= fileName %>_001`, ...). The devices exported to a target are the\n * `devices` list of ITS record, so deleting the target deletes the exposure and two targets never\n * share one.\n */\nimport {\n type ConfigUISchema,\n defineEntryKind,\n entryBody,\n type IntegrationTestConnectionResult,\n RecordIntegrationInstances,\n type RecordsAccess,\n} from '@camstack/types'\nimport { z } from 'zod'\n\nexport const <%= className %>_TARGET_KIND = '<%= fileName %>-target'\nexport const <%= className %>_ID_PREFIX = '<%= fileName %>_'\n\nexport const <%= className %>TargetsKind = defineEntryKind('targets', {\n title: '<%= displayName %> export targets',\n schema: entryBody({\n endpoint: z.string().optional(),\n token: z.string().optional().meta({ secret: true }),\n devices: z.array(z.string()).optional(),\n /** The target's own switch (D996). Absent means on. */\n enabled: z.boolean().optional(),\n }),\n writeTrigger: 'an operator adds, edits, switches or deletes a target, or exports a device to it',\n})\nexport type <%= className %>TargetBody = z.infer<typeof <%= className %>TargetsKind.schema>\n\n/** Every record kind this addon declares, keyed by its name. */\nexport const <%= className %>RecordKinds = { targets: <%= className %>TargetsKind } as const\n\n/** The next free minted id given the ids that exist (`<%= fileName %>_001`, `<%= fileName %>_002`, ...). */\nexport function next<%= className %>TargetId(existing: Iterable<string>): string {\n let highest = 0\n for (const id of existing) {\n if (!id.startsWith(<%= className %>_ID_PREFIX)) continue\n const n = Number(id.slice(<%= className %>_ID_PREFIX.length))\n if (Number.isInteger(n) && n > highest) highest = n\n }\n return <%= className %>_ID_PREFIX + String(highest + 1).padStart(3, '0')\n}\n\nexport function build<%= className %>TargetForm(addonId: string): ConfigUISchema {\n return {\n sections: [\n {\n id: 'target',\n title: 'Target',\n columns: 1,\n fields: [\n { type: 'text', key: 'name', label: 'Name' },\n { type: 'text', key: 'endpoint', label: 'Endpoint' },\n { type: 'password', key: 'token', label: 'Token', showToggle: true },\n {\n type: 'addon-action-button',\n addonId,\n key: '__resync',\n label: 'Re-announce',\n buttonLabel: 'Push every exposed device now',\n action: 'resync',\n paramsFromForm: { endpoint: 'endpoint' },\n },\n ],\n },\n ],\n }\n}\n\nexport interface <%= className %>TargetDeps {\n /** The ids of the targets that exist now; read per call, a minted id never reuses one. */\n readonly ids: () => readonly string[]\n /** Runs after every change; reload the exposure from the records. */\n readonly onChanged: (id: string) => Promise<void>\n readonly probe: (values: Readonly<Record<string, unknown>>) => Promise<IntegrationTestConnectionResult>\n}\n\nexport function open<%= className %>Targets(\n records: Pick<RecordsAccess, 'kind' | 'owner'>,\n deps: <%= className %>TargetDeps,\n): RecordIntegrationInstances<<%= className %>TargetBody> {\n return new RecordIntegrationInstances<<%= className %>TargetBody>(\n records,\n <%= className %>TargetsKind,\n {\n description: {\n role: 'services',\n instanceMode: 'multiple',\n kind: 'target',\n canTest: true,\n },\n formSchema: () => build<%= className %>TargetForm('<%= fileName %>'),\n initialBody: (name): <%= className %>TargetBody => ({ name, devices: [] }),\n mintId: () => next<%= className %>TargetId(deps.ids()),\n kindOf: () => <%= className %>_TARGET_KIND,\n // A target without an endpoint is unconfigured: it pushes nothing and KEEPS its devices.\n configured: (body) => (body.endpoint ?? '').length > 0,\n onChanged: (id) => deps.onChanged(id),\n test: ({ values }) => deps.probe(values),\n },\n )\n}\n";
|
|
8
|
+
export declare const EXPORTER_ADDON_TS = "/**\n * <%= displayName %> - an exporter (`device-export` + `integration-instances`, D1009). Every\n * exporter is multi-instance: each target is an instance with a minted id, and a membership change\n * ALWAYS names the target it changes. Exposure is the `devices` list of the target's record, keyed\n * by the instance id; an id this addon does not serve is refused by name, never answered empty.\n */\nimport {\n type AddonInitResult,\n BaseAddon,\n customAction,\n defineCustomActions,\n deviceExportCapability,\n deviceExportStatusInstanceOf,\n ExportInstanceUnknownError,\n type IDeviceExportProvider,\n type IntegrationTestConnectionResult,\n integrationInstancesCapability,\n type RecordKindHandle,\n} from '@camstack/types'\nimport { z } from 'zod'\nimport {\n open<%= className %>Targets,\n <%= className %>_TARGET_KIND,\n <%= className %>RecordKinds,\n <%= className %>TargetsKind,\n type <%= className %>TargetBody,\n} from './<%= fileName %>-instances.js'\n\nconst <%= className %>Actions = defineCustomActions({\n resync: customAction(\n z.object({ endpoint: z.string().optional() }),\n z.object({ summary: z.string() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n})\n\n/** The device kinds this exporter can carry; the device picker filters on it. */\nconst SUPPORTED_DEVICE_KINDS: readonly string[] = ['sensor', 'switch', 'light']\n\nexport class <%= className %>Addon extends BaseAddon<Readonly<Record<string, never>>> {\n private targets: RecordKindHandle<<%= className %>TargetBody> | null = null\n /** Target id to its record body; reloaded from the records after every change. */\n private book = new Map<string, <%= className %>TargetBody>()\n\n constructor() {\n super({})\n }\n\n protected override async onInitialize(): Promise<AddonInitResult> {\n const records = this.ctx.records\n if (records === undefined) {\n throw new Error('<%= fileName %>: ctx.records is required (hub-only addon)')\n }\n await records.declare(<%= className %>RecordKinds)\n this.targets = records.kind(<%= className %>TargetsKind)\n const instances = open<%= className %>Targets(records, {\n ids: () => [...this.book.keys()],\n onChanged: () => this.reload(),\n probe: (values) => this.probe(values),\n })\n await this.reload()\n return {\n providers: [\n { capability: deviceExportCapability, provider: this.buildExportProvider() },\n { capability: integrationInstancesCapability, provider: instances.toProvider() },\n ],\n customActions: <%= className %>Actions,\n actionHandlers: {\n resync: async () => {\n await this.reload()\n return { summary: 'Re-announced ' + this.book.size + ' target(s).' }\n },\n },\n }\n }\n\n /** Reload every target from the records; the synchronous read the event path needs. */\n private async reload(): Promise<void> {\n const targets = this.targets\n if (targets === null) return\n const page = await targets.query({ limit: 1000 })\n this.book = new Map(page.records.map((row) => [row.id, row.data]))\n }\n\n /** The body of a target this addon serves, or the named refusal. */\n private target(instanceId: string): <%= className %>TargetBody {\n const body = this.book.get(instanceId)\n if (body === undefined) throw new ExportInstanceUnknownError(this.ctx.id, instanceId)\n return body\n }\n\n private async setMembership(\n instanceId: string,\n deviceId: string,\n exposed: boolean,\n ): Promise<void> {\n const body = this.target(instanceId)\n const current = new Set(body.devices ?? [])\n if (exposed) current.add(deviceId)\n else current.delete(deviceId)\n await this.targets?.patch(instanceId, { devices: [...current] })\n await this.reload()\n }\n\n private buildExportProvider(): IDeviceExportProvider {\n return {\n getStatus: async (input) => {\n const instanceId = deviceExportStatusInstanceOf(input)\n const bodies =\n instanceId === undefined ? [...this.book.values()] : [this.target(instanceId)]\n return {\n linkState: bodies.some((b) => (b.endpoint ?? '').length > 0) ? 'linked' : 'unlinked',\n exposedDeviceCount: new Set(bodies.flatMap((b) => b.devices ?? [])).size,\n }\n },\n listInstances: async () =>\n [...this.book.entries()].map(([instanceId, body]) => ({\n instanceId,\n name: body.name,\n enabled: body.enabled !== false,\n kind: <%= className %>_TARGET_KIND,\n })),\n listSupportedDeviceKinds: async ({ instanceId }) => {\n if (instanceId !== undefined) this.target(instanceId)\n return [...SUPPORTED_DEVICE_KINDS]\n },\n listExposedDevices: async ({ instanceId }) => {\n const bodies =\n instanceId === undefined ? [...this.book.values()] : [this.target(instanceId)]\n return bodies.flatMap((b) => (b.devices ?? []).map((deviceId) => ({ deviceId })))\n },\n exposeDevice: async ({ instanceId, deviceId }) =>\n this.setMembership(instanceId, deviceId, true),\n unexposeDevice: async ({ instanceId, deviceId }) =>\n this.setMembership(instanceId, deviceId, false),\n getDeviceSettingsContribution: async () => null,\n getDeviceLiveContribution: async () => null,\n applyDeviceSettingsPatch: async () => ({ success: true as const }),\n }\n }\n\n /** Replace with a real call to the remote; `rejected` is a definite no, `inconclusive` is \"could not tell\". */\n private async probe(\n values: Readonly<Record<string, unknown>>,\n ): Promise<IntegrationTestConnectionResult> {\n const endpoint = values['endpoint']\n if (typeof endpoint !== 'string' || endpoint.length === 0) {\n return { success: false, status: 'rejected', error: 'Endpoint is required' }\n }\n return { success: true, status: 'validated' }\n }\n}\n\nexport default <%= className %>Addon\n";
|
|
9
|
+
//# sourceMappingURL=integration-exporter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"integration-exporter.d.ts","sourceRoot":"","sources":["../../src/scaffold/integration-exporter.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAO,MAAM,qBAAqB,oiIAyGjC,CAAA;AAED,eAAO,MAAM,iBAAiB,y2LA0J7B,CAAA"}
|