@molecule/api-resource 1.0.2 → 1.0.4

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 CHANGED
@@ -1,3 +1,4 @@
1
+
1
2
  Apache License
2
3
  Version 2.0, January 2004
3
4
  http://www.apache.org/licenses/
@@ -34,21 +35,33 @@
34
35
 
35
36
  "Work" shall mean the work of authorship, whether in Source or
36
37
  Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work.
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
38
40
 
39
41
  "Derivative Works" shall mean any work, whether in Source or Object
40
42
  form, that is based on (or derived from) the Work and for which the
41
43
  editorial revisions, annotations, elaborations, or other modifications
42
- represent, as a whole, an original work of authorship.
43
-
44
- "Contribution" shall mean any work of authorship, including the
45
- original version of the Work and any modifications or additions
46
- to that Work, that is intentionally submitted to the Licensor for
47
- inclusion in the Work by the copyright owner or by an individual or
48
- Legal Entity authorized to submit on behalf of the copyright owner.
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
49
62
 
50
63
  "Contributor" shall mean Licensor and any individual or Legal Entity
51
- on behalf of whom a Contribution has been received by the Licensor and
64
+ on behalf of whom a Contribution has been received by Licensor and
52
65
  subsequently incorporated within the Work.
53
66
 
54
67
  2. Grant of Copyright License. Subject to the terms and conditions of
@@ -61,8 +74,18 @@
61
74
  3. Grant of Patent License. Subject to the terms and conditions of
62
75
  this License, each Contributor hereby grants to You a perpetual,
63
76
  worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
- patent license to make, have made, use, offer to sell, sell, import,
65
- and otherwise transfer the Work.
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
66
89
 
67
90
  4. Redistribution. You may reproduce and distribute copies of the
68
91
  Work or Derivative Works thereof in any medium, with or without
@@ -84,23 +107,87 @@
84
107
  (d) If the Work includes a "NOTICE" text file as part of its
85
108
  distribution, then any Derivative Works that You distribute must
86
109
  include a readable copy of the attribution notices contained
87
- within such NOTICE file.
88
-
89
- 5. Submission of Contributions.
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
90
138
 
91
139
  6. Trademarks. This License does not grant permission to use the trade
92
- names, trademarks, service marks, or product names of the Licensor.
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
93
143
 
94
144
  7. Disclaimer of Warranty. Unless required by applicable law or
95
- agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
-
98
- 8. Limitation of Liability. In no event and under no legal theory shall
99
- any Contributor be liable to You for damages.
100
-
101
- 9. Accepting Warranty or Additional Liability.
102
-
103
- Copyright 2026 Molecule Dev, Inc.
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
104
191
 
105
192
  Licensed under the Apache License, Version 2.0 (the "License");
106
193
  you may not use this file except in compliance with the License.
package/README.md CHANGED
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-08-04T01:49:07.015Z
6
+ Generated: 2026-10-16T20:59:23.498Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-resource
@@ -18,6 +18,22 @@ Provides CRUD operation factories and request handler utilities for
18
18
  building RESTful API resources. Every `@molecule/api-resource-*` package
19
19
  (user, project, device, ...) is built on these factories.
20
20
 
21
+ **A handler returns `{ statusCode, headers?, body }` and NEVER writes to `res`** — not through
22
+ `res.json`, not through `res.send`, not through `res.end`. `createRequestHandler` is the wrapper
23
+ that applies the returned object (`res.set(headers)`, `res.status(statusCode)`, `res.send(body)`),
24
+ and a handler returns `null` only when the request should fall through to `next()`. Calling a
25
+ handler directly from your own route is therefore only correct if you apply that return value
26
+ yourself:
27
+
28
+ ```typescript
29
+ const { statusCode, headers, body } = await handler(req, res)
30
+ if (headers) res.set(headers)
31
+ res.status(statusCode).send(body)
32
+ ```
33
+
34
+ Monkey-patching `res.json` (or `res.send`/`res.end`) to re-shape a handler's answer intercepts
35
+ nothing the handler produces, so the request it was meant to answer is left unanswered and hangs.
36
+
21
37
  ## Quick Start
22
38
 
23
39
  ```typescript
@@ -76,19 +92,25 @@ npm install @molecule/api-resource @molecule/api-bond @molecule/api-database @mo
76
92
 
77
93
  ### Interfaces
78
94
 
79
- #### `ErrorFallback`
95
+ #### `Response`
80
96
 
81
- Fallback HTTP response used when a caught error is NOT a molecule-tagged error
82
- (i.e. a genuinely-unexpected failure).
97
+ Structured response object returned by resource handlers. Contains the HTTP
98
+ status code, optional headers, and the response body payload.
83
99
 
84
100
  ```typescript
85
- interface ErrorFallback {
86
- /** HTTP status for the fallback (typically 500). */
87
- status: number
88
- /** Human-readable fallback message (already localized by the caller). */
89
- message: string
90
- /** Machine-readable key the frontend maps to a localized message. */
91
- errorKey: string
101
+ interface Response {
102
+ /**
103
+ * HTTP status code to return.
104
+ */
105
+ statusCode: number
106
+ /**
107
+ * Optional map of HTTP header keys to values.
108
+ */
109
+ headers?: Record<string, string>
110
+ /**
111
+ * The response payload to return.
112
+ */
113
+ body: any
92
114
  }
93
115
  ```
94
116
 
@@ -191,25 +213,19 @@ interface Query {
191
213
  }
192
214
  ```
193
215
 
194
- #### `Response`
216
+ #### `ErrorFallback`
195
217
 
196
- Structured response object returned by resource handlers. Contains the HTTP
197
- status code, optional headers, and the response body payload.
218
+ Fallback HTTP response used when a caught error is NOT a molecule-tagged error
219
+ (i.e. a genuinely-unexpected failure).
198
220
 
199
221
  ```typescript
200
- interface Response {
201
- /**
202
- * HTTP status code to return.
203
- */
204
- statusCode: number
205
- /**
206
- * Optional map of HTTP header keys to values.
207
- */
208
- headers?: Record<string, string>
209
- /**
210
- * The response payload to return.
211
- */
212
- body: any
222
+ interface ErrorFallback {
223
+ /** HTTP status for the fallback (typically 500). */
224
+ status: number
225
+ /** Human-readable fallback message (already localized by the caller). */
226
+ message: string
227
+ /** Machine-readable key the frontend maps to a localized message. */
228
+ errorKey: string
213
229
  }
214
230
  ```
215
231
 
@@ -228,6 +244,9 @@ type Handler = (
228
244
  ) => Promise<Response | null | undefined> | Response | null | undefined
229
245
  ```
230
246
 
247
+ - `req` — The incoming HTTP request.
248
+ - `res` — The HTTP response (available but handlers should return a Response instead of calling `res` directly).
249
+
231
250
  #### `MoleculeNextFunction`
232
251
 
233
252
  Framework-agnostic next function. Call with no arguments to pass to the next
@@ -237,6 +256,8 @@ middleware, or with an error to trigger error-handling middleware.
237
256
  type MoleculeNextFunction = (err?: unknown) => void
238
257
  ```
239
258
 
259
+ - `err` — Optional error to forward to error-handling middleware.
260
+
240
261
  #### `MoleculeRequestHandler`
241
262
 
242
263
  Framework-agnostic middleware function signature matching Express's
@@ -537,38 +558,477 @@ const querySchema: z.ZodObject<
537
558
 
538
559
  #### `schema`
539
560
 
540
- Members:
561
+ Re-exported as a namespace — reach every member below through it (e.g. `schema.<name>`).
562
+
563
+ ##### `schema.basePropsSchema`
564
+
565
+ Base Zod schema with the three fields every resource row must have:
566
+ `id` (UUID), `createdAt` (ISO datetime), and `updatedAt` (ISO datetime).
567
+
568
+ ```typescript
569
+ const basePropsSchema: z.ZodObject<
570
+ { id: z.ZodString; createdAt: z.ZodString; updatedAt: z.ZodString },
571
+ z.core.$strip
572
+ >
573
+ ```
574
+
575
+ ##### `schema.BaseProps`
576
+
577
+ TypeScript type inferred from `basePropsSchema`, containing `id`, `createdAt`, and `updatedAt`.
578
+
579
+ ```typescript
580
+ type BaseProps = z.infer<typeof basePropsSchema>
581
+ ```
582
+
583
+ ##### `schema.responseSchema(propsSchema)`
584
+
585
+ Creates a Zod schema for the standard `{ statusCode, body }` response
586
+ returned by resource CRUD operations.
587
+
588
+ ```typescript
589
+ function responseSchema(
590
+ propsSchema: T,
591
+ ): z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>
592
+ ```
593
+
594
+ - `propsSchema` — The Zod schema for the resource's props (e.g. `userPropsSchema`).
595
+
596
+ **Returns:** A Zod schema that validates `{ statusCode: number, body: { props? } | T[] }`.
597
+
598
+ ##### `schema.resourceSchema(_propsSchema)`
599
+
600
+ Creates a Zod schema that validates a resource descriptor object
601
+ (`{ name, tableName, schema }`).
602
+
603
+ ```typescript
604
+ function resourceSchema(
605
+ _propsSchema: T,
606
+ ): z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>
607
+ ```
608
+
609
+ - `_propsSchema` — The Zod schema for the resource's props (used for type inference only).
610
+
611
+ **Returns:** A Zod schema that validates the resource descriptor shape.
612
+
613
+ ##### `schema.validate(schema, data)`
614
+
615
+ Validates data against a Zod schema, throwing an `Error` with a
616
+ human-readable message listing all validation failures if invalid.
617
+
618
+ ```typescript
619
+ function validate(
620
+ schema: z.ZodType<T, unknown, z.core.$ZodTypeInternals<T, unknown>>,
621
+ data: unknown,
622
+ ): T
623
+ ```
624
+
625
+ - `schema` — The Zod schema to validate against.
626
+ - `data` — The data to validate.
627
+
628
+ **Returns:** The parsed and typed data if validation succeeds.
629
+
630
+ ##### `schema.safeParse(schema, data)`
631
+
632
+ Validates data against a Zod schema without throwing. Returns a discriminated
633
+ union: `{ success: true, data }` on success or `{ success: false, error }` on failure.
634
+
635
+ ```typescript
636
+ function safeParse(
637
+ schema: z.ZodType<T, unknown, z.core.$ZodTypeInternals<T, unknown>>,
638
+ data: unknown,
639
+ ): { success: true; data: T } | { success: false; error: z.ZodError }
640
+ ```
641
+
642
+ - `schema` — The Zod schema to validate against.
643
+ - `data` — The data to validate.
644
+
645
+ **Returns:** A discriminated union indicating success with parsed data, or failure with a `ZodError`.
646
+
647
+ ##### `schema.partial(schema)`
648
+
649
+ Creates a schema where all fields are optional, suitable for validating
650
+ partial update payloads where only changed fields are sent.
651
+
652
+ ```typescript
653
+ function partial(
654
+ schema: z.ZodObject<T, z.core.$strip>,
655
+ ): z.ZodObject<{ [K in keyof T]: z.ZodOptional<T[K]> }, z.core.$strip>
656
+ ```
657
+
658
+ - `schema` — The Zod object schema to make partial.
541
659
 
542
- - `schema.basePropsSchema` — const: Base Zod schema with the three fields every resource row must have:
543
- - `schema.BaseProps` — type: TypeScript type inferred from `basePropsSchema`, containing `id`, `createdAt`, and `updatedAt`.
544
- - `schema.responseSchema` — function: Creates a Zod schema for the standard `{ statusCode, body }` response
545
- - `schema.resourceSchema` — function: Creates a Zod schema that validates a resource descriptor object
546
- - `schema.validate` — function: Validates data against a Zod schema, throwing an `Error` with a
547
- - `schema.safeParse` — function: Validates data against a Zod schema without throwing. Returns a discriminated
548
- - `schema.partial` — function: Creates a schema where all fields are optional, suitable for validating
549
- - `schema.pick` — function: Creates a schema with only the specified fields, useful for create payloads
660
+ **Returns:** A new Zod schema with all fields marked optional.
661
+
662
+ ##### `schema.pick(schema, keys)`
663
+
664
+ Creates a schema with only the specified fields, useful for create payloads
665
+ where only a subset of the full props should be provided by the client.
666
+
667
+ ```typescript
668
+ function pick(
669
+ schema: z.ZodObject<T, z.core.$strip>,
670
+ keys: readonly K[],
671
+ ): z.ZodObject<Pick<T, K>, z.core.$strip>
672
+ ```
673
+
674
+ - `schema` — The Zod object schema to pick from.
675
+ - `keys` — The field names to include in the new schema.
676
+
677
+ **Returns:** A new Zod schema containing only the picked fields.
550
678
 
551
679
  #### `types`
552
680
 
553
- Members:
681
+ Re-exported as a namespace — reach every member below through it (e.g. `types.<name>`).
682
+
683
+ ##### `types.BaseProps`
684
+
685
+ TypeScript type inferred from `basePropsSchema`, containing `id`, `createdAt`, and `updatedAt`.
686
+
687
+ ```typescript
688
+ type BaseProps = z.infer<typeof basePropsSchema>
689
+ ```
690
+
691
+ ##### `types.Props`
692
+
693
+ The resource's properties to be stored in the database.
694
+
695
+ Used by CRUD operations for type inference.
696
+
697
+ ```typescript
698
+ interface Props {
699
+ /**
700
+ * Usually a UUID.
701
+ */
702
+ id: string
703
+ /**
704
+ * When the resource was created.
705
+ *
706
+ * Usually an ISO 8601 timestamp.
707
+ */
708
+ createdAt: string
709
+ /**
710
+ * When the resource was last updated.
711
+ *
712
+ * Usually an ISO 8601 timestamp.
713
+ */
714
+ updatedAt: string
715
+ }
716
+ ```
717
+
718
+ ##### `types.Resource`
719
+
720
+ An object describing the resource.
554
721
 
555
- - `types.BaseProps` — type: TypeScript type inferred from `basePropsSchema`, containing `id`, `createdAt`, and `updatedAt`.
556
- - `types.Props` — interface: The resource's properties to be stored in the database.
557
- - `types.Resource` — interface: An object describing the resource.
558
- - `types.ZodResource` — interface: An object describing the resource with a Zod schema.
559
- - `types.Response` — interface: Standard response from resource operations.
722
+ The schema can be a Zod schema (z.ZodTypeAny) for new code,
723
+ or any other schema type for backward compatibility.
724
+
725
+ ```typescript
726
+ interface Resource<T = unknown> {
727
+ /**
728
+ * The name of the resource.
729
+ *
730
+ * @example User
731
+ */
732
+ name: string
733
+ /**
734
+ * The database table name for the resource.
735
+ *
736
+ * @example users
737
+ */
738
+ tableName: string
739
+ /**
740
+ * The schema used when validating props.
741
+ *
742
+ * Can be a Zod schema (z.ZodTypeAny) or other schema formats.
743
+ */
744
+ schema: T
745
+ }
746
+ ```
747
+
748
+ ##### `types.ZodResource`
749
+
750
+ An object describing the resource with a Zod schema.
751
+
752
+ Use this type when you want to enforce Zod schema usage.
753
+
754
+ ```typescript
755
+ interface ZodResource<T extends z.ZodTypeAny = z.ZodTypeAny> {
756
+ name: string
757
+ tableName: string
758
+ schema: T
759
+ }
760
+ ```
761
+
762
+ ##### `types.Response`
763
+
764
+ Standard response from resource operations.
765
+
766
+ ```typescript
767
+ interface Response<T = unknown> {
768
+ /**
769
+ * HTTP status code to return.
770
+ */
771
+ statusCode: number
772
+ /**
773
+ * The response payload.
774
+ */
775
+ body:
776
+ | {
777
+ props?: T
778
+ error?: string
779
+ errorKey?: string
780
+ }
781
+ | T[]
782
+ }
783
+ ```
560
784
 
561
785
  #### `utilities`
562
786
 
563
- Members:
787
+ Re-exported as a namespace — reach every member below through it (e.g. `utilities.<name>`).
788
+
789
+ ##### `utilities.ZodError`
790
+
791
+ An Error-like class used to store Zod validation issues.
792
+
793
+ ```typescript
794
+ interface ZodError<T = unknown> extends $ZodError<T> {
795
+ /** @deprecated Use the `z.treeifyError(err)` function instead. */
796
+ format(): core.$ZodFormattedError<T>
797
+ format<U>(mapper: (issue: core.$ZodIssue) => U): core.$ZodFormattedError<T, U>
798
+ /** @deprecated Use the `z.treeifyError(err)` function instead. */
799
+ flatten(): core.$ZodFlattenedError<T>
800
+ flatten<U>(mapper: (issue: core.$ZodIssue) => U): core.$ZodFlattenedError<T, U>
801
+ /** @deprecated Push directly to `.issues` instead. */
802
+ addIssue(issue: core.$ZodIssue): void
803
+ /** @deprecated Push directly to `.issues` instead. */
804
+ addIssues(issues: core.$ZodIssue[]): void
805
+ /** @deprecated Check `err.issues.length === 0` instead. */
806
+ isEmpty: boolean
807
+ }
808
+ ```
809
+
810
+ ##### `utilities.ZodSchema`
811
+
812
+ ````typescript
813
+ interface ZodType<
814
+ out Output = unknown,
815
+ out Input = unknown,
816
+ out Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<
817
+ Output,
818
+ Input
819
+ >,
820
+ > extends core.$ZodType<Output, Input, Internals> {
821
+ def: Internals['def']
822
+ type: Internals['def']['type']
823
+ /** @deprecated Use `.def` instead. */
824
+ _def: Internals['def']
825
+ /** @deprecated Use `z.output<typeof schema>` instead. */
826
+ _output: Internals['output']
827
+ /** @deprecated Use `z.input<typeof schema>` instead. */
828
+ _input: Internals['input']
829
+ '~standard': ZodStandardSchemaWithJSON<this>
830
+ /** Converts this schema to a JSON Schema representation. */
831
+ toJSONSchema(params?: core.ToJSONSchemaParams): core.ZodStandardJSONSchemaPayload<this>
832
+ check(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this
833
+ with(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this
834
+ clone(
835
+ def?: Internals['def'],
836
+ params?: {
837
+ parent: boolean
838
+ },
839
+ ): this
840
+ register<R extends core.$ZodRegistry>(
841
+ registry: R,
842
+ ...meta: this extends R['_schema']
843
+ ? undefined extends R['_meta']
844
+ ? [core.$replace<R['_meta'], this>?]
845
+ : [core.$replace<R['_meta'], this>]
846
+ : ['Incompatible schema']
847
+ ): this
848
+ brand<T extends PropertyKey = PropertyKey, Dir extends 'in' | 'out' | 'inout' = 'out'>(
849
+ value?: T,
850
+ ): PropertyKey extends T ? this : core.$ZodBranded<this, T, Dir>
851
+ parse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): core.output<this>
852
+ safeParse(
853
+ data: unknown,
854
+ params?: core.ParseContext<core.$ZodIssue>,
855
+ ): parse.ZodSafeParseResult<core.output<this>>
856
+ parseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>
857
+ safeParseAsync(
858
+ data: unknown,
859
+ params?: core.ParseContext<core.$ZodIssue>,
860
+ ): Promise<parse.ZodSafeParseResult<core.output<this>>>
861
+ spa: (
862
+ data: unknown,
863
+ params?: core.ParseContext<core.$ZodIssue>,
864
+ ) => Promise<parse.ZodSafeParseResult<core.output<this>>>
865
+ encode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): core.input<this>
866
+ decode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): core.output<this>
867
+ encodeAsync(
868
+ data: core.output<this>,
869
+ params?: core.ParseContext<core.$ZodIssue>,
870
+ ): Promise<core.input<this>>
871
+ decodeAsync(
872
+ data: core.input<this>,
873
+ params?: core.ParseContext<core.$ZodIssue>,
874
+ ): Promise<core.output<this>>
875
+ safeEncode(
876
+ data: core.output<this>,
877
+ params?: core.ParseContext<core.$ZodIssue>,
878
+ ): parse.ZodSafeParseResult<core.input<this>>
879
+ safeDecode(
880
+ data: core.input<this>,
881
+ params?: core.ParseContext<core.$ZodIssue>,
882
+ ): parse.ZodSafeParseResult<core.output<this>>
883
+ safeEncodeAsync(
884
+ data: core.output<this>,
885
+ params?: core.ParseContext<core.$ZodIssue>,
886
+ ): Promise<parse.ZodSafeParseResult<core.input<this>>>
887
+ safeDecodeAsync(
888
+ data: core.input<this>,
889
+ params?: core.ParseContext<core.$ZodIssue>,
890
+ ): Promise<parse.ZodSafeParseResult<core.output<this>>>
891
+ refine<Ch extends (arg: core.output<this>) => unknown | Promise<unknown>>(
892
+ check: Ch,
893
+ params?: string | core.$ZodCustomParams,
894
+ ): Ch extends (arg: any) => arg is infer R ? this & ZodType<R, core.input<this>> : this
895
+ superRefine(
896
+ refinement: (
897
+ arg: core.output<this>,
898
+ ctx: core.$RefinementCtx<core.output<this>>,
899
+ ) => void | Promise<void>,
900
+ params?: core.$ZodSuperRefineParams,
901
+ ): this
902
+ overwrite(fn: (x: core.output<this>) => core.output<this>): this
903
+ optional(): ZodOptional<this>
904
+ exactOptional(): ZodExactOptional<this>
905
+ nonoptional(params?: string | core.$ZodNonOptionalParams): ZodNonOptional<this>
906
+ nullable(): ZodNullable<this>
907
+ nullish(): ZodOptional<ZodNullable<this>>
908
+ default(def: util.NoUndefined<core.output<this>>): ZodDefault<this>
909
+ default(def: () => util.NoUndefined<core.output<this>>): ZodDefault<this>
910
+ prefault(def: () => core.input<this>): ZodPrefault<this>
911
+ prefault(def: core.input<this>): ZodPrefault<this>
912
+ array(): ZodArray<this>
913
+ or<T extends core.SomeType>(option: T): ZodUnion<[this, T]>
914
+ and<T extends core.SomeType>(incoming: T): ZodIntersection<this, T>
915
+ transform<NewOut>(
916
+ transform: (
917
+ arg: core.output<this>,
918
+ ctx: core.$RefinementCtx<core.output<this>>,
919
+ ) => NewOut | Promise<NewOut>,
920
+ ): ZodPipe<this, ZodTransform<Awaited<NewOut>, core.output<this>>>
921
+ catch(def: core.output<this>): ZodCatch<this>
922
+ catch(def: (ctx: core.$ZodCatchCtx) => core.output<this>): ZodCatch<this>
923
+ pipe<T extends core.$ZodType<any, core.output<this>>>(
924
+ target: T | core.$ZodType<any, core.output<this>>,
925
+ ): ZodPipe<this, T>
926
+ readonly(): ZodReadonly<this>
927
+ /** Returns a new instance that has been registered in `z.globalRegistry` with the specified description */
928
+ describe(description: string): this
929
+ description?: string
930
+ /** Returns the metadata associated with this instance in `z.globalRegistry` */
931
+ meta(): core.$replace<core.GlobalMeta, this> | undefined
932
+ /** Returns a new instance that has been registered in `z.globalRegistry` with the specified metadata */
933
+ meta(data: core.$replace<core.GlobalMeta, this>): this
934
+ /** @deprecated Try safe-parsing `undefined` (this is what `isOptional` does internally):
935
+ *
936
+ * ```ts
937
+ * const schema = z.string().optional();
938
+ * const isOptional = schema.safeParse(undefined).success; // true
939
+ * ```
940
+ */
941
+ isOptional(): boolean
942
+ /**
943
+ * @deprecated Try safe-parsing `null` (this is what `isNullable` does internally):
944
+ *
945
+ * ```ts
946
+ * const schema = z.string().nullable();
947
+ * const isNullable = schema.safeParse(null).success; // true
948
+ * ```
949
+ */
950
+ isNullable(): boolean
951
+ apply<T>(fn: (schema: this) => T): T
952
+ }
953
+ ````
954
+
955
+ ##### `utilities.getValidProps`
956
+
957
+ Validates resource props against a Zod schema, returning typed valid props or throwing
958
+ a descriptive error with field-level messages prefixed by the resource name.
959
+
960
+ ```typescript
961
+ const getValidProps: <Props>({
962
+ name,
963
+ schema,
964
+ props,
965
+ }: {
966
+ name: string
967
+ schema: ZodSchema<Props>
968
+ props: unknown
969
+ }) => Props
970
+ ```
971
+
972
+ - `options` — Validation options.
973
+ - `options.name` — The resource name (used in error messages, e.g., `"User.email: Required"`).
974
+ - `options.schema` — The Zod schema to validate against.
975
+ - `options.props` — The raw props to validate.
976
+
977
+ **Returns:** The validated and typed props.
978
+
979
+ ##### `utilities.safeParse`
980
+
981
+ Validates data against a Zod schema without throwing, returning a discriminated union.
982
+
983
+ ```typescript
984
+ const safeParse: <T>(
985
+ schema: ZodSchema<T>,
986
+ data: unknown,
987
+ ) => { success: true; data: T } | { success: false; error: ZodError }
988
+ ```
989
+
990
+ - `schema` — The Zod schema to validate against.
991
+ - `data` — The raw data to validate.
992
+
993
+ **Returns:** `{ success: true, data }` on success, or `{ success: false, error }` with a ZodError.
994
+
995
+ ##### `utilities.validate`
996
+
997
+ Validates data against a Zod schema, throwing a ZodError on failure.
998
+
999
+ ```typescript
1000
+ const validate: <T>(schema: ZodSchema<T>, data: unknown) => T
1001
+ ```
1002
+
1003
+ - `schema` — The Zod schema to validate against.
1004
+ - `data` — The raw data to validate.
1005
+
1006
+ **Returns:** The validated and typed data.
1007
+
1008
+ ##### `utilities.isEmail`
1009
+
1010
+ Basic regex for determining whether or not a string is an email address.
1011
+
1012
+ ```typescript
1013
+ const isEmail: (string: string, strict?: boolean) => boolean
1014
+ ```
1015
+
1016
+ - `string` — The string.
1017
+ - `strict` — Whether strict.
1018
+
1019
+ **Returns:** Whether email.
1020
+
1021
+ ##### `utilities.isUuid`
1022
+
1023
+ Basic regex for determining whether or not a string is a UUID.
1024
+
1025
+ ```typescript
1026
+ const isUuid: (uuid: string) => boolean
1027
+ ```
1028
+
1029
+ - `uuid` — The uuid.
564
1030
 
565
- - `utilities.getValidProps` — const: Validates resource props against a Zod schema, returning typed valid props or throwing
566
- - `utilities.safeParse` — const: Validates data against a Zod schema without throwing, returning a discriminated union.
567
- - `utilities.validate` — const: Validates data against a Zod schema, throwing a ZodError on failure.
568
- - `utilities.ZodError` — interface: An Error-like class used to store Zod validation issues.
569
- - `utilities.ZodSchema` — interface
570
- - `utilities.isEmail` — const: Basic regex for determining whether or not a string is an email address.
571
- - `utilities.isUuid` — const: Basic regex for determining whether or not a string is a UUID.
1031
+ **Returns:** Whether uuid.
572
1032
 
573
1033
  ## Injection Notes
574
1034
 
package/dist/index.d.ts CHANGED
@@ -5,6 +5,22 @@
5
5
  * building RESTful API resources. Every `@molecule/api-resource-*` package
6
6
  * (user, project, device, ...) is built on these factories.
7
7
  *
8
+ * **A handler returns `{ statusCode, headers?, body }` and NEVER writes to `res`** — not through
9
+ * `res.json`, not through `res.send`, not through `res.end`. `createRequestHandler` is the wrapper
10
+ * that applies the returned object (`res.set(headers)`, `res.status(statusCode)`, `res.send(body)`),
11
+ * and a handler returns `null` only when the request should fall through to `next()`. Calling a
12
+ * handler directly from your own route is therefore only correct if you apply that return value
13
+ * yourself:
14
+ *
15
+ * ```typescript
16
+ * const { statusCode, headers, body } = await handler(req, res)
17
+ * if (headers) res.set(headers)
18
+ * res.status(statusCode).send(body)
19
+ * ```
20
+ *
21
+ * Monkey-patching `res.json` (or `res.send`/`res.end`) to re-shape a handler's answer intercepts
22
+ * nothing the handler produces, so the request it was meant to answer is left unanswered and hangs.
23
+ *
8
24
  * @example
9
25
  * ```typescript
10
26
  * import { z } from 'zod'
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqFG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,aAAa,CAAA;AAC3B,cAAc,2BAA2B,CAAA;AACzC,cAAc,UAAU,CAAA;AACxB,cAAc,iBAAiB,CAAA;AAC/B,cAAc,WAAW,CAAA;AACzB,cAAc,YAAY,CAAA;AAC1B,cAAc,WAAW,CAAA;AACzB,cAAc,oBAAoB,CAAA;AAClC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,cAAc,aAAa,CAAA;AAC3B,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqGG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,aAAa,CAAA;AAC3B,cAAc,2BAA2B,CAAA;AACzC,cAAc,UAAU,CAAA;AACxB,cAAc,iBAAiB,CAAA;AAC/B,cAAc,WAAW,CAAA;AACzB,cAAc,YAAY,CAAA;AAC1B,cAAc,WAAW,CAAA;AACzB,cAAc,oBAAoB,CAAA;AAClC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,cAAc,aAAa,CAAA;AAC3B,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA"}
package/dist/index.js CHANGED
@@ -5,6 +5,22 @@
5
5
  * building RESTful API resources. Every `@molecule/api-resource-*` package
6
6
  * (user, project, device, ...) is built on these factories.
7
7
  *
8
+ * **A handler returns `{ statusCode, headers?, body }` and NEVER writes to `res`** — not through
9
+ * `res.json`, not through `res.send`, not through `res.end`. `createRequestHandler` is the wrapper
10
+ * that applies the returned object (`res.set(headers)`, `res.status(statusCode)`, `res.send(body)`),
11
+ * and a handler returns `null` only when the request should fall through to `next()`. Calling a
12
+ * handler directly from your own route is therefore only correct if you apply that return value
13
+ * yourself:
14
+ *
15
+ * ```typescript
16
+ * const { statusCode, headers, body } = await handler(req, res)
17
+ * if (headers) res.set(headers)
18
+ * res.status(statusCode).send(body)
19
+ * ```
20
+ *
21
+ * Monkey-patching `res.json` (or `res.send`/`res.end`) to re-shape a handler's answer intercepts
22
+ * nothing the handler produces, so the request it was meant to answer is left unanswered and hangs.
23
+ *
8
24
  * @example
9
25
  * ```typescript
10
26
  * import { z } from 'zod'
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqFG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,aAAa,CAAA;AAC3B,cAAc,2BAA2B,CAAA;AACzC,cAAc,UAAU,CAAA;AACxB,cAAc,iBAAiB,CAAA;AAC/B,cAAc,WAAW,CAAA;AACzB,cAAc,YAAY,CAAA;AAC1B,cAAc,WAAW,CAAA;AACzB,cAAc,oBAAoB,CAAA;AAClC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,cAAc,aAAa,CAAA;AAC3B,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqGG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,aAAa,CAAA;AAC3B,cAAc,2BAA2B,CAAA;AACzC,cAAc,UAAU,CAAA;AACxB,cAAc,iBAAiB,CAAA;AAC/B,cAAc,WAAW,CAAA;AACzB,cAAc,YAAY,CAAA;AAC1B,cAAc,WAAW,CAAA;AACzB,cAAc,oBAAoB,CAAA;AAClC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAA;AACrC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,cAAc,aAAa,CAAA;AAC3B,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-resource",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Resource CRUD operations and utilities for molecule.dev.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -40,7 +40,7 @@
40
40
  },
41
41
  "devDependencies": {
42
42
  "@molecule/api-bond": "1.0.2",
43
- "@molecule/api-database": "1.0.2",
43
+ "@molecule/api-database": "1.1.3",
44
44
  "@molecule/api-locales-resource": "1.0.2",
45
45
  "@molecule/api-utilities-validation": "1.0.2",
46
46
  "@types/node": "26.1.2",