|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * A fixture plugin that gives a served test boot what every real `single` |
| 5 | + * install has before its inline seed runs: an organization object holding the |
| 6 | + * Default Organization. |
| 7 | + * |
| 8 | + * ADR-0131 D1: a table the SQL driver creates carries its tenant column NOT |
| 9 | + * NULL. A real `os dev` / `os serve` composes authentication, which provisions |
| 10 | + * the Default Organization, and the engine stamps every organization-less seed |
| 11 | + * row with it (D9). `createStandaloneStack` alone composes no authentication, |
| 12 | + * so a suite that serves an artifact's seeds through it would have them refused |
| 13 | + * at the database. Spliced into the plugin list ahead of the app plugin (see |
| 14 | + * {@link withDefaultOrganization}), it starts after the default datasource and |
| 15 | + * before the app's `start()` seeds. |
| 16 | + * |
| 17 | + * The object mirrors the platform's: managed by better-auth, so it carries no |
| 18 | + * tenant column of its own; its row is seeded through the driver, as data at |
| 19 | + * rest. |
| 20 | + */ |
| 21 | +export const DEFAULT_ORGANIZATION_ID = 'org_default'; |
| 22 | + |
| 23 | +export function defaultOrganizationPlugin() { |
| 24 | + return { |
| 25 | + name: 'test.default-organization', |
| 26 | + version: '0.0.0', |
| 27 | + type: 'standard', |
| 28 | + dependencies: ['com.objectstack.runtime.default-datasource'], |
| 29 | + async init() {}, |
| 30 | + async start(ctx: { getService(name: string): any }) { |
| 31 | + const ql = ctx.getService('objectql'); |
| 32 | + if (!ql.getSchema('sys_organization')) { |
| 33 | + ql.registry.registerObject( |
| 34 | + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: { type: 'text', label: 'Name' } } }, |
| 35 | + 'test.default-organization', |
| 36 | + ); |
| 37 | + } |
| 38 | + await ql.syncObjectSchema('sys_organization'); |
| 39 | + const driver = ql.getDriverForObject('sys_organization'); |
| 40 | + if (await driver.findOne('sys_organization', { where: { id: DEFAULT_ORGANIZATION_ID } })) return; |
| 41 | + await driver.create('sys_organization', { id: DEFAULT_ORGANIZATION_ID, name: 'Default' }); |
| 42 | + }, |
| 43 | + }; |
| 44 | +} |
| 45 | + |
| 46 | +/** The served plugin list with {@link defaultOrganizationPlugin} ahead of every app plugin. */ |
| 47 | +export function withDefaultOrganization<T>(plugins: readonly T[]): T[] { |
| 48 | + const out = [...plugins]; |
| 49 | + const datasource = out.findIndex((p: any) => p?.name === 'com.objectstack.runtime.default-datasource'); |
| 50 | + out.splice(datasource + 1, 0, defaultOrganizationPlugin() as T); |
| 51 | + return out; |
| 52 | +} |
0 commit comments