@lafken/schedule 0.6.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/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Aníbal Emilio Jorquera Cornejo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # @lafken/schedule
2
+
3
+ `@lafken/schedule` simplifies the creation and management of Amazon EventBridge scheduled rules (Cron jobs) and their integration with AWS Lambda. It provides decorators to define scheduled tasks using standard cron expressions or structured time objects.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @lafken/schedule
9
+ ```
10
+
11
+ ## Configuration
12
+
13
+ Add the `ScheduleResolver` from the `@lafken/schedule/resolver` library to your application configuration.
14
+
15
+ ```typescript
16
+ import { ScheduleResolver } from '@lafken/schedule/resolver';
17
+
18
+ createApp({
19
+ name: 'awesome-app',
20
+ resolvers: [
21
+ new ScheduleResolver(),
22
+ ],
23
+ ...
24
+ });
25
+
26
+ // ...
27
+
28
+ @Schedule()
29
+ class GreetingSchedule {
30
+ // ...
31
+ }
32
+
33
+ const greetingModule = createModule({
34
+ name: 'greeting',
35
+ resources: [
36
+ GreetingSchedule
37
+ ]
38
+ });
39
+
40
+ ```
41
+
42
+ ## Features
43
+
44
+ ### Defining a Schedule Resource
45
+
46
+ Use the `@Schedule` decorator to define a class that contains scheduled tasks.
47
+
48
+ ```typescript
49
+ import { Schedule, Cron } from '@lafken/schedule';
50
+
51
+ @Schedule()
52
+ export class DataSyncService {
53
+ // ... cron handlers
54
+ }
55
+ ```
56
+
57
+ ### Defining Cron Tasks
58
+
59
+ Use the `@Cron` decorator to define a method as a scheduled task. You can configure the schedule using a standard cron string or a structured object.
60
+
61
+ #### Using Cron Strings
62
+
63
+ You can use standard AWS cron expressions: `cron(Minutes Hours Day-of-month Month Day-of-week Year)`.
64
+
65
+ ```typescript
66
+ @Cron({
67
+ schedule: 'cron(0 12 * * ? *)', // Run every day at 12:00 UTC
68
+ })
69
+ dailySync() {
70
+ console.log('Running daily sync...');
71
+ }
72
+ ```
73
+
74
+ #### Using Structured Schedule Objects
75
+
76
+ You can also define the schedule using a readable object format.
77
+
78
+ ```typescript
79
+ @Cron({
80
+ schedule: {
81
+ minute: '0',
82
+ hour: '8',
83
+ weekDay: 'MON-FRI',
84
+ },
85
+ })
86
+ weekdayStart() {
87
+ console.log('Starting weekday operations...');
88
+ }
89
+ ```
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './main';
2
+ export * from './resolver';
package/lib/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./main"), exports);
18
+ __exportStar(require("./resolver"), exports);
@@ -0,0 +1 @@
1
+ export * from './schedule';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./schedule"), exports);
@@ -0,0 +1,2 @@
1
+ export * from './schedule';
2
+ export * from './schedule.types';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./schedule"), exports);
18
+ __exportStar(require("./schedule.types"), exports);
@@ -0,0 +1,4 @@
1
+ import type { EventCronProps } from './schedule.types';
2
+ export declare const RESOURCE_TYPE: "CRON";
3
+ export declare const Schedule: (props?: import("@lafken/common").ResourceProps | undefined) => (constructor: Function) => void;
4
+ export declare const Cron: (props: EventCronProps) => (target: any, methodName: string, descriptor: PropertyDescriptor) => any;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Cron = exports.Schedule = exports.RESOURCE_TYPE = void 0;
4
+ const common_1 = require("@lafken/common");
5
+ exports.RESOURCE_TYPE = 'CRON';
6
+ exports.Schedule = (0, common_1.createResourceDecorator)({
7
+ type: exports.RESOURCE_TYPE,
8
+ callerFileIndex: 5,
9
+ });
10
+ const Cron = (props) => (0, common_1.createLambdaDecorator)({
11
+ getLambdaMetadata: (props, methodName) => ({
12
+ ...props,
13
+ name: methodName,
14
+ }),
15
+ })(props);
16
+ exports.Cron = Cron;
@@ -0,0 +1,42 @@
1
+ import type { LambdaMetadata } from '@lafken/common';
2
+ type ScheduleExpressions = number | '*' | '?' | (string & {});
3
+ export interface ScheduleTime {
4
+ day?: ScheduleExpressions;
5
+ hour?: ScheduleExpressions;
6
+ minute?: ScheduleExpressions;
7
+ month?: ScheduleExpressions;
8
+ weekDay?: ScheduleExpressions;
9
+ year?: ScheduleExpressions;
10
+ }
11
+ export interface EventCronProps {
12
+ /**
13
+ * Maximum event age.
14
+ *
15
+ * Specifies the maximum age of an event that can be sent to the rule's targets.
16
+ * Events older than this duration will be discarded.
17
+ */
18
+ maxEventAge?: number;
19
+ /**
20
+ * Retry attempts for failed events.
21
+ *
22
+ * Specifies the maximum number of times EventBridge will retry sending
23
+ * an event to the target if the initial attempt fails.
24
+ */
25
+ retryAttempts?: number;
26
+ /**
27
+ * Schedule for the EventBridge rule.
28
+ *
29
+ * Defines when the rule should trigger, either using a cron expression
30
+ * or a structured schedule object. This allows for time-based Lambda invocation
31
+ *
32
+ * You can provide:
33
+ * - A cron string in the standard AWS format: `cron(* * * * * *)`
34
+ * - A `ScheduleTime` object to specify individual fields:
35
+ * - `minute`, `hour`, `day`, `month`, `weekDay`, `year`
36
+ * - Each field can be a number, '*', '?', a range `${number}-${number}`
37
+ */
38
+ schedule: string | ScheduleTime;
39
+ }
40
+ export interface EventCronMetadata extends LambdaMetadata, EventCronProps {
41
+ }
42
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,16 @@
1
+ import { CloudwatchEventRule } from '@cdktf/provider-aws/lib/cloudwatch-event-rule';
2
+ import { type AppModule } from '@lafken/resolver';
3
+ import type { CronProps } from './cron.types';
4
+ declare const Cron_base: (new (...args: any[]) => {
5
+ isGlobal(module: import("@lafken/common").ModuleGlobalReferenceNames | (string & {}), id: string): void;
6
+ isDependent(resolveDependency: () => void): void;
7
+ readonly node: import("constructs").Node;
8
+ toString(): string;
9
+ }) & typeof CloudwatchEventRule;
10
+ export declare class Cron extends Cron_base {
11
+ private props;
12
+ constructor(scope: AppModule, id: string, props: CronProps);
13
+ addEventTarget(id: string): void;
14
+ private static buildScheduleExpression;
15
+ }
16
+ export {};
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Cron = void 0;
4
+ const cloudwatch_event_rule_1 = require("@cdktf/provider-aws/lib/cloudwatch-event-rule");
5
+ const cloudwatch_event_target_1 = require("@cdktf/provider-aws/lib/cloudwatch-event-target");
6
+ const resolver_1 = require("@lafken/resolver");
7
+ class Cron extends resolver_1.lafkenResource.make(cloudwatch_event_rule_1.CloudwatchEventRule) {
8
+ props;
9
+ constructor(scope, id, props) {
10
+ const { handler } = props;
11
+ super(scope, `${handler.name}-cron`, {
12
+ name: handler.name,
13
+ scheduleExpression: Cron.buildScheduleExpression(handler.schedule),
14
+ });
15
+ this.props = props;
16
+ this.isGlobal(scope.id, id);
17
+ this.addEventTarget(id);
18
+ }
19
+ addEventTarget(id) {
20
+ const { handler, resourceMetadata } = this.props;
21
+ const lambdaHandler = new resolver_1.LambdaHandler(this, `${handler.name}-${resourceMetadata.name}`, {
22
+ ...handler,
23
+ originalName: resourceMetadata.originalName,
24
+ filename: resourceMetadata.filename,
25
+ foldername: resourceMetadata.foldername,
26
+ suffix: 'event',
27
+ principal: 'events.amazonaws.com',
28
+ });
29
+ new cloudwatch_event_target_1.CloudwatchEventTarget(this, `${id}-event-target`, {
30
+ rule: this.name,
31
+ arn: lambdaHandler.arn,
32
+ retryPolicy: {
33
+ maximumRetryAttempts: handler.retryAttempts,
34
+ maximumEventAgeInSeconds: handler.maxEventAge,
35
+ },
36
+ });
37
+ }
38
+ static buildScheduleExpression(schedule) {
39
+ if (typeof schedule === 'string') {
40
+ return `cron(${schedule})`;
41
+ }
42
+ const { minute = '*', hour = '*', day = '*', month = '*', year = '*', weekDay = '*', } = schedule;
43
+ let dayValue;
44
+ let weekDayValue;
45
+ if (day && day !== '*' && day !== '?') {
46
+ dayValue = day.toString();
47
+ weekDayValue = '?';
48
+ }
49
+ else if (weekDay && weekDay !== '*' && weekDay !== '?') {
50
+ dayValue = '?';
51
+ weekDayValue = weekDay.toString();
52
+ }
53
+ else {
54
+ dayValue = day?.toString() ?? '*';
55
+ weekDayValue = '?';
56
+ }
57
+ return `cron(${minute} ${hour} ${dayValue} ${month} ${weekDayValue} ${year})`;
58
+ }
59
+ }
60
+ exports.Cron = Cron;
@@ -0,0 +1,6 @@
1
+ import type { ResourceMetadata } from '@lafken/common';
2
+ import type { EventCronMetadata } from '../../main';
3
+ export interface CronProps {
4
+ resourceMetadata: ResourceMetadata;
5
+ handler: EventCronMetadata;
6
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+ export * from './resolver';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./resolver"), exports);
@@ -0,0 +1,6 @@
1
+ import { type ClassResource } from '@lafken/common';
2
+ import { type AppModule, type ResolverType } from '@lafken/resolver';
3
+ export declare class ScheduleResolver implements ResolverType {
4
+ type: "CRON";
5
+ create(module: AppModule, resource: ClassResource): void;
6
+ }
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ScheduleResolver = void 0;
4
+ const common_1 = require("@lafken/common");
5
+ const resolver_1 = require("@lafken/resolver");
6
+ const main_1 = require("../main");
7
+ const cron_1 = require("./cron/cron");
8
+ class ScheduleResolver {
9
+ type = main_1.RESOURCE_TYPE;
10
+ create(module, resource) {
11
+ const metadata = (0, common_1.getResourceMetadata)(resource);
12
+ const handlers = (0, common_1.getResourceHandlerMetadata)(resource);
13
+ resolver_1.lambdaAssets.initializeMetadata({
14
+ foldername: metadata.foldername,
15
+ filename: metadata.filename,
16
+ minify: metadata.minify,
17
+ className: metadata.originalName,
18
+ methods: handlers.map((handler) => handler.name),
19
+ });
20
+ for (const handler of handlers) {
21
+ const id = `${handler.name}-${metadata.name}`;
22
+ new cron_1.Cron(module, id, {
23
+ handler,
24
+ resourceMetadata: metadata,
25
+ });
26
+ }
27
+ }
28
+ }
29
+ exports.ScheduleResolver = ScheduleResolver;
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@lafken/schedule",
3
+ "version": "0.6.0",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "exports": {
7
+ "./main": {
8
+ "import": "./lib/main/index.js",
9
+ "types": "./lib/main/index.d.ts",
10
+ "require": "./lib/main/index.js"
11
+ },
12
+ "./resolver": {
13
+ "import": "./lib/resolver/index.js",
14
+ "types": "./lib/resolver/index.d.ts",
15
+ "require": "./lib/resolver/index.js"
16
+ }
17
+ },
18
+ "typesVersions": {
19
+ "*": {
20
+ "main": [
21
+ "./lib/main/index.d.ts"
22
+ ],
23
+ "resolver": [
24
+ "./lib/resolver/index.d.ts"
25
+ ]
26
+ }
27
+ },
28
+ "files": [
29
+ "lib"
30
+ ],
31
+ "dependencies": {
32
+ "@cdktf/provider-aws": "21.22.0",
33
+ "cdktf": "0.21.0",
34
+ "constructs": "10.4.4",
35
+ "reflect-metadata": "0.2.2",
36
+ "@lafken/common": "0.6.0",
37
+ "@lafken/resolver": "0.6.0"
38
+ },
39
+ "devDependencies": {
40
+ "@jest/types": "^30.2.0",
41
+ "@types/jest": "30.0.0",
42
+ "jest": "30.2.0",
43
+ "ts-jest": "29.4.6",
44
+ "ts-node": "10.9.2"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "scripts": {
50
+ "build": "pnpm clean && tsc -p ./tsconfig.build.json",
51
+ "clean": "rm -rf ./lib",
52
+ "dev": "tsc -w",
53
+ "test": "jest",
54
+ "test:coverage": "jest --coverage"
55
+ }
56
+ }