Repository navigation
Expand file tree
/
Copy pathapp-plugin.ts
More file actions
2761 lines (2657 loc) · 151 KB
/
Copy pathapp-plugin.ts
File metadata and controls
2761 lines (2657 loc) · 151 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import {
Plugin,
PluginContext,
artifactPackageId,
createPluginPermissionEnforcer,
resolveArtifactPackageOrder,
wireAuthoredTranslationSync,
type PluginPermissionEnforcer,
} from '@objectstack/core';
import { resolveArtifactCollections } from './artifact-collections.js';
import {
registerArtifactGrantedPermissions,
type ArtifactGrantBinding,
} from './security/artifact-granted-permissions.js';
import {
applyArtifactForwardConversions,
assertProtocolCompat,
type ArtifactForwardConversionResult,
} from '@objectstack/metadata-core';
import { OBJECTQL_DRIVERS_READY_HOOK } from '@objectstack/objectql';
import { resolveTenancyPosture } from '@objectstack/types';
import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security';
import { SeedLoaderService } from './seed-loader.js';
import { recordSeedOutcome } from './seed-summary.js';
import { contributeCodeDatasourceNames } from './code-datasource-names.js';
import { mergeSeedDatasets, readSeedDatasets, registerSeedReplayerOnce } from './seed-datasets.js';
import { declareSeedSource, recordOrganizationReplay, type SeedLandingReport } from './seed-settlement.js';
import { loadDisabledPackageIds } from './package-state-store.js';
import type { IMetadataService, IObjectQLEngine, II18nService } from '@objectstack/spec/contracts';
import { normalizeFlowFunctionEntry, type NormalizedFlowFunction } from '@objectstack/spec/automation';
import { readServiceSelfInfo } from '@objectstack/spec/api';
import { SEED_WRITE_EXECUTION_CONTEXT } from '@objectstack/spec/kernel';
import { applyProtection } from '@objectstack/spec/shared';
import { QuickJSScriptRunner } from './sandbox/quickjs-runner.js';
import { hookBodyRunnerFactory, actionBodyRunnerFactory } from './sandbox/body-runner.js';
import { bindAppArtifactHandlers, scheduleAppArtifactJobs } from './app-artifact-handlers.js';
import { countServerTiming } from '@objectstack/observability';
/**
* The write options every seed insert must use — the shared
* {@link SEED_WRITE_EXECUTION_CONTEXT} posture, wrapped in the options bag
* `IObjectQLEngine.insert` takes. It no longer MIRRORS
* `SeedLoaderService.SEED_OPTIONS`; both now read the same export, so the two
* cannot drift apart (#17178).
*
* `skipTriggers` is the load-bearing part: seed rows are pre-existing end-state
* data, not user events, so firing "on create" automation for them is
* semantically wrong and was the vector for a self-trigger loop that wedged
* first boot. `isSystem` alone does NOT suppress dispatch — only `skipTriggers`
* does — so the two basic-insert fallbacks below used to seed with automation
* live while the main path had it suppressed (#3760).
*/
const SEED_WRITE_OPTIONS = { context: SEED_WRITE_EXECUTION_CONTEXT } as const;
/**
* Optional per-project context attached when AppPlugin is instantiated by the
* project kernel factory. Required for the `app:registered` / `app:unregistered`
* hooks that drive the org-scoped `sys_app` catalog. Standalone (single-tenant)
* usages may omit this — no catalog hooks are emitted in that case.
*/
export interface AppPluginProjectContext {
environmentId: string;
organizationId: string;
projectName?: string;
/** When the app comes from a package installation, the source package id. */
packageId?: string;
/** Defaults to 'package' when packageId is set, otherwise 'user'. */
source?: 'package' | 'user';
}
/**
* Who registers the stack-declared SECURITY collections (`positions`,
* `permissions`, `capabilities`, `sharingRules`) into the metadata service on
* this boot — the ADR-0057 block in `AppPlugin.start()`.
*
* - `'app-plugin'` (default): this plugin registers them itself. Every
* composition that has no artifact door is this shape — `new AppPlugin(config)`
* over a `defineStack()` module (`os serve` / `os migrate` host configs, the
* plain stacks in a config's `plugins[]`), `DevPlugin`, `@objectstack/verify`'s
* `bootStack`, an embedder.
* - `'artifact-door'`: the composition ALSO runs `MetadataPlugin` with
* `artifactSource` over the same artifact this bundle was read from, so the
* artifact door (`packages/metadata/src/plugin.ts`, `ARTIFACT_FIELD_TO_TYPE`)
* registers the strict-parsed, forward-converted, ADR-0010-stamped copy of
* every item and this plugin leaves those four collections to it (#12892
* step 2 — maintainer ruling 2026-08-29: the door owns the route).
* `createStandaloneStack` is the composition that says so.
*
* ⛔ Declare `'artifact-door'` ONLY beside a `MetadataPlugin({ artifactSource })`
* reading the same artifact: a declared collection with zero registrars boots
* green and logs nothing (measured on #12892 step 1), and the default is the
* registering branch precisely so a composition that never heard of this option
* cannot lose a registrar.
*/
export type AppPluginSecurityMetadataRegistrar = 'app-plugin' | 'artifact-door';
/**
* AppPlugin
*
* Adapts a generic App Bundle (Manifest + Runtime Code) into a Kernel Plugin.
*
* Responsibilities:
* 1. Register App Manifest as a service (for ObjectQL discovery)
* 2. Execute Runtime `onEnable` hook (for code logic) — withheld on a
* declaration boot that passes `skipOnEnable`
* 3. Auto-load i18n translation bundles into the kernel's i18n service
*/
export class AppPlugin implements Plugin {
name: string;
type = 'app' as const;
version?: string;
/**
* Ordering — declared, not positional (ADR-0116, the #4131 close of
* #4085). `init()` synchronously registers the manifest through the
* `manifest` service and seeds package state / sandbox runners through
* `objectql` — both registered by ObjectQLPlugin's init. For months that
* ordering held only because callers happened to `use()` this plugin in
* the right slot; #4085 is what the wrong slot looks like. Soft (order-
* if-present) rather than hard because AppPlugin is deliberately
* composed on engine-less kernels too (metadata-only one-shot commands,
* mock-engine tests) where it degrades: every `objectql` touch in init
* is behind a try/catch.
*
* `com.objectstack.auth` (ADR-0131 D3): under the `single` posture the
* auth plugin creates the Default Organization in its `start()`, and that
* organization must exist before this plugin's `start()` loads the inline
* seed — every seed row is stamped with it or refused. A kernel without
* the auth plugin that registers plugin-auth's identity objects
* (`com.objectstack.auth.identity-objects`, `createIdentityObjectsPlugin()`)
* registers the organization object too, and that plugin's `start()` keeps
* the same invariant, so it is ordered ahead for the same reason.
* Order-if-present: a composition with neither registers no organization
* object, and its seeds keep today's unstamped branch.
*/
optionalDependencies = [
'com.objectstack.engine.objectql',
'com.objectstack.auth',
'com.objectstack.auth.identity-objects',
];
/**
* The one init-time service this plugin CANNOT degrade without: a
* non-empty bundle is registered via `getService('manifest').register()`
* with no fallback. Declared so a composition that breaks it fails as a
* named ordering/composition error before init side effects (#4131).
* Cleared in the constructor for the empty-env no-op path, which never
* touches the service.
*/
requiresServices: string[] = ['manifest'];
/**
* Private to the type checker only: three readers outside this class read
* `bundle` structurally off a plugin entry, with no type to break when it
* changes. `stackDeclaresOrganizationRecordPage` (`@objectstack/core`,
* `stack-organization-record-page.ts`) looks for an app's own
* `sys_organization` record page; `@objectstack/cli`'s `serve.ts` looks for
* declared translations, and its `graft-runtime-hooks.ts` finds an app's
* bundle by manifest id to graft hooks onto. Renaming or reshaping this
* field silently blinds all three; change them together.
*/
private bundle: any;
/** Memoized backing store for {@link collections}. */
private resolvedCollections?: any;
private projectContext?: AppPluginProjectContext;
/**
* The context handed to `init()`, retained so `destroy()` can emit the
* `app:unregistered` catalog event. [#10772] `Plugin.destroy()` takes NO
* argument — it is the kernel's only teardown hook — so the context the
* old `stop(ctx)` alias received has to be captured at init time instead
* of arriving at teardown time.
*/
private initCtx?: PluginContext;
/**
* The enforcer holding this artifact's install-time GRANTED permission sets
* (ADR-0025 F4), or `undefined` when the artifact carried no
* `grantedPermissions` key — which is every artifact built before consent
* existed and every `defineStack()` config, so this stays `undefined` on
* every boot shape that ships today.
*
* Constructed in `init()` only when there is something to register, so a
* boot with no consent record allocates nothing and behaves byte-for-byte
* as it did. Public and readonly-by-accessor so the materialize seam that
* will QUERY it — and a composition pin — can reach the registry rather
* than rebuilding it from the artifact a second time.
*/
private grantEnforcer?: PluginPermissionEnforcer;
/** What `grantedPermissions` bound to on this artifact — see {@link ArtifactGrantBinding}. */
private grantBindingResult?: ArtifactGrantBinding;
/**
* [#21922] {@link codeDefinedDatasourceOwners}, computed once: the host's
* code-datasource set reads the names through the contribution `init()`
* registers, and `start()` registers the same list, so the two can never
* disagree about which datasources this artifact registers from code — and
* the residual-owner warning prints once, at whichever read comes first.
*/
private codeDatasourceOwners?: Array<{ datasource: any; owner: { packageId?: string; packageVersion?: string } }>;
/**
* [#23649] Set once {@link installDatasourceMapping} has handed the stack's
* rules to the engine, so `start()` installs them only on a composition
* whose engine never announced its pre-sync moment.
*/
private datasourceMappingInstalled = false;
/** Memoized backing store for {@link forwardConverted} — the boot's one conversion. */
private bootConversion?: ArtifactForwardConversionResult<any>;
/** When true, init/start become no-ops — env has no app payload. */
private readonly empty: boolean = false;
/**
* Suppress the inline boot seed (#3917). One-shot schema commands
* (`os migrate plan` / `os migrate apply`) boot the full plugin set purely
* to read metadata, and a boot that writes demo rows into the operator's
* live database before they have confirmed anything is the same class of
* bug as boot-time DDL. The `seed-replayer` service is still registered —
* it only writes when something calls it.
*/
private readonly skipSeedData: boolean;
/**
* Do not execute the bundle's `onEnable` (#21054) — the same one-shot
* schema commands as {@link skipSeedData}, for the same reason one step
* further. `os migrate plan` / `apply` compose this app for what it
* DECLARES; `onEnable` is the app's imperative code, and what it does —
* register handlers, drivers and lifecycle hooks, read and write data —
* belongs to a served boot. Measured on `examples/app-crm`: its `onEnable`
* hooks `kernel:bootstrapped` and reads `sys_position` /
* `sys_permission_set`, tables the plan's composition never declares, so
* every plan printed six `DATABASE_ERROR` lines.
*
* Read HERE, by the executor, rather than arranged by stripping the member
* off a copy of the bundle: this method alone resolves which object owns
* the hook (`bundle.default` before the bundle itself), a stripped copy
* would re-state that rule at the call site, and the boot would then log
* "No runtime.onEnable function found" about an app that has one.
*/
private readonly skipOnEnable: boolean;
/** Set by `start()` when {@link skipOnEnable} withheld an `onEnable` the bundle carries. */
private onEnableWithheldFlag = false;
/**
* See {@link AppPluginSecurityMetadataRegistrar}. Public and readonly so a
* composition test can pin which registrar a boot shape declared.
*/
readonly securityMetadataRegistrar: AppPluginSecurityMetadataRegistrar;
/**
* `this.bundle` with every package-owned collection resolved across BOTH
* artifact shapes — the flattened top level and `packages[]` (ADR-0130 D4 /
* option B, #15005; the resolution itself is `resolveArtifactCollections`
* in `./artifact-collections.ts`, package-private because every call site
* it has today ships in this package).
*
* ⛔ Read COLLECTIONS through this, never `this.bundle` — `this.bundle` is
* what the caller handed us and, on a multi-package option-B artifact, its
* `objects` / `jobs` / `data` / `translations` / `datasources` /
* `datasourceMapping` / `permissions` / `positions` are simply ABSENT while
* `packages[]` carries every one of them. Nothing throws on that path: the
* subsystem is handed an empty list and the app boots having lost the
* collection (#15004 measured 24 such subsystems).
*
* ENVELOPE keys stay on `this.bundle`, and the two are the same object
* whenever the bundle carries no `packages[]` — which is every
* single-package artifact and every `defineStack()` config — so this
* accessor cannot move the shape that ships today.
*
* Lazy so construction stays free of the ADR-0112 refusal a malformed
* `packages[]` raises: that refusal belongs to the boot, where the
* `manifest` service already raises it on the same bytes, not to `new
* AppPlugin(...)`.
*/
private get collections(): any {
return (this.resolvedCollections ??= resolveArtifactCollections(this.bundle));
}
/**
* [#22994] The ONE ADR-0087 forward conversion this boot runs over its
* definition, and the copy every reader in this plugin takes:
*
* - the `manifest` service's decomposition in `init()` (so the ObjectQL
* registry, which `GET /meta/<type>` lists and every reader of the
* flattened list — the email loader among them — reads as its code
* layer);
* - the security registrar in `start()`;
* - job scheduling (`scheduleAppArtifactJobs`, #23029);
* - the datasource readers, through {@link convertedCollection} (#23029):
* the code-defined registration and its owners, the reserved-name
* check and `connectDeclared`'s input;
* - the declared `apis` endpoints ({@link registerDeclaredApiEndpoints});
* - the hook binder (`bindAppArtifactHandlers`, #23090);
* - `loadTranslations` (#23090): the stack's own list through
* {@link convertedCollection}, a lifted `manifest.translations` list
* off the copy.
*
* The input is `{ ...manifest, ...collections }`, the definition the
* security block has converted since #12844, and for a bundle carrying no
* `packages[]` it is byte for byte the payload `init()` has always
* registered. So every reader above reads one conversion of one input,
* and none of them converts again. The door's
* own policy function decides the window, as at the artifact door: the
* same bytes, the same verdict.
*
* Only the converted copy goes forward. Which SOURCE a collection came
* from (the manifest or the stack, #18034) is still decided on the RAW
* inputs, at the security block, because the conversion can rewrite a
* collection KEY (`roles` -> `positions`).
*
* Memoized on first read. `init()` reads it only when the bundle carries
* no `packages[]`: resolving that list belongs to the `manifest` service's
* `register()` (#15292), and `collections` would resolve it here.
*
* `debug`, not `info`: on an artifact boot the door prints its own deduped
* operator summary for these bytes, and the notice is a fact about the
* authored floor, not a degradation.
*/
private forwardConverted(ctx: PluginContext): ArtifactForwardConversionResult<any> {
if (this.bootConversion === undefined) {
const collections = this.collections;
const manifest: any = collections?.manifest;
const conversion = applyArtifactForwardConversions(manifest ? { ...manifest, ...collections } : collections);
this.bootConversion = conversion;
if (conversion.notices.length > 0) {
ctx.logger.debug('[AppPlugin] applied ADR-0087 forward conversion to the stack definition', {
pluginName: this.name,
verdict: conversion.verdict,
authoredFloor: conversion.authoredFloor,
runtimeSpecVersion: conversion.runtimeSpecVersion,
notices: conversion.notices.length,
});
}
}
return this.bootConversion;
}
/**
* [#23029] One COLLECTION of the boot's converted copy
* ({@link forwardConverted}), for the datasource readers that used to read
* it off the RAW {@link collections}: the code-defined registration and its
* owners, the reserved-name check and `connectDeclared`'s input. A turso
* `config.timeout` or a memory `config.persistence.autoSaveInterval`
* authored by 17.x tooling is renamed by the conversion; read raw, the
* driver found no `*Ms` key and fell back to its default with no notice.
* [#23090] `loadTranslations` reads the stack's own `translations` through
* it too. (Job scheduling and the hook binder take the whole copy: see
* `start()`.)
*
* WHICH source the collection comes from is still decided on the raw
* inputs, as the security block decides it (#18034). The converted copy is
* `{ ...manifest, ...collections }`, so where the stack declares no such
* collection it would hand over the MANIFEST's key of that name — for
* `datasources` and `objects` the glob-pattern lists `ManifestSchema`
* declares, which these readers have never read. Where the stack declares
* it, the stack wins the spread, so the value is the stack's own, converted.
*/
private convertedCollection(ctx: PluginContext, key: 'datasources' | 'objects' | 'translations'): any {
if ((this.collections as Record<string, unknown> | null | undefined)?.[key] === undefined) return undefined;
return this.forwardConverted(ctx).definition?.[key];
}
/**
* The enforcer this artifact's consent records were registered on, or
* `undefined` when the artifact declared no `grantedPermissions` key.
*
* ⛔ `undefined` here means "no consent record for this environment", NEVER
* "denied": a caller that reads `undefined` as a deny bricks every boot
* shape that ships today (clause 1.3). The three states this distinguishes
* are written out on `registerArtifactGrantedPermissions`.
*/
get permissionEnforcer(): PluginPermissionEnforcer | undefined {
return this.grantEnforcer;
}
/**
* What the artifact's `grantedPermissions` map bound to on this boot —
* `undefined` when the key was absent. Public so a composition pin can read
* the binding without re-deriving it, and so a caller can tell a declared
* empty map (`declared: true`, nothing registered) from an absent one.
*/
get grantBinding(): ArtifactGrantBinding | undefined {
return this.grantBindingResult;
}
/**
* `true` once `start()` found an `onEnable` on this bundle and did NOT run
* it, because the composition passed `skipOnEnable` (#21054). `false` on
* every boot that runs it and on a bundle that carries none — so a caller
* reporting what its boot withheld names only what was really there.
*/
get onEnableWithheld(): boolean {
return this.onEnableWithheldFlag;
}
constructor(
bundle: any,
projectContext?: AppPluginProjectContext,
opts: {
skipSeedData?: boolean;
skipOnEnable?: boolean;
securityMetadataRegistrar?: AppPluginSecurityMetadataRegistrar;
} = {},
) {
this.bundle = bundle;
this.projectContext = projectContext;
this.skipSeedData = opts.skipSeedData ?? false;
this.skipOnEnable = opts.skipOnEnable ?? false;
// Refused loudly rather than defaulted: a misspelt registrar would
// otherwise fall through to whichever branch the typo happened to
// miss, and both branches are silent about what they did not do.
const registrar = opts.securityMetadataRegistrar ?? 'app-plugin';
if (registrar !== 'app-plugin' && registrar !== 'artifact-door') {
throw new Error(
`[AppPlugin] securityMetadataRegistrar '${String(registrar)}' is not one of `
+ `'app-plugin' | 'artifact-door'`,
);
}
this.securityMetadataRegistrar = registrar;
// Support both direct manifest (legacy) and Stack Definition (nested manifest)
const sys = bundle?.manifest || bundle;
const appId = sys?.id || sys?.name;
if (!appId) {
// No app id at all. Two scenarios:
// (a) Empty environment — the artifact only ships the bootstrap
// envelope ({ manifest: { plugins, drivers, engines }, functions: [] })
// with no app categories. We must NOT crash kernel boot
// here, otherwise every brand-new env returns 500.
// (b) Malformed envelope where an app payload exists but the
// caller forgot to pass `manifest`. We throw loudly with
// diagnostics so the bug surfaces immediately.
// App-category keys that indicate "this bundle was supposed to
// register an app". `manifest`/`functions` are envelope-level
// wrappers and don't count.
const APP_CATEGORY_KEYS = [
'objects', 'views', 'apps', 'pages', 'dashboards', 'reports',
'flows', 'workflows', 'triggers', 'agents', 'tools', 'skills',
'actions', 'permissions', 'positions', 'translations',
'sharingRules', 'ragPipelines', 'data', 'emailTemplates',
'docs', 'books',
];
const hasAppPayload = APP_CATEGORY_KEYS.some((k) => {
const v = (bundle && bundle[k]) ?? (sys && sys[k]);
return Array.isArray(v) && v.length > 0;
});
if (!hasAppPayload) {
// Empty env — degrade to a no-op plugin so kernel boot
// succeeds. Auth / data routes will still work; there's
// simply nothing to register. No manifest is registered on
// this path, so the init-service requirement is dropped —
// empty envs boot on kernels with no engine at all.
this.empty = true;
this.requiresServices = [];
const envSlug = projectContext?.environmentId
? projectContext.environmentId.slice(0, 8)
: 'empty';
this.name = `plugin.app.empty-${envSlug}`;
return;
}
// Has app payload but no id — genuine malformed envelope.
const bundleKeys = bundle && typeof bundle === 'object'
? Object.keys(bundle).slice(0, 20).join(',')
: typeof bundle;
const sysKeys = sys && typeof sys === 'object'
? Object.keys(sys).slice(0, 20).join(',')
: typeof sys;
const ctxHint = projectContext
? ` projectContext=${JSON.stringify({
environmentId: projectContext.environmentId,
packageId: projectContext.packageId,
source: projectContext.source,
})}`
: '';
throw new Error(
`[AppPlugin] bundle has app payload but no manifest.id / manifest.name — `
+ `cannot register as a plugin. bundleKeys=[${bundleKeys}] `
+ `sysKeys=[${sysKeys}]${ctxHint}`,
);
}
this.name = `plugin.app.${appId}`;
this.version = sys?.version;
}
init = async (ctx: PluginContext) => {
// [#10772] Retained for `destroy()`, which the kernel calls with no
// context. Assigned before anything that can throw, and before the
// empty-env early return, so teardown is armed on every path init
// takes.
this.initCtx = ctx;
// Bind the install-time GRANTED permission set (ADR-0025 F4, #13457)
// BEFORE anything this plugin registers on the kernel. This is the
// materialize-time moment the artifact contract names as the consumer
// of `EnvironmentArtifactSchema.grantedPermissions`, and it runs ahead
// of the empty-env return on purpose: a consent record that binds to
// nothing has to be heard on an empty environment too, which is exactly
// where an artifact carrying grants for packages it does not ship shows
// up. A no-op — not even an allocation — on every artifact that carries
// no `grantedPermissions` key.
this.bindGrantedPermissions(ctx);
// Install the engine-wide default hook body runner FIRST — even for
// empty envs (an empty env is exactly where a user will author their
// first Studio hook). Runs in init (Phase 1) so it is in place before
// ObjectQLPlugin.start binds metadata-service hooks in Phase 2 (#2588).
this.installDefaultHookBodyRunner(ctx);
// Same for the action runner — authored actions register in Phase 2's
// authored-action re-sync and need the sandbox bridge in place (#2605).
this.installDefaultActionBodyRunner(ctx);
// Feed per-hook execution time into the request-scoped perf collector
// so the `Server-Timing` header can split "hook time" from "DB time".
// Same boot point as the runners so it is in place before Phase 2 binds
// metadata-service hooks; a no-op unless perf-tuning is on.
this.installHookMetricsTiming(ctx);
// Wire the authored-translation sync (#2591) — also BEFORE the empty-env
// return: an empty env is exactly where a user authors their first
// Studio translation. Covers whatever `i18n` service this kernel ends
// up with (the core in-memory fallback included); idempotent across
// multiple wirers via the ownership marker in core.
wireAuthoredTranslationSync(ctx as any);
// Seed persisted package disable-state — also BEFORE the empty-env
// return (#5047). An empty env is EXACTLY the hydration-only scenario:
// the artifact ships no app payload, so every package in that
// environment arrives later from `sys_packages` (PackageServicePlugin's
// Phase 2 rehydrate) or from an HTTP install. Seeding after the return
// meant the registry's initial-disabled set stayed empty on those
// envs, and a package an operator had disabled came back ENABLED on
// every restart. The seed must land before ANY registration path runs,
// which is Phase 1, unconditionally.
this.seedPersistedDisabledPackages(ctx);
if (this.empty) {
ctx.logger.debug('[AppPlugin] empty env — no app payload, skipping init', {
pluginName: this.name,
});
return;
}
const sys = this.bundle.manifest || this.bundle;
const appId = sys.id || sys.name;
// ADR-0087 D1 — protocol handshake on the code-defined-stack LOAD seam,
// BEFORE the manifest is decomposed into the registry. A bundle whose
// declared `engines.protocol` excludes this runtime's major fails boot
// fast with the structured OS_PROTOCOL_INCOMPATIBLE diagnostic (naming
// the `migrate meta` command) instead of crashing later in a schema
// `.parse()` or renderer contract. Absent/unparsable ranges are admitted
// with a warning (grandfathering; never a false rejection).
assertProtocolCompat(sys, undefined, (m) => ctx.logger.warn(`[AppPlugin] ${m}`));
ctx.logger.info('Registering App Service', {
appId,
pluginName: this.name,
version: this.version
});
// Register the app manifest directly via the manifest service.
// This immediately decomposes the manifest into SchemaRegistry entries.
//
// [#22994] The CONVERTED copy, AFTER the handshake above (ADR-0087 D1
// before D2), and the same conversion the security block in `start()`
// registers from — see `forwardConverted`. Registering the raw bundle
// here is what made `GET /meta/<type>` list an item with its retired
// key (`_diagnostics.valid: false`) while `GET /meta/<type>/NAME`
// served the artifact door's converted copy of it, and what handed the
// email loader a template it refuses to send.
//
// A bundle carrying `packages[]` is handed over as it arrived, as before:
// `forwardConverted` would resolve `packages[]` here, ahead of the
// `manifest` service (#15292). Its package BODIES are already converted
// when the bundle came through `loadArtifactBundle`, which runs the
// ADR-0087 pass once over every body at load (#23027); a bundle handed
// to this plugin by any other route reaches the `manifest` service as
// authored.
const servicePayload = (this.bundle as { packages?: unknown }).packages === undefined
? this.forwardConverted(ctx).definition
: this.bundle.manifest
? { ...this.bundle.manifest, ...this.bundle }
: this.bundle;
ctx.getService<{ register(m: any): void }>('manifest').register(servicePayload);
// [#21922] The datasources this artifact registers from code join the
// host's code-datasource set HERE, in Phase 1, so the datasource-admin
// plugin's boot restore — a `start()` — never registers a stored row
// over one of them, whatever order the plugins were composed in. The
// in-memory registration itself stays in `start()` (see there).
//
// Contributed as a FUNCTION the set resolves at its first read, never
// resolved here: the names come from `collections`, which walks
// `packages[]`, and the manifest registration above is the one thing
// in `init()` allowed to touch `packages[]` (#15292's falsifier in
// `plugin-dev` pins it). `CodeDatasourceNames` says the rest.
contributeCodeDatasourceNames(ctx, () => this.codeDefinedDatasourceOwners(ctx)
.map(({ datasource }) => datasource?.name)
.filter((name): name is string => typeof name === 'string' && name.length > 0));
// [#23649] The stack's `datasourceMapping` governs the engine from its
// FIRST schema sync — see `honourDatasourceMappingBeforeSchemaSync`.
// Subscribed here and resolved there: the rules come from `collections`,
// which walks `packages[]`, and the registration above is the one thing
// in `init()` allowed to touch that list. A context with no hook bus (a
// mock) leaves `start()` to install the rules.
if (typeof (ctx as { hook?: unknown }).hook === 'function') {
ctx.hook(OBJECTQL_DRIVERS_READY_HOOK, (engine: unknown) =>
this.honourDatasourceMappingBeforeSchemaSync(ctx, engine as IObjectQLEngine, appId));
}
}
/**
* Register the install-time GRANTED permission set this artifact carries,
* one entry per consent-bearing package, on an enforcer this plugin owns
* (ADR-0025 F4 / #13457 — the consumer half of
* `EnvironmentArtifactSchema.grantedPermissions`).
*
* The whole method is behind the `=== undefined` gate below, and that gate
* is the clause-1.3 guarantee in code: an artifact with no consent record
* takes no branch, allocates no enforcer and registers nothing, so ABSENT
* can never become "denied". `{}` is not absent and does not take the early
* return — a declared-but-empty map is a consent record that names no
* package, which is a different reading and is recorded as one.
*
* ⛔ Never `??`/`||` on `grantedPermissions`: both spellings turn a declared
* `{}` into absence and erase a distinction the producer pins both ways.
*/
private bindGrantedPermissions(ctx: PluginContext): void {
if ((this.bundle as { grantedPermissions?: unknown } | null | undefined)?.grantedPermissions === undefined) {
return;
}
const enforcer = createPluginPermissionEnforcer(ctx.logger);
const binding = registerArtifactGrantedPermissions(this.bundle, enforcer, { logger: ctx.logger });
this.grantEnforcer = enforcer;
this.grantBindingResult = binding;
ctx.logger.info('[AppPlugin] registered install-time granted permissions', {
pluginName: this.name,
registered: [...binding.registered],
unregistered: [...binding.unregistered],
unbound: [...binding.unbound],
});
}
/**
* Seed persisted package disable-state into the registry's initial-disabled
* set, so every later registration path — boot artifact decomposition,
* marketplace / `sys_packages` rehydrate, local import — installs those
* packages DISABLED and they stay hidden after a restart.
*
* Runs in init (Phase 1) and BEFORE the empty-env return (#5047), for the
* same reason the runners above do: the seed only works if it is in place
* before the FIRST `installPackage` call, and on an empty env every
* package arrives from Phase 2 hydration rather than from this bundle.
* On a non-empty env it still lands before the manifest is decomposed,
* because that decomposition happens at the `manifest.register()` call at
* the end of init.
*
* Best-effort — never block boot on this. Degrades silently on kernels
* with no engine (metadata-only one-shot commands, mock-engine tests).
*/
private seedPersistedDisabledPackages(ctx: PluginContext): void {
try {
const ql = ctx.getService<{ registry?: { setInitialDisabledPackageIds?: (ids: Iterable<string>) => void } }>('objectql');
const setter = ql?.registry?.setInitialDisabledPackageIds;
if (typeof setter === 'function') {
const disabled = loadDisabledPackageIds(this.projectContext?.environmentId);
if (disabled.size > 0) {
setter.call(ql!.registry, disabled);
ctx.logger.info('[AppPlugin] seeded persisted disabled packages', {
environmentId: this.projectContext?.environmentId,
disabled: Array.from(disabled),
});
}
}
} catch (err) {
ctx.logger.warn('[AppPlugin] failed to seed persisted package state', {
error: (err as Error)?.message ?? String(err),
});
}
}
/**
* Install the engine's DEFAULT hook body runner (`engine.setDefaultBodyRunner`).
*
* Hooks authored at runtime (Studio → `protocol.saveMetaItem` → publish)
* bind through paths that pass no explicit `bodyRunner` — notably
* ObjectQLPlugin's metadata-service bind — so without this default their
* L1/L2 `body` is silently dropped by `bindHooksToEngine` and the hook
* never runs (#2588). The runtime owns the sandbox bridge (objectql stays
* sandbox-free), so this is the boot point that wires it: same
* QuickJS-sandboxed, capability-gated runner the `defineStack({ hooks })`
* bind already uses.
*
* `OS_DISABLE_AUTHORED_HOOKS=1` opts out for deployments that want
* runtime-authored (DB-stored, non-code-reviewed) hook bodies to stay
* inert; code-shipped hooks are unaffected (AppPlugin passes its own
* runner explicitly).
*
* Idempotent: the first AppPlugin to run installs it; the runner is
* bundle-agnostic (it only closes over the engine + logger).
*/
private installDefaultHookBodyRunner(ctx: PluginContext): void {
if (process.env.OS_DISABLE_AUTHORED_HOOKS === '1') {
ctx.logger.info('[AppPlugin] OS_DISABLE_AUTHORED_HOOKS=1 — runtime-authored hook bodies will not execute');
return;
}
let ql: IObjectQLEngine | undefined;
try {
ql = ctx.getService<IObjectQLEngine>('objectql');
} catch {
return; // no engine on this kernel — nothing to wire
}
if (!ql || typeof ql.setDefaultBodyRunner !== 'function') return;
// [#4251] The setter is first-wins — the engine keeps the first runner
// when several AppPlugins share one kernel; this caller no longer
// probes the engine's private `_defaultBodyRunner` field to find out.
const installed = ql.setDefaultBodyRunner(hookBodyRunnerFactory(new QuickJSScriptRunner(), {
ql,
logger: ctx.logger,
appId: 'runtime-authored',
}));
if (installed !== false) {
ctx.logger.info('[AppPlugin] Installed default hook body runner (runtime-authored hooks can execute)');
}
}
/**
* Install the engine's DEFAULT action body runner (`engine.setDefaultActionRunner`).
*
* The exact action-path parallel of {@link installDefaultHookBodyRunner}
* (#2605 item 1): actions authored at runtime (Studio → `action` metadata →
* publish) are registered by ObjectQLPlugin's authored-action re-sync,
* which lives in `objectql` and therefore has no sandbox of its own. This
* boot point hands it the same QuickJS-sandboxed runner that
* `defineStack({ actions })` bundles already execute through, so an
* authored `body` becomes a real `executeAction` handler instead of a
* silent "Action not found".
*
* `OS_DISABLE_AUTHORED_ACTIONS=1` opts out for deployments that want
* runtime-authored (DB-stored, non-code-reviewed) action bodies to stay
* inert; code-shipped actions are unaffected (AppPlugin registers those
* itself with its own runner).
*/
private installDefaultActionBodyRunner(ctx: PluginContext): void {
if (process.env.OS_DISABLE_AUTHORED_ACTIONS === '1') {
ctx.logger.info('[AppPlugin] OS_DISABLE_AUTHORED_ACTIONS=1 — runtime-authored action bodies will not execute');
return;
}
let ql: IObjectQLEngine | undefined;
try {
ql = ctx.getService<IObjectQLEngine>('objectql');
} catch {
return; // no engine on this kernel — nothing to wire
}
if (!ql || typeof ql.setDefaultActionRunner !== 'function') return;
// [#4251] First-wins setter — same as the hook body runner above.
const installed = ql.setDefaultActionRunner(actionBodyRunnerFactory(new QuickJSScriptRunner(), {
ql,
logger: ctx.logger,
appId: 'runtime-authored',
}));
if (installed !== false) {
ctx.logger.info('[AppPlugin] Installed default action body runner (runtime-authored actions can execute)');
}
}
/**
* Install an engine-wide {@link HookMetricsRecorder} that folds every
* hook's execution time into the request-scoped `Server-Timing` collector
* (the `hooks;dur=…;desc="N hooks"` span). This is the framework's ONLY
* caller of `setHookMetricsRecorder`, so it owns the engine's recorder;
* objectql stays observability-free (the lean `core` tier, ADR-0076) — the
* timing lives here in the runtime, which already depends on it.
*
* `countServerTiming` is a no-op unless a request opened a perf collector
* (perf-tuning mode), so this costs nothing when the feature is off. It
* composes with any recorder a host wired earlier (chains to it), and is
* idempotent across the multiple AppPlugins a multi-app env installs.
*/
private installHookMetricsTiming(ctx: PluginContext): void {
let ql: IObjectQLEngine | undefined;
try {
ql = ctx.getService<IObjectQLEngine>('objectql');
} catch {
return; // no engine on this kernel — nothing to wire
}
if (!ql || typeof ql.setHookMetricsRecorder !== 'function') return;
const existing = typeof ql.getHookMetricsRecorder === 'function'
? ql.getHookMetricsRecorder()
: undefined;
if (existing?.__perfTimingFeed) return; // already installed by a sibling AppPlugin
ql.setHookMetricsRecorder({
__perfTimingFeed: true,
recordExecution(label: any, outcome: any, durationMs: number) {
try { existing?.recordExecution?.(label, outcome, durationMs); } catch { /* keep timing isolated */ }
countServerTiming('hooks', durationMs, 'hooks');
},
recordSkip(label: any, reason: any) {
try { existing?.recordSkip?.(label, reason); } catch { /* noop */ }
},
recordRetry(label: any, attempt: number) {
try { existing?.recordRetry?.(label, attempt); } catch { /* noop */ }
},
});
ctx.logger.debug('[AppPlugin] Installed hook-metrics Server-Timing feed');
}
/**
* Hand the stack's `datasourceMapping` rules to the engine — the one
* install site, called at most once per boot. Answers whether there were
* rules to install.
*/
private installDatasourceMapping(ctx: PluginContext, ql: IObjectQLEngine, appId: string): boolean {
this.datasourceMappingInstalled = true;
const datasourceMapping = this.collections.datasourceMapping;
if (!Array.isArray(datasourceMapping)) return false;
ctx.logger.info('Configuring datasource mapping rules', {
appId,
ruleCount: datasourceMapping.length,
});
ql.setDatasourceMapping(datasourceMapping);
return datasourceMapping.length > 0;
}
/**
* [#23649] Make the stack's `datasourceMapping` govern the engine from its
* FIRST schema sync. Runs inside `ObjectQLPlugin.start()`, on
* `OBJECTQL_DRIVERS_READY_HOOK`: the boot's drivers are adopted and
* connected, and nothing has been synced, hydrated, read or written yet.
*
* Two steps, in this order:
*
* 1. install the rules ({@link installDatasourceMapping});
* 2. connect every declared datasource they route an ALREADY-REGISTERED
* object to — platform objects included — through the same
* `connectDeclared` `start()` calls (ADR-0062 D2 (d): "a datasource a
* mapping rule routes at least one registered object to is
* auto-connected at boot", fail-fast on a `declared-auto` failure). The
* connect also syncs those objects' schemas onto the datasource, and the
* engine plugin's own sync that follows finds them there.
*
* Before this, the rules were installed in `start()`, after the engine
* plugin's schema sync and after the auth plugin's Default Organization
* had both used the default store, and step 2 counted this app's own
* objects only. A `{ default: true, datasource: 'primary' }` rule then
* re-routed every platform object to a `primary` whose schema never
* synced: the server reported ready while the URL store held the platform
* tables and the Default Organization, and `primary` answered "no such
* table". A rule routing platform objects to a datasource nothing else
* addressed (`objectPattern: 'sys_*'`) left it never connected at all.
*
* Which objects a rule matches is the ENGINE's answer
* ({@link resolveMappedObjects}), over the same registry the sync reads.
* Objects registered after this moment are routed by the installed rules
* as they arrive; `start()` connects for them as it always has. A
* datasource no rule routes a registered object to is left to `start()`,
* which connects it by its other D2 reasons at the moment it always did.
*
* Connecting HERE, after the engine adopted its `driver.*` services, keeps
* the default driver what it was: the engine makes its first registered
* driver the default, so a mapped datasource connected earlier (in
* `init()`) would take that slot from a stack plugin's driver.
*/
private async honourDatasourceMappingBeforeSchemaSync(
ctx: PluginContext,
ql: IObjectQLEngine,
appId: string,
): Promise<void> {
if (this.datasourceMappingInstalled) return;
if (!this.installDatasourceMapping(ctx, ql, appId)) return;
const dsDefs = this.convertedCollection(ctx, 'datasources');
const dsList: any[] = Array.isArray(dsDefs)
? dsDefs
: dsDefs && typeof dsDefs === 'object'
? Object.entries(dsDefs).map(([name, def]) => ({ name, ...(def as any) }))
: [];
if (dsList.length === 0) return;
// Absent on a runtime without the datasource-admin plugin: declared
// datasources stay metadata-only there, and `start()` says so.
let connection:
| {
connectDeclared?: (input: {
datasources: any[];
objects?: Array<{ name?: string; datasource?: string }>;
mappedObjects?: Record<string, string[]>;
}) => Promise<Array<{ name: string; status: string }>>;
}
| undefined;
try {
connection = ctx.getService('datasource-connection');
} catch {
connection = undefined;
}
if (typeof connection?.connectDeclared !== 'function') return;
const registered = ql.registry.getAllObjects() as Array<{ name?: string; datasource?: string }>;
const mappedObjects = this.resolveMappedObjects(ql, registered);
const routedTo = dsList.filter(
(ds) => typeof ds?.name === 'string' && (mappedObjects[ds.name]?.length ?? 0) > 0,
);
if (routedTo.length === 0) return;
const declaredObjects = this.convertedCollection(ctx, 'objects');
try {
const results = await connection.connectDeclared({
datasources: routedTo,
objects: Array.isArray(declaredObjects) ? declaredObjects : [],
mappedObjects,
});
const connected = results.filter((r) => r.status === 'connected');
if (connected.length > 0) {
ctx.logger.info('Auto-connected declared datasources', {
appId,
connected: connected.map((r) => r.name),
before: 'schema sync',
});
}
} catch (err) {
// Same verdict and the same line as `start()`'s connect: a
// datasource a mapping routes objects to has no fallback store.
ctx.logger.error(
`[AppPlugin] declared-datasource auto-connect failed for app '${appId}': ${(err as Error)?.message ?? String(err)}`,
);
throw err;
}
}
/**
* Datasource name → the objects a `datasourceMapping` rule routes to it
* (#4462), asked of the ENGINE rather than re-derived here.
*
* The gate this feeds (`isDatasourceAddressed` (d)) and the routing that
* makes it correct (`ObjectQLEngine.getDriver` step 2) must agree exactly
* about which rules match which objects. A second matcher living in this
* plugin — or in the connection service — would drift by one clause and
* produce either a datasource connected that routing never uses, or one
* routed to and never connected, which is the defect itself.
*
* Objects with an EXPLICIT `object.datasource` binding are excluded: that
* binding outranks mapping in `getDriver`, so counting them here would let
* a mapping rule they never obey force a fail-fast on their behalf.
* `default` is excluded for the same reason `getDriver` lets it through —
* the host's default driver is registered under its natural name and needs
* no per-app connect.
*/
private resolveMappedObjects(
ql: IObjectQLEngine,
objects: Array<{ name?: string; datasource?: string }>,
): Record<string, string[]> {
const resolve = (ql as unknown as {
resolveMappedDatasource?: (objectName: string) => string | null;
}).resolveMappedDatasource;
if (typeof resolve !== 'function') return {};
const out: Record<string, string[]> = {};
for (const obj of objects) {
const name = obj?.name;
if (typeof name !== 'string' || !name) continue;
if (obj.datasource && obj.datasource !== 'default') continue;
let mapped: string | null = null;
try {
mapped = resolve.call(ql, name);
} catch {
continue; // a resolver that throws must not brick boot
}
if (!mapped || mapped === 'default') continue;
(out[mapped] ??= []).push(name);
}
return out;
}
/**
* Every code-defined datasource this artifact declares, each paired with
* the coordinates of the package that declares it — what `start()` hands
* `applyProtection` when it registers the datasource.
*
* [#21889] The federation service reads those coordinates back: its
* `getNamespace` (`@objectstack/service-datasource`) takes the datasource's
* `_packageId` to the engine registry's package record, whose
* `manifest.namespace` is the ADR-0028 prefix an object imported over the
* datasource must carry. Registered without coordinates, a code-defined
* datasource resolved no namespace: the import accepted an unprefixed
* name and the draft emitted one.
*
* The owner is read the way the metadata plugin's artifact door reads it
* (ADR-0130 D4, `packages/metadata/src/plugin.ts`), and for its reasons:
*
* - `packages` ABSENT: the artifact is its one package's body, so every
* datasource takes the manifest's id, the key `registerApp` installs the
* package under. The list is the stack's `datasources` (D7), read off
* the boot's converted copy ({@link convertedCollection}, #23029).
* - `packages` PRESENT: each body's datasources take THAT body's id
* (`artifactPackageId`, the one spelling `registerApp` keys on), in the
* order `resolveArtifactPackageOrder` gives, over the converted copy's
* bodies (#23029: the conversion replays every body). ⛔ Never the artifact's
* top-level manifest id on every entry: on a composed artifact that id
* is one member's, and stamping it everywhere hands one package another
* package's datasources (#14599). ⛔ Never a name-to-package index over
* the flattened list either: that is a second resolution path for
* ownership, and a dangling one fails silently.
* - A datasource no body declares (an artifact composed from a stack that
* already carried `packages` and one that did not) falls back to the
* artifact's own manifest id, as the door's residual sweep does, and is
* logged, because the artifact's two halves disagree.
*/
private codeDefinedDatasourceOwners(ctx: PluginContext): Array<{
datasource: any;