@kellanjs/actioncraft 0.0.2 → 0.2.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.
Files changed (88) hide show
  1. package/README.md +1263 -1
  2. package/dist/actioncraft-error.d.ts +23 -0
  3. package/dist/actioncraft-error.js +60 -0
  4. package/dist/actioncraft-error.js.map +1 -0
  5. package/dist/actioncraft-prev.d.ts +93 -0
  6. package/dist/actioncraft-prev.js +387 -0
  7. package/dist/actioncraft-prev.js.map +1 -0
  8. package/dist/actioncraft.d.ts +94 -40
  9. package/dist/actioncraft.js +337 -68
  10. package/dist/actioncraft.js.map +1 -1
  11. package/dist/api.d.ts +49 -0
  12. package/dist/api.js +84 -0
  13. package/dist/api.js.map +1 -0
  14. package/dist/classes/action-builder.d.ts +59 -0
  15. package/dist/classes/action-builder.js +95 -0
  16. package/dist/classes/action-builder.js.map +1 -0
  17. package/dist/classes/craft-builder.d.ts +66 -0
  18. package/dist/classes/craft-builder.js +129 -0
  19. package/dist/classes/craft-builder.js.map +1 -0
  20. package/dist/classes/crafter.d.ts +66 -0
  21. package/dist/classes/crafter.js +129 -0
  22. package/dist/classes/crafter.js.map +1 -0
  23. package/dist/classes/error.d.ts +23 -0
  24. package/dist/classes/error.js +60 -0
  25. package/dist/classes/error.js.map +1 -0
  26. package/dist/classes/executor/callbacks.d.ts +6 -0
  27. package/dist/classes/executor/callbacks.js +20 -0
  28. package/dist/classes/executor/callbacks.js.map +1 -0
  29. package/dist/classes/executor/errors.d.ts +29 -0
  30. package/dist/classes/executor/errors.js +114 -0
  31. package/dist/classes/executor/errors.js.map +1 -0
  32. package/dist/classes/executor/executor.d.ts +68 -0
  33. package/dist/classes/executor/executor.js +391 -0
  34. package/dist/classes/executor/executor.js.map +1 -0
  35. package/dist/classes/executor/logging.d.ts +2 -0
  36. package/dist/classes/executor/logging.js +8 -0
  37. package/dist/classes/executor/logging.js.map +1 -0
  38. package/dist/classes/executor/transformation.d.ts +17 -0
  39. package/dist/classes/executor/transformation.js +43 -0
  40. package/dist/classes/executor/transformation.js.map +1 -0
  41. package/dist/classes/executor/validation.d.ts +16 -0
  42. package/dist/classes/executor/validation.js +70 -0
  43. package/dist/classes/executor/validation.js.map +1 -0
  44. package/dist/classes/executor.d.ts +64 -0
  45. package/dist/classes/executor.js +354 -0
  46. package/dist/classes/executor.js.map +1 -0
  47. package/dist/classes/internal.d.ts +10 -0
  48. package/dist/classes/internal.js +5 -0
  49. package/dist/classes/internal.js.map +1 -0
  50. package/dist/core/errors.d.ts +2 -2
  51. package/dist/core/errors.js +5 -5
  52. package/dist/core/errors.js.map +1 -1
  53. package/dist/core/logging.d.ts +1 -1
  54. package/dist/core/transformation.d.ts +2 -2
  55. package/dist/core/validation.d.ts +4 -4
  56. package/dist/core/validation.js +14 -14
  57. package/dist/core/validation.js.map +1 -1
  58. package/dist/craft.d.ts +29 -0
  59. package/dist/craft.js +62 -0
  60. package/dist/craft.js.map +1 -0
  61. package/dist/error.d.ts +21 -6
  62. package/dist/error.js +59 -10
  63. package/dist/error.js.map +1 -1
  64. package/dist/index.d.ts +4 -3
  65. package/dist/index.js +4 -3
  66. package/dist/index.js.map +1 -1
  67. package/dist/initial.d.ts +14 -0
  68. package/dist/initial.js +47 -0
  69. package/dist/initial.js.map +1 -0
  70. package/dist/types/actions.d.ts +67 -25
  71. package/dist/types/builder.d.ts +92 -0
  72. package/dist/types/builder.js +2 -0
  73. package/dist/types/builder.js.map +1 -0
  74. package/dist/types/config.d.ts +4 -0
  75. package/dist/types/crafter.d.ts +87 -0
  76. package/dist/types/crafter.js +2 -0
  77. package/dist/types/crafter.js.map +1 -0
  78. package/dist/types/errors.d.ts +26 -18
  79. package/dist/types/inference.d.ts +41 -8
  80. package/dist/types/result.d.ts +8 -14
  81. package/dist/types/result.js +36 -4
  82. package/dist/types/result.js.map +1 -1
  83. package/dist/types/schemas.d.ts +7 -7
  84. package/dist/types/shared.d.ts +17 -7
  85. package/dist/utils.d.ts +30 -6
  86. package/dist/utils.js +68 -8
  87. package/dist/utils.js.map +1 -1
  88. package/package.json +3 -3
package/README.md CHANGED
@@ -1 +1,1263 @@
1
- ⚠️ Under Construction
1
+ ⚠️🚧 The library hasn't reached a stable release yet. Expect bugs and potentially breaking API changes until then.
2
+
3
+ # Actioncraft
4
+
5
+ Streamline your server actions.
6
+
7
+ - **🔒 Full Type Safety** - End-to-end TypeScript inference from input to output
8
+ - **📝 Schema Validation** - Works with Zod and any Standard Schema V1 compliant library
9
+ - **🎯 Fluent API** - Readable, discoverable builder pattern
10
+ - **⚡ Progressive Enhancement** - Works with and without JavaScript enabled
11
+ - **🔄 React Integration** - Built-in support for `useActionState` and form handling
12
+ - **🛡️ Error Management** - Structured error handling with custom error types
13
+ - **🔗 Lifecycle Hooks** - Callbacks for start, success, error, and completion events
14
+ - **📋 Form State Preservation** - Automatic form value retention on validation errors
15
+
16
+ ## Table of Contents
17
+
18
+ - [Quick Start](#quick-start)
19
+ - [Installation](#installation)
20
+ - [Overview](#overview)
21
+ - [Example](#example)
22
+ - [Result Format](#result-format)
23
+ - [Walkthrough](#walkthrough)
24
+ - [.config() - Configure Your Action](#config)
25
+ - [.schemas() - Add Validation](#schemas)
26
+ - [.errors() - Define Custom Errors](#errors)
27
+ - [.handler() - Implement Business Logic](#handler)
28
+ - [.callbacks() - Add Lifecycle Hooks](#callbacks)
29
+ - [Using Your Actions](#using-your-actions)
30
+ - [Basic Usage](#basic-usage)
31
+ - [Error Handling](#error-handling)
32
+ - [React Forms with useActionState](#react-forms-with-useactionstate)
33
+ - [Progressive Enhancement](#progressive-enhancement)
34
+ - [Complete Example](#complete-example)
35
+ - [Advanced Features](#advanced-features)
36
+ - [Bind Arguments](#bind-arguments)
37
+ - [Utilities](#utilities)
38
+ - [Type Inference](#type-inference)
39
+ - [Input Validation](#input-validation)
40
+ - [Integration Utilities](#integration-utilities)
41
+ - [Actioncraft Errors](#actioncraft-errors)
42
+ - [React Query](#react-query)
43
+
44
+ ## Quick Start
45
+
46
+ ### Installation
47
+
48
+ ```sh
49
+ npm install @kellanjs/actioncraft
50
+ ```
51
+
52
+ ### Overview
53
+
54
+ Actioncraft makes it easy to create type-safe server actions with first-class error-handling support.
55
+
56
+ The library supports two different syntax patterns, aptly referred to as the `action() api` and the `craft() api`. Both are functionally the same, so use whichever you prefer!
57
+
58
+ For the sake of simplicity, this document will use the same pattern (the `action() api`) for all usage examples, but either pattern would produce the exact same result.
59
+
60
+ #### action() api
61
+
62
+ ```typescript
63
+ export const example = action() // We call action() first to create a builder to use
64
+ .config(...)
65
+ .schemas(...)
66
+ .errors(...)
67
+ .handler(...)
68
+ .callbacks(...)
69
+ .craft(); // And we call craft() last to build and return your type-safe server action
70
+ ```
71
+
72
+ #### craft() api
73
+
74
+ ```typescript
75
+ // We call craft() first, and it provides us with a builder to use
76
+ export const example = craft(async (action) =>
77
+ action
78
+ .config(...)
79
+ .schemas(...)
80
+ .errors(...)
81
+ .handler(...)
82
+ .callbacks(...)
83
+ // No craft() needed here, because it's already wrapping everything!
84
+ );
85
+ ```
86
+
87
+ Actioncraft uses a fluent builder design, making it simple to chain one method after the next to create a full-featured server action. Regardless of which syntax pattern you use, the order in which the methods are defined is important for type inference to work properly, so you'll see the same structure repeated often throughout the documentation. Always make sure to chain your methods together like this for the best experience!
88
+
89
+ ### Example
90
+
91
+ With this basic structure in mind, let's see what a more detailed example looks like:
92
+
93
+ ```typescript
94
+ "use server";
95
+
96
+ import { action } from "@kellanjs/actioncraft";
97
+ import { z } from "zod";
98
+
99
+ const newUserInputSchema = z.object({
100
+ name: z.string(),
101
+ email: z.string().email(),
102
+ age: z.number(),
103
+ });
104
+
105
+ export const createNewUser = action()
106
+ // Define configuration settings
107
+ .config({
108
+ validationErrorFormat: "nested",
109
+ })
110
+ // Define the validation schema
111
+ .schemas({
112
+ inputSchema: newUserInputSchema,
113
+ })
114
+ // Define any errors that can occur in your action
115
+ .errors({
116
+ unauthorized: () =>
117
+ ({
118
+ type: "UNAUTHORIZED",
119
+ message: "You don't have permission to create users",
120
+ }) as const,
121
+ emailTaken: (email: string) =>
122
+ ({
123
+ type: "EMAIL_TAKEN",
124
+ message: `The email "${email}" is already registered`,
125
+ email,
126
+ }) as const,
127
+ })
128
+ // Define your server action logic
129
+ .handler(async ({ input, errors }) => {
130
+ // These are your validated input values
131
+ const { name, email, age } = input;
132
+
133
+ // If an error occurs, just return the result of the appropriate error function
134
+ if (!hasPermission()) return errors.unauthorized();
135
+
136
+ if (await emailExists(email)) return errors.emailTaken(email);
137
+
138
+ // Additional business logic here...
139
+
140
+ return { newUser };
141
+ })
142
+ // Define lifecycle callbacks
143
+ .callbacks({
144
+ onSettled: ({ result }) => {
145
+ // Log what happened if you want
146
+ },
147
+ })
148
+ .craft();
149
+ ```
150
+
151
+ ### Result Format
152
+
153
+ Server actions work best when you're returning serializable data. Throwing errors is less effective in this context, because Next.js will sanitize Error class objects that are thrown in your action, leaving you without useful error information on the client. You might see something in development, but in production, if you try to display `error.message`, you'll likely see something along the lines of: "An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details."
154
+
155
+ Actioncraft was designed with this fundamental behavior in mind! Instead of throwing errors, we're working exclusively with structured, serializable objects every step of the way, so errors in your action will always return the data you need.
156
+
157
+ The default result format should feel pretty familiar: `{ success: true, data: T } | { success: false, error: E }`
158
+
159
+ We'll look at errors in more detail later. But here's a simple example of one way you might work with an action result on the client:
160
+
161
+ ```typescript
162
+ const handleCreateNewUser = async (userData) => {
163
+ // Call your server action like you normally would and get the result
164
+ const result = await createNewUser(userData);
165
+
166
+ if (result.success) {
167
+ // If the action was successful, then you get back typed return data
168
+ toast.success("User created:", result.data.newUser);
169
+ } else {
170
+ // If the action was unsuccessful, then you get fully typed error handling
171
+ switch (result.error.type) {
172
+ case "INPUT_VALIDATION":
173
+ handleInputValidationErrorLogic();
174
+ break;
175
+ case "EMAIL_TAKEN":
176
+ showError(`Email ${result.error.email} is already taken`);
177
+ break;
178
+ case "UNAUTHORIZED":
179
+ handleAuthErrorLogic();
180
+ break;
181
+ case "UNHANDLED":
182
+ handleUncaughtExceptions();
183
+ break;
184
+ }
185
+ }
186
+ };
187
+ ```
188
+
189
+ ## Walkthrough
190
+
191
+ Now that we've covered the basic structure of an action and looked at a simple example, let's take a more detailed look at how Actioncraft works and what you can do with it.
192
+
193
+ ### .config()
194
+
195
+ Actioncraft provides several configuration options to customize your action. Sensible defaults are provided, so you only need to define the `config` if you specifically want to override something. When you want to customize a certain behavior, just pass a configuration object:
196
+
197
+ ```typescript
198
+ export const getUser = action()
199
+ .config({
200
+ name: "getUser",
201
+ useActionState: true,
202
+ resultFormat: "functional",
203
+ validationErrorFormat: "nested",
204
+ handleThrownError: (error) => ({
205
+ type: "CUSTOM_ERROR",
206
+ message: error.message,
207
+ }) as const,
208
+ })
209
+ .schemas(...)
210
+ .errors(...)
211
+ .handler(...)
212
+ .callbacks(...)
213
+ .craft();
214
+ ```
215
+
216
+ #### `name: string`
217
+
218
+ **Default:** `undefined`
219
+
220
+ An optional identifier for your action that will be included in error messages to help with debugging:
221
+
222
+ ```typescript
223
+ export const updateUserProfile = action()
224
+ .config({ name: "updateUserProfile" })
225
+ .schemas({ inputSchema: userSchema })
226
+ .handler(async ({ input }) => {
227
+ // Your handler logic
228
+ })
229
+ .craft();
230
+
231
+ // If validation fails, the error message will be:
232
+ // "Input validation failed in action \"updateUserProfile\""
233
+ // instead of just:
234
+ // "Input validation failed"
235
+ ```
236
+
237
+ #### `useActionState: boolean`
238
+
239
+ **Default:** `false`
240
+
241
+ Set to `true` to make your action compatible with React's `useActionState` hook:
242
+
243
+ ```typescript
244
+ export const getUser = action()
245
+ .config({ useActionState: true })
246
+ .schemas(...)
247
+ .errors(...)
248
+ .handler(...)
249
+ .callbacks(...)
250
+ .craft();
251
+
252
+ // Now you can use it with useActionState in your client components like this:
253
+ const [state, action] = useActionState(getUser, initial(getUser));
254
+ ```
255
+
256
+ #### `resultFormat: "api" | "functional"`
257
+
258
+ **Default:** `"api"`
259
+
260
+ Actioncraft supports two different return formats:
261
+
262
+ - **`"api"`**: `{ success: true, data: T } | { success: false, error: E }`
263
+ - **`"functional"`**: `{ type: "ok", value: T } | { type: "err", error: E }`
264
+
265
+ #### `validationErrorFormat: "flattened" | "nested"`
266
+
267
+ **Default:** `"flattened"`
268
+
269
+ Controls how validation errors are structured:
270
+
271
+ - **`"flattened"`**: Returns a flat array of error messages
272
+ - **`"nested"`**: Returns a nested object matching your schema structure
273
+
274
+ #### `handleThrownError: (error: unknown) => UserDefinedError`
275
+
276
+ By default, Actioncraft catches thrown errors and returns a structured error with type `"UNHANDLED"`. You can customize this behavior by passing an error handler function of your own:
277
+
278
+ ```typescript
279
+ export const getUser = action()
280
+ .config({
281
+ handleThrownError: (error) =>
282
+ ({
283
+ type: "CUSTOM_ERROR",
284
+ message:
285
+ error instanceof Error ? error.message : "Something went wrong",
286
+ timestamp: new Date().toISOString(),
287
+ }) as const,
288
+ })
289
+ .schemas(...)
290
+ .errors(...)
291
+ .handler(...)
292
+ .callbacks(...)
293
+ .craft();
294
+ ```
295
+
296
+ You can even implement more complex logic if you want:
297
+
298
+ ```typescript
299
+ handleThrownError: (error: unknown) => {
300
+ if (error instanceof Error) {
301
+ if (error.message.includes("ECONNREFUSED")) {
302
+ return {
303
+ type: "NETWORK_ERROR",
304
+ message: "Unable to connect to external service",
305
+ originalError: error.message,
306
+ } as const;
307
+ }
308
+
309
+ if (error.message.includes("timeout")) {
310
+ return {
311
+ type: "TIMEOUT_ERROR",
312
+ message: "Operation timed out",
313
+ originalError: error.message,
314
+ } as const;
315
+ }
316
+
317
+ if (error.message.includes("unauthorized")) {
318
+ return {
319
+ type: "AUTHENTICATION_ERROR",
320
+ message: "Authentication failed",
321
+ originalError: error.message,
322
+ } as const;
323
+ }
324
+
325
+ // Generic error transformation
326
+ return {
327
+ type: "CUSTOM_HANDLED_ERROR",
328
+ message: `Custom handler caught: ${error.message}`,
329
+ originalError: error.message,
330
+ } as const;
331
+ }
332
+
333
+ // Handle non-Error objects
334
+ return {
335
+ type: "UNKNOWN_ERROR_TYPE",
336
+ message: "An unknown error occurred",
337
+ originalError: String(error),
338
+ } as const;
339
+ };
340
+ ```
341
+
342
+ Actioncraft's types are smart enough to infer all of these possibilities back on the client:
343
+
344
+ ```typescript
345
+ if (!result.success) {
346
+ console.log(result.error.type);
347
+ // type: "INPUT_VALIDATION" | "INITIAL_STATE" | "NETWORK_ERROR" | "TIMEOUT_ERROR" | "AUTHENTICATION_ERROR" | "CUSTOM_HANDLED_ERROR" | "UNKNOWN_ERROR_TYPE"
348
+ }
349
+ ```
350
+
351
+ Pretty cool!
352
+
353
+ ### .schemas()
354
+
355
+ With our action configured, let's add validation using schemas. Actioncraft supports any library that implements the **Standard Schema V1** interface. Validation is handled automatically - you just need to provide the schemas:
356
+
357
+ ```typescript
358
+ export const getUser = action()
359
+ .config(...)
360
+ .schemas({
361
+ inputSchema,
362
+ outputSchema,
363
+ bindSchemas,
364
+ })
365
+ .errors(...)
366
+ .handler(...)
367
+ .callbacks(...)
368
+ .craft();
369
+ ```
370
+
371
+ #### Schema Options
372
+
373
+ ##### `inputSchema?: StandardSchemaV1`
374
+
375
+ Validates user input passed to the action. If validation fails, an "INPUT_VALIDATION" error is returned to the client.
376
+
377
+ ##### `outputSchema?: StandardSchemaV1`
378
+
379
+ Validates the data returned from your action. If validation fails, an "OUTPUT_VALIDATION" error is passed to callbacks, but the client always receives an "UNHANDLED" error (this is not affected by `handleThrownError`).
380
+
381
+ ##### `bindSchemas?: StandardSchemaV1[]`
382
+
383
+ Validates arguments bound to the action with `.bind()`. If validation fails, a "BIND_ARGS_VALIDATION" error is returned to the client.
384
+
385
+ ### .errors()
386
+
387
+ Now that we have validation set up, let's define custom errors that our action can return. Actioncraft makes error handling really easy by letting you define structured error types:
388
+
389
+ ```typescript
390
+ export const errorExamples = action()
391
+ .config(...)
392
+ .schemas(...)
393
+ .errors({
394
+ unauthorized: () =>
395
+ ({
396
+ type: "UNAUTHORIZED",
397
+ message: "You don't have permission to perform this action",
398
+ }) as const,
399
+ notFound: (id: string) =>
400
+ ({
401
+ type: "NOT_FOUND",
402
+ message: `User with ID ${id} not found`,
403
+ id,
404
+ }) as const,
405
+ emailTaken: (email: string) =>
406
+ ({
407
+ type: "EMAIL_TAKEN",
408
+ message: `The email "${email}" is already registered`,
409
+ email,
410
+ }) as const,
411
+ })
412
+ .handler(...)
413
+ .callbacks(...)
414
+ .craft();
415
+ ```
416
+
417
+ #### Error Structure
418
+
419
+ Each error is defined as a function called an **ErrorDefinition**:
420
+
421
+ - **Takes any arguments** you want (like IDs, emails, etc.)
422
+ - **Returns a UserDefinedError** object with:
423
+ - `type`: A string discriminator (required)
424
+ - `message`: Human-readable error message (optional)
425
+ - Any other custom fields you want
426
+
427
+ #### Why the `as const` Assertion?
428
+
429
+ The `as const` assertion is **required** for proper TypeScript inference. It ensures your error types are treated as literal types rather than generic:
430
+
431
+ ```typescript
432
+ // ❌ Without 'as const' - TypeScript infers { type: string, message: string } :(
433
+ badErrorDefinition: () => ({ type: "ERROR", message: "Something went wrong" });
434
+
435
+ // ✅ With 'as const' - TypeScript infers { type: "ERROR", message: "Something went wrong" } :D
436
+ goodErrorDefinition: () =>
437
+ ({ type: "ERROR", message: "Something went wrong" }) as const;
438
+ ```
439
+
440
+ Always remember the `as const` assertion when you define your errors!
441
+
442
+ #### Reusing Common Errors
443
+
444
+ Since error definitions are just functions, you can easily share common errors between actions:
445
+
446
+ ```typescript
447
+ // common-errors.ts
448
+ export const unauthorized = () =>
449
+ ({
450
+ type: "UNAUTHORIZED",
451
+ message: "You don't have permission to perform this action",
452
+ }) as const;
453
+
454
+ export const rateLimited = () =>
455
+ ({
456
+ type: "RATE_LIMITED",
457
+ message: "Too many requests. Please try again later.",
458
+ }) as const;
459
+
460
+ export const notFound = (resource: string, id: string) =>
461
+ ({
462
+ type: "NOT_FOUND",
463
+ message: `${resource} with ID ${id} not found`,
464
+ resource,
465
+ id,
466
+ }) as const;
467
+ ```
468
+
469
+ ```typescript
470
+ // get-user.ts
471
+ export const getUser = action()
472
+ .config(...)
473
+ .schemas(...)
474
+ .errors({
475
+ // Easily use common shared errors
476
+ unauthorized,
477
+ rateLimited,
478
+ notFound,
479
+ // Plus any action-specific errors you need
480
+ emailTaken: (email: string) =>
481
+ ({ type: "EMAIL_TAKEN", email }) as const,
482
+ })
483
+ .handler(...)
484
+ .callbacks(...)
485
+ .craft();
486
+ ```
487
+
488
+ #### Using Errors in Your Action Handler
489
+
490
+ Once defined, you can use these errors in your handler logic. When an error occurs, just call and return that particular error function:
491
+
492
+ ```typescript
493
+ export const getUser = action()
494
+ .config(...)
495
+ .schemas(...)
496
+ .errors(...)
497
+ .handler(async ({ input, errors }) => {
498
+ // Check permissions
499
+ if (!hasPermission(input.userId)) {
500
+ return errors.unauthorized();
501
+ }
502
+
503
+ // Find user
504
+ const user = await findUser(input.userId);
505
+ if (!user) {
506
+ return errors.notFound(input.userId);
507
+ }
508
+
509
+ // Success case
510
+ return { user };
511
+ })
512
+ .callbacks(...)
513
+ .craft();
514
+ ```
515
+
516
+ ### .handler()
517
+
518
+ The `handler` method is where you implement the core functionality of your server action. Actioncraft provides several helpful parameters to make things quick and easy for you:
519
+
520
+ ```typescript
521
+ export const getUser = action()
522
+ .config(...)
523
+ .schemas(...)
524
+ .errors(...)
525
+ .handler(async ({ input, bindArgs, errors, metadata }) => {
526
+ // Server action logic here
527
+ })
528
+ .callbacks(...)
529
+ .craft();
530
+ ```
531
+
532
+ #### Handler Parameters
533
+
534
+ ##### `input`
535
+
536
+ Contains the validated input values (or `undefined` if no input schema was provided).
537
+
538
+ ##### `bindArgs`
539
+
540
+ Contains an array of validated bound argument values (or an empty array if no bind schemas were provided).
541
+
542
+ ##### `errors`
543
+
544
+ Contains all the ErrorDefinition functions you defined in the `.errors()` method.
545
+
546
+ ##### `metadata`
547
+
548
+ Contains additional request information:
549
+
550
+ - `rawInput`: The original, unvalidated input data
551
+ - `rawBindArgs`: The original, unvalidated bound arguments array
552
+ - `prevState`: Previous state (when using `useActionState`)
553
+ - `actionId`: A unique identifier for the action instance
554
+
555
+ ### .callbacks()
556
+
557
+ Sometimes you need to hook into the action lifecycle for logging, analytics, or other side effects. The `callbacks` method lets you define functions that run at key moments:
558
+
559
+ ```typescript
560
+ export const getUser = action()
561
+ .config(...)
562
+ .schemas(...)
563
+ .errors(...)
564
+ .handler(...)
565
+ .callbacks({
566
+ onStart: ({metadata}) => { ... },
567
+ onSuccess: ({data}) => { ... },
568
+ onError: ({error}) => { ... },
569
+ onSettled: ({ result }) => { ... },
570
+ })
571
+ .craft();
572
+ ```
573
+
574
+ #### Callback Types
575
+
576
+ ##### `onStart?: (params: { metadata }) => Promise<void> | void`
577
+
578
+ Executes first, before any validation or action logic has occurred.
579
+
580
+ ##### `onSuccess?: (params: { data, metadata }) => Promise<void> | void`
581
+
582
+ Executes when your action completes successfully. The `data` parameter contains your action's typed return value.
583
+
584
+ ##### `onError?: (params: { error, metadata }) => Promise<void> | void`
585
+
586
+ Executes when your action returns an error (custom errors, validation failures, or unhandled exceptions).
587
+
588
+ ##### `onSettled?: (params: { result, metadata }) => Promise<void> | void`
589
+
590
+ Executes after your action completes, regardless of success or failure. Useful for cleanup or logging.
591
+
592
+ Note: All callback methods support async operations and won't affect your action's result, even if they throw errors.
593
+
594
+ ## Using Your Actions
595
+
596
+ Now that you know how to build actions with Actioncraft, let's see how you can use them in your application.
597
+
598
+ ### Basic Usage
599
+
600
+ You can call your action like any async function:
601
+
602
+ ```typescript
603
+ // client-component.ts
604
+ const handleClick = async () => {
605
+ const result = await createNewUser({
606
+ name: "John",
607
+ email: "john@example.com",
608
+ age: 25,
609
+ });
610
+
611
+ if (result.success) {
612
+ // Action succeeded
613
+ console.log("User created:", result.data.newUser);
614
+ } else {
615
+ // Action failed
616
+ console.log("Error:", result.error.type);
617
+ console.log("Message:", result.error.message);
618
+ }
619
+ };
620
+ ```
621
+
622
+ ### Error Handling
623
+
624
+ Thanks to some carefully crafted types, you can always determine exactly what kind of error you're dealing with:
625
+
626
+ ```typescript
627
+ const result = await createNewUser(formData);
628
+
629
+ if (!result.success) {
630
+ switch (result.error.type) {
631
+ case "INPUT_VALIDATION":
632
+ showValidationErrors(result.error.issues);
633
+ break;
634
+ case "UNAUTHORIZED":
635
+ redirectToLogin();
636
+ break;
637
+ case "EMAIL_TAKEN":
638
+ showError(`Email ${result.error.email} is already taken`);
639
+ break;
640
+ case "UNHANDLED":
641
+ showGenericError();
642
+ break;
643
+ }
644
+ }
645
+ ```
646
+
647
+ ### React Forms with useActionState
648
+
649
+ For React forms, you can use actions configured for `useActionState`:
650
+
651
+ ```typescript
652
+ export const updateUser = action()
653
+ .config({ useActionState: true })
654
+ .schemas(...)
655
+ .errors(...)
656
+ .handler(...)
657
+ .callbacks(...)
658
+ .craft();
659
+ ```
660
+
661
+ When `useActionState: true` is set, your action's return type changes to include a `values` field. This field contains the raw input values that were last passed to the action. However, on successful executions where an input schema is defined, it contains the validated input values instead.
662
+
663
+ #### The `initial()` Helper
664
+
665
+ When using `useActionState`, you have to provide the hook with a proper initial state that matches the return type of your action. That's where Actioncraft's `initial` function comes in. It returns a special error object with type `"INITIAL_STATE"` that you can use to detect when the form hasn't been submitted yet:
666
+
667
+ ```typescript
668
+ function UserForm() {
669
+ const [state, action] = useActionState(updateUser, initial(updateUser));
670
+ // `state` initializes as:
671
+ // { success: false,
672
+ // error: { type: "INITIAL_STATE", message: "Action has not been executed yet" },
673
+ // values: undefined }
674
+
675
+ return (
676
+ <form action={action}>
677
+ <input name="name" defaultValue={state.values?.name} />
678
+ <input name="email" defaultValue={state.values?.email} />
679
+
680
+ {!state.success && state.error.type !== "INITIAL_STATE" && (
681
+ <p>Error: {state.error.message}</p>
682
+ )}
683
+
684
+ <button type="submit">Update User</button>
685
+ </form>
686
+ );
687
+ }
688
+ ```
689
+
690
+ ### Progressive Enhancement
691
+
692
+ By providing a schema which supports FormData, your action can work with or without JavaScript. For example, when using Zod, you can use the `zod-form-data` library to provide FormData support for your action:
693
+
694
+ ```typescript
695
+ // This action handles FormData from server-side form submissions
696
+ export const createNewUser = action()
697
+ .config({ useActionState: true })
698
+ .schemas({
699
+ inputSchema: zfd.formData({
700
+ name: zfd.text(),
701
+ email: zfd.text(z.string().email()),
702
+ }),
703
+ })
704
+ .handler(async ({ input }) => {
705
+ // Save the validated user data to database
706
+ const user = await db.user.create({
707
+ data: {
708
+ name: input.name,
709
+ email: input.email,
710
+ },
711
+ });
712
+
713
+ // Send welcome email
714
+ await sendWelcomeEmail(user.email);
715
+
716
+ return { user };
717
+ })
718
+ .craft();
719
+ ```
720
+
721
+ ## Complete Example
722
+
723
+ Now that we've gone over how to create actions and how to use them on the client, let's check out a more thorough example that puts a lot of these ideas together:
724
+
725
+ ```typescript
726
+ "use server";
727
+
728
+ import { action } from "@kellanjs/actioncraft";
729
+ import { revalidatePath } from "next/cache";
730
+ import { z } from "zod";
731
+
732
+ const updateProfileSchema = z.object({
733
+ name: z.string().min(1, "Name is required"),
734
+ email: z.string().email("Invalid email"),
735
+ bio: z.string().max(500, "Bio must be under 500 characters"),
736
+ });
737
+
738
+ export const updateProfile = action()
739
+ .config({ useActionState: true })
740
+ .schemas({ inputSchema: updateProfileSchema })
741
+ .errors({
742
+ unauthorized: () =>
743
+ ({ type: "UNAUTHORIZED", message: "Please log in" }) as const,
744
+ emailTaken: (email: string) =>
745
+ ({
746
+ type: "EMAIL_TAKEN",
747
+ message: `Email ${email} is already taken`,
748
+ email,
749
+ }) as const,
750
+ rateLimited: () =>
751
+ ({
752
+ type: "RATE_LIMITED",
753
+ message: "Too many requests. Please try again later.",
754
+ }) as const,
755
+ })
756
+ .handler(async ({ input, errors }) => {
757
+ // Check authentication
758
+ const session = await getSession();
759
+ if (!session) return errors.unauthorized();
760
+
761
+ // Check rate limiting
762
+ if (await isRateLimited(session.userId)) {
763
+ return errors.rateLimited();
764
+ }
765
+
766
+ // Check if email is taken
767
+ const existingUser = await getUserByEmail(input.email);
768
+ if (existingUser && existingUser.id !== session.userId) {
769
+ return errors.emailTaken(input.email);
770
+ }
771
+
772
+ // Update user
773
+ const updatedUser = await updateUser(session.userId, input);
774
+
775
+ return { user: updatedUser };
776
+ })
777
+ .callbacks({
778
+ onStart: ({ metadata }) => {
779
+ // Track when profile updates begin
780
+ analytics.track("profile_update_started", {
781
+ userId: metadata.prevState?.success
782
+ ? metadata.prevState.data?.user?.id
783
+ : null,
784
+ });
785
+ },
786
+ onSuccess: ({ data }) => {
787
+ revalidatePath("/profile");
788
+ logUserActivity(data.user.id, "profile_updated");
789
+ },
790
+ onError: ({ error }) => {
791
+ if (error.type === "UNHANDLED") {
792
+ logError("Profile update failed", error);
793
+ }
794
+ },
795
+ onSettled: ({ result }) => {
796
+ // Log completion for monitoring and analytics
797
+ analytics.track("profile_update_completed", {
798
+ success: result.success,
799
+ });
800
+ },
801
+ })
802
+ .craft();
803
+ ```
804
+
805
+ ```typescript
806
+ "use client";
807
+
808
+ import { useActionState } from "react";
809
+ import { updateProfile } from "./actions";
810
+ import { initial } from "@kellanjs/actioncraft";
811
+
812
+ export default function ProfileForm() {
813
+ const [state, action] = useActionState(updateProfile, initial(updateProfile));
814
+
815
+ return (
816
+ <form action={action}>
817
+ <input
818
+ name="name"
819
+ placeholder="Name"
820
+ defaultValue={state.values?.name}
821
+ />
822
+
823
+ <input
824
+ name="email"
825
+ type="email"
826
+ placeholder="Email"
827
+ defaultValue={state.values?.email}
828
+ />
829
+
830
+ <textarea
831
+ name="bio"
832
+ placeholder="Bio"
833
+ defaultValue={state.values?.bio}
834
+ />
835
+
836
+ {state.success && (
837
+ <div className="success">
838
+ <p>Profile updated successfully!</p>
839
+ </div>
840
+ )}
841
+
842
+ {!state.success && state.error.type !== "INITIAL_STATE" && (
843
+ <div className="error">
844
+ {state.error.type === "EMAIL_TAKEN" && (
845
+ <p>That email is already taken. Please use a different one.</p>
846
+ )}
847
+ {state.error.type === "UNAUTHORIZED" && (
848
+ <p>Please log in to update your profile.</p>
849
+ )}
850
+ {state.error.type === "RATE_LIMITED" && (
851
+ <p>Too many requests. Please try again later.</p>
852
+ )}
853
+ {state.error.type === "INPUT_VALIDATION" && (
854
+ <ul>
855
+ {state.error.issues.map((issue, i) => (
856
+ <li key={i}>{issue.message}</li>
857
+ ))}
858
+ </ul>
859
+ )}
860
+ </div>
861
+ )}
862
+
863
+ <button type="submit">Update Profile</button>
864
+ </form>
865
+ );
866
+ }
867
+ ```
868
+
869
+ ## Advanced Features
870
+
871
+ ### Bind Arguments
872
+
873
+ Actioncraft supports binding arguments to actions. Just provide schemas, and you'll get the validated bindArgs values to use in the action handler.
874
+
875
+ If validation fails, an error with type `BIND_ARGS_VALIDATION` is returned to the client.
876
+
877
+ #### Example: Multi-Tenant Action
878
+
879
+ ```typescript
880
+ export const createPost = action()
881
+ .schemas({
882
+ bindSchemas: [z.string()], // Organization ID
883
+ inputSchema: z.object({
884
+ title: z.string(),
885
+ content: z.string(),
886
+ }),
887
+ })
888
+ .handler(async ({ bindArgs, input }) => {
889
+ const [organizationId] = bindArgs;
890
+
891
+ const post = await db.post.create({
892
+ data: {
893
+ ...input,
894
+ organizationId,
895
+ },
896
+ });
897
+
898
+ return { post };
899
+ })
900
+ .craft();
901
+
902
+ // Create organization-specific actions
903
+ const createPostForOrgA = createPost.bind(null, "org-a-id");
904
+ const createPostForOrgB = createPost.bind(null, "org-b-id");
905
+
906
+ // Each bound action automatically includes the correct org ID
907
+ const result = await createPostForOrgA({
908
+ title: "My Post",
909
+ content: "Post content...",
910
+ });
911
+ ```
912
+
913
+ #### Example: Configuration Binding
914
+
915
+ ```typescript
916
+ export const sendEmail = action()
917
+ .schemas({
918
+ bindSchemas: [
919
+ z.object({
920
+ apiKey: z.string(),
921
+ fromEmail: z.string(),
922
+ }),
923
+ ],
924
+ inputSchema: z.object({
925
+ to: z.string().email(),
926
+ subject: z.string(),
927
+ body: z.string(),
928
+ }),
929
+ })
930
+ .handler(async ({ bindArgs, input }) => {
931
+ const [config] = bindArgs;
932
+
933
+ // Use the bound configuration
934
+ const emailService = new EmailService(config.apiKey);
935
+ const result = await emailService.send({
936
+ from: config.fromEmail,
937
+ to: input.to,
938
+ subject: input.subject,
939
+ body: input.body,
940
+ });
941
+
942
+ return { messageId: result.id };
943
+ })
944
+ .craft();
945
+
946
+ // Create environment-specific email actions
947
+ const sendProductionEmail = sendEmail.bind(null, {
948
+ apiKey: process.env.PROD_EMAIL_API_KEY,
949
+ fromEmail: "noreply@company.com",
950
+ });
951
+
952
+ const sendDevelopmentEmail = sendEmail.bind(null, {
953
+ apiKey: process.env.DEV_EMAIL_API_KEY,
954
+ fromEmail: "dev@company.com",
955
+ });
956
+ ```
957
+
958
+ ## Utilities
959
+
960
+ Actioncraft provides several utilities to help you work with your actions more effectively.
961
+
962
+ ### Type Inference
963
+
964
+ These utilities extract useful type information from your actions.
965
+
966
+ #### Using `$Infer`
967
+
968
+ Every crafted action includes an `$Infer` property that provides direct access to all inferred types:
969
+
970
+ - **`$Infer.Input`** - The input type that the action expects
971
+ - **`$Infer.Data`** - The success data type from your action's return value
972
+ - **`$Infer.Errors`** - All possible error types your action can return
973
+ - **`$Infer.Result`** - The complete result type (success and error cases)
974
+
975
+ #### Type Extraction Example
976
+
977
+ ```typescript
978
+ import { action } from "@kellanjs/actioncraft";
979
+ import { z } from "zod";
980
+
981
+ export const updateUser = action()
982
+ .schemas({
983
+ inputSchema: z.object({
984
+ id: z.string(),
985
+ name: z.string(),
986
+ email: z.string().email(),
987
+ }),
988
+ })
989
+ .errors({
990
+ notFound: (id: string) => ({ type: "NOT_FOUND", id }) as const,
991
+ unauthorized: () => ({ type: "UNAUTHORIZED" }) as const,
992
+ })
993
+ .handler(async ({ input, errors }) => {
994
+ // ... implementation
995
+ return { user: input, updatedAt: new Date() };
996
+ })
997
+ .craft();
998
+
999
+ // Extracted types using $Infer:
1000
+ type ActionInput = typeof updateUser.$Infer.Input;
1001
+ // { id: string, name: string, email: string }
1002
+
1003
+ type ActionData = typeof updateUser.$Infer.Data;
1004
+ // { user: { id: string, name: string, email: string }, updatedAt: Date }
1005
+
1006
+ type ActionErrors = typeof updateUser.$Infer.Errors;
1007
+ // { type: "NOT_FOUND", id: string } | { type: "UNAUTHORIZED" } |
1008
+ // { type: "INPUT_VALIDATION", issues: ... } | { type: "UNHANDLED", message: string }
1009
+
1010
+ type ActionResult = typeof updateUser.$Infer.Result;
1011
+ // { success: true, data: { user: UserInput, updatedAt: Date } } |
1012
+ // { success: false, error: { type: "NOT_FOUND", id: string } | ... }
1013
+ ```
1014
+
1015
+ #### Using `Infer` Types
1016
+
1017
+ You can also use these alternative type inference utilities if you prefer:
1018
+
1019
+ ```typescript
1020
+ import type {
1021
+ InferInput,
1022
+ InferResult,
1023
+ InferData,
1024
+ InferErrors,
1025
+ } from "@kellanjs/actioncraft";
1026
+
1027
+ type ActionInput = InferInput<typeof updateUser>;
1028
+ type ActionResult = InferResult<typeof updateUser>;
1029
+ type ActionData = InferData<typeof updateUser>;
1030
+ type ActionErrors = InferErrors<typeof updateUser>;
1031
+ ```
1032
+
1033
+ These provide the exact same type information as the `$Infer` utility.
1034
+
1035
+ ### Input Validation
1036
+
1037
+ #### Using `$validate`
1038
+
1039
+ Actioncraft provides a utility to help you easily validate data against a particular action's input schema. The `$validate` method is available on every crafted action by default, and runs the same validation logic used during action execution. This is especially useful when you want to perform client-side validation before calling an action:
1040
+
1041
+ ```typescript
1042
+ // On the server...
1043
+ export const createUser = action()
1044
+ .schemas({ inputSchema: userSchema })
1045
+ .handler(async ({ input }) => ({ user: input }))
1046
+ .craft();
1047
+
1048
+ // On the client...
1049
+ // Validate input without executing the action
1050
+ const result = await createUser.$validate({
1051
+ name: "John",
1052
+ email: "john@example.com",
1053
+ age: 25,
1054
+ });
1055
+
1056
+ if (result.success) {
1057
+ console.log("Valid input:", result.data);
1058
+ // Now we can call the action, knowing that input validation will succeed
1059
+ } else {
1060
+ console.log("Validation failed:", result.error);
1061
+ }
1062
+ ```
1063
+
1064
+ #### Validation Results
1065
+
1066
+ Returns `{ success: true, data: ValidatedInput }` on success, or `{ success: false, error: ValidationError }` on failure.
1067
+
1068
+ ## Integration Utilities
1069
+
1070
+ Actioncraft comes with several utilities intended to make it easier to integrate with libraries like React Query.
1071
+
1072
+ ### Actioncraft Errors
1073
+
1074
+ #### `ActioncraftError`
1075
+
1076
+ A standard Error class that wraps Actioncraft error data while preserving type information:
1077
+
1078
+ ```typescript
1079
+ // The error preserves all your action's error data in the `cause` property
1080
+ if (error instanceof ActioncraftError) {
1081
+ console.log(error.message); // "Actioncraft Error: EMAIL_TAKEN - Email already exists"
1082
+ console.log(error.cause); // { type: "EMAIL_TAKEN", message: "Email already exists", email: "user@example.com" }
1083
+ }
1084
+ ```
1085
+
1086
+ #### `unwrap(result)`
1087
+
1088
+ Extracts the data from a successful result or throws an `ActioncraftError`:
1089
+
1090
+ ```typescript
1091
+ const result = await createNewUser(data);
1092
+ const userData = unwrap(result); // Throws if result.success === false
1093
+ ```
1094
+
1095
+ #### `throwable(action)`
1096
+
1097
+ Wraps an action to automatically throw errors as `ActioncraftError` instances instead of returning them as objects:
1098
+
1099
+ ```typescript
1100
+ const throwingAction = throwable(myAction);
1101
+ const userData = await throwingAction(data); // Throws on error
1102
+ ```
1103
+
1104
+ #### `isActioncraftError(error, action)`
1105
+
1106
+ Type guard that checks if an error is an `ActioncraftError`. When called with just an error object, it performs basic structural validation. When called with both error and action, it additionally verifies that the error originated from that specific action, providing full type inference for that action's error types.
1107
+
1108
+ ```typescript
1109
+ try {
1110
+ const data = await throwable(updateUser)(userData);
1111
+ console.log("Updated user data", data); // We know data exists at this point
1112
+ } catch (error) {
1113
+ // Basic usage - checks if error is any ActioncraftError
1114
+ if (isActioncraftError(error)) {
1115
+ console.log("This is an ActioncraftError:", error.cause.type);
1116
+ // error.cause has generic typing here
1117
+ }
1118
+
1119
+ // Advanced usage - verifies error came from the given action
1120
+ if (isActioncraftError(error, updateUser)) {
1121
+ // error.cause is now typed with updateUser's specific error types
1122
+ switch (error.cause.type) {
1123
+ case "EMAIL_TAKEN":
1124
+ showError(`Email ${error.cause.email} is already taken`);
1125
+ break;
1126
+ case "UNAUTHORIZED":
1127
+ redirectToLogin();
1128
+ break;
1129
+ case "INPUT_VALIDATION":
1130
+ showValidationErrors(error.cause.issues);
1131
+ break;
1132
+ }
1133
+ }
1134
+ }
1135
+ ```
1136
+
1137
+ **Key Differences:**
1138
+
1139
+ - **Without action parameter**: Performs basic structural validation, returns `true` for any `ActioncraftError`
1140
+ - **With action parameter**: Additionally verifies the error originated from that specific action and provides full type inference for that action's error types
1141
+
1142
+ #### `getActionId(action)`
1143
+
1144
+ Utility to extract the unique ID from a crafted action. Useful for debugging and logging purposes.
1145
+
1146
+ ### React Query
1147
+
1148
+ Now let's see how to use these utilities most effectively when working with React Query!
1149
+
1150
+ #### Usage with useQuery
1151
+
1152
+ Use the `unwrap()` utility for data fetching queries:
1153
+
1154
+ ```typescript
1155
+ import { useQuery } from "@tanstack/react-query";
1156
+ import { fetchUserProfile } from "./actions";
1157
+ import { unwrap } from "@kellanjs/actioncraft";
1158
+
1159
+ function UserProfile({ userId }: { userId: string }) {
1160
+ const { data, error, isLoading } = useQuery({
1161
+ queryKey: ["user", userId],
1162
+ queryFn: async () => {
1163
+ const result = await fetchUserProfile({ userId });
1164
+ return unwrap(result); // Throws ActioncraftError on failure
1165
+ },
1166
+ });
1167
+
1168
+ if (isLoading) return <div>Loading...</div>;
1169
+
1170
+ if (error) {
1171
+ if (isActioncraftError(error, fetchUserProfile)) {
1172
+ // Full type inference for your action's specific error types
1173
+ switch (error.cause.type) {
1174
+ case "USER_NOT_FOUND":
1175
+ return <div>User not found</div>;
1176
+ case "UNAUTHORIZED":
1177
+ return <div>Please log in</div>;
1178
+ default:
1179
+ return <div>Error: {error.cause.message}</div>;
1180
+ }
1181
+ }
1182
+ return <div>Unexpected error occurred</div>;
1183
+ }
1184
+
1185
+ return (
1186
+ <div>
1187
+ <h1>{data.user.name}</h1>
1188
+ <p>{data.user.email}</p>
1189
+ </div>
1190
+ );
1191
+ }
1192
+ ```
1193
+
1194
+ If you're like me, and that query function is too verbose for your tastes, you can simplify it:
1195
+
1196
+ ```typescript
1197
+ queryFn: () => unwrap(fetchUserProfile({ userId }));
1198
+ ```
1199
+
1200
+ `unwrap` is designed to handle both Results and Promises of Results, and since React Query will handle awaiting the resolved Promise, this syntax will work just fine.
1201
+
1202
+ #### Usage with useMutation
1203
+
1204
+ Use the `throwable()` utility for mutations:
1205
+
1206
+ ```typescript
1207
+ import { useMutation, useQueryClient } from "@tanstack/react-query";
1208
+ import { updateUserProfile } from "./actions";
1209
+ import { throwable, isActioncraftError } from "@kellanjs/actioncraft";
1210
+
1211
+ function EditProfileForm() {
1212
+ const queryClient = useQueryClient();
1213
+
1214
+ const mutation = useMutation({
1215
+ mutationFn: throwable(updateUserProfile), // Throws ActioncraftError on failure
1216
+ onSuccess: (data) => {
1217
+ // data is properly typed as your action's success data
1218
+ queryClient.invalidateQueries({ queryKey: ["user", data.user.id] });
1219
+ },
1220
+ onError: (error) => {
1221
+ if (isActioncraftError(error, updateUserProfile)) {
1222
+ // Handle specific error types with full type safety
1223
+ switch (error.cause.type) {
1224
+ case "UNAUTHORIZED":
1225
+ redirectToLogin();
1226
+ break;
1227
+ case "INPUT_VALIDATION":
1228
+ showValidationErrors(error.cause.issues);
1229
+ break;
1230
+ case "EMAIL_TAKEN":
1231
+ showToast(`Email ${error.cause.email} is already taken`);
1232
+ break;
1233
+ default:
1234
+ showToast(error.cause.message || "Update failed");
1235
+ }
1236
+ } else {
1237
+ showToast("An unexpected error occurred");
1238
+ }
1239
+ },
1240
+ });
1241
+
1242
+ const handleSubmit = (formData: FormData) => {
1243
+ mutation.mutate(formData);
1244
+ };
1245
+
1246
+ return (
1247
+ <form onSubmit={handleSubmit}>
1248
+ {/* form fields */}
1249
+ <button type="submit" disabled={mutation.isPending}>
1250
+ {mutation.isPending ? "Updating..." : "Update Profile"}
1251
+ </button>
1252
+ </form>
1253
+ );
1254
+ }
1255
+ ```
1256
+
1257
+ ## Thanks
1258
+
1259
+ If you made it this far, thanks for checking out the library, and I hope you find it useful in your projects!
1260
+
1261
+ ## License
1262
+
1263
+ Actioncraft is open source under the terms of the [MIT license](https://github.com/kellanjs/actioncraft/blob/main/LICENSE).