@camstack/core 0.1.0 → 0.1.2
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/builtins/local-backup/index.d.mts +42 -0
- package/dist/builtins/local-backup/index.d.ts +42 -0
- package/dist/builtins/local-backup/index.js +188 -0
- package/dist/builtins/local-backup/index.js.map +1 -0
- package/dist/builtins/local-backup/index.mjs +11 -0
- package/dist/builtins/local-backup/index.mjs.map +1 -0
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.d.mts +2 -0
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.d.ts +2 -0
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +210 -0
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.js.map +1 -0
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +10 -0
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs.map +1 -0
- package/dist/builtins/sqlite-storage/index.d.mts +4 -0
- package/dist/builtins/sqlite-storage/index.d.ts +4 -0
- package/dist/builtins/sqlite-storage/index.js +1025 -0
- package/dist/builtins/sqlite-storage/index.js.map +1 -0
- package/dist/builtins/sqlite-storage/index.mjs +31 -0
- package/dist/builtins/sqlite-storage/index.mjs.map +1 -0
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.d.mts +2 -0
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.d.ts +2 -0
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +317 -0
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.js.map +1 -0
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +10 -0
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs.map +1 -0
- package/dist/builtins/winston-logging/index.d.mts +30 -0
- package/dist/builtins/winston-logging/index.d.ts +30 -0
- package/dist/builtins/winston-logging/index.js +185 -0
- package/dist/builtins/winston-logging/index.js.map +1 -0
- package/dist/builtins/winston-logging/index.mjs +11 -0
- package/dist/builtins/winston-logging/index.mjs.map +1 -0
- package/dist/chunk-2F3XZYRW.mjs +89 -0
- package/dist/chunk-2F3XZYRW.mjs.map +1 -0
- package/dist/chunk-LQFPAEQF.mjs +147 -0
- package/dist/chunk-LQFPAEQF.mjs.map +1 -0
- package/dist/chunk-QEMJH3KY.mjs +48 -0
- package/dist/chunk-QEMJH3KY.mjs.map +1 -0
- package/dist/chunk-R3DIIBBX.mjs +532 -0
- package/dist/chunk-R3DIIBBX.mjs.map +1 -0
- package/dist/chunk-SO4LROOT.mjs +150 -0
- package/dist/chunk-SO4LROOT.mjs.map +1 -0
- package/dist/chunk-SPA4JBKN.mjs +175 -0
- package/dist/chunk-SPA4JBKN.mjs.map +1 -0
- package/dist/chunk-YXNXYYHL.mjs +282 -0
- package/dist/chunk-YXNXYYHL.mjs.map +1 -0
- package/dist/dist-N7SR63RN.mjs +3515 -0
- package/dist/dist-N7SR63RN.mjs.map +1 -0
- package/dist/filesystem-storage.addon-C42r589X.d.mts +57 -0
- package/dist/filesystem-storage.addon-C42r589X.d.ts +57 -0
- package/dist/index.d.mts +1064 -101
- package/dist/index.d.ts +1064 -101
- package/dist/index.js +14673 -560
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6360 -534
- package/dist/index.mjs.map +1 -1
- package/dist/onnxruntime_binding-6Q6HXASN.node +0 -0
- package/dist/onnxruntime_binding-EKZT2NRK.node +0 -0
- package/dist/onnxruntime_binding-P6S7V3CI.node +0 -0
- package/dist/onnxruntime_binding-PJNNIIUO.node +0 -0
- package/dist/onnxruntime_binding-UN6SPTQK.node +0 -0
- package/dist/sql-schema-CKz78rId.d.mts +97 -0
- package/dist/sql-schema-CKz78rId.d.ts +97 -0
- package/dist/sqlite-settings.addon-DigoKwpZ.d.mts +70 -0
- package/dist/sqlite-settings.addon-DigoKwpZ.d.ts +70 -0
- package/dist/storage-location-manager-UQRGHTCA.mjs +8 -0
- package/dist/storage-location-manager-UQRGHTCA.mjs.map +1 -0
- package/dist/wrapper-Y55ADNM5.mjs +3652 -0
- package/dist/wrapper-Y55ADNM5.mjs.map +1 -0
- package/package.json +77 -6
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// src/builtins/local-backup/local-backup.ts
|
|
2
|
+
import { randomUUID } from "crypto";
|
|
3
|
+
var LocalBackupService = class {
|
|
4
|
+
constructor(config, logger, eventBus, storage) {
|
|
5
|
+
this.config = config;
|
|
6
|
+
this.logger = logger;
|
|
7
|
+
this.eventBus = eventBus;
|
|
8
|
+
this.storage = storage;
|
|
9
|
+
}
|
|
10
|
+
manifests = [];
|
|
11
|
+
/** Create a backup of specified locations */
|
|
12
|
+
async backup(options) {
|
|
13
|
+
const id = randomUUID();
|
|
14
|
+
const timestamp = Date.now();
|
|
15
|
+
const locations = options?.locations ?? ["config", "events", "logs"];
|
|
16
|
+
this.logger.info(`Starting backup ${id} (${locations.join(", ")})`);
|
|
17
|
+
const manifest = {
|
|
18
|
+
id,
|
|
19
|
+
timestamp,
|
|
20
|
+
label: options?.label,
|
|
21
|
+
locations,
|
|
22
|
+
sizeMB: 0,
|
|
23
|
+
path: `${this.config.backupDir}/${id}`
|
|
24
|
+
};
|
|
25
|
+
const updated = [...this.manifests, manifest];
|
|
26
|
+
this.manifests = updated;
|
|
27
|
+
await this.pruneOldBackups();
|
|
28
|
+
this.eventBus.emit({
|
|
29
|
+
id: randomUUID(),
|
|
30
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
31
|
+
source: { type: "addon", id: "local-backup" },
|
|
32
|
+
category: "backup.completed",
|
|
33
|
+
data: { backupId: id, locations: [...locations], sizeMB: manifest.sizeMB }
|
|
34
|
+
});
|
|
35
|
+
this.logger.info(`Backup ${id} completed`);
|
|
36
|
+
return manifest;
|
|
37
|
+
}
|
|
38
|
+
/** Restore from a backup */
|
|
39
|
+
async restore(backupId) {
|
|
40
|
+
const manifest = this.manifests.find((m) => m.id === backupId);
|
|
41
|
+
if (!manifest) throw new Error(`Backup ${backupId} not found`);
|
|
42
|
+
this.logger.info(`Restoring from backup ${backupId}`);
|
|
43
|
+
this.eventBus.emit({
|
|
44
|
+
id: randomUUID(),
|
|
45
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
46
|
+
source: { type: "addon", id: "local-backup" },
|
|
47
|
+
category: "backup.restored",
|
|
48
|
+
data: { backupId }
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/** List all backups sorted by timestamp descending */
|
|
52
|
+
list() {
|
|
53
|
+
return [...this.manifests].sort((a, b) => b.timestamp - a.timestamp);
|
|
54
|
+
}
|
|
55
|
+
/** Delete a specific backup */
|
|
56
|
+
async delete(backupId) {
|
|
57
|
+
this.manifests = this.manifests.filter((m) => m.id !== backupId);
|
|
58
|
+
}
|
|
59
|
+
async pruneOldBackups() {
|
|
60
|
+
const sorted = [...this.manifests].sort((a, b) => a.timestamp - b.timestamp);
|
|
61
|
+
while (sorted.length > this.config.retentionCount) {
|
|
62
|
+
const oldest = sorted.shift();
|
|
63
|
+
if (oldest) {
|
|
64
|
+
this.logger.info(`Pruning old backup ${oldest.id}`);
|
|
65
|
+
this.manifests = this.manifests.filter((m) => m.id !== oldest.id);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// src/builtins/local-backup/local-backup.addon.ts
|
|
72
|
+
import * as path from "path";
|
|
73
|
+
var LocalBackupAddon = class {
|
|
74
|
+
manifest = {
|
|
75
|
+
id: "local-backup",
|
|
76
|
+
name: "Local Backup",
|
|
77
|
+
version: "1.0.0",
|
|
78
|
+
capabilities: ["backup"]
|
|
79
|
+
};
|
|
80
|
+
service = null;
|
|
81
|
+
currentConfig = {
|
|
82
|
+
retentionCount: 7
|
|
83
|
+
};
|
|
84
|
+
async initialize(context) {
|
|
85
|
+
this.currentConfig = {
|
|
86
|
+
retentionCount: context.addonConfig.retentionCount ?? this.currentConfig.retentionCount
|
|
87
|
+
};
|
|
88
|
+
const backupConfig = {
|
|
89
|
+
backupDir: path.join(context.locationPaths.data, "backups"),
|
|
90
|
+
retentionCount: this.currentConfig.retentionCount
|
|
91
|
+
};
|
|
92
|
+
this.service = new LocalBackupService(
|
|
93
|
+
backupConfig,
|
|
94
|
+
context.logger,
|
|
95
|
+
context.eventBus,
|
|
96
|
+
context.storage
|
|
97
|
+
);
|
|
98
|
+
context.logger.info("Local Backup initialized");
|
|
99
|
+
}
|
|
100
|
+
async shutdown() {
|
|
101
|
+
this.service = null;
|
|
102
|
+
}
|
|
103
|
+
getService() {
|
|
104
|
+
if (!this.service) throw new Error("Local Backup not initialized");
|
|
105
|
+
return this.service;
|
|
106
|
+
}
|
|
107
|
+
getCapabilityProvider(name) {
|
|
108
|
+
if (name === "backup" && this.service) {
|
|
109
|
+
return this.service;
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
getConfigSchema() {
|
|
114
|
+
return {
|
|
115
|
+
sections: [
|
|
116
|
+
{
|
|
117
|
+
id: "backup-retention",
|
|
118
|
+
title: "Backup Retention",
|
|
119
|
+
description: "How many local backup snapshots to keep on disk.",
|
|
120
|
+
columns: 1,
|
|
121
|
+
fields: [
|
|
122
|
+
{
|
|
123
|
+
type: "number",
|
|
124
|
+
key: "retentionCount",
|
|
125
|
+
label: "Retention Count",
|
|
126
|
+
description: "Number of backup snapshots to keep before deleting the oldest",
|
|
127
|
+
min: 1,
|
|
128
|
+
max: 100,
|
|
129
|
+
step: 1
|
|
130
|
+
}
|
|
131
|
+
]
|
|
132
|
+
}
|
|
133
|
+
]
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
getConfig() {
|
|
137
|
+
return { ...this.currentConfig };
|
|
138
|
+
}
|
|
139
|
+
async onConfigChange(config) {
|
|
140
|
+
this.currentConfig = {
|
|
141
|
+
retentionCount: config.retentionCount ?? this.currentConfig.retentionCount
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
export {
|
|
147
|
+
LocalBackupService,
|
|
148
|
+
LocalBackupAddon
|
|
149
|
+
};
|
|
150
|
+
//# sourceMappingURL=chunk-SO4LROOT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/builtins/local-backup/local-backup.ts","../src/builtins/local-backup/local-backup.addon.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport type { IScopedLogger, IEventBus, IStorageLocation, BackupManifest } from '@camstack/types'\n\nexport type { BackupManifest }\n\nexport interface BackupConfig {\n readonly backupDir: string\n readonly retentionCount: number\n}\n\nexport class LocalBackupService {\n private manifests: BackupManifest[] = []\n\n constructor(\n private readonly config: BackupConfig,\n private readonly logger: IScopedLogger,\n private readonly eventBus: IEventBus,\n private readonly storage: IStorageLocation,\n ) {}\n\n /** Create a backup of specified locations */\n async backup(options?: {\n locations?: string[]\n label?: string\n }): Promise<BackupManifest> {\n const id = randomUUID()\n const timestamp = Date.now()\n const locations = options?.locations ?? ['config', 'events', 'logs']\n\n this.logger.info(`Starting backup ${id} (${locations.join(', ')})`)\n\n const manifest: BackupManifest = {\n id,\n timestamp,\n label: options?.label,\n locations,\n sizeMB: 0,\n path: `${this.config.backupDir}/${id}`,\n }\n\n const updated = [...this.manifests, manifest]\n this.manifests = updated\n\n await this.pruneOldBackups()\n\n this.eventBus.emit({\n id: randomUUID(),\n timestamp: new Date(),\n source: { type: 'addon', id: 'local-backup' },\n category: 'backup.completed',\n data: { backupId: id, locations: [...locations], sizeMB: manifest.sizeMB },\n })\n\n this.logger.info(`Backup ${id} completed`)\n return manifest\n }\n\n /** Restore from a backup */\n async restore(backupId: string): Promise<void> {\n const manifest = this.manifests.find((m) => m.id === backupId)\n if (!manifest) throw new Error(`Backup ${backupId} not found`)\n\n this.logger.info(`Restoring from backup ${backupId}`)\n\n this.eventBus.emit({\n id: randomUUID(),\n timestamp: new Date(),\n source: { type: 'addon', id: 'local-backup' },\n category: 'backup.restored',\n data: { backupId },\n })\n }\n\n /** List all backups sorted by timestamp descending */\n list(): readonly BackupManifest[] {\n return [...this.manifests].sort((a, b) => b.timestamp - a.timestamp)\n }\n\n /** Delete a specific backup */\n async delete(backupId: string): Promise<void> {\n this.manifests = this.manifests.filter((m) => m.id !== backupId)\n }\n\n private async pruneOldBackups(): Promise<void> {\n const sorted = [...this.manifests].sort((a, b) => a.timestamp - b.timestamp)\n\n while (sorted.length > this.config.retentionCount) {\n const oldest = sorted.shift()\n if (oldest) {\n this.logger.info(`Pruning old backup ${oldest.id}`)\n this.manifests = this.manifests.filter((m) => m.id !== oldest.id)\n }\n }\n }\n}\n","import * as path from 'node:path'\nimport type {\n ICamstackAddon, AddonManifest, AddonContext,\n IConfigurable, ConfigUISchema, CapabilityProviderMap,\n} from '@camstack/types'\nimport { LocalBackupService } from './local-backup'\nimport type { BackupConfig } from './local-backup'\n\nexport class LocalBackupAddon implements ICamstackAddon, IConfigurable {\n readonly manifest: AddonManifest = {\n id: 'local-backup',\n name: 'Local Backup',\n version: '1.0.0',\n capabilities: ['backup'],\n }\n\n private service: LocalBackupService | null = null\n private currentConfig = {\n retentionCount: 7,\n }\n\n async initialize(context: AddonContext): Promise<void> {\n this.currentConfig = {\n retentionCount: (context.addonConfig.retentionCount as number) ?? this.currentConfig.retentionCount,\n }\n const backupConfig: BackupConfig = {\n backupDir: path.join(context.locationPaths.data, 'backups'),\n retentionCount: this.currentConfig.retentionCount,\n }\n this.service = new LocalBackupService(\n backupConfig,\n context.logger,\n context.eventBus,\n context.storage,\n )\n context.logger.info('Local Backup initialized')\n }\n\n async shutdown(): Promise<void> {\n this.service = null\n }\n\n getService(): LocalBackupService {\n if (!this.service) throw new Error('Local Backup not initialized')\n return this.service\n }\n\n getCapabilityProvider<K extends keyof CapabilityProviderMap>(\n name: K,\n ): CapabilityProviderMap[K] | null {\n if (name === 'backup' as string && this.service) {\n return this.service as unknown as CapabilityProviderMap[K]\n }\n return null\n }\n\n getConfigSchema(): ConfigUISchema {\n return {\n sections: [\n {\n id: 'backup-retention',\n title: 'Backup Retention',\n description: 'How many local backup snapshots to keep on disk.',\n columns: 1,\n fields: [\n {\n type: 'number',\n key: 'retentionCount',\n label: 'Retention Count',\n description: 'Number of backup snapshots to keep before deleting the oldest',\n min: 1,\n max: 100,\n step: 1,\n },\n ],\n },\n ],\n }\n }\n\n getConfig(): Record<string, unknown> {\n return { ...this.currentConfig }\n }\n\n async onConfigChange(config: Record<string, unknown>): Promise<void> {\n this.currentConfig = {\n retentionCount: (config.retentionCount as number) ?? this.currentConfig.retentionCount,\n }\n }\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAUpB,IAAM,qBAAN,MAAyB;AAAA,EAG9B,YACmB,QACA,QACA,UACA,SACjB;AAJiB;AACA;AACA;AACA;AAAA,EAChB;AAAA,EAPK,YAA8B,CAAC;AAAA;AAAA,EAUvC,MAAM,OAAO,SAGe;AAC1B,UAAM,KAAK,WAAW;AACtB,UAAM,YAAY,KAAK,IAAI;AAC3B,UAAM,YAAY,SAAS,aAAa,CAAC,UAAU,UAAU,MAAM;AAEnE,SAAK,OAAO,KAAK,mBAAmB,EAAE,KAAK,UAAU,KAAK,IAAI,CAAC,GAAG;AAElE,UAAM,WAA2B;AAAA,MAC/B;AAAA,MACA;AAAA,MACA,OAAO,SAAS;AAAA,MAChB;AAAA,MACA,QAAQ;AAAA,MACR,MAAM,GAAG,KAAK,OAAO,SAAS,IAAI,EAAE;AAAA,IACtC;AAEA,UAAM,UAAU,CAAC,GAAG,KAAK,WAAW,QAAQ;AAC5C,SAAK,YAAY;AAEjB,UAAM,KAAK,gBAAgB;AAE3B,SAAK,SAAS,KAAK;AAAA,MACjB,IAAI,WAAW;AAAA,MACf,WAAW,oBAAI,KAAK;AAAA,MACpB,QAAQ,EAAE,MAAM,SAAS,IAAI,eAAe;AAAA,MAC5C,UAAU;AAAA,MACV,MAAM,EAAE,UAAU,IAAI,WAAW,CAAC,GAAG,SAAS,GAAG,QAAQ,SAAS,OAAO;AAAA,IAC3E,CAAC;AAED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ACnB,gBAAiB,OAAO,kBAA6B,KAAK,cAAc;AAAA,IAC1E;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// src/builtins/sqlite-storage/filesystem-storage-provider.ts
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as path from "path";
|
|
4
|
+
var STORAGE_LOCATION_TYPES = [
|
|
5
|
+
"recordings-high",
|
|
6
|
+
"recordings-low",
|
|
7
|
+
"recordings-clips",
|
|
8
|
+
"event-images",
|
|
9
|
+
"models",
|
|
10
|
+
"addons-data",
|
|
11
|
+
"cache",
|
|
12
|
+
"logs"
|
|
13
|
+
];
|
|
14
|
+
var DEFAULT_LOCATION_SUBDIRS = {
|
|
15
|
+
"recordings-high": "recordings-high",
|
|
16
|
+
"recordings-low": "recordings-low",
|
|
17
|
+
"recordings-clips": "recordings-clips",
|
|
18
|
+
"event-images": "event-images",
|
|
19
|
+
"models": "models",
|
|
20
|
+
"addons-data": "addons-data",
|
|
21
|
+
"cache": "/tmp/camstack-cache",
|
|
22
|
+
"logs": "logs"
|
|
23
|
+
};
|
|
24
|
+
var FilesystemStorageProvider = class {
|
|
25
|
+
id = "local";
|
|
26
|
+
name = "Local Filesystem";
|
|
27
|
+
supportedLocations = [...STORAGE_LOCATION_TYPES];
|
|
28
|
+
rootPath;
|
|
29
|
+
locationPaths;
|
|
30
|
+
constructor(rootPath, overrides) {
|
|
31
|
+
this.rootPath = path.resolve(rootPath);
|
|
32
|
+
this.locationPaths = /* @__PURE__ */ new Map();
|
|
33
|
+
for (const loc of STORAGE_LOCATION_TYPES) {
|
|
34
|
+
const override = overrides?.[loc];
|
|
35
|
+
if (override) {
|
|
36
|
+
this.locationPaths.set(loc, path.resolve(override));
|
|
37
|
+
} else {
|
|
38
|
+
const subdir = DEFAULT_LOCATION_SUBDIRS[loc];
|
|
39
|
+
this.locationPaths.set(
|
|
40
|
+
loc,
|
|
41
|
+
path.isAbsolute(subdir) ? subdir : path.join(this.rootPath, subdir)
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
resolve(location, relativePath) {
|
|
47
|
+
const base = this.locationPaths.get(location);
|
|
48
|
+
if (!base) throw new Error(`Unknown storage location: ${location}`);
|
|
49
|
+
return path.join(base, relativePath);
|
|
50
|
+
}
|
|
51
|
+
async write(location, relativePath, data) {
|
|
52
|
+
const filePath = this.resolve(location, relativePath);
|
|
53
|
+
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
54
|
+
if (Buffer.isBuffer(data)) {
|
|
55
|
+
await fs.promises.writeFile(filePath, data);
|
|
56
|
+
} else {
|
|
57
|
+
const writeStream = fs.createWriteStream(filePath);
|
|
58
|
+
await new Promise((resolve2, reject) => {
|
|
59
|
+
data.pipe(writeStream);
|
|
60
|
+
writeStream.on("finish", resolve2);
|
|
61
|
+
writeStream.on("error", reject);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
async read(location, relativePath) {
|
|
66
|
+
return fs.promises.readFile(this.resolve(location, relativePath));
|
|
67
|
+
}
|
|
68
|
+
async exists(location, relativePath) {
|
|
69
|
+
try {
|
|
70
|
+
await fs.promises.access(this.resolve(location, relativePath));
|
|
71
|
+
return true;
|
|
72
|
+
} catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async list(location, prefix) {
|
|
77
|
+
const base = this.locationPaths.get(location);
|
|
78
|
+
if (!base) return [];
|
|
79
|
+
const dir = prefix ? path.join(base, prefix) : base;
|
|
80
|
+
try {
|
|
81
|
+
const entries = await fs.promises.readdir(dir, { withFileTypes: true });
|
|
82
|
+
return entries.map((e) => prefix ? `${prefix}/${e.name}` : e.name);
|
|
83
|
+
} catch {
|
|
84
|
+
return [];
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async delete(location, relativePath) {
|
|
88
|
+
const filePath = this.resolve(location, relativePath);
|
|
89
|
+
await fs.promises.rm(filePath, { force: true });
|
|
90
|
+
}
|
|
91
|
+
async getAvailableSpace(location) {
|
|
92
|
+
const base = this.locationPaths.get(location);
|
|
93
|
+
if (!base) return null;
|
|
94
|
+
try {
|
|
95
|
+
const stats = await fs.promises.statfs(base);
|
|
96
|
+
return stats.bavail * stats.bsize;
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async initialize() {
|
|
102
|
+
for (const [, dirPath] of this.locationPaths) {
|
|
103
|
+
await fs.promises.mkdir(dirPath, { recursive: true });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async shutdown() {
|
|
107
|
+
}
|
|
108
|
+
/** Get the resolved path for a location type */
|
|
109
|
+
getLocationPath(location) {
|
|
110
|
+
const p = this.locationPaths.get(location);
|
|
111
|
+
if (!p) throw new Error(`Unknown storage location: ${location}`);
|
|
112
|
+
return p;
|
|
113
|
+
}
|
|
114
|
+
/** Get the root path */
|
|
115
|
+
getRootPath() {
|
|
116
|
+
return this.rootPath;
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// src/builtins/sqlite-storage/filesystem-storage.addon.ts
|
|
121
|
+
var FilesystemStorageAddon = class {
|
|
122
|
+
manifest = {
|
|
123
|
+
id: "filesystem-storage",
|
|
124
|
+
name: "Local Filesystem Storage",
|
|
125
|
+
version: "1.0.0",
|
|
126
|
+
capabilities: [{ name: "storage", mode: "collection" }]
|
|
127
|
+
};
|
|
128
|
+
provider = null;
|
|
129
|
+
currentConfig = {
|
|
130
|
+
rootPath: "camstack-data"
|
|
131
|
+
};
|
|
132
|
+
async initialize(context) {
|
|
133
|
+
const rootPath = context.addonConfig.rootPath ?? this.currentConfig.rootPath;
|
|
134
|
+
this.currentConfig.rootPath = rootPath;
|
|
135
|
+
const overrides = {};
|
|
136
|
+
for (const key of Object.keys(context.addonConfig)) {
|
|
137
|
+
if (key.startsWith("override.")) {
|
|
138
|
+
const loc = key.slice("override.".length);
|
|
139
|
+
overrides[loc] = context.addonConfig[key];
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
this.provider = new FilesystemStorageProvider(rootPath, overrides);
|
|
143
|
+
await this.provider.initialize();
|
|
144
|
+
context.logger.info(`Filesystem storage initialized at ${this.provider.getRootPath()}`);
|
|
145
|
+
}
|
|
146
|
+
async shutdown() {
|
|
147
|
+
await this.provider?.shutdown();
|
|
148
|
+
}
|
|
149
|
+
getCapabilityProvider(name) {
|
|
150
|
+
if (name === "storage" && this.provider) {
|
|
151
|
+
return this.provider;
|
|
152
|
+
}
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
getProvider() {
|
|
156
|
+
return this.provider;
|
|
157
|
+
}
|
|
158
|
+
getConfigSchema() {
|
|
159
|
+
return { sections: [] };
|
|
160
|
+
}
|
|
161
|
+
getConfig() {
|
|
162
|
+
return { ...this.currentConfig };
|
|
163
|
+
}
|
|
164
|
+
async onConfigChange(config) {
|
|
165
|
+
this.currentConfig.rootPath = config.rootPath ?? this.currentConfig.rootPath;
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
var filesystem_storage_addon_default = FilesystemStorageAddon;
|
|
169
|
+
|
|
170
|
+
export {
|
|
171
|
+
FilesystemStorageProvider,
|
|
172
|
+
FilesystemStorageAddon,
|
|
173
|
+
filesystem_storage_addon_default
|
|
174
|
+
};
|
|
175
|
+
//# sourceMappingURL=chunk-SPA4JBKN.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/builtins/sqlite-storage/filesystem-storage-provider.ts","../src/builtins/sqlite-storage/filesystem-storage.addon.ts"],"sourcesContent":["import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport type {\n IStorageProvider as INewStorageProvider,\n StorageLocationType,\n} from '@camstack/types'\n\n// Inline constants to avoid runtime dependency on @camstack/types\n// (types is external in tsup bundle, may not be resolvable from data/addons/)\nconst STORAGE_LOCATION_TYPES: readonly StorageLocationType[] = [\n 'recordings-high', 'recordings-low', 'recordings-clips', 'event-images',\n 'models', 'addons-data', 'cache', 'logs',\n]\n\nconst DEFAULT_LOCATION_SUBDIRS: Readonly<Record<StorageLocationType, string>> = {\n 'recordings-high': 'recordings-high',\n 'recordings-low': 'recordings-low',\n 'recordings-clips': 'recordings-clips',\n 'event-images': 'event-images',\n 'models': 'models',\n 'addons-data': 'addons-data',\n 'cache': '/tmp/camstack-cache',\n 'logs': 'logs',\n}\n\n/**\n * Filesystem storage provider — serves all location types from a local directory tree.\n *\n * Default layout:\n * {rootPath}/recordings-high/\n * {rootPath}/recordings-low/\n * {rootPath}/recordings-clips/\n * {rootPath}/event-images/\n * {rootPath}/models/\n * {rootPath}/addons-data/\n * {rootPath}/logs/\n * /tmp/camstack-cache/ (cache is always local)\n *\n * Individual location paths can be overridden.\n */\nexport class FilesystemStorageProvider implements INewStorageProvider {\n readonly id = 'local'\n readonly name = 'Local Filesystem'\n readonly supportedLocations: readonly StorageLocationType[] = [...STORAGE_LOCATION_TYPES]\n\n private readonly rootPath: string\n private readonly locationPaths: Map<StorageLocationType, string>\n\n constructor(rootPath: string, overrides?: Partial<Record<StorageLocationType, string>>) {\n this.rootPath = path.resolve(rootPath)\n this.locationPaths = new Map()\n\n for (const loc of STORAGE_LOCATION_TYPES) {\n const override = overrides?.[loc]\n if (override) {\n this.locationPaths.set(loc, path.resolve(override))\n } else {\n const subdir = DEFAULT_LOCATION_SUBDIRS[loc]\n // Absolute paths (like /tmp/camstack-cache) are used as-is\n this.locationPaths.set(\n loc,\n path.isAbsolute(subdir) ? subdir : path.join(this.rootPath, subdir),\n )\n }\n }\n }\n\n resolve(location: StorageLocationType, relativePath: string): string {\n const base = this.locationPaths.get(location)\n if (!base) throw new Error(`Unknown storage location: ${location}`)\n return path.join(base, relativePath)\n }\n\n async write(location: StorageLocationType, relativePath: string, data: Buffer | NodeJS.ReadableStream): Promise<void> {\n const filePath = this.resolve(location, relativePath)\n await fs.promises.mkdir(path.dirname(filePath), { recursive: true })\n\n if (Buffer.isBuffer(data)) {\n await fs.promises.writeFile(filePath, data)\n } else {\n // Stream\n const writeStream = fs.createWriteStream(filePath)\n await new Promise<void>((resolve, reject) => {\n (data as NodeJS.ReadableStream).pipe(writeStream)\n writeStream.on('finish', resolve)\n writeStream.on('error', reject)\n })\n }\n }\n\n async read(location: StorageLocationType, relativePath: string): Promise<Buffer> {\n return fs.promises.readFile(this.resolve(location, relativePath))\n }\n\n async exists(location: StorageLocationType, relativePath: string): Promise<boolean> {\n try {\n await fs.promises.access(this.resolve(location, relativePath))\n return true\n } catch {\n return false\n }\n }\n\n async list(location: StorageLocationType, prefix?: string): Promise<readonly string[]> {\n const base = this.locationPaths.get(location)\n if (!base) return []\n const dir = prefix ? path.join(base, prefix) : base\n try {\n const entries = await fs.promises.readdir(dir, { withFileTypes: true })\n return entries.map(e => (prefix ? `${prefix}/${e.name}` : e.name))\n } catch {\n return []\n }\n }\n\n async delete(location: StorageLocationType, relativePath: string): Promise<void> {\n const filePath = this.resolve(location, relativePath)\n await fs.promises.rm(filePath, { force: true })\n }\n\n async getAvailableSpace(location: StorageLocationType): Promise<number | null> {\n const base = this.locationPaths.get(location)\n if (!base) return null\n try {\n const stats = await fs.promises.statfs(base)\n return stats.bavail * stats.bsize\n } catch {\n return null\n }\n }\n\n async initialize(): Promise<void> {\n for (const [, dirPath] of this.locationPaths) {\n await fs.promises.mkdir(dirPath, { recursive: true })\n }\n }\n\n async shutdown(): Promise<void> {\n // Nothing to clean up for filesystem\n }\n\n /** Get the resolved path for a location type */\n getLocationPath(location: StorageLocationType): string {\n const p = this.locationPaths.get(location)\n if (!p) throw new Error(`Unknown storage location: ${location}`)\n return p\n }\n\n /** Get the root path */\n getRootPath(): string {\n return this.rootPath\n }\n}\n\nexport default FilesystemStorageProvider\n","import type {\n ICamstackAddon,\n AddonManifest,\n AddonContext,\n IConfigurable,\n ConfigUISchema,\n CapabilityProviderMap,\n} from '@camstack/types'\nimport { FilesystemStorageProvider } from './filesystem-storage-provider'\n\n/**\n * Filesystem Storage addon — provides local disk storage for all location types.\n * Capability: 'storage' (collection)\n */\nexport class FilesystemStorageAddon implements ICamstackAddon, IConfigurable {\n readonly manifest: AddonManifest = {\n id: 'filesystem-storage',\n name: 'Local Filesystem Storage',\n version: '1.0.0',\n capabilities: [{ name: 'storage', mode: 'collection' }],\n }\n\n private provider: FilesystemStorageProvider | null = null\n private currentConfig = {\n rootPath: 'camstack-data',\n }\n\n async initialize(context: AddonContext): Promise<void> {\n const rootPath = (context.addonConfig.rootPath as string) ?? this.currentConfig.rootPath\n this.currentConfig.rootPath = rootPath\n\n // Read location overrides from config\n const overrides: Partial<Record<string, string>> = {}\n for (const key of Object.keys(context.addonConfig)) {\n if (key.startsWith('override.')) {\n const loc = key.slice('override.'.length)\n overrides[loc] = context.addonConfig[key] as string\n }\n }\n\n this.provider = new FilesystemStorageProvider(rootPath, overrides as any)\n await this.provider.initialize()\n context.logger.info(`Filesystem storage initialized at ${this.provider.getRootPath()}`)\n }\n\n async shutdown(): Promise<void> {\n await this.provider?.shutdown()\n }\n\n getCapabilityProvider<K extends keyof CapabilityProviderMap>(\n name: K,\n ): CapabilityProviderMap[K] | null {\n if (name === 'storage' && this.provider) {\n return this.provider as unknown as CapabilityProviderMap[K]\n }\n return null\n }\n\n getProvider(): FilesystemStorageProvider | null {\n return this.provider\n }\n\n getConfigSchema(): ConfigUISchema {\n return { sections: [] }\n }\n\n getConfig(): Record<string, unknown> {\n return { ...this.currentConfig }\n }\n\n async onConfigChange(config: Record<string, unknown>): Promise<void> {\n this.currentConfig.rootPath = (config.rootPath as string) ?? this.currentConfig.rootPath\n }\n}\n\nexport default FilesystemStorageAddon\n"],"mappings":";AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;AAQtB,IAAM,yBAAyD;AAAA,EAC7D;AAAA,EAAmB;AAAA,EAAkB;AAAA,EAAoB;AAAA,EACzD;AAAA,EAAU;AAAA,EAAe;AAAA,EAAS;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K,UAAU;AACvC,aAAO,KAAK;AAAA,IACd;AACA,WAAO;AAAA,EACT;AAAA,EAEA,cAAgD;AAC9C,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,kBAAkC;AAChC,WAAO,EAAE,UAAU,CAAC,EAAE;AAAA,EACxB;AAAA,EAEA,YAAqC;AACnC,WAAO,EAAE,GAAG,KAAK,cAAc;AAAA,EACjC;AAAA,EAEA,MAAM,eAAe,QAAgD;AACnE,SAAK,cAAc,WAAY,OAAO,YAAuB,KAAK,cAAc;AAAA,EAClF;AACF;AAEA,IAAO,mCAAQ;","names":["resolve"]}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// src/builtins/sqlite-storage/sqlite-settings-backend.ts
|
|
2
|
+
import Database from "better-sqlite3";
|
|
3
|
+
import { randomUUID } from "crypto";
|
|
4
|
+
var SqliteSettingsBackend = class {
|
|
5
|
+
constructor(dbPath, runtimeDefaults) {
|
|
6
|
+
this.dbPath = dbPath;
|
|
7
|
+
this.runtimeDefaults = runtimeDefaults ?? {};
|
|
8
|
+
}
|
|
9
|
+
db = null;
|
|
10
|
+
ensuredTables = /* @__PURE__ */ new Set();
|
|
11
|
+
runtimeDefaults;
|
|
12
|
+
async initialize() {
|
|
13
|
+
const dir = this.dbPath.substring(0, this.dbPath.lastIndexOf("/"));
|
|
14
|
+
if (dir) {
|
|
15
|
+
const fs = await import("fs");
|
|
16
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
17
|
+
}
|
|
18
|
+
this.db = new Database(this.dbPath);
|
|
19
|
+
this.db.pragma("journal_mode = WAL");
|
|
20
|
+
this.db.pragma("foreign_keys = ON");
|
|
21
|
+
const isEmpty = await this.isEmpty("system-settings");
|
|
22
|
+
if (isEmpty) {
|
|
23
|
+
await this.seedDefaults();
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
async shutdown() {
|
|
27
|
+
this.db?.close();
|
|
28
|
+
this.db = null;
|
|
29
|
+
}
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
// ISettingsBackend implementation
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
async get(collection, key) {
|
|
34
|
+
this.ensureTable(collection);
|
|
35
|
+
const row = this.getDb().prepare(`SELECT data FROM "${collection}" WHERE id = ?`).get(key);
|
|
36
|
+
if (!row) return void 0;
|
|
37
|
+
return JSON.parse(row.data);
|
|
38
|
+
}
|
|
39
|
+
async set(collection, key, value) {
|
|
40
|
+
this.ensureTable(collection);
|
|
41
|
+
this.getDb().prepare(`INSERT INTO "${collection}" (id, data) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data`).run(key, JSON.stringify(value));
|
|
42
|
+
}
|
|
43
|
+
async query(collection, filter) {
|
|
44
|
+
this.ensureTable(collection);
|
|
45
|
+
let sql = `SELECT id, data FROM "${collection}"`;
|
|
46
|
+
const params = [];
|
|
47
|
+
const whereClauses = [];
|
|
48
|
+
if (filter?.where) {
|
|
49
|
+
for (const [field, value] of Object.entries(filter.where)) {
|
|
50
|
+
if (field === "id") {
|
|
51
|
+
whereClauses.push("id = ?");
|
|
52
|
+
params.push(value);
|
|
53
|
+
} else {
|
|
54
|
+
whereClauses.push(`json_extract(data, '$.${field}') = ?`);
|
|
55
|
+
params.push(typeof value === "object" ? JSON.stringify(value) : value);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (filter?.whereIn) {
|
|
60
|
+
for (const [field, values] of Object.entries(filter.whereIn)) {
|
|
61
|
+
const placeholders = values.map(() => "?").join(", ");
|
|
62
|
+
if (field === "id") {
|
|
63
|
+
whereClauses.push(`id IN (${placeholders})`);
|
|
64
|
+
} else {
|
|
65
|
+
whereClauses.push(`json_extract(data, '$.${field}') IN (${placeholders})`);
|
|
66
|
+
}
|
|
67
|
+
params.push(...values);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (filter?.whereBetween) {
|
|
71
|
+
for (const [field, [low, high]] of Object.entries(filter.whereBetween)) {
|
|
72
|
+
if (field === "id") {
|
|
73
|
+
whereClauses.push("id BETWEEN ? AND ?");
|
|
74
|
+
} else {
|
|
75
|
+
whereClauses.push(`json_extract(data, '$.${field}') BETWEEN ? AND ?`);
|
|
76
|
+
}
|
|
77
|
+
params.push(low, high);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (whereClauses.length > 0) {
|
|
81
|
+
sql += ` WHERE ${whereClauses.join(" AND ")}`;
|
|
82
|
+
}
|
|
83
|
+
if (filter?.orderBy) {
|
|
84
|
+
const dir = filter.orderBy.direction === "desc" ? "DESC" : "ASC";
|
|
85
|
+
if (filter.orderBy.field === "id") {
|
|
86
|
+
sql += ` ORDER BY id ${dir}`;
|
|
87
|
+
} else {
|
|
88
|
+
sql += ` ORDER BY json_extract(data, '$.${filter.orderBy.field}') ${dir}`;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (filter?.limit) {
|
|
92
|
+
sql += ` LIMIT ?`;
|
|
93
|
+
params.push(filter.limit);
|
|
94
|
+
}
|
|
95
|
+
if (filter?.offset) {
|
|
96
|
+
sql += ` OFFSET ?`;
|
|
97
|
+
params.push(filter.offset);
|
|
98
|
+
}
|
|
99
|
+
const rows = this.getDb().prepare(sql).all(...params);
|
|
100
|
+
return rows.map((row) => ({
|
|
101
|
+
id: row.id,
|
|
102
|
+
data: JSON.parse(row.data)
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
async insert(collection, record) {
|
|
106
|
+
this.ensureTable(collection);
|
|
107
|
+
const id = record.id || randomUUID();
|
|
108
|
+
this.getDb().prepare(`INSERT INTO "${collection}" (id, data) VALUES (?, ?)`).run(id, JSON.stringify(record.data));
|
|
109
|
+
}
|
|
110
|
+
async update(collection, id, data) {
|
|
111
|
+
this.ensureTable(collection);
|
|
112
|
+
this.getDb().prepare(`UPDATE "${collection}" SET data = ? WHERE id = ?`).run(JSON.stringify(data), id);
|
|
113
|
+
}
|
|
114
|
+
async delete(collection, key) {
|
|
115
|
+
this.ensureTable(collection);
|
|
116
|
+
this.getDb().prepare(`DELETE FROM "${collection}" WHERE id = ?`).run(key);
|
|
117
|
+
}
|
|
118
|
+
async count(collection, filter) {
|
|
119
|
+
this.ensureTable(collection);
|
|
120
|
+
if (!filter) {
|
|
121
|
+
const row = this.getDb().prepare(`SELECT COUNT(*) AS cnt FROM "${collection}"`).get();
|
|
122
|
+
return row?.cnt ?? 0;
|
|
123
|
+
}
|
|
124
|
+
const rows = await this.query(collection, { ...filter, limit: void 0, offset: void 0 });
|
|
125
|
+
return rows.length;
|
|
126
|
+
}
|
|
127
|
+
async isEmpty(collection) {
|
|
128
|
+
this.ensureTable(collection);
|
|
129
|
+
const row = this.getDb().prepare(`SELECT COUNT(*) AS cnt FROM "${collection}"`).get();
|
|
130
|
+
return (row?.cnt ?? 0) === 0;
|
|
131
|
+
}
|
|
132
|
+
// ---------------------------------------------------------------------------
|
|
133
|
+
// Legacy SettingsStore compatibility (used by ConfigManager.setSettingsStore)
|
|
134
|
+
// ---------------------------------------------------------------------------
|
|
135
|
+
/** Get a system setting by dot-notation key */
|
|
136
|
+
getSystem(key) {
|
|
137
|
+
this.ensureTable("system-settings");
|
|
138
|
+
const row = this.getDb().prepare('SELECT data FROM "system-settings" WHERE id = ?').get(key);
|
|
139
|
+
if (!row) return void 0;
|
|
140
|
+
return JSON.parse(row.data);
|
|
141
|
+
}
|
|
142
|
+
/** Set a system setting */
|
|
143
|
+
setSystem(key, value) {
|
|
144
|
+
this.ensureTable("system-settings");
|
|
145
|
+
this.getDb().prepare('INSERT INTO "system-settings" (id, data) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data').run(key, JSON.stringify(value));
|
|
146
|
+
}
|
|
147
|
+
/** Get all system settings as flat key-value */
|
|
148
|
+
getAllSystem() {
|
|
149
|
+
this.ensureTable("system-settings");
|
|
150
|
+
const rows = this.getDb().prepare('SELECT id, data FROM "system-settings"').all();
|
|
151
|
+
return Object.fromEntries(rows.map((r) => [r.id, JSON.parse(r.data)]));
|
|
152
|
+
}
|
|
153
|
+
/** Get all settings for an addon */
|
|
154
|
+
getAllAddon(addonId) {
|
|
155
|
+
this.ensureTable("addon-settings");
|
|
156
|
+
const rows = this.getDb().prepare(`SELECT id, data FROM "addon-settings" WHERE json_extract(data, '$.addonId') = ?`).all(addonId);
|
|
157
|
+
if (rows.length === 0) return {};
|
|
158
|
+
const result = {};
|
|
159
|
+
for (const row of rows) {
|
|
160
|
+
const parsed = JSON.parse(row.data);
|
|
161
|
+
const key = row.id.startsWith(`${addonId}.`) ? row.id.slice(addonId.length + 1) : row.id;
|
|
162
|
+
result[key] = parsed.value ?? parsed;
|
|
163
|
+
}
|
|
164
|
+
return result;
|
|
165
|
+
}
|
|
166
|
+
/** Bulk-set all settings for an addon */
|
|
167
|
+
setAllAddon(addonId, config) {
|
|
168
|
+
this.ensureTable("addon-settings");
|
|
169
|
+
const db = this.getDb();
|
|
170
|
+
const deleteStmt = db.prepare(`DELETE FROM "addon-settings" WHERE id LIKE ? || '%'`);
|
|
171
|
+
const insertStmt = db.prepare('INSERT INTO "addon-settings" (id, data) VALUES (?, ?)');
|
|
172
|
+
db.transaction(() => {
|
|
173
|
+
deleteStmt.run(`${addonId}.`);
|
|
174
|
+
for (const [key, value] of Object.entries(config)) {
|
|
175
|
+
insertStmt.run(`${addonId}.${key}`, JSON.stringify({ addonId, key, value }));
|
|
176
|
+
}
|
|
177
|
+
})();
|
|
178
|
+
}
|
|
179
|
+
/** Get all settings for a provider */
|
|
180
|
+
getAllProvider(providerId) {
|
|
181
|
+
return this.getAllScoped("provider-settings", providerId);
|
|
182
|
+
}
|
|
183
|
+
/** Set a provider setting */
|
|
184
|
+
setProvider(providerId, key, value) {
|
|
185
|
+
this.setScopedKey("provider-settings", providerId, key, value);
|
|
186
|
+
}
|
|
187
|
+
/** Get all settings for a device */
|
|
188
|
+
getAllDevice(deviceId) {
|
|
189
|
+
return this.getAllScoped("device-settings", deviceId);
|
|
190
|
+
}
|
|
191
|
+
/** Set a device setting */
|
|
192
|
+
setDevice(deviceId, key, value) {
|
|
193
|
+
this.setScopedKey("device-settings", deviceId, key, value);
|
|
194
|
+
}
|
|
195
|
+
/** Seed system-settings with runtime defaults (first boot) */
|
|
196
|
+
async seedDefaults() {
|
|
197
|
+
this.ensureTable("system-settings");
|
|
198
|
+
const insert = this.getDb().prepare(
|
|
199
|
+
'INSERT OR IGNORE INTO "system-settings" (id, data) VALUES (?, ?)'
|
|
200
|
+
);
|
|
201
|
+
this.getDb().transaction(() => {
|
|
202
|
+
for (const [key, value] of Object.entries(this.runtimeDefaults)) {
|
|
203
|
+
insert.run(key, JSON.stringify(value));
|
|
204
|
+
}
|
|
205
|
+
})();
|
|
206
|
+
}
|
|
207
|
+
// ---------------------------------------------------------------------------
|
|
208
|
+
// Private helpers
|
|
209
|
+
// ---------------------------------------------------------------------------
|
|
210
|
+
getDb() {
|
|
211
|
+
if (!this.db) throw new Error("SqliteSettingsBackend not initialized \u2014 call initialize() first");
|
|
212
|
+
return this.db;
|
|
213
|
+
}
|
|
214
|
+
ensureTable(collection) {
|
|
215
|
+
if (this.ensuredTables.has(collection)) return;
|
|
216
|
+
this.getDb().exec(
|
|
217
|
+
`CREATE TABLE IF NOT EXISTS "${collection}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)`
|
|
218
|
+
);
|
|
219
|
+
this.ensuredTables.add(collection);
|
|
220
|
+
}
|
|
221
|
+
getAllScoped(collection, scopeId) {
|
|
222
|
+
this.ensureTable(collection);
|
|
223
|
+
const rows = this.getDb().prepare(`SELECT id, data FROM "${collection}" WHERE id LIKE ? || '.%'`).all(scopeId);
|
|
224
|
+
const result = {};
|
|
225
|
+
for (const row of rows) {
|
|
226
|
+
const key = row.id.slice(scopeId.length + 1);
|
|
227
|
+
const parsed = JSON.parse(row.data);
|
|
228
|
+
result[key] = parsed.value ?? parsed;
|
|
229
|
+
}
|
|
230
|
+
return result;
|
|
231
|
+
}
|
|
232
|
+
setScopedKey(collection, scopeId, key, value) {
|
|
233
|
+
this.ensureTable(collection);
|
|
234
|
+
this.getDb().prepare(`INSERT INTO "${collection}" (id, data) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET data = excluded.data`).run(`${scopeId}.${key}`, JSON.stringify({ scopeId, key, value }));
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
// src/builtins/sqlite-storage/sqlite-settings.addon.ts
|
|
239
|
+
var SqliteSettingsAddon = class {
|
|
240
|
+
manifest = {
|
|
241
|
+
id: "sqlite-settings",
|
|
242
|
+
name: "SQLite Settings",
|
|
243
|
+
version: "1.0.0",
|
|
244
|
+
capabilities: [{ name: "settings-store", mode: "singleton" }]
|
|
245
|
+
};
|
|
246
|
+
backend = null;
|
|
247
|
+
async initialize(context) {
|
|
248
|
+
const dbPath = context.storageProvider ? context.storageProvider.resolve("addons-data", `${context.id.replace("addon:", "")}/camstack.db`) : context.dataDir ? `${context.dataDir}/camstack.db` : "camstack-data/addons-data/sqlite-settings/camstack.db";
|
|
249
|
+
const runtimeDefaults = context.addonConfig._runtimeDefaults ?? {};
|
|
250
|
+
this.backend = new SqliteSettingsBackend(dbPath, runtimeDefaults);
|
|
251
|
+
await this.backend.initialize();
|
|
252
|
+
context.logger.info(`SQLite settings initialized at ${dbPath}`);
|
|
253
|
+
}
|
|
254
|
+
async shutdown() {
|
|
255
|
+
await this.backend?.shutdown();
|
|
256
|
+
}
|
|
257
|
+
getBackend() {
|
|
258
|
+
return this.backend;
|
|
259
|
+
}
|
|
260
|
+
getCapabilityProvider(name) {
|
|
261
|
+
if (name === "settings-store" && this.backend) {
|
|
262
|
+
return this.backend;
|
|
263
|
+
}
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
getConfigSchema() {
|
|
267
|
+
return { sections: [] };
|
|
268
|
+
}
|
|
269
|
+
getConfig() {
|
|
270
|
+
return {};
|
|
271
|
+
}
|
|
272
|
+
async onConfigChange(_config) {
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
var sqlite_settings_addon_default = SqliteSettingsAddon;
|
|
276
|
+
|
|
277
|
+
export {
|
|
278
|
+
SqliteSettingsBackend,
|
|
279
|
+
SqliteSettingsAddon,
|
|
280
|
+
sqlite_settings_addon_default
|
|
281
|
+
};
|
|
282
|
+
//# sourceMappingURL=chunk-YXNXYYHL.mjs.map
|