@notation/resource 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,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.
@@ -0,0 +1,352 @@
1
+ type IfAllPropertiesOptional<T, Y, N> = T extends Partial<T> ? (Partial<T> extends T ? Y : N) : N;
2
+ type OptionalIfAllPropertiesOptional<K extends string, T> = IfAllPropertiesOptional<T, {
3
+ [Key in K]?: T;
4
+ }, {
5
+ [Key in K]: T;
6
+ }>;
7
+ type Fallback<T, U> = T extends undefined ? U : T;
8
+ type NoInfer<T> = [T][T extends any ? 0 : never];
9
+ /**
10
+ * Flattens an intersection into a single object type.
11
+ *
12
+ * Keeps mapped types readable in IntelliSense without the assignability
13
+ * checks a conditional-based unwrap would cost.
14
+ */
15
+ type Simplify<T> = {
16
+ [K in keyof T]: T[K];
17
+ } & {};
18
+ /**
19
+ * Deeply makes all properties optional.
20
+ */
21
+ type DeepPartial<T> = {
22
+ [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
23
+ };
24
+ type OptionalKeys<T> = {
25
+ [K in keyof T]: undefined extends T[K] ? never : K;
26
+ }[keyof T];
27
+ /**
28
+ * Pick the required (non-optional) keys from T.
29
+ */
30
+ type OmitOptional<T> = Pick<T, OptionalKeys<T>>;
31
+ /**
32
+ * Pick the optional keys from T.
33
+ */
34
+ type PickOptional<T> = Omit<T, OptionalKeys<T>>;
35
+
36
+ /**
37
+ * Structural holder for a value type.
38
+ *
39
+ * Used as a phantom type carrier: schema value types are resolved from the
40
+ * resource's API schema, so items only carry metadata. Where a narrower type
41
+ * than the API's is wanted, `valueType: typed<T>()` overrides it. Any zod
42
+ * type is also structurally assignable, so zod validators can be used as
43
+ * overrides without this package depending on zod.
44
+ */
45
+ type TypedValue<T> = {
46
+ _output: T;
47
+ };
48
+ /**
49
+ * Phantom value-type override for a schema item.
50
+ * Purely type-level; carries no runtime information.
51
+ */
52
+ declare const typed: <T>() => TypedValue<T>;
53
+ type DefineResourceApiSchema = {
54
+ Key: any;
55
+ CreateParams: any;
56
+ UpdateParams: any;
57
+ ReadResult: any;
58
+ };
59
+ /**
60
+ * A schema item is metadata about one property of a resource.
61
+ *
62
+ * Its value type is taken from the resource's API schema (see
63
+ * {@link ResolveSchema}); `valueType` is only needed to override that, or to
64
+ * type properties that exist in no API type.
65
+ */
66
+ type SchemaItem<T = any> = {
67
+ valueType?: TypedValue<T>;
68
+ presence: "required" | "optional";
69
+ sensitive?: true;
70
+ hidden?: true;
71
+ volatile?: true;
72
+ } & ({
73
+ propertyType: "param";
74
+ immutable?: true;
75
+ defaultValue?: T;
76
+ primaryKey?: true;
77
+ secondaryKey?: true;
78
+ } | {
79
+ propertyType: "computed";
80
+ primaryKey?: true;
81
+ } | {
82
+ propertyType: "derived";
83
+ });
84
+ /** A schema as authored: metadata per property. */
85
+ type Schema = Record<string, SchemaItem<any>>;
86
+ /**
87
+ * A schema whose items all carry a resolved value type.
88
+ *
89
+ * Deliberately loose (the mappers read `valueType` and the metadata flags
90
+ * conditionally): schema safety is enforced where schemas are authored, via
91
+ * {@link SchemaFromApi}, not in the type plumbing downstream of it.
92
+ */
93
+ type ResolvedSchema = Record<string, any>;
94
+ type UpdateParamsOf<Api extends DefineResourceApiSchema> = Fallback<Api["UpdateParams"], Api["CreateParams"]>;
95
+ type ReadResultOf<Api extends DefineResourceApiSchema> = Fallback<Api["ReadResult"], {}>;
96
+ /**
97
+ * The value type of schema item `K`: an explicit `valueType` override wins,
98
+ * otherwise the type comes from the API schema (params take precedence over
99
+ * read results, since read results often widen param types).
100
+ */
101
+ type SchemaItemValue<Api extends DefineResourceApiSchema, S extends Schema, K extends keyof S> = S[K] extends {
102
+ valueType: TypedValue<infer T>;
103
+ } ? T : K extends keyof Api["CreateParams"] ? Exclude<Api["CreateParams"][K], undefined> : K extends keyof Api["Key"] ? Exclude<Api["Key"][K], undefined> : K extends keyof UpdateParamsOf<Api> ? Exclude<UpdateParamsOf<Api>[K], undefined> : K extends keyof ReadResultOf<Api> ? Exclude<ReadResultOf<Api>[K], undefined> : MissingValueType<K>;
104
+ /**
105
+ * Marker for schema keys found in no API schema type and lacking a
106
+ * `valueType` override. Deliberately unusable, so the mistake surfaces at
107
+ * the first use of the property rather than silently typing it `unknown`.
108
+ */
109
+ type MissingValueType<K> = {
110
+ error: "Schema key not found in API schema types; add it there or set an explicit valueType";
111
+ key: K;
112
+ };
113
+ /**
114
+ * Pairs each schema item with its value type, resolved from the API schema.
115
+ * Computed once per resource, when the schema is defined.
116
+ */
117
+ type ResolveSchema<Api extends DefineResourceApiSchema, S extends Schema> = {
118
+ [K in keyof S]: S[K] & {
119
+ valueType: TypedValue<SchemaItemValue<Api, S, K>>;
120
+ };
121
+ };
122
+ type ComputedPrimaryKey<S extends ResolvedSchema> = FallbackToVoid<MapSchema<S, {
123
+ propertyType: "param";
124
+ }, "primaryKey">>;
125
+ type FallbackToVoid<T> = {} extends T ? void : T;
126
+ type CompoundKey<S extends ResolvedSchema> = MapSchema<S, never, "primaryKey" | "secondaryKey">;
127
+ type Params<S extends ResolvedSchema> = MapSchema<S, {
128
+ propertyType: "computed" | "derived";
129
+ }>;
130
+ type Result<S extends ResolvedSchema> = DeepPartial<MapSchema<S, {
131
+ propertyType: "param" | "derived";
132
+ }>>;
133
+ type Output<S extends ResolvedSchema> = MapSchema<S>;
134
+ type State<S extends ResolvedSchema> = MapSchema<S, {
135
+ hidden: true;
136
+ }>;
137
+ /**
138
+ * What a schema must look like for a given API schema: propertyType,
139
+ * presence and mutability are forced per key by where (and how) the key
140
+ * appears in the API types. A `valueType` override, when given, must stay
141
+ * assignable to the API's type for that key.
142
+ */
143
+ type SchemaFromApi<ApiCompoundKey, ApiCreateParams, ApiUpdateParams, ApiReadResult> = {
144
+ [K in keyof ApiCompoundKey]: SchemaItem<ApiCompoundKey[K]> & ({
145
+ primaryKey: true;
146
+ } | {
147
+ secondaryKey: true;
148
+ });
149
+ } & {
150
+ [K in keyof OmitOptional<Omit<ApiCreateParams, keyof ApiCompoundKey>>]: SchemaItem<ApiCreateParams[K]> & {
151
+ propertyType: "param";
152
+ presence: "required";
153
+ };
154
+ } & {
155
+ [K in keyof PickOptional<Omit<ApiCreateParams, keyof ApiCompoundKey>>]: SchemaItem<ApiCreateParams[K]> & {
156
+ propertyType: "param";
157
+ presence: "optional";
158
+ };
159
+ } & {
160
+ [K in keyof Omit<ApiCreateParams, keyof ApiUpdateParams>]: SchemaItem<ApiCreateParams[K]> & {
161
+ propertyType: "param";
162
+ immutable: true;
163
+ };
164
+ } & {
165
+ [K in keyof Omit<ApiReadResult, keyof ApiCreateParams | keyof ApiCompoundKey>]: SchemaItem<ApiReadResult[K]> & {
166
+ propertyType: "computed";
167
+ };
168
+ };
169
+ /**
170
+ * Maps `valueType` to its output type.
171
+ * Makes optional fields optional.
172
+ * Excludes properties matching the `ExcludeConditions` type.
173
+ * When `IncludeKey` is given, keeps only items that have that property.
174
+ */
175
+ type MapSchema<S extends ResolvedSchema, ExcludeConditions = never, IncludeKey = any> = Simplify<{
176
+ [K in keyof S as S[K] extends {
177
+ presence: "optional";
178
+ } | ExcludeConditions ? never : IncludeKey extends keyof S[K] ? K : never]: S[K]["valueType"]["_output"];
179
+ } & {
180
+ [K in keyof S as S[K] extends ExcludeConditions ? never : S[K] extends {
181
+ presence: "optional";
182
+ } ? IncludeKey extends keyof S[K] ? K : never : never]?: S[K]["valueType"]["_output"];
183
+ }>;
184
+
185
+ /** Plain data passed from one attempt of an operation to the next. */
186
+ type ResourceOperationContext = Readonly<Record<string, unknown>>;
187
+ /**
188
+ * A `read` operation throws this error when no resource exists for its key.
189
+ */
190
+ declare class ResourceNotFoundError extends Error {
191
+ readonly _tag: "ResourceNotFoundError";
192
+ constructor(message: string, options?: ErrorOptions);
193
+ static is(error: unknown): error is ResourceNotFoundError;
194
+ }
195
+ /**
196
+ * An operation throws this error when it has not finished.
197
+ *
198
+ * The reconciler waits for `retryAfterMs`, then calls the same operation again
199
+ * with `callbackContext`.
200
+ */
201
+ declare class ResourceOperationPendingError extends Error {
202
+ readonly _tag: "ResourceOperationPendingError";
203
+ /** Milliseconds to wait before the next attempt. */
204
+ readonly retryAfterMs: number;
205
+ /** Plain data passed to the next attempt of the same operation. */
206
+ readonly callbackContext?: ResourceOperationContext;
207
+ constructor(message: string, options: ErrorOptions & {
208
+ retryAfterMs: number;
209
+ callbackContext?: ResourceOperationContext;
210
+ });
211
+ static is(error: unknown): error is ResourceOperationPendingError;
212
+ }
213
+ type ResourceOperationSignal = ResourceNotFoundError | ResourceOperationPendingError;
214
+
215
+ type ResourceType = `${string}/${string}/${string}`;
216
+ type ResourceOpts<C, D> = OptionalIfAllPropertiesOptional<"config", C> & OptionalIfAllPropertiesOptional<"dependencies", D> & {
217
+ id: string;
218
+ };
219
+ /**
220
+ * The object types a resource's schema gives rise to.
221
+ *
222
+ * These are derived from the schema exactly once, when `defineSchema` is
223
+ * called (see {@link InferResourceTypes}). Everything downstream — operation
224
+ * callbacks, instances, dependency inference — is generic over this small
225
+ * bag of plain object types, so the schema literal never re-enters type
226
+ * inference.
227
+ */
228
+ type ResourceTypes = {
229
+ params: any;
230
+ compoundKey: any;
231
+ primaryKey: any;
232
+ result: any;
233
+ state: any;
234
+ output: any;
235
+ };
236
+ type InferResourceTypes<S extends ResolvedSchema> = {
237
+ params: Params<S>;
238
+ compoundKey: CompoundKey<S>;
239
+ primaryKey: ComputedPrimaryKey<S>;
240
+ result: Result<S>;
241
+ state: State<S>;
242
+ output: Output<S>;
243
+ };
244
+ interface BaseResource {
245
+ readonly type: ResourceType;
246
+ readonly schema: Schema;
247
+ readonly config: any;
248
+ id: string;
249
+ groupId: number;
250
+ groupType: string;
251
+ readonly output: {};
252
+ readonly dependencies: Record<string, BaseResource | void>;
253
+ readonly key: {};
254
+ create: (params: any, context?: ResourceOperationContext) => Promise<{} | void>;
255
+ read?: (key: any, context?: ResourceOperationContext) => Promise<Record<string, any>>;
256
+ update?: (key: any, patch: any, params: any, state: any, context?: ResourceOperationContext) => Promise<void>;
257
+ delete: (key: any, state: any, context?: ResourceOperationContext) => Promise<void>;
258
+ getParams(): Promise<{}>;
259
+ toState(output: {}): {};
260
+ toComparable(output: {}): {};
261
+ setOutput(result: {}): void;
262
+ deriveParams?: (opts: {
263
+ id: string;
264
+ config: any;
265
+ deps: any;
266
+ }) => Record<string, any> | Promise<Record<string, any>>;
267
+ }
268
+ declare abstract class Resource<T extends ResourceTypes = ResourceTypes, D extends Record<string, BaseResource | void> = {}, C extends Record<string, any> = T["params"]> implements BaseResource {
269
+ config: C;
270
+ id: string;
271
+ groupId: number;
272
+ groupType: string;
273
+ output: T["output"];
274
+ dependencies: NoInfer<D>;
275
+ abstract type: ResourceType;
276
+ abstract schema: Schema;
277
+ abstract create: (params: T["params"], context?: ResourceOperationContext) => Promise<T["primaryKey"]>;
278
+ abstract read?: (key: T["compoundKey"], context?: ResourceOperationContext) => Promise<T["result"]>;
279
+ abstract update?: (key: T["compoundKey"], patch: T["params"], params: T["params"], state: T["state"], context?: ResourceOperationContext) => Promise<void>;
280
+ abstract delete: (key: T["compoundKey"], state: T["state"], context?: ResourceOperationContext) => Promise<void>;
281
+ abstract deriveParams(opts: {
282
+ id: string;
283
+ config: C;
284
+ deps: D;
285
+ }): Record<string, any> | Promise<Record<string, any>>;
286
+ constructor(opts: ResourceOpts<C, D>);
287
+ get key(): T["compoundKey"];
288
+ setOutput(output: T["output"]): void;
289
+ toComparable(output: T["output"]): T["output"];
290
+ toState(output: T["output"]): T["state"];
291
+ getParams(): Promise<T["params"]>;
292
+ }
293
+ type DefineResourceMeta = {
294
+ type: ResourceType;
295
+ };
296
+ type ResourceOperationsOptions<T extends ResourceTypes, IntrinsicParams extends Partial<T["params"]>> = {
297
+ create: (params: T["params"], context?: ResourceOperationContext) => Promise<T["primaryKey"]>;
298
+ read?: (key: T["compoundKey"], context?: ResourceOperationContext) => Promise<T["result"]>;
299
+ update?: (key: T["compoundKey"], patch: T["params"], params: T["params"], state: T["state"], context?: ResourceOperationContext) => Promise<void>;
300
+ delete: (key: T["compoundKey"], state: T["state"], context?: ResourceOperationContext) => Promise<void>;
301
+ deriveParams?: (opts: {
302
+ config: Partial<T["params"]>;
303
+ }) => IntrinsicParams | Promise<IntrinsicParams>;
304
+ };
305
+ type ResourceDependenciesBuilder<T extends ResourceTypes, IntrinsicParams extends Partial<T["params"]>, Dependencies extends Record<string, BaseResource | void>> = {
306
+ deriveParams: <DepAwareParams extends Partial<T["params"]>>(deriveParams: (opts: {
307
+ id: string;
308
+ config: T["params"];
309
+ deps: Dependencies;
310
+ }) => DepAwareParams | Promise<DepAwareParams>) => ResourceClass<T, Dependencies, Omit<T["params"], keyof IntrinsicParams | keyof DepAwareParams>>;
311
+ };
312
+ type ResourceClass<T extends ResourceTypes, D extends Record<string, BaseResource | void> = {}, C extends Record<string, any> = T["params"], IntrinsicParams extends Partial<T["params"]> = {}> = {
313
+ new (opts: ResourceOpts<C, D>): Resource<T, D, C>;
314
+ readonly type: ResourceType;
315
+ requireDependencies: <Dependencies extends Record<string, BaseResource | void>>() => ResourceDependenciesBuilder<T, IntrinsicParams, Dependencies>;
316
+ };
317
+ type ResourceSchemaBuilder<T extends ResourceTypes> = {
318
+ defineOperations: <IntrinsicParams extends Partial<T["params"]> = {}>(opts: ResourceOperationsOptions<T, IntrinsicParams>) => ResourceClass<T, {}, Omit<T["params"], keyof IntrinsicParams>, IntrinsicParams>;
319
+ };
320
+ type ResourceBuilder<ApiSchema extends DefineResourceApiSchema> = {
321
+ defineSchema: <S extends Schema & SchemaFromApi<ApiSchema["Key"], ApiSchema["CreateParams"], Fallback<ApiSchema["UpdateParams"], ApiSchema["CreateParams"]>, Fallback<ApiSchema["ReadResult"], {}>>>(schema: S) => ResourceSchemaBuilder<InferResourceTypes<ResolveSchema<ApiSchema, S>>>;
322
+ };
323
+ declare function defineResource<ApiSchema extends DefineResourceApiSchema>(meta: DefineResourceMeta): ResourceBuilder<ApiSchema>;
324
+ declare const resource: typeof defineResource;
325
+
326
+ type ResourceGroupOptions = {
327
+ /**
328
+ * Optional pre-assigned ID. Used outside graph collection.
329
+ */
330
+ id?: number;
331
+ dependencies?: Record<string, number>;
332
+ [key: string]: any;
333
+ };
334
+ declare abstract class ResourceGroup {
335
+ #private;
336
+ type: string;
337
+ id: number;
338
+ dependencies: Record<string, number>;
339
+ config: Record<string, any>;
340
+ resources: BaseResource[];
341
+ constructor(type: string, opts: ResourceGroupOptions);
342
+ add<T extends BaseResource>(resource: T): T;
343
+ findResource<T extends new (...opts: any[]) => BaseResource>(ResourceClass: T): InstanceType<T> | undefined;
344
+ }
345
+
346
+ type ResourceGraph = {
347
+ resourceGroups: ResourceGroup[];
348
+ resources: BaseResource[];
349
+ };
350
+ declare function collectResourceGraph(evaluate: () => unknown | Promise<unknown>): Promise<ResourceGraph>;
351
+
352
+ export { type BaseResource, type CompoundKey, type ComputedPrimaryKey, type DeepPartial, type DefineResourceApiSchema, type DefineResourceMeta, type Fallback, type IfAllPropertiesOptional, type InferResourceTypes, type MapSchema, type NoInfer, type OmitOptional, type OptionalIfAllPropertiesOptional, type Output, type Params, type PickOptional, type ResolveSchema, type ResolvedSchema, Resource, type ResourceBuilder, type ResourceClass, type ResourceDependenciesBuilder, type ResourceGraph, ResourceGroup, type ResourceGroupOptions, ResourceNotFoundError, type ResourceOperationContext, ResourceOperationPendingError, type ResourceOperationSignal, type ResourceOperationsOptions, type ResourceOpts, type ResourceSchemaBuilder, type ResourceType, type ResourceTypes, type Result, type Schema, type SchemaFromApi, type SchemaItem, type Simplify, type State, type TypedValue, collectResourceGraph, defineResource, resource, typed };
package/dist/index.js ADDED
@@ -0,0 +1,216 @@
1
+ // src/resource.schema.ts
2
+ var typed = () => ({});
3
+
4
+ // src/resource.ts
5
+ var Resource = class {
6
+ config;
7
+ id;
8
+ groupId = -1;
9
+ groupType = "";
10
+ output = null;
11
+ dependencies = {};
12
+ constructor(opts) {
13
+ this.id = opts.id;
14
+ this.config = opts.config || {};
15
+ this.dependencies = opts.dependencies || {};
16
+ return this;
17
+ }
18
+ get key() {
19
+ const key = {};
20
+ for (const [k, v] of Object.entries(this.schema)) {
21
+ if (v.primaryKey || v.secondaryKey) {
22
+ key[k] = this.output[k];
23
+ }
24
+ }
25
+ return key;
26
+ }
27
+ setOutput(output) {
28
+ this.output = output;
29
+ }
30
+ toComparable(output) {
31
+ const parsed = {};
32
+ for (const [k, v] of Object.entries(this.schema)) {
33
+ if (v.volatile) continue;
34
+ if (v.hidden) continue;
35
+ if (v.propertyType !== "param") continue;
36
+ if (k in output) {
37
+ parsed[k] = output[k];
38
+ }
39
+ }
40
+ return parsed;
41
+ }
42
+ toState(output) {
43
+ const parsed = {};
44
+ for (const [k, v] of Object.entries(this.schema)) {
45
+ if (v.hidden) continue;
46
+ if (k in output) {
47
+ parsed[k] = output[k];
48
+ }
49
+ }
50
+ return parsed;
51
+ }
52
+ async getParams() {
53
+ return {
54
+ ...this.config,
55
+ ...await this.deriveParams({
56
+ id: this.id,
57
+ config: this.config,
58
+ deps: this.dependencies
59
+ })
60
+ };
61
+ }
62
+ };
63
+ function defineResource(meta) {
64
+ return {
65
+ defineSchema(schema) {
66
+ const builder = {
67
+ defineOperations(opts) {
68
+ class SimpleResource extends Resource {
69
+ static type = meta.type;
70
+ type = meta.type;
71
+ schema = schema;
72
+ create = opts.create;
73
+ read = opts.read ? opts.read : void 0;
74
+ update = opts.update ? opts.update : void 0;
75
+ delete = opts.delete;
76
+ async deriveParams() {
77
+ if (!opts.deriveParams) return {};
78
+ return await opts.deriveParams({
79
+ config: this.config
80
+ });
81
+ }
82
+ static requireDependencies() {
83
+ return {
84
+ deriveParams(deriveParams) {
85
+ return class DependencyAwareResource extends SimpleResource {
86
+ async deriveParams() {
87
+ const superParams = await super.deriveParams();
88
+ return {
89
+ ...superParams,
90
+ ...await deriveParams({
91
+ id: this.id,
92
+ config: this.config,
93
+ deps: this.dependencies
94
+ })
95
+ };
96
+ }
97
+ };
98
+ }
99
+ };
100
+ }
101
+ }
102
+ return SimpleResource;
103
+ }
104
+ };
105
+ return builder;
106
+ }
107
+ };
108
+ }
109
+ var resource = defineResource;
110
+
111
+ // src/resource-operation.ts
112
+ var ResourceNotFoundError = class extends Error {
113
+ _tag = "ResourceNotFoundError";
114
+ constructor(message, options) {
115
+ super(message, options);
116
+ this.name = "ResourceNotFoundError";
117
+ }
118
+ static is(error) {
119
+ return hasTag(error, "ResourceNotFoundError");
120
+ }
121
+ };
122
+ var ResourceOperationPendingError = class extends Error {
123
+ _tag = "ResourceOperationPendingError";
124
+ /** Milliseconds to wait before the next attempt. */
125
+ retryAfterMs;
126
+ /** Plain data passed to the next attempt of the same operation. */
127
+ callbackContext;
128
+ constructor(message, options) {
129
+ super(message, options);
130
+ this.name = "ResourceOperationPendingError";
131
+ this.retryAfterMs = options.retryAfterMs;
132
+ this.callbackContext = options.callbackContext;
133
+ if (!Number.isFinite(options.retryAfterMs) || options.retryAfterMs < 0) {
134
+ throw new RangeError("retryAfterMs must be a non-negative number");
135
+ }
136
+ }
137
+ static is(error) {
138
+ return hasTag(error, "ResourceOperationPendingError") && "retryAfterMs" in error && typeof error.retryAfterMs === "number";
139
+ }
140
+ };
141
+ function hasTag(error, tag) {
142
+ return typeof error === "object" && error !== null && "_tag" in error && error._tag === tag;
143
+ }
144
+
145
+ // src/resource-collection.ts
146
+ var activeCollection;
147
+ async function collectResourceGraph(evaluate) {
148
+ if (activeCollection) {
149
+ throw new Error("A resource graph is already being collected.");
150
+ }
151
+ const collection = {
152
+ graph: { resourceGroups: [], resources: [] },
153
+ nextResourceGroupId: 0
154
+ };
155
+ activeCollection = collection;
156
+ try {
157
+ await evaluate();
158
+ return collection.graph;
159
+ } finally {
160
+ activeCollection = void 0;
161
+ }
162
+ }
163
+ function getActiveResourceCollection() {
164
+ return activeCollection;
165
+ }
166
+
167
+ // src/resource-group.ts
168
+ var ResourceGroup = class {
169
+ type;
170
+ id;
171
+ dependencies;
172
+ config;
173
+ resources;
174
+ #graph;
175
+ constructor(type, opts) {
176
+ const { dependencies, id, ...config } = opts;
177
+ const collection = getActiveResourceCollection();
178
+ this.type = type;
179
+ this.#graph = collection?.graph;
180
+ this.id = collection ? collection.nextResourceGroupId++ : id ?? -1;
181
+ this.dependencies = dependencies || {};
182
+ this.config = config || {};
183
+ this.resources = [];
184
+ collection?.graph.resourceGroups.push(this);
185
+ return this;
186
+ }
187
+ add(resource2) {
188
+ if (this.#graph) {
189
+ if (this.#graph.resources.includes(resource2)) {
190
+ throw new Error(
191
+ `Resource ${resource2.type} has already been registered.`
192
+ );
193
+ }
194
+ this.#graph.resources.push(resource2);
195
+ } else if (this.resources.includes(resource2)) {
196
+ throw new Error(`Resource ${resource2.type} has already been registered.`);
197
+ }
198
+ resource2.groupId = this.id;
199
+ resource2.groupType = this.type;
200
+ this.resources.push(resource2);
201
+ return resource2;
202
+ }
203
+ findResource(ResourceClass) {
204
+ return this.resources.find((r) => r instanceof ResourceClass);
205
+ }
206
+ };
207
+ export {
208
+ Resource,
209
+ ResourceGroup,
210
+ ResourceNotFoundError,
211
+ ResourceOperationPendingError,
212
+ collectResourceGraph,
213
+ defineResource,
214
+ resource,
215
+ typed
216
+ };
package/package.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "type": "module",
3
+ "name": "@notation/resource",
4
+ "version": "0.13.0",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "scripts": {
17
+ "build": "tsup --clean",
18
+ "dev": "tsup --watch"
19
+ }
20
+ }