@objectstack/plugin-trigger-schedule 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,68 @@
1
+ # @objectstack/plugin-trigger-schedule
2
+
3
+ Auto-launch ObjectStack flows on a schedule (cron / interval / once).
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* schedule trigger lives here, as a plugin. It delegates timing to the
8
+ platform `IJobService` (the `'job'` service), so it stays adapter-agnostic: the
9
+ job service selects a cron-capable adapter (e.g. the durable `DbJobAdapter` or
10
+ `CronJobAdapter`) for cron schedules and the interval adapter for the rest.
11
+
12
+ This is the sibling of `@objectstack/plugin-trigger-record-change` — same
13
+ engine baseline, a different event source.
14
+
15
+ ## What it does
16
+
17
+ A flow whose `start` node declares a schedule:
18
+
19
+ ```ts
20
+ {
21
+ type: 'start',
22
+ config: {
23
+ schedule: { type: 'cron', expression: '0 1 * * *', timezone: 'UTC' },
24
+ condition: "...", // optional start-condition gate
25
+ },
26
+ }
27
+ // or simply: a flow with `type: 'schedule'` and a start-node schedule descriptor
28
+ ```
29
+
30
+ auto-launches on that schedule — no manual `engine.execute()`. When it fires,
31
+ the flow runs with `event: 'schedule'` and `params: { jobId, flowName, schedule }`
32
+ in its context.
33
+
34
+ ### Schedule shapes
35
+
36
+ `normalizeSchedule` accepts the canonical `JobSchedule` plus shorthands:
37
+
38
+ | Input | Normalized |
39
+ | ---------------------------------------------- | ---------------------------------------- |
40
+ | `{ type: 'cron', expression, timezone? }` | cron |
41
+ | `'0 1 * * *'` (bare string) | `{ type: 'cron', expression: '0 1 * * *' }` |
42
+ | `{ cron }` / `{ expression }` | cron |
43
+ | `{ type: 'interval', intervalMs }` / `{ every }` | interval |
44
+ | `{ type: 'once', at }` / `{ at }` | once |
45
+
46
+ ## Usage
47
+
48
+ ```ts
49
+ import { AutomationServicePlugin } from '@objectstack/service-automation';
50
+ import { JobServicePlugin } from '@objectstack/service-job';
51
+ import { ScheduleTriggerPlugin } from '@objectstack/plugin-trigger-schedule';
52
+
53
+ kernel
54
+ .use(new AutomationServicePlugin()) // engine + flows
55
+ .use(new JobServicePlugin()) // the 'job' service (cron/interval/db)
56
+ .use(new ScheduleTriggerPlugin()); // ← makes schedule flows live
57
+ ```
58
+
59
+ Depends on the job service plugin (`com.objectstack.service.job`) so its
60
+ `kernel:ready` adapter upgrade runs first; the job service is nonetheless
61
+ resolved lazily per bind, so adapter upgrades are always picked up. If the
62
+ automation or job service is unavailable, the plugin logs a warning and no-ops
63
+ rather than failing startup.
64
+
65
+ ## Error isolation
66
+
67
+ A flow that throws during a scheduled run is logged and swallowed — it never
68
+ crashes the job runner.
@@ -0,0 +1,111 @@
1
+ import { Plugin, PluginContext } from '@objectstack/core';
2
+ import { AutomationContext, JobSchedule, JobHandler } from '@objectstack/spec/contracts';
3
+
4
+ /**
5
+ * ScheduleTriggerPlugin
6
+ *
7
+ * Makes schedule-triggered flows actually fire. The automation engine ships the
8
+ * `FlowTrigger` wiring (it parses each flow's start node — `flow.type ===
9
+ * 'schedule'` or a start-node `config.schedule` descriptor — into a binding and
10
+ * calls `trigger.start(...)`), but the *concrete* schedule trigger lives here as
11
+ * a plugin and delegates timing to the platform `IJobService` (the `'job'`
12
+ * service). This mirrors the connector / record-change split (engine baseline +
13
+ * trigger plugin).
14
+ *
15
+ * With this plugin (and a job service) installed, a flow whose start node
16
+ * declares `config: { schedule: { type: 'cron', expression: '0 1 * * *' } }`
17
+ * auto-launches on that schedule — no manual `engine.execute()`.
18
+ *
19
+ * Depends on the job service plugin so its `kernel:ready` upgrade (to the
20
+ * durable DbJobAdapter) runs before ours; the job service is nonetheless
21
+ * resolved lazily per `start()` so we always use its current adapter.
22
+ */
23
+ declare class ScheduleTriggerPlugin implements Plugin {
24
+ name: string;
25
+ type: string;
26
+ version: string;
27
+ dependencies: string[];
28
+ init(ctx: PluginContext): Promise<void>;
29
+ start(ctx: PluginContext): Promise<void>;
30
+ private resolveService;
31
+ }
32
+
33
+ /**
34
+ * Structural mirror of the automation engine's `FlowTriggerBinding`
35
+ * (service-automation/src/engine.ts). Declared locally so this trigger plugin
36
+ * stays decoupled from the automation package — same pattern the record-change
37
+ * trigger and the connector / messaging integrations use. The engine parses the
38
+ * flow's start node and hands us a binding whose `schedule` carries the
39
+ * cron/interval/once descriptor.
40
+ */
41
+ interface FlowTriggerBinding {
42
+ readonly flowName: string;
43
+ readonly object?: string;
44
+ readonly event?: string;
45
+ readonly condition?: string | {
46
+ dialect?: string;
47
+ source?: string;
48
+ ast?: unknown;
49
+ };
50
+ readonly schedule?: unknown;
51
+ readonly config?: Record<string, unknown>;
52
+ }
53
+ /**
54
+ * Structural mirror of the engine's `FlowTrigger` extension point. The engine
55
+ * calls {@link start} with a parsed binding + a callback that runs the flow,
56
+ * and {@link stop} when the flow is unregistered/disabled.
57
+ */
58
+ interface FlowTrigger {
59
+ readonly type: string;
60
+ start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void;
61
+ stop(flowName: string): void;
62
+ }
63
+ /**
64
+ * The slice of `IJobService` this trigger needs: schedule a named job and
65
+ * cancel it. Typed structurally so the plugin depends on the spec contract
66
+ * shape, not a concrete adapter.
67
+ */
68
+ interface JobServiceSurface {
69
+ schedule(name: string, schedule: JobSchedule, handler: JobHandler): Promise<void>;
70
+ cancel(name: string): Promise<void>;
71
+ }
72
+ /** Minimal logger surface (matches core's `ctx.logger`). */
73
+ interface TriggerLogger {
74
+ info(msg: string, ...args: unknown[]): void;
75
+ warn(msg: string, ...args: unknown[]): void;
76
+ debug?(msg: string, ...args: unknown[]): void;
77
+ }
78
+ /**
79
+ * Normalize a flow's raw `schedule` descriptor into a {@link JobSchedule}, or
80
+ * `null` if it can't be understood. Accepts the canonical
81
+ * `{ type: 'cron'|'interval'|'once', ... }` shape plus a few ergonomic
82
+ * shorthands (a bare cron string, `{ cron }`, `{ expression }`, `{ every }` /
83
+ * `{ intervalMs }`, `{ at }`).
84
+ */
85
+ declare function normalizeSchedule(raw: unknown): JobSchedule | null;
86
+ /**
87
+ * ScheduleTrigger
88
+ *
89
+ * Bridges the automation engine's {@link FlowTrigger} extension point to the
90
+ * platform {@link JobServiceSurface}. For each schedule-triggered flow the
91
+ * engine activates, it registers a job whose handler runs the flow; the job
92
+ * service owns the actual cron/interval/once timing (so this trigger stays
93
+ * adapter-agnostic — cron schedules need a cron-capable adapter, which the
94
+ * job service selects).
95
+ *
96
+ * The job service is resolved lazily (per `start()`) via the supplied accessor,
97
+ * so we always pick up the job service's *upgraded* adapter (e.g. the durable
98
+ * DbJobAdapter that replaces the bootstrap interval adapter on `kernel:ready`).
99
+ */
100
+ declare class ScheduleTrigger implements FlowTrigger {
101
+ readonly type = "schedule";
102
+ private readonly getJobService;
103
+ private readonly logger;
104
+ /** flowName → job name registered for it, so stop() can cancel it. */
105
+ private readonly bound;
106
+ constructor(getJobService: () => JobServiceSurface | null, logger: TriggerLogger);
107
+ start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void;
108
+ stop(flowName: string): void;
109
+ }
110
+
111
+ export { type FlowTrigger, type FlowTriggerBinding, type JobServiceSurface, ScheduleTrigger, ScheduleTriggerPlugin, type TriggerLogger, normalizeSchedule };
@@ -0,0 +1,111 @@
1
+ import { Plugin, PluginContext } from '@objectstack/core';
2
+ import { AutomationContext, JobSchedule, JobHandler } from '@objectstack/spec/contracts';
3
+
4
+ /**
5
+ * ScheduleTriggerPlugin
6
+ *
7
+ * Makes schedule-triggered flows actually fire. The automation engine ships the
8
+ * `FlowTrigger` wiring (it parses each flow's start node — `flow.type ===
9
+ * 'schedule'` or a start-node `config.schedule` descriptor — into a binding and
10
+ * calls `trigger.start(...)`), but the *concrete* schedule trigger lives here as
11
+ * a plugin and delegates timing to the platform `IJobService` (the `'job'`
12
+ * service). This mirrors the connector / record-change split (engine baseline +
13
+ * trigger plugin).
14
+ *
15
+ * With this plugin (and a job service) installed, a flow whose start node
16
+ * declares `config: { schedule: { type: 'cron', expression: '0 1 * * *' } }`
17
+ * auto-launches on that schedule — no manual `engine.execute()`.
18
+ *
19
+ * Depends on the job service plugin so its `kernel:ready` upgrade (to the
20
+ * durable DbJobAdapter) runs before ours; the job service is nonetheless
21
+ * resolved lazily per `start()` so we always use its current adapter.
22
+ */
23
+ declare class ScheduleTriggerPlugin implements Plugin {
24
+ name: string;
25
+ type: string;
26
+ version: string;
27
+ dependencies: string[];
28
+ init(ctx: PluginContext): Promise<void>;
29
+ start(ctx: PluginContext): Promise<void>;
30
+ private resolveService;
31
+ }
32
+
33
+ /**
34
+ * Structural mirror of the automation engine's `FlowTriggerBinding`
35
+ * (service-automation/src/engine.ts). Declared locally so this trigger plugin
36
+ * stays decoupled from the automation package — same pattern the record-change
37
+ * trigger and the connector / messaging integrations use. The engine parses the
38
+ * flow's start node and hands us a binding whose `schedule` carries the
39
+ * cron/interval/once descriptor.
40
+ */
41
+ interface FlowTriggerBinding {
42
+ readonly flowName: string;
43
+ readonly object?: string;
44
+ readonly event?: string;
45
+ readonly condition?: string | {
46
+ dialect?: string;
47
+ source?: string;
48
+ ast?: unknown;
49
+ };
50
+ readonly schedule?: unknown;
51
+ readonly config?: Record<string, unknown>;
52
+ }
53
+ /**
54
+ * Structural mirror of the engine's `FlowTrigger` extension point. The engine
55
+ * calls {@link start} with a parsed binding + a callback that runs the flow,
56
+ * and {@link stop} when the flow is unregistered/disabled.
57
+ */
58
+ interface FlowTrigger {
59
+ readonly type: string;
60
+ start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void;
61
+ stop(flowName: string): void;
62
+ }
63
+ /**
64
+ * The slice of `IJobService` this trigger needs: schedule a named job and
65
+ * cancel it. Typed structurally so the plugin depends on the spec contract
66
+ * shape, not a concrete adapter.
67
+ */
68
+ interface JobServiceSurface {
69
+ schedule(name: string, schedule: JobSchedule, handler: JobHandler): Promise<void>;
70
+ cancel(name: string): Promise<void>;
71
+ }
72
+ /** Minimal logger surface (matches core's `ctx.logger`). */
73
+ interface TriggerLogger {
74
+ info(msg: string, ...args: unknown[]): void;
75
+ warn(msg: string, ...args: unknown[]): void;
76
+ debug?(msg: string, ...args: unknown[]): void;
77
+ }
78
+ /**
79
+ * Normalize a flow's raw `schedule` descriptor into a {@link JobSchedule}, or
80
+ * `null` if it can't be understood. Accepts the canonical
81
+ * `{ type: 'cron'|'interval'|'once', ... }` shape plus a few ergonomic
82
+ * shorthands (a bare cron string, `{ cron }`, `{ expression }`, `{ every }` /
83
+ * `{ intervalMs }`, `{ at }`).
84
+ */
85
+ declare function normalizeSchedule(raw: unknown): JobSchedule | null;
86
+ /**
87
+ * ScheduleTrigger
88
+ *
89
+ * Bridges the automation engine's {@link FlowTrigger} extension point to the
90
+ * platform {@link JobServiceSurface}. For each schedule-triggered flow the
91
+ * engine activates, it registers a job whose handler runs the flow; the job
92
+ * service owns the actual cron/interval/once timing (so this trigger stays
93
+ * adapter-agnostic — cron schedules need a cron-capable adapter, which the
94
+ * job service selects).
95
+ *
96
+ * The job service is resolved lazily (per `start()`) via the supplied accessor,
97
+ * so we always pick up the job service's *upgraded* adapter (e.g. the durable
98
+ * DbJobAdapter that replaces the bootstrap interval adapter on `kernel:ready`).
99
+ */
100
+ declare class ScheduleTrigger implements FlowTrigger {
101
+ readonly type = "schedule";
102
+ private readonly getJobService;
103
+ private readonly logger;
104
+ /** flowName → job name registered for it, so stop() can cancel it. */
105
+ private readonly bound;
106
+ constructor(getJobService: () => JobServiceSurface | null, logger: TriggerLogger);
107
+ start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void;
108
+ stop(flowName: string): void;
109
+ }
110
+
111
+ export { type FlowTrigger, type FlowTriggerBinding, type JobServiceSurface, ScheduleTrigger, ScheduleTriggerPlugin, type TriggerLogger, normalizeSchedule };
package/dist/index.js ADDED
@@ -0,0 +1,175 @@
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
+ ScheduleTrigger: () => ScheduleTrigger,
24
+ ScheduleTriggerPlugin: () => ScheduleTriggerPlugin,
25
+ normalizeSchedule: () => normalizeSchedule
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/schedule-trigger.ts
30
+ var JOB_PREFIX = "flow-schedule";
31
+ function normalizeSchedule(raw) {
32
+ if (raw == null) return null;
33
+ if (typeof raw === "string") {
34
+ const expr = raw.trim();
35
+ return expr ? { type: "cron", expression: expr } : null;
36
+ }
37
+ if (typeof raw !== "object") return null;
38
+ const s = raw;
39
+ const type = typeof s.type === "string" ? s.type : void 0;
40
+ if (type === "cron" || !type && (typeof s.cron === "string" || typeof s.expression === "string")) {
41
+ const expression = typeof s.expression === "string" && s.expression || typeof s.cron === "string" && s.cron || void 0;
42
+ if (!expression) return null;
43
+ const out = { type: "cron", expression };
44
+ if (typeof s.timezone === "string") out.timezone = s.timezone;
45
+ return out;
46
+ }
47
+ if (type === "interval" || !type && (typeof s.intervalMs === "number" || typeof s.every === "number")) {
48
+ const intervalMs = typeof s.intervalMs === "number" && s.intervalMs || typeof s.every === "number" && s.every || void 0;
49
+ if (!intervalMs || intervalMs <= 0) return null;
50
+ return { type: "interval", intervalMs };
51
+ }
52
+ if (type === "once" || !type && typeof s.at === "string") {
53
+ const at = typeof s.at === "string" ? s.at : void 0;
54
+ if (!at) return null;
55
+ return { type: "once", at };
56
+ }
57
+ return null;
58
+ }
59
+ var ScheduleTrigger = class {
60
+ constructor(getJobService, logger) {
61
+ this.type = "schedule";
62
+ /** flowName → job name registered for it, so stop() can cancel it. */
63
+ this.bound = /* @__PURE__ */ new Map();
64
+ this.getJobService = getJobService;
65
+ this.logger = logger;
66
+ }
67
+ start(binding, callback) {
68
+ const raw = binding.schedule ?? binding.config?.schedule;
69
+ const schedule = normalizeSchedule(raw);
70
+ if (!schedule) {
71
+ this.logger.warn(
72
+ `[schedule] flow '${binding.flowName}' has no recognizable schedule descriptor \u2014 not bound`
73
+ );
74
+ return;
75
+ }
76
+ const jobService = this.getJobService();
77
+ if (!jobService || typeof jobService.schedule !== "function") {
78
+ this.logger.warn(
79
+ `[schedule] job service unavailable \u2014 flow '${binding.flowName}' not scheduled`
80
+ );
81
+ return;
82
+ }
83
+ this.stop(binding.flowName);
84
+ const jobName = `${JOB_PREFIX}:${binding.flowName}`;
85
+ const handler = async ({ jobId }) => {
86
+ try {
87
+ const ctx = {
88
+ event: "schedule",
89
+ params: {
90
+ jobId,
91
+ flowName: binding.flowName,
92
+ schedule
93
+ }
94
+ };
95
+ await callback(ctx);
96
+ } catch (err) {
97
+ this.logger.warn(
98
+ `[schedule] flow '${binding.flowName}' execution failed: ${err?.message ?? String(err)}`
99
+ );
100
+ }
101
+ };
102
+ this.bound.set(binding.flowName, jobName);
103
+ void Promise.resolve(jobService.schedule(jobName, schedule, handler)).then(() => {
104
+ this.logger.info(
105
+ `[schedule] bound flow '${binding.flowName}' \u2192 ${schedule.type}` + (schedule.expression ? ` '${schedule.expression}'` : "") + (schedule.intervalMs ? ` every ${schedule.intervalMs}ms` : "") + (schedule.at ? ` at ${schedule.at}` : "")
106
+ );
107
+ }).catch((err) => {
108
+ this.bound.delete(binding.flowName);
109
+ this.logger.warn(
110
+ `[schedule] failed to schedule flow '${binding.flowName}': ${err?.message ?? String(err)}`
111
+ );
112
+ });
113
+ }
114
+ stop(flowName) {
115
+ const jobName = this.bound.get(flowName);
116
+ if (!jobName) return;
117
+ this.bound.delete(flowName);
118
+ const jobService = this.getJobService();
119
+ if (!jobService || typeof jobService.cancel !== "function") return;
120
+ void Promise.resolve(jobService.cancel(jobName)).then(() => this.logger.debug?.(`[schedule] unbound flow '${flowName}'`)).catch((err) => {
121
+ this.logger.warn(
122
+ `[schedule] failed to unbind flow '${flowName}': ${err?.message ?? String(err)}`
123
+ );
124
+ });
125
+ }
126
+ };
127
+
128
+ // src/plugin.ts
129
+ var ScheduleTriggerPlugin = class {
130
+ constructor() {
131
+ this.name = "com.objectstack.trigger.schedule";
132
+ this.type = "standard";
133
+ this.version = "7.3.0";
134
+ this.dependencies = ["com.objectstack.service.job"];
135
+ }
136
+ async init(ctx) {
137
+ ctx.logger.info("Schedule trigger plugin initialized");
138
+ }
139
+ async start(ctx) {
140
+ ctx.hook("kernel:ready", async () => {
141
+ const automation = this.resolveService(ctx, "automation");
142
+ if (!automation || typeof automation.registerTrigger !== "function") {
143
+ ctx.logger.warn(
144
+ "ScheduleTriggerPlugin: automation service not available \u2014 schedule trigger NOT installed"
145
+ );
146
+ return;
147
+ }
148
+ if (!this.resolveService(ctx, "job")) {
149
+ ctx.logger.warn(
150
+ "ScheduleTriggerPlugin: job service not available \u2014 scheduled flows will not run until one is registered"
151
+ );
152
+ }
153
+ const trigger = new ScheduleTrigger(
154
+ () => this.resolveService(ctx, "job"),
155
+ ctx.logger
156
+ );
157
+ automation.registerTrigger(trigger);
158
+ ctx.logger.info("ScheduleTriggerPlugin: schedule trigger registered");
159
+ });
160
+ }
161
+ resolveService(ctx, name) {
162
+ try {
163
+ return ctx.getService(name) ?? null;
164
+ } catch {
165
+ return null;
166
+ }
167
+ }
168
+ };
169
+ // Annotate the CommonJS export names for ESM import in node:
170
+ 0 && (module.exports = {
171
+ ScheduleTrigger,
172
+ ScheduleTriggerPlugin,
173
+ normalizeSchedule
174
+ });
175
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/schedule-trigger.ts","../src/plugin.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport { ScheduleTriggerPlugin } from './plugin.js';\nexport { ScheduleTrigger, normalizeSchedule } from './schedule-trigger.js';\nexport type {\n FlowTrigger,\n FlowTriggerBinding,\n JobServiceSurface,\n TriggerLogger,\n} from './schedule-trigger.js';\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { AutomationContext } from '@objectstack/spec/contracts';\nimport type { JobSchedule, JobHandler } from '@objectstack/spec/contracts';\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 record-change\n * trigger and the connector / messaging integrations use. The engine parses the\n * flow's start node and hands us a binding whose `schedule` carries the\n * cron/interval/once descriptor.\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 `IJobService` this trigger needs: schedule a named job and\n * cancel it. Typed structurally so the plugin depends on the spec contract\n * shape, not a concrete adapter.\n */\nexport interface JobServiceSurface {\n schedule(name: string, schedule: JobSchedule, handler: JobHandler): Promise<void>;\n cancel(name: string): Promise<void>;\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 JOB_PREFIX = 'flow-schedule';\n\n/**\n * Normalize a flow's raw `schedule` descriptor into a {@link JobSchedule}, or\n * `null` if it can't be understood. Accepts the canonical\n * `{ type: 'cron'|'interval'|'once', ... }` shape plus a few ergonomic\n * shorthands (a bare cron string, `{ cron }`, `{ expression }`, `{ every }` /\n * `{ intervalMs }`, `{ at }`).\n */\nexport function normalizeSchedule(raw: unknown): JobSchedule | null {\n if (raw == null) return null;\n\n // Bare cron string, e.g. '0 1 * * *'.\n if (typeof raw === 'string') {\n const expr = raw.trim();\n return expr ? { type: 'cron', expression: expr } : null;\n }\n\n if (typeof raw !== 'object') return null;\n const s = raw as Record<string, unknown>;\n\n const type = typeof s.type === 'string' ? s.type : undefined;\n\n if (type === 'cron' || (!type && (typeof s.cron === 'string' || typeof s.expression === 'string'))) {\n const expression =\n (typeof s.expression === 'string' && s.expression) ||\n (typeof s.cron === 'string' && s.cron) ||\n undefined;\n if (!expression) return null;\n const out: JobSchedule = { type: 'cron', expression };\n if (typeof s.timezone === 'string') out.timezone = s.timezone;\n return out;\n }\n\n if (type === 'interval' || (!type && (typeof s.intervalMs === 'number' || typeof s.every === 'number'))) {\n const intervalMs =\n (typeof s.intervalMs === 'number' && s.intervalMs) ||\n (typeof s.every === 'number' && s.every) ||\n undefined;\n if (!intervalMs || intervalMs <= 0) return null;\n return { type: 'interval', intervalMs };\n }\n\n if (type === 'once' || (!type && typeof s.at === 'string')) {\n const at = typeof s.at === 'string' ? s.at : undefined;\n if (!at) return null;\n return { type: 'once', at };\n }\n\n return null;\n}\n\n/**\n * ScheduleTrigger\n *\n * Bridges the automation engine's {@link FlowTrigger} extension point to the\n * platform {@link JobServiceSurface}. For each schedule-triggered flow the\n * engine activates, it registers a job whose handler runs the flow; the job\n * service owns the actual cron/interval/once timing (so this trigger stays\n * adapter-agnostic — cron schedules need a cron-capable adapter, which the\n * job service selects).\n *\n * The job service is resolved lazily (per `start()`) via the supplied accessor,\n * so we always pick up the job service's *upgraded* adapter (e.g. the durable\n * DbJobAdapter that replaces the bootstrap interval adapter on `kernel:ready`).\n */\nexport class ScheduleTrigger implements FlowTrigger {\n readonly type = 'schedule';\n\n private readonly getJobService: () => JobServiceSurface | null;\n private readonly logger: TriggerLogger;\n /** flowName → job name registered for it, so stop() can cancel it. */\n private readonly bound = new Map<string, string>();\n\n constructor(getJobService: () => JobServiceSurface | null, logger: TriggerLogger) {\n this.getJobService = getJobService;\n this.logger = logger;\n }\n\n start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void {\n const raw = binding.schedule ?? (binding.config as Record<string, unknown> | undefined)?.schedule;\n const schedule = normalizeSchedule(raw);\n if (!schedule) {\n this.logger.warn(\n `[schedule] flow '${binding.flowName}' has no recognizable schedule descriptor — not bound`,\n );\n return;\n }\n\n const jobService = this.getJobService();\n if (!jobService || typeof jobService.schedule !== 'function') {\n this.logger.warn(\n `[schedule] job service unavailable — flow '${binding.flowName}' not scheduled`,\n );\n return;\n }\n\n // Idempotent: drop any prior schedule for this flow before re-binding\n // (covers disable→enable cycles and hot reload).\n this.stop(binding.flowName);\n\n const jobName = `${JOB_PREFIX}:${binding.flowName}`;\n\n const handler: JobHandler = async ({ jobId }) => {\n try {\n const ctx: AutomationContext = {\n event: 'schedule',\n params: {\n jobId,\n flowName: binding.flowName,\n schedule,\n },\n };\n await callback(ctx);\n } catch (err) {\n // Error isolation: a scheduled flow failure must not crash the\n // job runner / ticker. Log and swallow.\n this.logger.warn(\n `[schedule] flow '${binding.flowName}' execution failed: ${(err as Error)?.message ?? String(err)}`,\n );\n }\n };\n\n this.bound.set(binding.flowName, jobName);\n // FlowTrigger.start is sync; the job service's schedule() is async.\n // Fire-and-forget with error logging.\n void Promise.resolve(jobService.schedule(jobName, schedule, handler))\n .then(() => {\n this.logger.info(\n `[schedule] bound flow '${binding.flowName}' → ${schedule.type}` +\n (schedule.expression ? ` '${schedule.expression}'` : '') +\n (schedule.intervalMs ? ` every ${schedule.intervalMs}ms` : '') +\n (schedule.at ? ` at ${schedule.at}` : ''),\n );\n })\n .catch((err) => {\n this.bound.delete(binding.flowName);\n this.logger.warn(\n `[schedule] failed to schedule flow '${binding.flowName}': ${(err as Error)?.message ?? String(err)}`,\n );\n });\n }\n\n stop(flowName: string): void {\n const jobName = this.bound.get(flowName);\n if (!jobName) return;\n this.bound.delete(flowName);\n const jobService = this.getJobService();\n if (!jobService || typeof jobService.cancel !== 'function') return;\n void Promise.resolve(jobService.cancel(jobName))\n .then(() => this.logger.debug?.(`[schedule] unbound flow '${flowName}'`))\n .catch((err) => {\n this.logger.warn(\n `[schedule] failed to unbind flow '${flowName}': ${(err as Error)?.message ?? String(err)}`,\n );\n });\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport { ScheduleTrigger } from './schedule-trigger.js';\nimport type { FlowTrigger, JobServiceSurface } from './schedule-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 * ScheduleTriggerPlugin\n *\n * Makes schedule-triggered flows actually fire. The automation engine ships the\n * `FlowTrigger` wiring (it parses each flow's start node — `flow.type ===\n * 'schedule'` or a start-node `config.schedule` descriptor — into a binding and\n * calls `trigger.start(...)`), but the *concrete* schedule trigger lives here as\n * a plugin and delegates timing to the platform `IJobService` (the `'job'`\n * service). This mirrors the connector / record-change split (engine baseline +\n * trigger plugin).\n *\n * With this plugin (and a job service) installed, a flow whose start node\n * declares `config: { schedule: { type: 'cron', expression: '0 1 * * *' } }`\n * auto-launches on that schedule — no manual `engine.execute()`.\n *\n * Depends on the job service plugin so its `kernel:ready` upgrade (to the\n * durable DbJobAdapter) runs before ours; the job service is nonetheless\n * resolved lazily per `start()` so we always use its current adapter.\n */\nexport class ScheduleTriggerPlugin implements Plugin {\n name = 'com.objectstack.trigger.schedule';\n type = 'standard';\n version = '7.3.0';\n dependencies = ['com.objectstack.service.job'];\n\n async init(ctx: PluginContext): Promise<void> {\n ctx.logger.info('Schedule trigger plugin initialized');\n }\n\n async start(ctx: PluginContext): Promise<void> {\n // The automation service + job service are resolvable once the kernel is\n // ready (kernel:ready fires after AutomationServicePlugin.start() has\n // pulled flows in and after the job service upgrades its adapter).\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 'ScheduleTriggerPlugin: automation service not available — schedule trigger NOT installed',\n );\n return;\n }\n\n // Probe once for a clear startup warning; the trigger re-resolves\n // lazily on each start() so adapter upgrades are always picked up.\n if (!this.resolveService<JobServiceSurface>(ctx, 'job')) {\n ctx.logger.warn(\n 'ScheduleTriggerPlugin: job service not available — scheduled flows will not run until one is registered',\n );\n }\n\n const trigger = new ScheduleTrigger(\n () => this.resolveService<JobServiceSurface>(ctx, 'job'),\n ctx.logger,\n );\n automation.registerTrigger(trigger);\n ctx.logger.info('ScheduleTriggerPlugin: schedule 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"],"mappings":";;;;;;;;;;;;;;;;;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,YAAM,UAAU,IAAI;AAAA,QAChB,MAAM,KAAK,eAAkC,KAAK,KAAK;AAAA,QACvD,IAAI;AAAA,MACR;AACA,iBAAW,gBAAgB,OAAO;AAClC,UAAI,OAAO,KAAK,oDAAoD;AAAA,IACxE,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;AACJ;","names":[]}
package/dist/index.mjs ADDED
@@ -0,0 +1,146 @@
1
+ // src/schedule-trigger.ts
2
+ var JOB_PREFIX = "flow-schedule";
3
+ function normalizeSchedule(raw) {
4
+ if (raw == null) return null;
5
+ if (typeof raw === "string") {
6
+ const expr = raw.trim();
7
+ return expr ? { type: "cron", expression: expr } : null;
8
+ }
9
+ if (typeof raw !== "object") return null;
10
+ const s = raw;
11
+ const type = typeof s.type === "string" ? s.type : void 0;
12
+ if (type === "cron" || !type && (typeof s.cron === "string" || typeof s.expression === "string")) {
13
+ const expression = typeof s.expression === "string" && s.expression || typeof s.cron === "string" && s.cron || void 0;
14
+ if (!expression) return null;
15
+ const out = { type: "cron", expression };
16
+ if (typeof s.timezone === "string") out.timezone = s.timezone;
17
+ return out;
18
+ }
19
+ if (type === "interval" || !type && (typeof s.intervalMs === "number" || typeof s.every === "number")) {
20
+ const intervalMs = typeof s.intervalMs === "number" && s.intervalMs || typeof s.every === "number" && s.every || void 0;
21
+ if (!intervalMs || intervalMs <= 0) return null;
22
+ return { type: "interval", intervalMs };
23
+ }
24
+ if (type === "once" || !type && typeof s.at === "string") {
25
+ const at = typeof s.at === "string" ? s.at : void 0;
26
+ if (!at) return null;
27
+ return { type: "once", at };
28
+ }
29
+ return null;
30
+ }
31
+ var ScheduleTrigger = class {
32
+ constructor(getJobService, logger) {
33
+ this.type = "schedule";
34
+ /** flowName → job name registered for it, so stop() can cancel it. */
35
+ this.bound = /* @__PURE__ */ new Map();
36
+ this.getJobService = getJobService;
37
+ this.logger = logger;
38
+ }
39
+ start(binding, callback) {
40
+ const raw = binding.schedule ?? binding.config?.schedule;
41
+ const schedule = normalizeSchedule(raw);
42
+ if (!schedule) {
43
+ this.logger.warn(
44
+ `[schedule] flow '${binding.flowName}' has no recognizable schedule descriptor \u2014 not bound`
45
+ );
46
+ return;
47
+ }
48
+ const jobService = this.getJobService();
49
+ if (!jobService || typeof jobService.schedule !== "function") {
50
+ this.logger.warn(
51
+ `[schedule] job service unavailable \u2014 flow '${binding.flowName}' not scheduled`
52
+ );
53
+ return;
54
+ }
55
+ this.stop(binding.flowName);
56
+ const jobName = `${JOB_PREFIX}:${binding.flowName}`;
57
+ const handler = async ({ jobId }) => {
58
+ try {
59
+ const ctx = {
60
+ event: "schedule",
61
+ params: {
62
+ jobId,
63
+ flowName: binding.flowName,
64
+ schedule
65
+ }
66
+ };
67
+ await callback(ctx);
68
+ } catch (err) {
69
+ this.logger.warn(
70
+ `[schedule] flow '${binding.flowName}' execution failed: ${err?.message ?? String(err)}`
71
+ );
72
+ }
73
+ };
74
+ this.bound.set(binding.flowName, jobName);
75
+ void Promise.resolve(jobService.schedule(jobName, schedule, handler)).then(() => {
76
+ this.logger.info(
77
+ `[schedule] bound flow '${binding.flowName}' \u2192 ${schedule.type}` + (schedule.expression ? ` '${schedule.expression}'` : "") + (schedule.intervalMs ? ` every ${schedule.intervalMs}ms` : "") + (schedule.at ? ` at ${schedule.at}` : "")
78
+ );
79
+ }).catch((err) => {
80
+ this.bound.delete(binding.flowName);
81
+ this.logger.warn(
82
+ `[schedule] failed to schedule flow '${binding.flowName}': ${err?.message ?? String(err)}`
83
+ );
84
+ });
85
+ }
86
+ stop(flowName) {
87
+ const jobName = this.bound.get(flowName);
88
+ if (!jobName) return;
89
+ this.bound.delete(flowName);
90
+ const jobService = this.getJobService();
91
+ if (!jobService || typeof jobService.cancel !== "function") return;
92
+ void Promise.resolve(jobService.cancel(jobName)).then(() => this.logger.debug?.(`[schedule] unbound flow '${flowName}'`)).catch((err) => {
93
+ this.logger.warn(
94
+ `[schedule] failed to unbind flow '${flowName}': ${err?.message ?? String(err)}`
95
+ );
96
+ });
97
+ }
98
+ };
99
+
100
+ // src/plugin.ts
101
+ var ScheduleTriggerPlugin = class {
102
+ constructor() {
103
+ this.name = "com.objectstack.trigger.schedule";
104
+ this.type = "standard";
105
+ this.version = "7.3.0";
106
+ this.dependencies = ["com.objectstack.service.job"];
107
+ }
108
+ async init(ctx) {
109
+ ctx.logger.info("Schedule trigger plugin initialized");
110
+ }
111
+ async start(ctx) {
112
+ ctx.hook("kernel:ready", async () => {
113
+ const automation = this.resolveService(ctx, "automation");
114
+ if (!automation || typeof automation.registerTrigger !== "function") {
115
+ ctx.logger.warn(
116
+ "ScheduleTriggerPlugin: automation service not available \u2014 schedule trigger NOT installed"
117
+ );
118
+ return;
119
+ }
120
+ if (!this.resolveService(ctx, "job")) {
121
+ ctx.logger.warn(
122
+ "ScheduleTriggerPlugin: job service not available \u2014 scheduled flows will not run until one is registered"
123
+ );
124
+ }
125
+ const trigger = new ScheduleTrigger(
126
+ () => this.resolveService(ctx, "job"),
127
+ ctx.logger
128
+ );
129
+ automation.registerTrigger(trigger);
130
+ ctx.logger.info("ScheduleTriggerPlugin: schedule trigger registered");
131
+ });
132
+ }
133
+ resolveService(ctx, name) {
134
+ try {
135
+ return ctx.getService(name) ?? null;
136
+ } catch {
137
+ return null;
138
+ }
139
+ }
140
+ };
141
+ export {
142
+ ScheduleTrigger,
143
+ ScheduleTriggerPlugin,
144
+ normalizeSchedule
145
+ };
146
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schedule-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 { JobSchedule, JobHandler } from '@objectstack/spec/contracts';\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 record-change\n * trigger and the connector / messaging integrations use. The engine parses the\n * flow's start node and hands us a binding whose `schedule` carries the\n * cron/interval/once descriptor.\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 `IJobService` this trigger needs: schedule a named job and\n * cancel it. Typed structurally so the plugin depends on the spec contract\n * shape, not a concrete adapter.\n */\nexport interface JobServiceSurface {\n schedule(name: string, schedule: JobSchedule, handler: JobHandler): Promise<void>;\n cancel(name: string): Promise<void>;\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 JOB_PREFIX = 'flow-schedule';\n\n/**\n * Normalize a flow's raw `schedule` descriptor into a {@link JobSchedule}, or\n * `null` if it can't be understood. Accepts the canonical\n * `{ type: 'cron'|'interval'|'once', ... }` shape plus a few ergonomic\n * shorthands (a bare cron string, `{ cron }`, `{ expression }`, `{ every }` /\n * `{ intervalMs }`, `{ at }`).\n */\nexport function normalizeSchedule(raw: unknown): JobSchedule | null {\n if (raw == null) return null;\n\n // Bare cron string, e.g. '0 1 * * *'.\n if (typeof raw === 'string') {\n const expr = raw.trim();\n return expr ? { type: 'cron', expression: expr } : null;\n }\n\n if (typeof raw !== 'object') return null;\n const s = raw as Record<string, unknown>;\n\n const type = typeof s.type === 'string' ? s.type : undefined;\n\n if (type === 'cron' || (!type && (typeof s.cron === 'string' || typeof s.expression === 'string'))) {\n const expression =\n (typeof s.expression === 'string' && s.expression) ||\n (typeof s.cron === 'string' && s.cron) ||\n undefined;\n if (!expression) return null;\n const out: JobSchedule = { type: 'cron', expression };\n if (typeof s.timezone === 'string') out.timezone = s.timezone;\n return out;\n }\n\n if (type === 'interval' || (!type && (typeof s.intervalMs === 'number' || typeof s.every === 'number'))) {\n const intervalMs =\n (typeof s.intervalMs === 'number' && s.intervalMs) ||\n (typeof s.every === 'number' && s.every) ||\n undefined;\n if (!intervalMs || intervalMs <= 0) return null;\n return { type: 'interval', intervalMs };\n }\n\n if (type === 'once' || (!type && typeof s.at === 'string')) {\n const at = typeof s.at === 'string' ? s.at : undefined;\n if (!at) return null;\n return { type: 'once', at };\n }\n\n return null;\n}\n\n/**\n * ScheduleTrigger\n *\n * Bridges the automation engine's {@link FlowTrigger} extension point to the\n * platform {@link JobServiceSurface}. For each schedule-triggered flow the\n * engine activates, it registers a job whose handler runs the flow; the job\n * service owns the actual cron/interval/once timing (so this trigger stays\n * adapter-agnostic — cron schedules need a cron-capable adapter, which the\n * job service selects).\n *\n * The job service is resolved lazily (per `start()`) via the supplied accessor,\n * so we always pick up the job service's *upgraded* adapter (e.g. the durable\n * DbJobAdapter that replaces the bootstrap interval adapter on `kernel:ready`).\n */\nexport class ScheduleTrigger implements FlowTrigger {\n readonly type = 'schedule';\n\n private readonly getJobService: () => JobServiceSurface | null;\n private readonly logger: TriggerLogger;\n /** flowName → job name registered for it, so stop() can cancel it. */\n private readonly bound = new Map<string, string>();\n\n constructor(getJobService: () => JobServiceSurface | null, logger: TriggerLogger) {\n this.getJobService = getJobService;\n this.logger = logger;\n }\n\n start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void {\n const raw = binding.schedule ?? (binding.config as Record<string, unknown> | undefined)?.schedule;\n const schedule = normalizeSchedule(raw);\n if (!schedule) {\n this.logger.warn(\n `[schedule] flow '${binding.flowName}' has no recognizable schedule descriptor — not bound`,\n );\n return;\n }\n\n const jobService = this.getJobService();\n if (!jobService || typeof jobService.schedule !== 'function') {\n this.logger.warn(\n `[schedule] job service unavailable — flow '${binding.flowName}' not scheduled`,\n );\n return;\n }\n\n // Idempotent: drop any prior schedule for this flow before re-binding\n // (covers disable→enable cycles and hot reload).\n this.stop(binding.flowName);\n\n const jobName = `${JOB_PREFIX}:${binding.flowName}`;\n\n const handler: JobHandler = async ({ jobId }) => {\n try {\n const ctx: AutomationContext = {\n event: 'schedule',\n params: {\n jobId,\n flowName: binding.flowName,\n schedule,\n },\n };\n await callback(ctx);\n } catch (err) {\n // Error isolation: a scheduled flow failure must not crash the\n // job runner / ticker. Log and swallow.\n this.logger.warn(\n `[schedule] flow '${binding.flowName}' execution failed: ${(err as Error)?.message ?? String(err)}`,\n );\n }\n };\n\n this.bound.set(binding.flowName, jobName);\n // FlowTrigger.start is sync; the job service's schedule() is async.\n // Fire-and-forget with error logging.\n void Promise.resolve(jobService.schedule(jobName, schedule, handler))\n .then(() => {\n this.logger.info(\n `[schedule] bound flow '${binding.flowName}' → ${schedule.type}` +\n (schedule.expression ? ` '${schedule.expression}'` : '') +\n (schedule.intervalMs ? ` every ${schedule.intervalMs}ms` : '') +\n (schedule.at ? ` at ${schedule.at}` : ''),\n );\n })\n .catch((err) => {\n this.bound.delete(binding.flowName);\n this.logger.warn(\n `[schedule] failed to schedule flow '${binding.flowName}': ${(err as Error)?.message ?? String(err)}`,\n );\n });\n }\n\n stop(flowName: string): void {\n const jobName = this.bound.get(flowName);\n if (!jobName) return;\n this.bound.delete(flowName);\n const jobService = this.getJobService();\n if (!jobService || typeof jobService.cancel !== 'function') return;\n void Promise.resolve(jobService.cancel(jobName))\n .then(() => this.logger.debug?.(`[schedule] unbound flow '${flowName}'`))\n .catch((err) => {\n this.logger.warn(\n `[schedule] failed to unbind flow '${flowName}': ${(err as Error)?.message ?? String(err)}`,\n );\n });\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport type { Plugin, PluginContext } from '@objectstack/core';\nimport { ScheduleTrigger } from './schedule-trigger.js';\nimport type { FlowTrigger, JobServiceSurface } from './schedule-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 * ScheduleTriggerPlugin\n *\n * Makes schedule-triggered flows actually fire. The automation engine ships the\n * `FlowTrigger` wiring (it parses each flow's start node — `flow.type ===\n * 'schedule'` or a start-node `config.schedule` descriptor — into a binding and\n * calls `trigger.start(...)`), but the *concrete* schedule trigger lives here as\n * a plugin and delegates timing to the platform `IJobService` (the `'job'`\n * service). This mirrors the connector / record-change split (engine baseline +\n * trigger plugin).\n *\n * With this plugin (and a job service) installed, a flow whose start node\n * declares `config: { schedule: { type: 'cron', expression: '0 1 * * *' } }`\n * auto-launches on that schedule — no manual `engine.execute()`.\n *\n * Depends on the job service plugin so its `kernel:ready` upgrade (to the\n * durable DbJobAdapter) runs before ours; the job service is nonetheless\n * resolved lazily per `start()` so we always use its current adapter.\n */\nexport class ScheduleTriggerPlugin implements Plugin {\n name = 'com.objectstack.trigger.schedule';\n type = 'standard';\n version = '7.3.0';\n dependencies = ['com.objectstack.service.job'];\n\n async init(ctx: PluginContext): Promise<void> {\n ctx.logger.info('Schedule trigger plugin initialized');\n }\n\n async start(ctx: PluginContext): Promise<void> {\n // The automation service + job service are resolvable once the kernel is\n // ready (kernel:ready fires after AutomationServicePlugin.start() has\n // pulled flows in and after the job service upgrades its adapter).\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 'ScheduleTriggerPlugin: automation service not available — schedule trigger NOT installed',\n );\n return;\n }\n\n // Probe once for a clear startup warning; the trigger re-resolves\n // lazily on each start() so adapter upgrades are always picked up.\n if (!this.resolveService<JobServiceSurface>(ctx, 'job')) {\n ctx.logger.warn(\n 'ScheduleTriggerPlugin: job service not available — scheduled flows will not run until one is registered',\n );\n }\n\n const trigger = new ScheduleTrigger(\n () => this.resolveService<JobServiceSurface>(ctx, 'job'),\n ctx.logger,\n );\n automation.registerTrigger(trigger);\n ctx.logger.info('ScheduleTriggerPlugin: schedule 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"],"mappings":";AAkDA,IAAM,aAAa;AASZ,SAAS,kBAAkB,KAAkC;AAChE,MAAI,OAAO,KAAM,QAAO;AAGxB,MAAI,OAAO,QAAQ,UAAU;AACzB,UAAM,OAAO,IAAI,KAAK;AACtB,WAAO,OAAO,EAAE,MAAM,QAAQ,YAAY,KAAK,IAAI;AAAA,EACvD;AAEA,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAM,IAAI;AAEV,QAAM,OAAO,OAAO,EAAE,SAAS,WAAW,EAAE,OAAO;AAEnD,MAAI,SAAS,UAAW,CAAC,SAAS,OAAO,EAAE,SAAS,YAAY,OAAO,EAAE,eAAe,WAAY;AAChG,UAAM,aACD,OAAO,EAAE,eAAe,YAAY,EAAE,cACtC,OAAO,EAAE,SAAS,YAAY,EAAE,QACjC;AACJ,QAAI,CAAC,WAAY,QAAO;AACxB,UAAM,MAAmB,EAAE,MAAM,QAAQ,WAAW;AACpD,QAAI,OAAO,EAAE,aAAa,SAAU,KAAI,WAAW,EAAE;AACrD,WAAO;AAAA,EACX;AAEA,MAAI,SAAS,cAAe,CAAC,SAAS,OAAO,EAAE,eAAe,YAAY,OAAO,EAAE,UAAU,WAAY;AACrG,UAAM,aACD,OAAO,EAAE,eAAe,YAA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C,6BAA6B;AAAA;AAAA,EAE7C,MAAM,KAAK,KAAmC;AAC1C,QAAI,OAAO,KAAK,qCAAqC;AAAA,EACzD;AAAA,EAEA,MAAM,MAAM,KAAmC;AAI3C,QAAI,KAAK,gBAAgB,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;AAIA,UAAI,CAAC,KAAK,eAAkC,KAAK,KAAK,GAAG;AACrD,YAAI,OAAO;AAAA,UACP;AAAA,QACJ;AAAA,MACJ;AAEA,YAAM,UAAU,IAAI;AAAA,QAChB,MAAM,KAAK,eAAkC,KAAK,KAAK;AAAA,QACvD,IAAI;AAAA,MACR;AACA,iBAAW,gBAAgB,OAAO;AAClC,UAAI,OAAO,KAAK,oDAAoD;AAAA,IACxE,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;AACJ;","names":[]}
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@objectstack/plugin-trigger-schedule",
3
+ "version": "7.4.0",
4
+ "license": "Apache-2.0",
5
+ "description": "Schedule flow trigger for ObjectStack — auto-launches flows on a cron/interval/once schedule via the IJobService (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
+ "schedule",
31
+ "cron"
32
+ ],
33
+ "author": "ObjectStack",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "https://github.com/objectstack-ai/framework.git",
37
+ "directory": "packages/plugins/plugin-trigger-schedule"
38
+ },
39
+ "homepage": "https://objectstack.ai/docs",
40
+ "bugs": "https://github.com/objectstack-ai/framework/issues",
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "files": [
45
+ "dist",
46
+ "README.md"
47
+ ],
48
+ "engines": {
49
+ "node": ">=18.0.0"
50
+ },
51
+ "scripts": {
52
+ "build": "tsup --config ../../../tsup.config.ts",
53
+ "test": "vitest run --passWithNoTests"
54
+ }
55
+ }