Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(plugins): seed configSchema defaults into stored config at load (#812)
Yudhi Armyndharis458ced353ffa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5464c6837..ee2bf9450 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -108,6 +108,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0with fetching gated to `qr_ready` (no more expected-but-noisy 400 console errors), and enabling aplugin with unset required config opens its config dialog with a warning instead of failing with araw sandbox error.+- Plugins whose config schema declares field defaults no longer fail to enable with those values+ missing: defaults are now seeded into the stored config at load time (fresh installs and every+ boot), without ever overwriting explicit values. Required fields without a declared default still+ need real operator input.## [0.9.0] - 2026-07-18diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.tsindex f5bcaf9d9..ff7a4dbda 100644--- a/src/core/plugins/plugin-loader.service.spec.ts+++ b/src/core/plugins/plugin-loader.service.spec.ts@@ -115,7 +115,7 @@ describe('dispatchConversationMedia', () => {import * as fs from 'fs';import * as os from 'os';-import { PluginLoaderService } from './plugin-loader.service';+import { PluginLoaderService, seedConfigDefaults } from './plugin-loader.service';import { ConfigService } from '@nestjs/config';import { ModuleRef } from '@nestjs/core';import { HookManager } from '../hooks';@@ -464,6 +464,91 @@ describe('PluginLoaderService — prunes registry ghosts of removed built-ins',});});+describe('PluginLoaderService — loadPlugin seeds configSchema defaults', () => {+ let tmpDir: string;+ let pluginsDir: string;+ let loader: PluginLoaderService;+ let storage: PluginStorageService;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-seed-'));+ pluginsDir = path.join(tmpDir, 'plugins');+ fs.mkdirSync(pluginsDir, { recursive: true });+ const config = {+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),+ } as unknown as ConfigService;+ storage = new PluginStorageService(config);+ loader = new PluginLoaderService(config, new HookManager(), storage, {} as unknown as ModuleRef);+ });+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++ it('seeds defaults into the runtime instance and the persisted registry entry at load', () => {+ const dir = path.join(pluginsDir, 'seeded-plg');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(+ path.join(dir, 'manifest.json'),+ JSON.stringify({+ id: 'seeded-plg',+ name: 'seeded-plg',+ version: '1.0.0',+ type: 'extension',+ main: 'index.js',+ configSchema: {+ type: 'object',+ properties: { timezone: { type: 'string', default: 'UTC' } },+ },+ }),+ );+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');++ loader.onModuleInit();++ expect(loader.getPlugin('seeded-plg')?.config).toEqual({ timezone: 'UTC' });+ expect(storage.getPluginEntry('seeded-plg')?.config).toEqual({ timezone: 'UTC' });+ });+});++describe('seedConfigDefaults', () => {+ const schema = {+ type: 'object' as const,+ properties: {+ timezone: { type: 'string' as const, default: 'UTC' },+ cooldownSec: { type: 'number' as const, default: 3600 },+ schedule: { type: 'object' as const, required: true }, // no default — must stay absent+ rules: { type: 'array' as const, default: [{ q: 'hi', a: 'hello' }] },+ },+ };++ it('seeds schema defaults for absent keys only', () => {+ const out = seedConfigDefaults(schema, { timezone: 'Asia/Jakarta' });+ expect(out).toEqual({+ timezone: 'Asia/Jakarta', // explicit value wins+ cooldownSec: 3600,+ rules: [{ q: 'hi', a: 'hello' }],+ });+ expect(out).not.toHaveProperty('schedule'); // required-without-default is never invented+ });++ it('returns the input unchanged when nothing is missing (and no schema)', () => {+ const config = { timezone: 'UTC', cooldownSec: 1, rules: [] };+ expect(seedConfigDefaults(schema, config)).toBe(config);+ expect(seedConfigDefaults(undefined, config)).toBe(config);+ });++ it('deep-clones object/array defaults so runtime and persisted copies cannot share references', () => {+ const out = seedConfigDefaults(schema, {});+ const again = seedConfigDefaults(schema, {});+ expect(out.rules).toEqual(again.rules);+ expect(out.rules).not.toBe(again.rules);+ expect((out.rules as unknown[])[0]).not.toBe((again.rules as unknown[])[0]);+ });++ it('null is an explicit value and is not overwritten by the default', () => {+ const out = seedConfigDefaults(schema, { timezone: null });+ expect(out.timezone).toBeNull();+ });+});+describe('PluginLoaderService — enable concurrency', () => {let tmpDir: string;let loader: PluginLoaderService;diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex f8dae7313..ffb8437e1 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -24,6 +24,7 @@ import {IPlugin,PluginType,PluginLogger,+ PluginConfigSchema,validateIngressManifest,warnUnauthenticatedIngressRoutes,} from './plugin.interfaces';@@ -139,6 +140,32 @@ export function dispatchConversationMedia(// temporarily-unreadable plugin dir (e.g. an unmounted volume) never loses its persisted config.const LEGACY_REMOVED_PLUGIN_IDS = new Set(['auto-reply', 'translation']);+/**+ * Fill config keys the schema declares a `default` for and that are absent (undefined) in the+ * stored config. Seeding happens at LOAD time (fresh installs and every boot), so a plugin whose+ * schema fields carry defaults never runs its lifecycle with them missing — the failure class of+ * "enable throws: <field> is required/has no value" for defaulted fields. Explicit values — even+ * null — are never overwritten, and object/array defaults are deep-cloned so the seeded runtime+ * config and the persisted entry can't share a mutable reference. Required fields WITHOUT a+ * declared default stay absent on purpose: those need real operator input, not an invented value.+ */+export function seedConfigDefaults(+ schema: PluginConfigSchema | undefined,+ config: Record<string, unknown>,+): Record<string, unknown> {+ const properties = schema?.properties;+ if (!properties) return config;+ let seeded: Record<string, unknown> | undefined;+ for (const [key, field] of Object.entries(properties)) {+ if (config[key] !== undefined || field === null || typeof field !== 'object') continue;+ const value = field.default;+ if (value === undefined) continue;+ if (!seeded) seeded = { ...config };+ seeded[key] = value !== null && typeof value === 'object' ? structuredClone(value) : value;+ }+ return seeded ?? config;+}+@Injectable()export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {private readonly logger = createLogger('PluginLoaderService');@@ -282,7 +309,9 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {const pluginInstance: PluginInstance = {manifest,status: PluginStatus.INSTALLED,- config: storedConfig,+ // Seed schema-declared defaults under the stored config, so a defaulted field is never+ // missing when the plugin later runs (explicit values are never overwritten).+ config: seedConfigDefaults(manifest.configSchema, storedConfig),instance: null,loadedAt: new Date(),builtIn: false,@@ -325,7 +354,9 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {name: manifest.name,version: manifest.version,status: PluginStatus.INSTALLED,- config: existing?.config ?? {},+ // The operator's persisted config survives, with schema-declared defaults seeded under it so+ // the persisted entry matches the seeded runtime config (see loadPlugin).+ config: seedConfigDefaults(manifest.configSchema, existing?.config ?? {}),builtIn,installedAt: existing?.installedAt ?? new Date(),updatedAt: new Date(),