@objectstack/plugin-trigger-record-change 7.4.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute
108
+ must include a readable copy of the attribution notices
109
+ contained within such NOTICE file, excluding those notices
110
+ that do not pertain to any part of the Derivative Works,
111
+ in at least one of the following places: within a NOTICE
112
+ text file distributed as part of the Derivative Works; within
113
+ the Source form or documentation, if provided along with
114
+ the Derivative Works; or, within a display generated by the
115
+ Derivative Works, if and wherever such third-party notices
116
+ normally appear. The contents of the NOTICE file are for
117
+ informational purposes only and do not modify the License.
118
+ You may add Your own attribution notices within Derivative
119
+ Works that You distribute, alongside or as an addendum to
120
+ the NOTICE text from the Work, provided that such additional
121
+ attribution notices cannot be construed as modifying the
122
+ License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 ObjectStack
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/LICENSE.apache ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute
108
+ must include a readable copy of the attribution notices
109
+ contained within such NOTICE file, excluding those notices
110
+ that do not pertain to any part of the Derivative Works,
111
+ in at least one of the following places: within a NOTICE
112
+ text file distributed as part of the Derivative Works; within
113
+ the Source form or documentation, if provided along with
114
+ the Derivative Works; or, within a display generated by the
115
+ Derivative Works, if and wherever such third-party notices
116
+ normally appear. The contents of the NOTICE file are for
117
+ informational purposes only and do not modify the License.
118
+ You may add Your own attribution notices within Derivative
119
+ Works that You distribute, alongside or as an addendum to
120
+ the NOTICE text from the Work, provided that such additional
121
+ attribution notices cannot be construed as modifying the
122
+ License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 ObjectStack
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # @objectstack/plugin-trigger-record-change
2
+
3
+ Auto-launch ObjectStack flows on record changes.
4
+
5
+ The automation engine ships the `FlowTrigger` extension point and the wiring
6
+ that turns a flow's `start` node into a normalized trigger binding — but the
7
+ *concrete* record-change trigger lives here, as a plugin. This mirrors the
8
+ connector split (engine baseline + `connector-rest` plugin) and reuses the same
9
+ `kernel:ready` → `getService('objectql')` pattern `plugin-audit` uses to reach
10
+ the data engine's lifecycle-hook surface.
11
+
12
+ ## What it does
13
+
14
+ A flow whose `start` node declares a record-change trigger:
15
+
16
+ ```ts
17
+ {
18
+ type: 'start',
19
+ config: {
20
+ objectName: 'showcase_task',
21
+ triggerType: 'record-after-update',
22
+ condition: "status == 'done' && previous.status != 'done'", // optional
23
+ },
24
+ }
25
+ ```
26
+
27
+ auto-launches whenever a matching mutation happens — no manual
28
+ `engine.execute()`. The engine evaluates the optional `condition` (the start
29
+ node gate) before running the flow, with `record` (the new row) and `previous`
30
+ (the old row) in scope.
31
+
32
+ ### Trigger event → hook mapping
33
+
34
+ | `triggerType` | ObjectQL hook |
35
+ | ------------------------ | -------------- |
36
+ | `record-after-create` | `afterInsert` |
37
+ | `record-after-update` | `afterUpdate` |
38
+ | `record-after-delete` | `afterDelete` |
39
+ | `record-before-create` | `beforeInsert` |
40
+ | `record-before-update` | `beforeUpdate` |
41
+ | `record-before-delete` | `beforeDelete` |
42
+
43
+ ## Usage
44
+
45
+ ```ts
46
+ import { AutomationServicePlugin } from '@objectstack/service-automation';
47
+ import { MessagingServicePlugin } from '@objectstack/service-messaging';
48
+ import { RecordChangeTriggerPlugin } from '@objectstack/plugin-trigger-record-change';
49
+
50
+ kernel
51
+ .use(new AutomationServicePlugin()) // engine + flows
52
+ .use(new MessagingServicePlugin()) // notify channels (optional)
53
+ .use(new RecordChangeTriggerPlugin()); // ← makes record-change flows live
54
+ ```
55
+
56
+ Requires the ObjectQL engine (`com.objectstack.engine.objectql`). If either the
57
+ automation service or the data engine is unavailable at `kernel:ready`, the
58
+ plugin logs a warning and no-ops rather than failing startup.
59
+
60
+ ## Error isolation
61
+
62
+ A flow that throws during a triggered run is logged and swallowed — it never
63
+ breaks the CRUD write that triggered it.
@@ -0,0 +1,118 @@
1
+ import { Plugin, PluginContext } from '@objectstack/core';
2
+ import { AutomationContext } from '@objectstack/spec/contracts';
3
+ import { HookContext } from '@objectstack/spec/data';
4
+
5
+ /**
6
+ * RecordChangeTriggerPlugin
7
+ *
8
+ * Makes record-change-triggered flows actually fire. The automation engine
9
+ * ships the `FlowTrigger` wiring (it parses each flow's start node into a
10
+ * binding and calls `trigger.start(...)`), but the *concrete* record-change
11
+ * trigger — the one that subscribes to ObjectQL lifecycle hooks — lives here as
12
+ * a plugin. This mirrors the connector split (engine baseline + connector-rest
13
+ * plugin) and reuses plugin-audit's `kernel:ready` → `getService('objectql')`
14
+ * pattern to reach the data engine's hook surface.
15
+ *
16
+ * With this plugin installed, a flow whose start node declares
17
+ * `config: { objectName, triggerType: 'record-after-update', condition }`
18
+ * auto-launches on the matching mutation — no manual `engine.execute()`.
19
+ */
20
+ declare class RecordChangeTriggerPlugin implements Plugin {
21
+ name: string;
22
+ type: string;
23
+ version: string;
24
+ dependencies: string[];
25
+ init(ctx: PluginContext): Promise<void>;
26
+ start(ctx: PluginContext): Promise<void>;
27
+ private resolveService;
28
+ private resolveDataEngine;
29
+ }
30
+
31
+ /**
32
+ * Structural mirror of the automation engine's `FlowTriggerBinding`
33
+ * (service-automation/src/engine.ts). Declared locally so this trigger plugin
34
+ * stays decoupled from the automation package — same pattern the connector /
35
+ * messaging integrations use to avoid a hard build edge. The engine parses the
36
+ * flow's start node and hands us one of these per activated flow.
37
+ */
38
+ interface FlowTriggerBinding {
39
+ readonly flowName: string;
40
+ readonly object?: string;
41
+ readonly event?: string;
42
+ readonly condition?: string | {
43
+ dialect?: string;
44
+ source?: string;
45
+ ast?: unknown;
46
+ };
47
+ readonly schedule?: unknown;
48
+ readonly config?: Record<string, unknown>;
49
+ }
50
+ /**
51
+ * Structural mirror of the engine's `FlowTrigger` extension point. The engine
52
+ * calls {@link start} with a parsed binding + a callback that runs the flow,
53
+ * and {@link stop} when the flow is unregistered/disabled.
54
+ */
55
+ interface FlowTrigger {
56
+ readonly type: string;
57
+ start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void;
58
+ stop(flowName: string): void;
59
+ }
60
+ /**
61
+ * The slice of the ObjectQL data engine this trigger needs: subscribe to a
62
+ * lifecycle hook, and (for teardown) drop all hooks owned by a packageId.
63
+ * Typed structurally because `IDataEngine` (the public contract) doesn't model
64
+ * the hook surface, but the concrete engine implements both.
65
+ */
66
+ interface RecordChangeDataEngine {
67
+ registerHook(event: string, handler: (ctx: HookContext) => unknown | Promise<unknown>, options?: {
68
+ object?: string | string[];
69
+ priority?: number;
70
+ packageId?: string;
71
+ }): void;
72
+ unregisterHooksByPackage?(packageId: string): number;
73
+ }
74
+ /** Minimal logger surface (matches core's `ctx.logger`). */
75
+ interface TriggerLogger {
76
+ info(msg: string, ...args: unknown[]): void;
77
+ warn(msg: string, ...args: unknown[]): void;
78
+ debug?(msg: string, ...args: unknown[]): void;
79
+ }
80
+ /**
81
+ * Map a flow start node's `triggerType` (e.g. `record-after-update`) to an
82
+ * ObjectQL `HookEvent` (e.g. `afterUpdate`). Returns `null` for anything that
83
+ * isn't a `record-(before|after)-(create|insert|update|delete)` token.
84
+ */
85
+ declare function triggerTypeToHookEvent(triggerType: string | undefined): string | null;
86
+ /**
87
+ * RecordChangeTrigger
88
+ *
89
+ * Bridges the automation engine's {@link FlowTrigger} extension point to
90
+ * ObjectQL lifecycle hooks. For each flow the engine activates, it subscribes
91
+ * to the matching hook event (filtered to the flow's target object) and, when
92
+ * the hook fires, builds an {@link AutomationContext} from the new/old record
93
+ * and invokes the engine-supplied callback (which runs the flow — the engine
94
+ * owns the start-node condition gate, so we don't re-evaluate it here).
95
+ *
96
+ * Each flow's hooks are registered under a per-flow packageId so {@link stop}
97
+ * can tear exactly that flow's subscription down via
98
+ * `unregisterHooksByPackage`, without touching other flows or audit hooks.
99
+ */
100
+ declare class RecordChangeTrigger implements FlowTrigger {
101
+ readonly type = "record_change";
102
+ private readonly engine;
103
+ private readonly logger;
104
+ /** flowName → packageId used for its hook(s), so stop() can unregister it. */
105
+ private readonly bound;
106
+ constructor(engine: RecordChangeDataEngine, logger: TriggerLogger);
107
+ start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void;
108
+ stop(flowName: string): void;
109
+ /**
110
+ * Build the flow execution context from an ObjectQL hook context. The new
111
+ * record comes from `ctx.result` (after-hooks) or falls back to the
112
+ * mutation input doc / previous row; the old record from `ctx.previous`
113
+ * (with the `__previous` stash audit also uses as a fallback).
114
+ */
115
+ private buildContext;
116
+ }
117
+
118
+ export { type FlowTrigger, type FlowTriggerBinding, type RecordChangeDataEngine, RecordChangeTrigger, RecordChangeTriggerPlugin, type TriggerLogger, triggerTypeToHookEvent };
@@ -0,0 +1,118 @@
1
+ import { Plugin, PluginContext } from '@objectstack/core';
2
+ import { AutomationContext } from '@objectstack/spec/contracts';
3
+ import { HookContext } from '@objectstack/spec/data';
4
+
5
+ /**
6
+ * RecordChangeTriggerPlugin
7
+ *
8
+ * Makes record-change-triggered flows actually fire. The automation engine
9
+ * ships the `FlowTrigger` wiring (it parses each flow's start node into a
10
+ * binding and calls `trigger.start(...)`), but the *concrete* record-change
11
+ * trigger — the one that subscribes to ObjectQL lifecycle hooks — lives here as
12
+ * a plugin. This mirrors the connector split (engine baseline + connector-rest
13
+ * plugin) and reuses plugin-audit's `kernel:ready` → `getService('objectql')`
14
+ * pattern to reach the data engine's hook surface.
15
+ *
16
+ * With this plugin installed, a flow whose start node declares
17
+ * `config: { objectName, triggerType: 'record-after-update', condition }`
18
+ * auto-launches on the matching mutation — no manual `engine.execute()`.
19
+ */
20
+ declare class RecordChangeTriggerPlugin implements Plugin {
21
+ name: string;
22
+ type: string;
23
+ version: string;
24
+ dependencies: string[];
25
+ init(ctx: PluginContext): Promise<void>;
26
+ start(ctx: PluginContext): Promise<void>;
27
+ private resolveService;
28
+ private resolveDataEngine;
29
+ }
30
+
31
+ /**
32
+ * Structural mirror of the automation engine's `FlowTriggerBinding`
33
+ * (service-automation/src/engine.ts). Declared locally so this trigger plugin
34
+ * stays decoupled from the automation package — same pattern the connector /
35
+ * messaging integrations use to avoid a hard build edge. The engine parses the
36
+ * flow's start node and hands us one of these per activated flow.
37
+ */
38
+ interface FlowTriggerBinding {
39
+ readonly flowName: string;
40
+ readonly object?: string;
41
+ readonly event?: string;
42
+ readonly condition?: string | {
43
+ dialect?: string;
44
+ source?: string;
45
+ ast?: unknown;
46
+ };
47
+ readonly schedule?: unknown;
48
+ readonly config?: Record<string, unknown>;
49
+ }
50
+ /**
51
+ * Structural mirror of the engine's `FlowTrigger` extension point. The engine
52
+ * calls {@link start} with a parsed binding + a callback that runs the flow,
53
+ * and {@link stop} when the flow is unregistered/disabled.
54
+ */
55
+ interface FlowTrigger {
56
+ readonly type: string;
57
+ start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void;
58
+ stop(flowName: string): void;
59
+ }
60
+ /**
61
+ * The slice of the ObjectQL data engine this trigger needs: subscribe to a
62
+ * lifecycle hook, and (for teardown) drop all hooks owned by a packageId.
63
+ * Typed structurally because `IDataEngine` (the public contract) doesn't model
64
+ * the hook surface, but the concrete engine implements both.
65
+ */
66
+ interface RecordChangeDataEngine {
67
+ registerHook(event: string, handler: (ctx: HookContext) => unknown | Promise<unknown>, options?: {
68
+ object?: string | string[];
69
+ priority?: number;
70
+ packageId?: string;
71
+ }): void;
72
+ unregisterHooksByPackage?(packageId: string): number;
73
+ }
74
+ /** Minimal logger surface (matches core's `ctx.logger`). */
75
+ interface TriggerLogger {
76
+ info(msg: string, ...args: unknown[]): void;
77
+ warn(msg: string, ...args: unknown[]): void;
78
+ debug?(msg: string, ...args: unknown[]): void;
79
+ }
80
+ /**
81
+ * Map a flow start node's `triggerType` (e.g. `record-after-update`) to an
82
+ * ObjectQL `HookEvent` (e.g. `afterUpdate`). Returns `null` for anything that
83
+ * isn't a `record-(before|after)-(create|insert|update|delete)` token.
84
+ */
85
+ declare function triggerTypeToHookEvent(triggerType: string | undefined): string | null;
86
+ /**
87
+ * RecordChangeTrigger
88
+ *
89
+ * Bridges the automation engine's {@link FlowTrigger} extension point to
90
+ * ObjectQL lifecycle hooks. For each flow the engine activates, it subscribes
91
+ * to the matching hook event (filtered to the flow's target object) and, when
92
+ * the hook fires, builds an {@link AutomationContext} from the new/old record
93
+ * and invokes the engine-supplied callback (which runs the flow — the engine
94
+ * owns the start-node condition gate, so we don't re-evaluate it here).
95
+ *
96
+ * Each flow's hooks are registered under a per-flow packageId so {@link stop}
97
+ * can tear exactly that flow's subscription down via
98
+ * `unregisterHooksByPackage`, without touching other flows or audit hooks.
99
+ */
100
+ declare class RecordChangeTrigger implements FlowTrigger {
101
+ readonly type = "record_change";
102
+ private readonly engine;
103
+ private readonly logger;
104
+ /** flowName → packageId used for its hook(s), so stop() can unregister it. */
105
+ private readonly bound;
106
+ constructor(engine: RecordChangeDataEngine, logger: TriggerLogger);
107
+ start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void;
108
+ stop(flowName: string): void;
109
+ /**
110
+ * Build the flow execution context from an ObjectQL hook context. The new
111
+ * record comes from `ctx.result` (after-hooks) or falls back to the
112
+ * mutation input doc / previous row; the old record from `ctx.previous`
113
+ * (with the `__previous` stash audit also uses as a fallback).
114
+ */
115
+ private buildContext;
116
+ }
117
+
118
+ export { type FlowTrigger, type FlowTriggerBinding, type RecordChangeDataEngine, RecordChangeTrigger, RecordChangeTriggerPlugin, type TriggerLogger, triggerTypeToHookEvent };
package/dist/index.js ADDED
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ RecordChangeTrigger: () => RecordChangeTrigger,
24
+ RecordChangeTriggerPlugin: () => RecordChangeTriggerPlugin,
25
+ triggerTypeToHookEvent: () => triggerTypeToHookEvent
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/record-change-trigger.ts
30
+ var TRIGGER_PREFIX = "com.objectstack.trigger.record-change";
31
+ function triggerTypeToHookEvent(triggerType) {
32
+ if (!triggerType) return null;
33
+ const m = /^record-(before|after)-(create|insert|update|delete)$/.exec(triggerType.trim());
34
+ if (!m) return null;
35
+ const phase = m[1];
36
+ const op = m[2];
37
+ const verb = op === "create" || op === "insert" ? "Insert" : op.charAt(0).toUpperCase() + op.slice(1);
38
+ return `${phase}${verb}`;
39
+ }
40
+ var RecordChangeTrigger = class {
41
+ constructor(engine, logger) {
42
+ this.type = "record_change";
43
+ /** flowName → packageId used for its hook(s), so stop() can unregister it. */
44
+ this.bound = /* @__PURE__ */ new Map();
45
+ this.engine = engine;
46
+ this.logger = logger;
47
+ }
48
+ start(binding, callback) {
49
+ const hookEvent = triggerTypeToHookEvent(binding.event);
50
+ if (!hookEvent) {
51
+ this.logger.warn(
52
+ `[record-change] flow '${binding.flowName}' has unsupported trigger event '${binding.event ?? "(none)"}' \u2014 not bound`
53
+ );
54
+ return;
55
+ }
56
+ this.stop(binding.flowName);
57
+ const packageId = `${TRIGGER_PREFIX}:${binding.flowName}`;
58
+ const handler = async (ctx) => {
59
+ try {
60
+ const automationCtx = this.buildContext(binding, ctx);
61
+ await callback(automationCtx);
62
+ } catch (err) {
63
+ this.logger.warn(
64
+ `[record-change] flow '${binding.flowName}' execution failed: ${err?.message ?? String(err)}`
65
+ );
66
+ }
67
+ };
68
+ this.engine.registerHook(hookEvent, handler, {
69
+ object: binding.object,
70
+ packageId
71
+ });
72
+ this.bound.set(binding.flowName, packageId);
73
+ this.logger.info(
74
+ `[record-change] bound flow '${binding.flowName}' \u2192 ${hookEvent}${binding.object ? ` on '${binding.object}'` : ""}`
75
+ );
76
+ }
77
+ stop(flowName) {
78
+ const packageId = this.bound.get(flowName);
79
+ if (!packageId) return;
80
+ try {
81
+ this.engine.unregisterHooksByPackage?.(packageId);
82
+ } catch (err) {
83
+ this.logger.warn(
84
+ `[record-change] failed to unbind flow '${flowName}': ${err?.message ?? String(err)}`
85
+ );
86
+ }
87
+ this.bound.delete(flowName);
88
+ this.logger.debug?.(`[record-change] unbound flow '${flowName}'`);
89
+ }
90
+ /**
91
+ * Build the flow execution context from an ObjectQL hook context. The new
92
+ * record comes from `ctx.result` (after-hooks) or falls back to the
93
+ * mutation input doc / previous row; the old record from `ctx.previous`
94
+ * (with the `__previous` stash audit also uses as a fallback).
95
+ */
96
+ buildContext(binding, ctx) {
97
+ const input = ctx.input ?? {};
98
+ const after = ctx.result;
99
+ const previous = ctx.previous ?? (ctx.__previous ?? void 0);
100
+ const record = after && typeof after === "object" ? after : input.doc && typeof input.doc === "object" ? input.doc : previous && typeof previous === "object" ? previous : {};
101
+ const session = ctx.session ?? {};
102
+ return {
103
+ record,
104
+ previous,
105
+ object: binding.object ?? ctx.object,
106
+ event: binding.event,
107
+ userId: session.userId,
108
+ // Expose the record as params too, so flows with named `isInput`
109
+ // variables matching record fields get them seeded.
110
+ params: record
111
+ };
112
+ }
113
+ };
114
+
115
+ // src/plugin.ts
116
+ var RecordChangeTriggerPlugin = class {
117
+ constructor() {
118
+ this.name = "com.objectstack.trigger.record-change";
119
+ this.type = "standard";
120
+ this.version = "7.3.0";
121
+ this.dependencies = ["com.objectstack.engine.objectql"];
122
+ }
123
+ async init(ctx) {
124
+ ctx.logger.info("Record-change trigger plugin initialized");
125
+ }
126
+ async start(ctx) {
127
+ ctx.hook("kernel:ready", async () => {
128
+ const automation = this.resolveService(ctx, "automation");
129
+ if (!automation || typeof automation.registerTrigger !== "function") {
130
+ ctx.logger.warn(
131
+ "RecordChangeTriggerPlugin: automation service not available \u2014 record-change trigger NOT installed"
132
+ );
133
+ return;
134
+ }
135
+ const engine = this.resolveDataEngine(ctx);
136
+ if (!engine || typeof engine.registerHook !== "function") {
137
+ ctx.logger.warn(
138
+ "RecordChangeTriggerPlugin: ObjectQL engine not available \u2014 record-change trigger NOT installed"
139
+ );
140
+ return;
141
+ }
142
+ const trigger = new RecordChangeTrigger(engine, ctx.logger);
143
+ automation.registerTrigger(trigger);
144
+ ctx.logger.info("RecordChangeTriggerPlugin: record-change trigger registered");
145
+ });
146
+ }
147
+ resolveService(ctx, name) {
148
+ try {
149
+ return ctx.getService(name) ?? null;
150
+ } catch {
151
+ return null;
152
+ }
153
+ }
154
+ resolveDataEngine(ctx) {
155
+ return this.resolveService(ctx, "objectql") ?? this.resolveService(ctx, "data");
156
+ }
157
+ };
158
+ // Annotate the CommonJS export names for ESM import in node:
159
+ 0 && (module.exports = {
160
+ RecordChangeTrigger,
161
+ RecordChangeTriggerPlugin,
162
+ triggerTypeToHookEvent
163
+ });
164
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/record-change-trigger.ts","../src/plugin.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport { RecordChangeTriggerPlugin } from './plugin.js';\nexport {\n RecordChangeTrigger,\n triggerTypeToHookEvent,\n} from './record-change-trigger.js';\nexport type {\n FlowTrigger,\n FlowTriggerBinding,\n RecordChangeDataEngine,\n TriggerLogger,\n} from './record-change-trigger.js';\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { AutomationContext } from '@objectstack/spec/contracts';\nimport type { HookContext } from '@objectstack/spec/data';\n\n/**\n * Structural mirror of the automation engine's `FlowTriggerBinding`\n * (service-automation/src/engine.ts). Declared locally so this trigger plugin\n * stays decoupled from the automation package — same pattern the connector /\n * messaging integrations use to avoid a hard build edge. The engine parses the\n * flow's start node and hands us one of these per activated flow.\n */\nexport interface FlowTriggerBinding {\n readonly flowName: string;\n readonly object?: string;\n readonly event?: string;\n readonly condition?: string | { dialect?: string; source?: string; ast?: unknown };\n readonly schedule?: unknown;\n readonly config?: Record<string, unknown>;\n}\n\n/**\n * Structural mirror of the engine's `FlowTrigger` extension point. The engine\n * calls {@link start} with a parsed binding + a callback that runs the flow,\n * and {@link stop} when the flow is unregistered/disabled.\n */\nexport interface FlowTrigger {\n readonly type: string;\n start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void;\n stop(flowName: string): void;\n}\n\n/**\n * The slice of the ObjectQL data engine this trigger needs: subscribe to a\n * lifecycle hook, and (for teardown) drop all hooks owned by a packageId.\n * Typed structurally because `IDataEngine` (the public contract) doesn't model\n * the hook surface, but the concrete engine implements both.\n */\nexport interface RecordChangeDataEngine {\n registerHook(\n event: string,\n handler: (ctx: HookContext) => unknown | Promise<unknown>,\n options?: { object?: string | string[]; priority?: number; packageId?: string },\n ): void;\n unregisterHooksByPackage?(packageId: string): number;\n}\n\n/** Minimal logger surface (matches core's `ctx.logger`). */\nexport interface TriggerLogger {\n info(msg: string, ...args: unknown[]): void;\n warn(msg: string, ...args: unknown[]): void;\n debug?(msg: string, ...args: unknown[]): void;\n}\n\nconst TRIGGER_PREFIX = 'com.objectstack.trigger.record-change';\n\n/**\n * Map a flow start node's `triggerType` (e.g. `record-after-update`) to an\n * ObjectQL `HookEvent` (e.g. `afterUpdate`). Returns `null` for anything that\n * isn't a `record-(before|after)-(create|insert|update|delete)` token.\n */\nexport function triggerTypeToHookEvent(triggerType: string | undefined): string | null {\n if (!triggerType) return null;\n const m = /^record-(before|after)-(create|insert|update|delete)$/.exec(triggerType.trim());\n if (!m) return null;\n const phase = m[1]; // 'before' | 'after'\n const op = m[2]; // create|insert|update|delete\n const verb = op === 'create' || op === 'insert' ? 'Insert' : op.charAt(0).toUpperCase() + op.slice(1);\n return `${phase}${verb}`; // e.g. 'afterUpdate', 'beforeDelete'\n}\n\n/**\n * RecordChangeTrigger\n *\n * Bridges the automation engine's {@link FlowTrigger} extension point to\n * ObjectQL lifecycle hooks. For each flow the engine activates, it subscribes\n * to the matching hook event (filtered to the flow's target object) and, when\n * the hook fires, builds an {@link AutomationContext} from the new/old record\n * and invokes the engine-supplied callback (which runs the flow — the engine\n * owns the start-node condition gate, so we don't re-evaluate it here).\n *\n * Each flow's hooks are registered under a per-flow packageId so {@link stop}\n * can tear exactly that flow's subscription down via\n * `unregisterHooksByPackage`, without touching other flows or audit hooks.\n */\nexport class RecordChangeTrigger implements FlowTrigger {\n readonly type = 'record_change';\n\n private readonly engine: RecordChangeDataEngine;\n private readonly logger: TriggerLogger;\n /** flowName → packageId used for its hook(s), so stop() can unregister it. */\n private readonly bound = new Map<string, string>();\n\n constructor(engine: RecordChangeDataEngine, logger: TriggerLogger) {\n this.engine = engine;\n this.logger = logger;\n }\n\n start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void {\n const hookEvent = triggerTypeToHookEvent(binding.event);\n if (!hookEvent) {\n this.logger.warn(\n `[record-change] flow '${binding.flowName}' has unsupported trigger event '${binding.event ?? '(none)'}' — not bound`,\n );\n return;\n }\n\n // Idempotent: drop any prior subscription for this flow before re-binding\n // (covers disable→enable cycles and hot reload).\n this.stop(binding.flowName);\n\n const packageId = `${TRIGGER_PREFIX}:${binding.flowName}`;\n\n const handler = async (ctx: HookContext): Promise<void> => {\n try {\n const automationCtx = this.buildContext(binding, ctx);\n await callback(automationCtx);\n } catch (err) {\n // Error isolation: a flow failure must NEVER break the CRUD write\n // that triggered it. Log and swallow.\n this.logger.warn(\n `[record-change] flow '${binding.flowName}' execution failed: ${(err as Error)?.message ?? String(err)}`,\n );\n }\n };\n\n this.engine.registerHook(hookEvent, handler, {\n object: binding.object,\n packageId,\n });\n this.bound.set(binding.flowName, packageId);\n this.logger.info(\n `[record-change] bound flow '${binding.flowName}' → ${hookEvent}${binding.object ? ` on '${binding.object}'` : ''}`,\n );\n }\n\n stop(flowName: string): void {\n const packageId = this.bound.get(flowName);\n if (!packageId) return;\n try {\n this.engine.unregisterHooksByPackage?.(packageId);\n } catch (err) {\n this.logger.warn(\n `[record-change] failed to unbind flow '${flowName}': ${(err as Error)?.message ?? String(err)}`,\n );\n }\n this.bound.delete(flowName);\n this.logger.debug?.(`[record-change] unbound flow '${flowName}'`);\n }\n\n /**\n * Build the flow execution context from an ObjectQL hook context. The new\n * record comes from `ctx.result` (after-hooks) or falls back to the\n * mutation input doc / previous row; the old record from `ctx.previous`\n * (with the `__previous` stash audit also uses as a fallback).\n */\n private buildContext(binding: FlowTriggerBinding, ctx: HookContext): AutomationContext {\n const input = (ctx.input ?? {}) as { doc?: Record<string, unknown>; id?: unknown };\n const after = ctx.result as Record<string, unknown> | undefined;\n const previous =\n (ctx.previous as Record<string, unknown> | undefined) ??\n ((ctx as unknown as { __previous?: Record<string, unknown> }).__previous ?? undefined);\n\n const record: Record<string, unknown> =\n after && typeof after === 'object'\n ? after\n : input.doc && typeof input.doc === 'object'\n ? input.doc\n : previous && typeof previous === 'object'\n ? previous\n : {};\n\n const session = (ctx.session ?? {}) as { userId?: string };\n\n return {\n record,\n previous,\n object: binding.object ?? ctx.object,\n event: binding.event,\n userId: session.userId,\n // Expose the record as params too, so flows with named `isInput`\n // variables matching record fields get them seeded.\n params: record,\n };\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport { RecordChangeTrigger } from './record-change-trigger.js';\nimport type { FlowTrigger, RecordChangeDataEngine } from './record-change-trigger.js';\n\n/**\n * The slice of the automation engine this plugin needs: register a trigger on\n * its `FlowTrigger` extension point. Declared structurally so the plugin does\n * not take a build dependency on `@objectstack/service-automation`.\n */\ninterface AutomationTriggerRegistry {\n registerTrigger(trigger: FlowTrigger): void;\n unregisterTrigger?(type: string): void;\n}\n\n/**\n * RecordChangeTriggerPlugin\n *\n * Makes record-change-triggered flows actually fire. The automation engine\n * ships the `FlowTrigger` wiring (it parses each flow's start node into a\n * binding and calls `trigger.start(...)`), but the *concrete* record-change\n * trigger — the one that subscribes to ObjectQL lifecycle hooks — lives here as\n * a plugin. This mirrors the connector split (engine baseline + connector-rest\n * plugin) and reuses plugin-audit's `kernel:ready` → `getService('objectql')`\n * pattern to reach the data engine's hook surface.\n *\n * With this plugin installed, a flow whose start node declares\n * `config: { objectName, triggerType: 'record-after-update', condition }`\n * auto-launches on the matching mutation — no manual `engine.execute()`.\n */\nexport class RecordChangeTriggerPlugin implements Plugin {\n name = 'com.objectstack.trigger.record-change';\n type = 'standard';\n version = '7.3.0';\n dependencies = ['com.objectstack.engine.objectql'];\n\n async init(ctx: PluginContext): Promise<void> {\n ctx.logger.info('Record-change trigger plugin initialized');\n }\n\n async start(ctx: PluginContext): Promise<void> {\n // ObjectQL engine + the automation service are only resolvable once the\n // kernel is ready (kernel:ready fires after AutomationServicePlugin.start()\n // has pulled flows into the engine, so binding order is correct).\n ctx.hook('kernel:ready', async () => {\n const automation = this.resolveService<AutomationTriggerRegistry>(ctx, 'automation');\n if (!automation || typeof automation.registerTrigger !== 'function') {\n ctx.logger.warn(\n 'RecordChangeTriggerPlugin: automation service not available — record-change trigger NOT installed',\n );\n return;\n }\n\n const engine = this.resolveDataEngine(ctx);\n if (!engine || typeof engine.registerHook !== 'function') {\n ctx.logger.warn(\n 'RecordChangeTriggerPlugin: ObjectQL engine not available — record-change trigger NOT installed',\n );\n return;\n }\n\n const trigger = new RecordChangeTrigger(engine, ctx.logger);\n automation.registerTrigger(trigger);\n ctx.logger.info('RecordChangeTriggerPlugin: record-change trigger registered');\n });\n }\n\n private resolveService<T>(ctx: PluginContext, name: string): T | null {\n try {\n return ctx.getService<T>(name) ?? null;\n } catch {\n return null;\n }\n }\n\n private resolveDataEngine(ctx: PluginContext): RecordChangeDataEngine | null {\n // Primary alias 'objectql', fallback 'data' (some kernels register the\n // engine under both) — same lookup plugin-audit uses.\n return (\n this.resolveService<RecordChangeDataEngine>(ctx, 'objectql') ??\n this.resolveService<RecordChangeDataEngine>(ctx, 'data')\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsDA,IAAM,iBAAiB;AAOhB,SAAS,uBAAuB,aAAgD;AACnF,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,IAAI,wDAAwD,KAAK,YAAY,KAAK,CAAC;AACzF,MAAI,CAAC,EAAG,QAAO;AACf,QAAM,QAAQ,EAAE,CAAC;AACjB,QAAM,KAAK,EAAE,CAAC;AACd,QAAM,OAAO,OAAO,YAAY,OAAO,WAAW,WAAW,GAAG,OAAO,CAAC,EAAE,YAAY,IAAI,GAAG,MAAM,CAAC;AACpG,SAAO,GAAG,KAAK,GAAG,IAAI;AAC1B;AAgBO,IAAM,sBAAN,MAAiD;AA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D,iBAAW,gBAAgB,OAAO;AAClC,UAAI,OAAO,KAAK,6DAA6D;AAAA,IACjF,CAAC;AAAA,EACL;AAAA,EAEQ,eAAkB,KAAoB,MAAwB;AAClE,QAAI;AACA,aAAO,IAAI,WAAc,IAAI,KAAK;AAAA,IACtC,QAAQ;AACJ,aAAO;AAAA,IACX;AAAA,EACJ;AAAA,EAEQ,kBAAkB,KAAmD;AAGzE,WACI,KAAK,eAAuC,KAAK,UAAU,KAC3D,KAAK,eAAuC,KAAK,MAAM;AAAA,EAE/D;AACJ;","names":[]}
package/dist/index.mjs ADDED
@@ -0,0 +1,135 @@
1
+ // src/record-change-trigger.ts
2
+ var TRIGGER_PREFIX = "com.objectstack.trigger.record-change";
3
+ function triggerTypeToHookEvent(triggerType) {
4
+ if (!triggerType) return null;
5
+ const m = /^record-(before|after)-(create|insert|update|delete)$/.exec(triggerType.trim());
6
+ if (!m) return null;
7
+ const phase = m[1];
8
+ const op = m[2];
9
+ const verb = op === "create" || op === "insert" ? "Insert" : op.charAt(0).toUpperCase() + op.slice(1);
10
+ return `${phase}${verb}`;
11
+ }
12
+ var RecordChangeTrigger = class {
13
+ constructor(engine, logger) {
14
+ this.type = "record_change";
15
+ /** flowName → packageId used for its hook(s), so stop() can unregister it. */
16
+ this.bound = /* @__PURE__ */ new Map();
17
+ this.engine = engine;
18
+ this.logger = logger;
19
+ }
20
+ start(binding, callback) {
21
+ const hookEvent = triggerTypeToHookEvent(binding.event);
22
+ if (!hookEvent) {
23
+ this.logger.warn(
24
+ `[record-change] flow '${binding.flowName}' has unsupported trigger event '${binding.event ?? "(none)"}' \u2014 not bound`
25
+ );
26
+ return;
27
+ }
28
+ this.stop(binding.flowName);
29
+ const packageId = `${TRIGGER_PREFIX}:${binding.flowName}`;
30
+ const handler = async (ctx) => {
31
+ try {
32
+ const automationCtx = this.buildContext(binding, ctx);
33
+ await callback(automationCtx);
34
+ } catch (err) {
35
+ this.logger.warn(
36
+ `[record-change] flow '${binding.flowName}' execution failed: ${err?.message ?? String(err)}`
37
+ );
38
+ }
39
+ };
40
+ this.engine.registerHook(hookEvent, handler, {
41
+ object: binding.object,
42
+ packageId
43
+ });
44
+ this.bound.set(binding.flowName, packageId);
45
+ this.logger.info(
46
+ `[record-change] bound flow '${binding.flowName}' \u2192 ${hookEvent}${binding.object ? ` on '${binding.object}'` : ""}`
47
+ );
48
+ }
49
+ stop(flowName) {
50
+ const packageId = this.bound.get(flowName);
51
+ if (!packageId) return;
52
+ try {
53
+ this.engine.unregisterHooksByPackage?.(packageId);
54
+ } catch (err) {
55
+ this.logger.warn(
56
+ `[record-change] failed to unbind flow '${flowName}': ${err?.message ?? String(err)}`
57
+ );
58
+ }
59
+ this.bound.delete(flowName);
60
+ this.logger.debug?.(`[record-change] unbound flow '${flowName}'`);
61
+ }
62
+ /**
63
+ * Build the flow execution context from an ObjectQL hook context. The new
64
+ * record comes from `ctx.result` (after-hooks) or falls back to the
65
+ * mutation input doc / previous row; the old record from `ctx.previous`
66
+ * (with the `__previous` stash audit also uses as a fallback).
67
+ */
68
+ buildContext(binding, ctx) {
69
+ const input = ctx.input ?? {};
70
+ const after = ctx.result;
71
+ const previous = ctx.previous ?? (ctx.__previous ?? void 0);
72
+ const record = after && typeof after === "object" ? after : input.doc && typeof input.doc === "object" ? input.doc : previous && typeof previous === "object" ? previous : {};
73
+ const session = ctx.session ?? {};
74
+ return {
75
+ record,
76
+ previous,
77
+ object: binding.object ?? ctx.object,
78
+ event: binding.event,
79
+ userId: session.userId,
80
+ // Expose the record as params too, so flows with named `isInput`
81
+ // variables matching record fields get them seeded.
82
+ params: record
83
+ };
84
+ }
85
+ };
86
+
87
+ // src/plugin.ts
88
+ var RecordChangeTriggerPlugin = class {
89
+ constructor() {
90
+ this.name = "com.objectstack.trigger.record-change";
91
+ this.type = "standard";
92
+ this.version = "7.3.0";
93
+ this.dependencies = ["com.objectstack.engine.objectql"];
94
+ }
95
+ async init(ctx) {
96
+ ctx.logger.info("Record-change trigger plugin initialized");
97
+ }
98
+ async start(ctx) {
99
+ ctx.hook("kernel:ready", async () => {
100
+ const automation = this.resolveService(ctx, "automation");
101
+ if (!automation || typeof automation.registerTrigger !== "function") {
102
+ ctx.logger.warn(
103
+ "RecordChangeTriggerPlugin: automation service not available \u2014 record-change trigger NOT installed"
104
+ );
105
+ return;
106
+ }
107
+ const engine = this.resolveDataEngine(ctx);
108
+ if (!engine || typeof engine.registerHook !== "function") {
109
+ ctx.logger.warn(
110
+ "RecordChangeTriggerPlugin: ObjectQL engine not available \u2014 record-change trigger NOT installed"
111
+ );
112
+ return;
113
+ }
114
+ const trigger = new RecordChangeTrigger(engine, ctx.logger);
115
+ automation.registerTrigger(trigger);
116
+ ctx.logger.info("RecordChangeTriggerPlugin: record-change trigger registered");
117
+ });
118
+ }
119
+ resolveService(ctx, name) {
120
+ try {
121
+ return ctx.getService(name) ?? null;
122
+ } catch {
123
+ return null;
124
+ }
125
+ }
126
+ resolveDataEngine(ctx) {
127
+ return this.resolveService(ctx, "objectql") ?? this.resolveService(ctx, "data");
128
+ }
129
+ };
130
+ export {
131
+ RecordChangeTrigger,
132
+ RecordChangeTriggerPlugin,
133
+ triggerTypeToHookEvent
134
+ };
135
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/record-change-trigger.ts","../src/plugin.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { AutomationContext } from '@objectstack/spec/contracts';\nimport type { HookContext } from '@objectstack/spec/data';\n\n/**\n * Structural mirror of the automation engine's `FlowTriggerBinding`\n * (service-automation/src/engine.ts). Declared locally so this trigger plugin\n * stays decoupled from the automation package — same pattern the connector /\n * messaging integrations use to avoid a hard build edge. The engine parses the\n * flow's start node and hands us one of these per activated flow.\n */\nexport interface FlowTriggerBinding {\n readonly flowName: string;\n readonly object?: string;\n readonly event?: string;\n readonly condition?: string | { dialect?: string; source?: string; ast?: unknown };\n readonly schedule?: unknown;\n readonly config?: Record<string, unknown>;\n}\n\n/**\n * Structural mirror of the engine's `FlowTrigger` extension point. The engine\n * calls {@link start} with a parsed binding + a callback that runs the flow,\n * and {@link stop} when the flow is unregistered/disabled.\n */\nexport interface FlowTrigger {\n readonly type: string;\n start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void;\n stop(flowName: string): void;\n}\n\n/**\n * The slice of the ObjectQL data engine this trigger needs: subscribe to a\n * lifecycle hook, and (for teardown) drop all hooks owned by a packageId.\n * Typed structurally because `IDataEngine` (the public contract) doesn't model\n * the hook surface, but the concrete engine implements both.\n */\nexport interface RecordChangeDataEngine {\n registerHook(\n event: string,\n handler: (ctx: HookContext) => unknown | Promise<unknown>,\n options?: { object?: string | string[]; priority?: number; packageId?: string },\n ): void;\n unregisterHooksByPackage?(packageId: string): number;\n}\n\n/** Minimal logger surface (matches core's `ctx.logger`). */\nexport interface TriggerLogger {\n info(msg: string, ...args: unknown[]): void;\n warn(msg: string, ...args: unknown[]): void;\n debug?(msg: string, ...args: unknown[]): void;\n}\n\nconst TRIGGER_PREFIX = 'com.objectstack.trigger.record-change';\n\n/**\n * Map a flow start node's `triggerType` (e.g. `record-after-update`) to an\n * ObjectQL `HookEvent` (e.g. `afterUpdate`). Returns `null` for anything that\n * isn't a `record-(before|after)-(create|insert|update|delete)` token.\n */\nexport function triggerTypeToHookEvent(triggerType: string | undefined): string | null {\n if (!triggerType) return null;\n const m = /^record-(before|after)-(create|insert|update|delete)$/.exec(triggerType.trim());\n if (!m) return null;\n const phase = m[1]; // 'before' | 'after'\n const op = m[2]; // create|insert|update|delete\n const verb = op === 'create' || op === 'insert' ? 'Insert' : op.charAt(0).toUpperCase() + op.slice(1);\n return `${phase}${verb}`; // e.g. 'afterUpdate', 'beforeDelete'\n}\n\n/**\n * RecordChangeTrigger\n *\n * Bridges the automation engine's {@link FlowTrigger} extension point to\n * ObjectQL lifecycle hooks. For each flow the engine activates, it subscribes\n * to the matching hook event (filtered to the flow's target object) and, when\n * the hook fires, builds an {@link AutomationContext} from the new/old record\n * and invokes the engine-supplied callback (which runs the flow — the engine\n * owns the start-node condition gate, so we don't re-evaluate it here).\n *\n * Each flow's hooks are registered under a per-flow packageId so {@link stop}\n * can tear exactly that flow's subscription down via\n * `unregisterHooksByPackage`, without touching other flows or audit hooks.\n */\nexport class RecordChangeTrigger implements FlowTrigger {\n readonly type = 'record_change';\n\n private readonly engine: RecordChangeDataEngine;\n private readonly logger: TriggerLogger;\n /** flowName → packageId used for its hook(s), so stop() can unregister it. */\n private readonly bound = new Map<string, string>();\n\n constructor(engine: RecordChangeDataEngine, logger: TriggerLogger) {\n this.engine = engine;\n this.logger = logger;\n }\n\n start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void {\n const hookEvent = triggerTypeToHookEvent(binding.event);\n if (!hookEvent) {\n this.logger.warn(\n `[record-change] flow '${binding.flowName}' has unsupported trigger event '${binding.event ?? '(none)'}' — not bound`,\n );\n return;\n }\n\n // Idempotent: drop any prior subscription for this flow before re-binding\n // (covers disable→enable cycles and hot reload).\n this.stop(binding.flowName);\n\n const packageId = `${TRIGGER_PREFIX}:${binding.flowName}`;\n\n const handler = async (ctx: HookContext): Promise<void> => {\n try {\n const automationCtx = this.buildContext(binding, ctx);\n await callback(automationCtx);\n } catch (err) {\n // Error isolation: a flow failure must NEVER break the CRUD write\n // that triggered it. Log and swallow.\n this.logger.warn(\n `[record-change] flow '${binding.flowName}' execution failed: ${(err as Error)?.message ?? String(err)}`,\n );\n }\n };\n\n this.engine.registerHook(hookEvent, handler, {\n object: binding.object,\n packageId,\n });\n this.bound.set(binding.flowName, packageId);\n this.logger.info(\n `[record-change] bound flow '${binding.flowName}' → ${hookEvent}${binding.object ? ` on '${binding.object}'` : ''}`,\n );\n }\n\n stop(flowName: string): void {\n const packageId = this.bound.get(flowName);\n if (!packageId) return;\n try {\n this.engine.unregisterHooksByPackage?.(packageId);\n } catch (err) {\n this.logger.warn(\n `[record-change] failed to unbind flow '${flowName}': ${(err as Error)?.message ?? String(err)}`,\n );\n }\n this.bound.delete(flowName);\n this.logger.debug?.(`[record-change] unbound flow '${flowName}'`);\n }\n\n /**\n * Build the flow execution context from an ObjectQL hook context. The new\n * record comes from `ctx.result` (after-hooks) or falls back to the\n * mutation input doc / previous row; the old record from `ctx.previous`\n * (with the `__previous` stash audit also uses as a fallback).\n */\n private buildContext(binding: FlowTriggerBinding, ctx: HookContext): AutomationContext {\n const input = (ctx.input ?? {}) as { doc?: Record<string, unknown>; id?: unknown };\n const after = ctx.result as Record<string, unknown> | undefined;\n const previous =\n (ctx.previous as Record<string, unknown> | undefined) ??\n ((ctx as unknown as { __previous?: Record<string, unknown> }).__previous ?? undefined);\n\n const record: Record<string, unknown> =\n after && typeof after === 'object'\n ? after\n : input.doc && typeof input.doc === 'object'\n ? input.doc\n : previous && typeof previous === 'object'\n ? previous\n : {};\n\n const session = (ctx.session ?? {}) as { userId?: string };\n\n return {\n record,\n previous,\n object: binding.object ?? ctx.object,\n event: binding.event,\n userId: session.userId,\n // Expose the record as params too, so flows with named `isInput`\n // variables matching record fields get them seeded.\n params: record,\n };\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport { RecordChangeTrigger } from './record-change-trigger.js';\nimport type { FlowTrigger, RecordChangeDataEngine } from './record-change-trigger.js';\n\n/**\n * The slice of the automation engine this plugin needs: register a trigger on\n * its `FlowTrigger` extension point. Declared structurally so the plugin does\n * not take a build dependency on `@objectstack/service-automation`.\n */\ninterface AutomationTriggerRegistry {\n registerTrigger(trigger: FlowTrigger): void;\n unregisterTrigger?(type: string): void;\n}\n\n/**\n * RecordChangeTriggerPlugin\n *\n * Makes record-change-triggered flows actually fire. The automation engine\n * ships the `FlowTrigger` wiring (it parses each flow's start node into a\n * binding and calls `trigger.start(...)`), but the *concrete* record-change\n * trigger — the one that subscribes to ObjectQL lifecycle hooks — lives here as\n * a plugin. This mirrors the connector split (engine baseline + connector-rest\n * plugin) and reuses plugin-audit's `kernel:ready` → `getService('objectql')`\n * pattern to reach the data engine's hook surface.\n *\n * With this plugin installed, a flow whose start node declares\n * `config: { objectName, triggerType: 'record-after-update', condition }`\n * auto-launches on the matching mutation — no manual `engine.execute()`.\n */\nexport class RecordChangeTriggerPlugin implements Plugin {\n name = 'com.objectstack.trigger.record-change';\n type = 'standard';\n version = '7.3.0';\n dependencies = ['com.objectstack.engine.objectql'];\n\n async init(ctx: PluginContext): Promise<void> {\n ctx.logger.info('Record-change trigger plugin initialized');\n }\n\n async start(ctx: PluginContext): Promise<void> {\n // ObjectQL engine + the automation service are only resolvable once the\n // kernel is ready (kernel:ready fires after AutomationServicePlugin.start()\n // has pulled flows into the engine, so binding order is correct).\n ctx.hook('kernel:ready', async () => {\n const automation = this.resolveService<AutomationTriggerRegistry>(ctx, 'automation');\n if (!automation || typeof automation.registerTrigger !== 'function') {\n ctx.logger.warn(\n 'RecordChangeTriggerPlugin: automation service not available — record-change trigger NOT installed',\n );\n return;\n }\n\n const engine = this.resolveDataEngine(ctx);\n if (!engine || typeof engine.registerHook !== 'function') {\n ctx.logger.warn(\n 'RecordChangeTriggerPlugin: ObjectQL engine not available — record-change trigger NOT installed',\n );\n return;\n }\n\n const trigger = new RecordChangeTrigger(engine, ctx.logger);\n automation.registerTrigger(trigger);\n ctx.logger.info('RecordChangeTriggerPlugin: record-change trigger registered');\n });\n }\n\n private resolveService<T>(ctx: PluginContext, name: string): T | null {\n try {\n return ctx.getService<T>(name) ?? null;\n } catch {\n return null;\n }\n }\n\n private resolveDataEngine(ctx: PluginContext): RecordChangeDataEngine | null {\n // Primary alias 'objectql', fallback 'data' (some kernels register the\n // engine under both) — same lookup plugin-audit uses.\n return (\n this.resolveService<RecordChangeDataEngine>(ctx, 'objectql') ??\n this.resolveService<RecordChangeDataEngine>(ctx, 'data')\n );\n }\n}\n"],"mappings":";AAsDA,IAAM,iBAAiB;AAOhB,SA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gB,YAAY;AACjC,YAAM,aAAa,KAAK,eAA0C,KAAK,YAAY;AACnF,UAAI,CAAC,cAAc,OAAO,WAAW,oBAAoB,YAAY;AACjE,YAAI,OAAO;AAAA,UACP;AAAA,QACJ;AACA;AAAA,MACJ;AAEA,YAAM,SAAS,KAAK,kBAAkB,GAAG;AACzC,UAAI,CAAC,UAAU,OAAO,OAAO,iBAAiB,YAAY;AACtD,YAAI,OAAO;AAAA,UACP;AAAA,QACJ;AACA;AAAA,MACJ;AAEA,YAAM,UAAU,IAAI,oBAAoB,QAAQ,IAAI,MAAM;AAC1D,iBAAW,gBAAgB,OAAO;AAClC,UAAI,OAAO,KAAK,6DAA6D;AAAA,IACjF,CAAC;AAAA,EACL;AAAA,EAEQ,eAAkB,KAAoB,MAAwB;AAClE,QAAI;AACA,aAAO,IAAI,WAAc,IAAI,KAAK;AAAA,IACtC,QAAQ;AACJ,aAAO;AAAA,IACX;AAAA,EACJ;AAAA,EAEQ,kBAAkB,KAAmD;AAGzE,WACI,KAAK,eAAuC,KAAK,UAAU,KAC3D,KAAK,eAAuC,KAAK,MAAM;AAAA,EAE/D;AACJ;","names":[]}
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@objectstack/plugin-trigger-record-change",
3
+ "version": "7.4.0",
4
+ "license": "Apache-2.0",
5
+ "description": "Record-change flow trigger for ObjectStack — auto-launches flows on object insert/update/delete via ObjectQL lifecycle hooks (ADR-0018)",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "dependencies": {
16
+ "@objectstack/core": "7.4.0",
17
+ "@objectstack/spec": "7.4.0"
18
+ },
19
+ "devDependencies": {
20
+ "@types/node": "^25.9.1",
21
+ "typescript": "^6.0.3",
22
+ "vitest": "^4.1.7"
23
+ },
24
+ "keywords": [
25
+ "objectstack",
26
+ "plugin",
27
+ "automation",
28
+ "flow",
29
+ "trigger",
30
+ "record-change"
31
+ ],
32
+ "author": "ObjectStack",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/objectstack-ai/framework.git",
36
+ "directory": "packages/plugins/plugin-trigger-record-change"
37
+ },
38
+ "homepage": "https://objectstack.ai/docs",
39
+ "bugs": "https://github.com/objectstack-ai/framework/issues",
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "files": [
44
+ "dist",
45
+ "README.md"
46
+ ],
47
+ "engines": {
48
+ "node": ">=18.0.0"
49
+ },
50
+ "scripts": {
51
+ "build": "tsup --config ../../../tsup.config.ts",
52
+ "test": "vitest run --passWithNoTests"
53
+ }
54
+ }