|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { describe, it, expect } from 'vitest'; |
| 4 | +// STATIC on purpose, like audit-writers.test.ts: the plugin's own kernel:ready |
| 5 | +// hook imports the translation bundle lazily, and a static import here moves |
| 6 | +// that cold-start cost to collection, which no test's timeout is charged for. |
| 7 | +import { createMemoryI18n } from '@objectstack/core'; |
| 8 | +import { AuditTranslations } from './translations/index.js'; |
| 9 | +import { AuditPlugin, type AuditPluginOptions } from './audit-plugin.js'; |
| 10 | + |
| 11 | +/** |
| 12 | + * `AuditPluginOptions.getLocale` — the host locale resolver, driven through the |
| 13 | + * PLUGIN (init → start → kernel:ready), not through `installAuditWriters` |
| 14 | + * directly: the option is only worth anything if the plugin really hands it to |
| 15 | + * the writers ahead of the settings-derived locale it builds itself. |
| 16 | + * |
| 17 | + * The settings service answers `ja-JP` throughout, so every outcome is |
| 18 | + * distinguishable: the host's locale (zh-CN), the settings fallback (ja-JP), |
| 19 | + * and the English literal a locale-less write degrades to. |
| 20 | + */ |
| 21 | + |
| 22 | +interface CapturedRow { |
| 23 | + object: string; |
| 24 | + row: Record<string, any>; |
| 25 | +} |
| 26 | + |
| 27 | +/** A fake ObjectQL engine: records hooks (honouring `object` / `excludeObjects`) and created rows. */ |
| 28 | +function makeEngine() { |
| 29 | + const hooks = new Map<string, Array<{ fn: (ctx: any) => any; opts: any }>>(); |
| 30 | + const created: CapturedRow[] = []; |
| 31 | + const api = { |
| 32 | + sudo: () => ({ |
| 33 | + object(name: string) { |
| 34 | + return { |
| 35 | + async create(row: Record<string, any>) { |
| 36 | + created.push({ object: name, row }); |
| 37 | + return { id: `${name}-${created.length}`, ...row }; |
| 38 | + }, |
| 39 | + }; |
| 40 | + }, |
| 41 | + }), |
| 42 | + }; |
| 43 | + const schemas: Record<string, Record<string, any>> = { |
| 44 | + sys_audit_log: { name: 'sys_audit_log', fields: {} }, |
| 45 | + sys_activity: { name: 'sys_activity', fields: {} }, |
| 46 | + person_qualification: { |
| 47 | + name: 'person_qualification', |
| 48 | + label: 'Qualification', |
| 49 | + fields: { id: { type: 'text' }, name: { type: 'text' } }, |
| 50 | + }, |
| 51 | + }; |
| 52 | + for (const f of ['id', 'action', 'user_id', 'actor', 'object_name', 'record_id', 'old_value', 'new_value', 'tenant_id']) { |
| 53 | + schemas.sys_audit_log.fields[f] = { type: 'text' }; |
| 54 | + } |
| 55 | + for (const f of ['id', 'type', 'timestamp', 'summary', 'actor_id', 'object_name', 'record_id', 'record_label', 'metadata']) { |
| 56 | + schemas.sys_activity.fields[f] = { type: 'text' }; |
| 57 | + } |
| 58 | + const engine = { |
| 59 | + getSchema(name: string) { |
| 60 | + return schemas[name]; |
| 61 | + }, |
| 62 | + registerHook(event: string, fn: (ctx: any) => any, opts?: any) { |
| 63 | + const list = hooks.get(event) ?? []; |
| 64 | + list.push({ fn, opts: opts ?? {} }); |
| 65 | + hooks.set(event, list); |
| 66 | + }, |
| 67 | + unregisterHooksByPackage() { |
| 68 | + /* no-op */ |
| 69 | + }, |
| 70 | + }; |
| 71 | + async function fire(event: string, ctx: any) { |
| 72 | + for (const { fn, opts } of hooks.get(event) ?? []) { |
| 73 | + if (opts.object && opts.object !== ctx.object) continue; |
| 74 | + if (Array.isArray(opts.excludeObjects) && opts.excludeObjects.includes(ctx.object)) continue; |
| 75 | + await fn({ ...ctx, event, api }); |
| 76 | + } |
| 77 | + } |
| 78 | + return { engine, fire, created }; |
| 79 | +} |
| 80 | + |
| 81 | +/** A settings occupant whose `localization.locale` is `ja-JP` (the fallback every case can see). */ |
| 82 | +function makeSettings(locale = 'ja-JP') { |
| 83 | + const values: Record<string, unknown> = { locale }; |
| 84 | + return { |
| 85 | + // `resolveLocalizationContext` takes the settings path only when `get` exists, then prefers `getMany`. |
| 86 | + async get(_ns: string, key: string) { |
| 87 | + return values[key] === undefined ? undefined : { value: values[key] }; |
| 88 | + }, |
| 89 | + async getMany(_ns: string, keys: string[]) { |
| 90 | + return Object.fromEntries(keys.map((k) => [k, values[k] === undefined ? undefined : { value: values[k] }])); |
| 91 | + }, |
| 92 | + }; |
| 93 | +} |
| 94 | + |
| 95 | +async function boot(options?: AuditPluginOptions, services: { settings?: unknown } = { settings: makeSettings() }) { |
| 96 | + const { engine, fire, created } = makeEngine(); |
| 97 | + const i18n = createMemoryI18n(); |
| 98 | + for (const [locale, data] of Object.entries(AuditTranslations)) { |
| 99 | + i18n.loadTranslations(locale, data as Record<string, unknown>); |
| 100 | + } |
| 101 | + const registry = new Map<string, unknown>([ |
| 102 | + ['objectql', engine], |
| 103 | + ['manifest', { register() {} }], |
| 104 | + ['i18n', i18n], |
| 105 | + ]); |
| 106 | + if (services.settings !== undefined) registry.set('settings', services.settings); |
| 107 | + const readyHooks: Array<() => Promise<void> | void> = []; |
| 108 | + const warns: Array<{ msg: string; meta?: Record<string, unknown> }> = []; |
| 109 | + const logger = { |
| 110 | + info() {}, |
| 111 | + warn(msg: string, meta?: Record<string, unknown>) { |
| 112 | + warns.push({ msg: String(msg), meta }); |
| 113 | + }, |
| 114 | + error() {}, |
| 115 | + debug() {}, |
| 116 | + child() { |
| 117 | + return logger; |
| 118 | + }, |
| 119 | + }; |
| 120 | + const ctx = { |
| 121 | + logger, |
| 122 | + getService(name: string) { |
| 123 | + return registry.get(name); |
| 124 | + }, |
| 125 | + registerService(name: string, svc: unknown) { |
| 126 | + registry.set(name, svc); |
| 127 | + }, |
| 128 | + hook(event: string, fn: () => Promise<void> | void) { |
| 129 | + if (event === 'kernel:ready') readyHooks.push(fn); |
| 130 | + }, |
| 131 | + } as any; |
| 132 | + const plugin = options === undefined ? new AuditPlugin() : new AuditPlugin(options); |
| 133 | + await plugin.init(ctx); |
| 134 | + await plugin.start(ctx); |
| 135 | + for (const fn of readyHooks) await fn(); |
| 136 | + |
| 137 | + const insert = (tenant = 'org-1', user = 'user-1', name = 'OC-00001') => |
| 138 | + fire('afterInsert', { |
| 139 | + object: 'person_qualification', |
| 140 | + input: { id: `q-${name}` }, |
| 141 | + result: { id: `q-${name}`, name }, |
| 142 | + session: { organizationId: tenant, userId: user }, |
| 143 | + }); |
| 144 | + const summaries = () => created.filter((c) => c.object === 'sys_activity').map((c) => c.row.summary); |
| 145 | + const localeWarns = () => warns.filter((w) => w.msg.includes('getLocale')); |
| 146 | + return { insert, summaries, created, localeWarns }; |
| 147 | +} |
| 148 | + |
| 149 | +const ZH = '创建了 Qualification "OC-00001"'; |
| 150 | +const JA = 'Qualification「OC-00001」を作成しました'; |
| 151 | +const EN = 'Created Qualification "OC-00001"'; |
| 152 | + |
| 153 | +describe('AuditPlugin — host locale resolver (AuditPluginOptions.getLocale)', () => { |
| 154 | + it('pin: a create on a tracked object writes sys_activity.summary in the resolver\'s locale', async () => { |
| 155 | + const calls: Array<[string | undefined, string | undefined]> = []; |
| 156 | + const { insert, summaries, localeWarns } = await boot({ |
| 157 | + getLocale: async (tenantId, userId) => { |
| 158 | + calls.push([tenantId, userId]); |
| 159 | + return 'zh-CN'; |
| 160 | + }, |
| 161 | + }); |
| 162 | + await insert(); |
| 163 | + expect(summaries()).toEqual([ZH]); |
| 164 | + // Asked with the write's organization and user, ahead of the settings read. |
| 165 | + expect(calls).toEqual([['org-1', 'user-1']]); |
| 166 | + expect(localeWarns()).toEqual([]); |
| 167 | + }); |
| 168 | + |
| 169 | + it('a synchronous answer counts, and is used in its canonical form', async () => { |
| 170 | + const { insert, summaries } = await boot({ getLocale: () => ' zh-cn ' }); |
| 171 | + await insert(); |
| 172 | + expect(summaries()).toEqual([ZH]); |
| 173 | + }); |
| 174 | + |
| 175 | + it('fallback: a resolver answering undefined gives today\'s settings-derived locale', async () => { |
| 176 | + const { insert, summaries, localeWarns } = await boot({ getLocale: async () => undefined }); |
| 177 | + await insert(); |
| 178 | + expect(summaries()).toEqual([JA]); |
| 179 | + expect(localeWarns()).toEqual([]); |
| 180 | + }); |
| 181 | + |
| 182 | + it('fallback: null and a blank string are "no answer" too, silently', async () => { |
| 183 | + const asNull = await boot({ getLocale: (async () => null) as unknown as AuditPluginOptions['getLocale'] }); |
| 184 | + await asNull.insert(); |
| 185 | + expect(asNull.summaries()).toEqual([JA]); |
| 186 | + expect(asNull.localeWarns()).toEqual([]); |
| 187 | + |
| 188 | + const blank = await boot({ getLocale: () => ' ' }); |
| 189 | + await blank.insert(); |
| 190 | + expect(blank.summaries()).toEqual([JA]); |
| 191 | + expect(blank.localeWarns()).toEqual([]); |
| 192 | + }); |
| 193 | + |
| 194 | + it('absent: with no option the summary is the settings-derived one (the existing-behaviour control)', async () => { |
| 195 | + const withSettings = await boot(); |
| 196 | + await withSettings.insert(); |
| 197 | + expect(withSettings.summaries()).toEqual([JA]); |
| 198 | + |
| 199 | + // An options bag without the member is the same as no bag at all. |
| 200 | + const emptyBag = await boot({}); |
| 201 | + await emptyBag.insert(); |
| 202 | + expect(emptyBag.summaries()).toEqual([JA]); |
| 203 | + |
| 204 | + // And no settings service either: the built-in en-US default — English. |
| 205 | + const bare = await boot(undefined, {}); |
| 206 | + await bare.insert(); |
| 207 | + expect(bare.summaries()).toEqual([EN]); |
| 208 | + }); |
| 209 | + |
| 210 | + it('throw: falls through to the settings-derived locale, logged once at warn with the error, and the write lands', async () => { |
| 211 | + let calls = 0; |
| 212 | + const { insert, summaries, created, localeWarns } = await boot({ |
| 213 | + getLocale: () => { |
| 214 | + calls += 1; |
| 215 | + throw new Error('locale store unreachable'); |
| 216 | + }, |
| 217 | + }); |
| 218 | + await insert('org-1', 'user-1', 'OC-00001'); |
| 219 | + // A second scope asks again (the writer memoizes per tenant/user) and throws again. |
| 220 | + await insert('org-2', 'user-2', 'OC-00002'); |
| 221 | + expect(calls).toBe(2); |
| 222 | + expect(summaries()).toEqual([JA, 'Qualification「OC-00002」を作成しました']); |
| 223 | + // The audited write is not failed by the host's fault: both ledger rows landed. |
| 224 | + expect(created.filter((c) => c.object === 'sys_audit_log')).toHaveLength(2); |
| 225 | + const warned = localeWarns(); |
| 226 | + expect(warned).toHaveLength(1); |
| 227 | + expect(warned[0].msg).toMatch(/host getLocale resolver threw/); |
| 228 | + expect(warned[0].meta).toEqual({ err: 'locale store unreachable' }); |
| 229 | + }); |
| 230 | + |
| 231 | + it('throw: a rejected promise falls through the same way', async () => { |
| 232 | + const { insert, summaries, localeWarns } = await boot({ |
| 233 | + getLocale: () => Promise.reject(new Error('timeout')), |
| 234 | + }); |
| 235 | + await insert(); |
| 236 | + expect(summaries()).toEqual([JA]); |
| 237 | + expect(localeWarns()).toHaveLength(1); |
| 238 | + expect(localeWarns()[0].meta).toEqual({ err: 'timeout' }); |
| 239 | + }); |
| 240 | + |
| 241 | + it('an answer that is not a well-formed BCP-47 tag falls back, logged once at warn', async () => { |
| 242 | + const { insert, summaries, localeWarns } = await boot({ getLocale: () => 'zh_CN' }); |
| 243 | + await insert('org-1', 'user-1', 'OC-00001'); |
| 244 | + await insert('org-2', 'user-2', 'OC-00002'); |
| 245 | + expect(summaries()).toEqual([JA, 'Qualification「OC-00002」を作成しました']); |
| 246 | + const warned = localeWarns(); |
| 247 | + expect(warned).toHaveLength(1); |
| 248 | + expect(warned[0].msg).toContain('"zh_CN"'); |
| 249 | + expect(warned[0].msg).toMatch(/not a well-formed BCP-47 locale tag/); |
| 250 | + }); |
| 251 | +}); |
0 commit comments