@routecraft/routecraft 0.1.1
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 +201 -0
- package/README.md +65 -0
- package/dist/index.cjs +9 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1454 -0
- package/dist/index.d.ts +1454 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/package.json +51 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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 must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# @routecraft/routecraft
|
|
2
|
+
|
|
3
|
+
Type-safe integration and automation framework for TypeScript/Node.js.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @routecraft/routecraft
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
or
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pnpm add @routecraft/routecraft
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Quick Start
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import { craft, simple, log } from '@routecraft/routecraft';
|
|
21
|
+
|
|
22
|
+
export default craft()
|
|
23
|
+
.id('my-route')
|
|
24
|
+
.from(simple('Hello, World!'))
|
|
25
|
+
.to(log());
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Features
|
|
29
|
+
|
|
30
|
+
- 🎯 **Type-safe**: Full TypeScript support with intelligent type inference
|
|
31
|
+
- 🔌 **Extensible**: Easy-to-write adapters for any integration
|
|
32
|
+
- 🚀 **Performant**: Built for high-throughput data processing
|
|
33
|
+
- 🛠️ **Developer-friendly**: Intuitive DSL inspired by Apache Camel
|
|
34
|
+
- 📦 **Lightweight**: Minimal dependencies
|
|
35
|
+
|
|
36
|
+
## Documentation
|
|
37
|
+
|
|
38
|
+
For comprehensive documentation, examples, and guides, visit [routecraft.dev](https://routecraft.dev).
|
|
39
|
+
|
|
40
|
+
## Example
|
|
41
|
+
|
|
42
|
+
```typescript
|
|
43
|
+
import { craft, timer, log } from '@routecraft/routecraft';
|
|
44
|
+
|
|
45
|
+
export default craft()
|
|
46
|
+
.id('timer-example')
|
|
47
|
+
.from(timer({ intervalMs: 1000 }))
|
|
48
|
+
.transform((ex) => ({ timestamp: Date.now() }))
|
|
49
|
+
.to(log());
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Contributing
|
|
53
|
+
|
|
54
|
+
Contributions are welcome! Please see our [Contributing Guide](https://github.com/routecraftjs/routecraft/blob/main/CONTRIBUTING.md).
|
|
55
|
+
|
|
56
|
+
## License
|
|
57
|
+
|
|
58
|
+
Apache-2.0
|
|
59
|
+
|
|
60
|
+
## Links
|
|
61
|
+
|
|
62
|
+
- [Documentation](https://routecraft.dev)
|
|
63
|
+
- [GitHub Repository](https://github.com/routecraftjs/routecraft)
|
|
64
|
+
- [Issue Tracker](https://github.com/routecraftjs/routecraft/issues)
|
|
65
|
+
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
'use strict';var pino=require('pino');require('@standard-schema/spec');var l="https://routecraft.dev/docs/reference/errors",C={RC1001:{category:"Definition",message:"Route definition failed validation",suggestion:"Ensure a source is defined: start with from(adapter)",docs:`${l}#rc-1001`},RC1002:{category:"Definition",message:"Duplicate route id",suggestion:"Ensure each route id is unique or set routeOptions.id",docs:`${l}#rc-1002`},RC2001:{category:"DSL",message:"Invalid operation type",suggestion:"Use a supported operator and verify the step name",docs:`${l}#rc-2001`},RC2002:{category:"DSL",message:"Missing from step",suggestion:"Start the route with from and a valid source adapter",docs:`${l}#rc-2002`},RC3001:{category:"Lifecycle",message:"Route failed to start",suggestion:"Ensure the route is not aborted and adapters are configured",docs:`${l}#rc-3001`},RC3002:{category:"Lifecycle",message:"Context failed to start",suggestion:"Validate plugin exports and global configuration",docs:`${l}#rc-3002`},RC5001:{category:"Adapter",message:"Source adapter threw",suggestion:"Verify connectivity and adapter options",docs:`${l}#rc-5001`},RC5002:{category:"Adapter",message:"Processing step threw",suggestion:"Add guards to transforms and processors",docs:`${l}#rc-5002`},RC5003:{category:"Adapter",message:"Destination adapter threw",suggestion:"Verify destination connectivity and options",docs:`${l}#rc-5003`},RC5004:{category:"Adapter",message:"Split operation failed",suggestion:"Ensure the input is iterable and guarded",docs:`${l}#rc-5004`},RC5005:{category:"Adapter",message:"Aggregation operation failed",suggestion:"Validate partial shapes and defaults",docs:`${l}#rc-5005`},RC5006:{category:"Adapter",message:"Transform function threw",suggestion:"Narrow input types and add guards",docs:`${l}#rc-5006`},RC5007:{category:"Adapter",message:"Tap step threw",suggestion:"Keep tap side effects resilient",docs:`${l}#rc-5007`},RC5008:{category:"Adapter",message:"Filter predicate threw",suggestion:"Guard against missing properties and unexpected shapes",docs:`${l}#rc-5008`},RC5009:{category:"Adapter",message:"Validation failed",suggestion:"Adjust the schema or coerce input",docs:`${l}#rc-5009`},RC9901:{category:"Runtime",message:"Unknown error",suggestion:"Check logs and enable debug level",docs:`${l}#rc-9901`}},k=class extends Error{constructor(t,r,n){super(r.message,{cause:n});this.rc=t;this.meta=r;this.name="RouteCraftError";}toString(){let t=`[${this.rc}] ${this.meta.message}`;return this.meta.suggestion&&(t+=`
|
|
2
|
+
Suggestion, ${this.meta.suggestion}`),t+=`
|
|
3
|
+
Docs, ${this.meta.docs}`,this.cause instanceof Error&&(t+=`
|
|
4
|
+
Caused by: ${this.cause.message}`,this.cause.stack&&(t+=`
|
|
5
|
+
Stack trace:
|
|
6
|
+
${this.cause.stack}`)),t}static parse(t){return t instanceof Error?{message:t.message,error:t}:{message:String(t),error:new Error(String(t))}}};function g(o,e,t){let r=C[o],n={...r,...t||{},docs:t?.docs??r.docs},s=e?k.parse(e).error:void 0;return new k(o,n,s)}var ne=process.env.NODE_ENV!=="production";function oe(){try{return undefined?.("pino-pretty"),!0}catch{return false}}var I=pino.pino({level:process.env.LOG_LEVEL||"warn",formatters:{level:o=>({level:o.toUpperCase()})},timestamp:()=>`,"time":"${new Date().toISOString()}"`,...ne&&oe()?{transport:{target:"pino-pretty",options:{colorize:true,ignore:"pid,hostname",translateTime:"SYS:standard"}}}:{}});function w(o){return o?o instanceof S?I.child({contextId:o.contextId}):o instanceof b?I.child({contextId:o.context.contextId,routeId:o.definition.id}):o instanceof P?I.child({contextId:o.context.contextId,routeId:o.headers["routecraft.route"],exchangeId:o.id,correlationId:o.headers["routecraft.correlation_id"]}):I:I}var x=w();var K=class{handler;buffer=[];async enqueue(e){return this.handler?await this.handler(e):(this.buffer.push(e),Promise.resolve({}))}setHandler(e){this.handler=e;let t=this.buffer;return t.length>0&&((async()=>{for(;t.length>0;)await e(t.shift());})(),this.buffer=[]),Promise.resolve()}clear(){return this.handler=void 0,this.buffer=[],Promise.resolve()}};var b=class{constructor(e,t,r){this.context=e;this.definition=t;this.assertNotAborted(),this.abortController=r??new AbortController,this.logger=w(this),this.messageChannel=new K,this.consumer=new this.definition.consumer.type(this.context,this.definition,this.messageChannel,this.definition.consumer.options),this.abortController.signal.addEventListener("abort",n=>{try{this.context.emit("routeStopping",{route:this,reason:n?.reason});}finally{this.context.emit("routeStopped",{route:this});}});}abortController;logger;messageChannel;consumer;get signal(){return this.abortController.signal}buildExchange(e,t){return new P(this.context,{body:e,headers:{...t,"routecraft.correlation_id":crypto.randomUUID(),"routecraft.route":this.definition.id,"routecraft.operation":"from"}})}async start(){return this.assertNotAborted(),this.logger.info(`Starting route "${this.definition.id}"`),this.consumer.register((e,t)=>this.handler(this.buildExchange(e,t))),this.context.emit("routeStarted",{route:this}),this.definition.source.subscribe(this.context,(e,t)=>this.messageChannel.enqueue({message:e,headers:t??{}}),this.abortController)}stop(){this.logger.info(`Stopping route "${this.definition.id}"`),this.messageChannel.clear(),this.abortController.abort("Route stop() called");}async handler(e){e.logger.debug(`Processing initial exchange ${e.id} on route "${this.definition.id}"`);let t=[{exchange:e,steps:[...this.definition.steps]}],r=e;for(;t.length>0;){let{exchange:n,steps:s}=t.shift();if(s.length===0){r=n;continue}let[i,...c]=s,p={...n,headers:{...n.headers,"routecraft.operation":i.operation}};p.logger.debug(`Processing step ${i.operation} on exchange ${p.id}`);try{await i.execute(p,c,t);}catch(a){let u=this.processError(i.operation,a);p.logger.warn(u,`Step ${i.operation} failed for exchange ${p.id}`),this.context.emit("error",{error:u,route:this,exchange:p});}}return r}assertNotAborted(){if(this.abortController?.signal.aborted)throw g("RC3001",void 0,{message:`${C.RC3001.message}: ${this.definition.id}`})}processError(e,t){let r="RC5002";return g(r,t,{message:`${C[r].message}: op=${e} route=${this.definition.id}`})}};var S=class{contextId=crypto.randomUUID();routes=[];controllers=new Map;store=new Map;logger;handlers=new Map;constructor(e){if(this.logger=w(this),e){if(e.store)for(let[t,r]of e.store.entries())this.store.set(t,r);if(e.on)for(let[t,r]of Object.entries(e.on))Array.isArray(r)?r.forEach(n=>this.on(t,n)):r&&this.on(t,r);}}on(e,t){let r=this.handlers.get(e)??new Set;return r.add(t),this.handlers.set(e,r),()=>{r.delete(t);}}emit(e,t){let r={ts:new Date().toISOString(),context:this,details:t},n=this.handlers.get(e);if(!(!n||n.size===0))for(let s of Array.from(n))try{s(r);}catch(i){this.logger.warn(i,"Event handler threw"),e!=="error"&&this.emit("error",{error:i});}}registerRoutes(...e){let t=e.map(s=>s.id),r=t.some((s,i)=>t.indexOf(s)!==i),n=e.some(s=>this.routes.some(i=>i.definition.id===s.id));if(r||n){let s=t.find((i,c)=>t.indexOf(i)!==c)??e.find(i=>this.routes.some(c=>c.definition.id===i.id))?.id??"unknown";throw g("RC1002",void 0,{message:`${C.RC1002.message}: ${s}`})}for(let s of e){if(!s.source||!s.source.subscribe)throw g("RC1001",void 0,{message:`${C.RC1001.message}: ${s.id}`});let i=new AbortController;this.controllers.set(s.id,i);let c=new b(this,s,i);this.routes.push(c),this.emit("routeRegistered",{route:c});}}getRoutes(){return this.routes}getStore(e){return this.store.get(e)}setStore(e,t){this.store.set(e,t);}getRouteById(e){return this.routes.find(t=>t.definition.id===e)}async start(){return this.logger.info("Starting Routecraft context"),this.emit("contextStarting",{}),this.logger.info("Starting all routes"),this.emit("contextStarted",{}),Promise.allSettled(this.routes.map(async e=>{try{return this.logger.debug(`Starting route "${e.definition.id}"`),this.emit("routeStarting",{route:e}),await e.start(),this.logger.debug(`Route "${e.definition.id}" ended.`),{routeId:e.definition.id,success:!0}}catch(t){throw this.logger.error(t,`Failed to start route "${e.definition.id}"`),this.emit("error",{error:t,route:e}),this.controllers.get(e.definition.id)?.abort(),t}})).then(e=>{if(e.every(r=>r.status==="fulfilled"))return this.logger.info("All routes have completed. Stopping context..."),this.stop();this.logger.info(`Some routes ended or failed, but the context remains active.
|
|
7
|
+
Call context.stop() or let other indefinite routes continue.`);}).catch(e=>{throw this.logger.error(e,"Context start failed"),this.emit("error",{error:e}),e})}async stop(){this.logger.info("Stopping Routecraft context"),this.emit("contextStopping",{reason:void 0});for(let e of this.routes)this.logger.debug("Stopping route controller"),this.controllers.get(e.definition.id)?.abort("context.stop()");this.logger.info("Routecraft context stopped"),this.emit("contextStopped",{});}};var m=(d=>(d.FROM="from",d.PROCESS="process",d.TO="to",d.SPLIT="split",d.AGGREGATE="aggregate",d.TRANSFORM="transform",d.TAP="tap",d.FILTER="filter",d.VALIDATE="validate",d.ENRICH="enrich",d.HEADER="header",d))(m||{}),v=(a=>(a.OPERATION="routecraft.operation",a.ROUTE_ID="routecraft.route",a.CORRELATION_ID="routecraft.correlation_id",a.SPLIT_HIERARCHY="routecraft.split_hierarchy",a.TIMER_TIME="routecraft.timer.time",a.TIMER_FIRED_TIME="routecraft.timer.firedTime",a.TIMER_PERIOD_MS="routecraft.timer.periodMs",a.TIMER_COUNTER="routecraft.timer.counter",a.TIMER_NEXT_RUN="routecraft.timer.nextRun",a))(v||{}),P=class{constructor(e,t){this.context=e;this.id=t?.id||crypto.randomUUID(),this.headers={"routecraft.route":crypto.randomUUID(),"routecraft.operation":"from","routecraft.correlation_id":crypto.randomUUID(),...t?.headers||{}},this.body=t?.body||{},this.logger=w(this);}id;headers;body;logger};var V=class{operation="process";adapter;constructor(e){this.adapter=typeof e=="function"?{process:e}:e;}async execute(e,t,r){let n=await Promise.resolve(this.adapter.process(e));r.push({exchange:n,steps:t});}};var z=class{operation="to";adapter;constructor(e){this.adapter=typeof e=="function"?{send:e}:e;}async execute(e,t,r){await this.adapter.send(e),r.push({exchange:e,steps:t});}};var O=class{operation="split";adapter;constructor(e){this.adapter=typeof e=="function"?{split:e}:e;}async execute(e,t,r){let n=await Promise.resolve(this.adapter.split(e.body)),s=crypto.randomUUID(),c=[...e.headers["routecraft.split_hierarchy"]||[],s];n.forEach(p=>{let a={...e,id:crypto.randomUUID(),body:p,headers:{...e.headers,"routecraft.split_hierarchy":c}};a.logger.debug(`Pushing split exchange ${a.id} to queue, splitHierarchy: ${a.headers["routecraft.split_hierarchy"]}`),r.push({exchange:a,steps:t});});}};var j=class{operation="aggregate";adapter;constructor(e){this.adapter=typeof e=="function"?{aggregate:e}:e;}async execute(e,t,r){let n=e.headers["routecraft.split_hierarchy"];if(!n){let a=await Promise.resolve(this.adapter.aggregate([e]));r.push({exchange:a,steps:t});return}let s=n[n.length-1],i=[e];for(let a=0;a<r.length;){let u=r[a];u.exchange.headers["routecraft.split_hierarchy"]?.at(-1)===s?(i.push(u.exchange),r.splice(a,1)):a++;}let c=await Promise.resolve(this.adapter.aggregate(i)),p=n.slice(0,-1);p.length>0?c.headers["routecraft.split_hierarchy"]=p:delete c.headers["routecraft.split_hierarchy"],r.push({exchange:c,steps:t});}};var Q=class{operation="transform";adapter;constructor(e){this.adapter=typeof e=="function"?{transform:e}:e;}async execute(e,t,r){let n=await Promise.resolve(this.adapter.transform(e.body));r.push({exchange:{...e,body:n},steps:t});}};var q=class{operation="tap";adapter;constructor(e){this.adapter=typeof e=="function"?{tap:e}:e;}async execute(e,t,r){let n={...e,body:structuredClone(e.body),headers:structuredClone(e.headers)};try{await this.adapter.tap(n);}catch(s){let i=g("RC5007",s,{message:`Error tapping exchange ${n.id}`,suggestion:"Check the tap function for any errors or wrap it in a try/catch block."});n.logger.info(i,`Error tapping exchange ${n.id}`);}r.push({exchange:e,steps:t});}};var D=class{operation="filter";adapter;constructor(e){this.adapter=typeof e=="function"?{filter:e}:e;}async execute(e,t,r){try{if(!await Promise.resolve(this.adapter.filter(e))){e.logger.debug(`Filter rejected exchange ${e.id}`);return}}catch(n){let s=g("RC5008",n,{message:`Error filtering exchange ${e.id}`});e.logger.warn(s,`Error filtering exchange ${e.id}`);}r.push({exchange:e,steps:t});}};var te=(o,e)=>{let t=typeof o.body=="object"&&o.body!==null?o.body:{value:o.body};return {...o,body:{...t,...typeof e=="object"&&e!==null?e:{value:e}}}},G=class{operation="enrich";adapter;aggregator;constructor(e,t){this.adapter=typeof e=="function"?{enrich:e,adapterId:crypto.randomUUID()}:e,this.aggregator=t;}async execute(e,t,r){let n=await Promise.resolve(this.adapter.enrich(e)),s=this.aggregator||te,i=await Promise.resolve(s(e,n));r.push({exchange:i,steps:t});}};var H=class{constructor(e,t,r,n){this.context=e;this.definition=t;this.channel=r;this.options=n;}async register(e){this.channel.setHandler(async t=>await e(t.message,t.headers));}};var M=class{constructor(e,t,r,n){this.context=e;this.definition=t;this.channel=r;this.options={size:n.size??1e3,time:n.time??10*1e3,merge:n.merge??(s=>{let i={};for(let c of s)for(let[p,a]of Object.entries(c.headers??{}))i[p]=a;return {message:s.map(c=>c.message),headers:i}})};}options;async register(e){let t=[],r=[],n=null,s=async()=>{if(t.length>0){let i=t,c=r;t=[],r=[];try{let p=this.options.merge(i),a=await e(p.message,p.headers);for(let{resolve:u}of c)u(a);}catch(p){this.context.logger.warn(p,`Error in batch consumer for route "${this.definition.id}":`);for(let{reject:a}of c)a(p);}}n&&(clearTimeout(n),n=null);};this.channel.setHandler(async i=>{let c=new Promise((p,a)=>{t.push(i),r.push({resolve:p,reject:a});});return t.length===1&&(n&&clearTimeout(n),n=setTimeout(async()=>{await s();},this.options.time)),t.length>=this.options.size&&await s(),c});}};var Y=class extends D{operation="validate";constructor(e){super(async t=>{let r=e["~standard"].validate(t.body);if(r instanceof Promise&&(r=await r),r.issues){let n=g("RC5009",r.issues,{message:`Error validating exchange ${t.id}`});return t.logger.debug(n,`Error validating exchange ${t.id}`),false}else return true});}};var X=class{operation="header";adapter;constructor(e,t){let r=typeof t=="function"?t:()=>t;this.adapter={key:e,set:r};}async execute(e,t,r){let n=await Promise.resolve(this.adapter.set(e));r.push({exchange:{...e,headers:{...e.headers,[this.adapter.key]:n}},steps:t});}};var $=class{config;definitions=[];initialStores=new Map;eventHandlers=new Map;constructor(){}with(e){if(this.config=e,e.store)for(let[t,r]of e.store.entries())this.initialStores.set(t,r);if(e.on)for(let[t,r]of Object.entries(e.on)){let n=t;if(Array.isArray(r))r.forEach(s=>{let i=this.eventHandlers.get(n)??new Set;i.add(s),this.eventHandlers.set(n,i);});else if(r){let s=this.eventHandlers.get(n)??new Set;s.add(r),this.eventHandlers.set(n,s);}}return this}on(e,t){let r=this.eventHandlers.get(e)??new Set;return r.add(t),this.eventHandlers.set(e,r),this}store(e,t){return this.initialStores.set(e,t),this}routes(e){return Array.isArray(e)?e.forEach(t=>{t instanceof A?this.definitions.push(...t.build()):this.definitions.push(t);}):e instanceof A?this.definitions.push(...e.build()):this.definitions.push(e),this}build(){let e=new S(this.config);for(let[t,r]of this.initialStores)this.config?.store?.has(t)||e.setStore(t,r);for(let[t,r]of this.eventHandlers.entries())for(let n of r)e.on(t,n);return e.registerRoutes(...this.definitions),e}},A=class{currentRoute;routes=[];pendingOptions;constructor(){}withType(){return this}id(e){return this.pendingOptions={...this.pendingOptions??{},id:e},x.debug(`Staging route id "${e}" for next route`),this}batch(e){let t={size:e?.size,time:e?.flushIntervalMs};return this.pendingOptions={...this.pendingOptions??{},consumer:{type:M,options:t}},x.debug("Staging batch processing for next route"),this}from(e){let t=this.pendingOptions?.id??crypto.randomUUID().toString(),r=this.pendingOptions?.consumer??{type:H,options:void 0};return x.debug(`Creating route definition with id "${t}"`),this.currentRoute={id:t,source:typeof e=="function"?{subscribe:e}:e,steps:[],consumer:{type:r.type,options:r.options??void 0}},this.pendingOptions=void 0,this.routes.push(this.currentRoute),this.withType()}requireSource(){if(!this.currentRoute)throw g("RC2002");return this.currentRoute}addStep(e){let t=this.requireSource();return x.debug(`Adding ${e.operation} step to route "${t.id}"`),t.steps.push(e),this.withType()}process(e){return this.addStep(new V(e)),this.withType()}to(e){let t=this.requireSource();return x.debug(`Adding destination step to route "${t.id}"`),t.steps.push(new z(e)),this.withType()}split(e){let t=this.requireSource();if(x.debug(`Adding split step to route "${t.id}"`),e)t.steps.push(new O(e));else {let r=n=>{if(!Array.isArray(n))throw g("RC2001",void 0,{message:"Default splitter can only be used with arrays",suggestion:"Provide a custom splitter or ensure the input is an array"});return n};t.steps.push(new O(r));}return this.withType()}aggregate(e){return this.addStep(new j(e)),this.withType()}transform(e){return this.addStep(new Q(e)),this.withType()}header(e,t){return this.addStep(new X(e,t)),this.withType()}map(e){let t=r=>{let n={};for(let[s,i]of Object.entries(e))n[s]=i(r);return n};return this.transform(t)}tap(e){return this.addStep(new q(e)),this.withType()}filter(e){return this.addStep(new D(e)),this.withType()}validate(e){return this.addStep(new Y(e)),this.withType()}enrich(e,t){return this.addStep(new G(e,t)),this.withType()}build(){return x.debug(`Building ${this.routes.length} routes`),this.routes}};var N=class{constructor(e){this.producer=e;}adapterId="routecraft.adapter.simple";async subscribe(e,t,r){e.logger.info("Producing messages");let n;try{n=await this.producer();}catch(s){throw e.logger.error(s,"Failed to produce messages"),r.abort(),s}if(Array.isArray(n)){e.logger.debug(`Processing array of ${n.length} messages`);try{await Promise.all(n.map(s=>t(s).catch(i=>{throw e.logger.error(i,"Failed to process message"),i})));}finally{e.logger.debug("Finished processing array of messages"),r.abort();}}else {e.logger.debug("Processing single message");try{await t(n);}catch(s){throw e.logger.error(s,"Failed to process message"),s}finally{e.logger.debug("Finished processing single message"),r.abort();}}}};var _=class{adapterId="routecraft.adapter.noop";send(e){return e.logger.info({id:e.id},"Discarding message"),Promise.resolve()}};var L=class{constructor(e){this.formatter=e;}adapterId="routecraft.adapter.log";send(e){return console.log(this.formatter?this.formatter(e):this.baseExchange(e)),Promise.resolve()}tap(e){return console.log(this.formatter?this.formatter(e):this.baseExchange(e)),Promise.resolve()}baseExchange(e){let{id:t,body:r,headers:n}=e;return {id:t,body:r,headers:n}}};var F=class o{constructor(e,t={}){this.options=t;this.rawEndpoint=e;}adapterId="routecraft.adapter.direct";static ADAPTER_DIRECT_STORE="routecraft.adapter.direct.store";static ADAPTER_DIRECT_OPTIONS="routecraft.adapter.direct.options";rawEndpoint;get sanitizedEndpoint(){return this.rawEndpoint.replace(/[^a-zA-Z0-9]/g,"-")}async subscribe(e,t,r){e.logger.info(`Setting up subscription for direct endpoint "${this.sanitizedEndpoint}"`);let n=this.directChannel(e);if(r.signal.aborted){e.logger.debug(`Subscription aborted for direct endpoint "${this.sanitizedEndpoint}"`);return}await n.subscribe(e,this.sanitizedEndpoint,async s=>await t(s.body,s.headers)),r.signal.addEventListener("abort",async()=>{await n.unsubscribe(e,this.sanitizedEndpoint);});}directChannel(e){let t=e.getStore(o.ADAPTER_DIRECT_STORE);if(t||(t=new Map,e.setStore(o.ADAPTER_DIRECT_STORE,t)),!t.has(this.sanitizedEndpoint)){let r=this.mergedOptions(e);if(r.channelType){let n=r.channelType;t.set(this.sanitizedEndpoint,new n(this.rawEndpoint));}else t.set(this.sanitizedEndpoint,new ee);}return t.get(this.sanitizedEndpoint)}async send(e){let t=e;t.logger.debug(`Preparing to send message to direct endpoint "${this.sanitizedEndpoint}"`);let n=await this.directChannel(t.context).send(this.sanitizedEndpoint,t);n&&n!==t&&(t.body=n.body);}mergedOptions(e){return {...e.getStore(o.ADAPTER_DIRECT_OPTIONS),...this.options}}},ee=class{handler=null;async send(e,t){return this.handler?await this.handler(t):t}async subscribe(e,t,r){this.handler=r;}async unsubscribe(e,t){this.handler=null;}};var B=class{constructor(e){this.options=e;}adapterId="routecraft.adapter.timer";subscribe(e,t,r){let{intervalMs:n=1e3,delayMs:s=0,repeatCount:i=1/0,fixedRate:c=false,exactTime:p,jitterMs:a=0}=this.options||{},u;if(p){let d=new Date,[h,T,f]=p.split(":").map(Number),y=new Date(d);y.setHours(h,T,f,0),y.getTime()<=d.getTime()&&y.setDate(y.getDate()+1),u=y.getTime();}else u=Date.now()+s;return new Promise(d=>{let h=0;(async()=>{for(;h<i&&!r.signal.aborted;){let f;c?p?f=u+h*24*60*60*1e3:f=u+h*n:h===0?f=u:f=Date.now()+n;let y=Date.now(),R=f-y;if(R<0&&(R=0),a>0){let Z=Math.floor(Math.random()*a);R+=Z;}if(await new Promise(Z=>setTimeout(Z,R)),r.signal.aborted)break;let J=new Date;h++;let E;c?p?E=u+h*24*60*60*1e3:E=u+h*n:E=Date.now()+n;let W={"routecraft.timer.time":J.toISOString(),"routecraft.timer.firedTime":J.toISOString(),"routecraft.timer.periodMs":p?1440*60*1e3:n,"routecraft.timer.counter":h,"routecraft.timer.nextRun":new Date(E).toISOString()};await t(void 0,W);}d();})();})}};var U=class{constructor(e){this.options=e;}adapterId="routecraft.adapter.fetch";async enrich(e){return await this.performFetch(e)}async send(e){await this.performFetch(e);}async performFetch(e){let t=this.options.method??"GET",r=this.resolveRequired(this.options.url,e),n={...this.resolve(this.options.headers,e)??{}},s=this.resolve(this.options.query,e),i=this.resolve(this.options.body,e),c=this.options.throwOnHttpError??true,p=this.options.timeoutMs??void 0,a=this.appendQuery(r,s??{}),u;i!=null&&(typeof i=="string"||i instanceof Uint8Array||i instanceof ArrayBuffer?u=i:(n["Content-Type"]||(n["Content-Type"]="application/json"),u=JSON.stringify(i)));let d=p?new AbortController:void 0,h=p?setTimeout(()=>d.abort(),p):void 0;try{let T=await globalThis.fetch(a,{method:t,headers:n,body:u,signal:d?.signal});if(c&&!T.ok){let E=await T.text();throw new Error(`HTTP ${T.status}: ${E}`)}let f={};T.headers.forEach((E,W)=>{f[W]=E;});let y=await T.text(),R=y;if((f["content-type"]?.toLowerCase()||"").includes("application/json"))try{R=JSON.parse(y);}catch{R=y;}return {status:T.status,headers:f,body:R,url:T.url||a}}finally{h&&clearTimeout(h);}}resolve(e,t){return typeof e=="function"?e(t):e}resolveRequired(e,t){return typeof e=="function"?e(t):e}appendQuery(e,t){if(!t||Object.keys(t).length===0)return e;let r=new URL(e,this.base(e));for(let[n,s]of Object.entries(t))r.searchParams.set(n,String(s));return r.toString()}base(e){try{let t=new URL(e);return `${t.protocol}//${t.host}`}catch{return}}};function se(){return new $}function ie(){return new A}function ae(o){return new N(typeof o=="function"?o:()=>o)}function pe(){return new _}function ce(o){return new L(o)}function de(o,e){return new F(o,e)}function ue(o){return new B(o)}function le(o){return new U(o)}
|
|
8
|
+
exports.BatchConsumer=M;exports.ContextBuilder=$;exports.CraftContext=S;exports.DefaultExchange=P;exports.DefaultRoute=b;exports.DirectAdapter=F;exports.FetchAdapter=U;exports.HeadersKeys=v;exports.LogAdapter=L;exports.NoopAdapter=_;exports.OperationType=m;exports.RC=C;exports.RouteBuilder=A;exports.RouteCraftError=k;exports.SimpleAdapter=N;exports.SimpleConsumer=H;exports.TimerAdapter=B;exports.context=se;exports.craft=ie;exports.createLogger=w;exports.defaultEnrichAggregator=te;exports.direct=de;exports.error=g;exports.fetch=le;exports.log=ce;exports.logger=x;exports.noop=pe;exports.simple=ae;exports.timer=ue;//# sourceMappingURL=index.cjs.map
|
|
9
|
+
//# sourceMappingURL=index.cjs.map
|