@toggld/node 0.1.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
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."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
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.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
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.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
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.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
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]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,90 @@
1
+ # @toggld/node
2
+
3
+ The Toggld SDK for Node.js. Evaluate feature flags from your backend against the
4
+ Toggld flag API.
5
+
6
+ Two API surfaces ship from one implementation:
7
+
8
+ - **`@toggld/node`** — a plain Promise API. No Effect types in any signature.
9
+ - **`@toggld/node/effect`** — the native [Effect](https://effect.website) API:
10
+ the client as a service + `Layer`.
11
+
12
+ > **Remote evaluation only (for now).** Every call hits the flag API, which
13
+ > evaluates the flag against your context and returns the resolved value
14
+ > (OpenFeature "remote evaluation" over the OFREP endpoints). Local in-process
15
+ > evaluation with a background definition sync — the `@toggld/engine` path — is a
16
+ > later milestone; see [ADR-0001](../../docs/adr/0001-packaging-and-sdk-strategy.md).
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pnpm add @toggld/node
22
+ ```
23
+
24
+ ## Promise API
25
+
26
+ ```ts
27
+ import { ToggldClient } from "@toggld/node"
28
+
29
+ const client = await ToggldClient.create({
30
+ sdkKey: process.env.TOGGLD_SDK_KEY!, // an evaluation API key
31
+ endpoint: "https://your-flag-api.example.com",
32
+ })
33
+
34
+ // Typed getters — return the default on any error, never throw.
35
+ const on = await client.getBooleanValue("new-checkout", false, {
36
+ targetingKey: "user-123",
37
+ plan: "premium",
38
+ })
39
+
40
+ // Full OpenFeature evaluation details.
41
+ const details = await client.getStringDetails("theme", "light", { targetingKey: "user-123" })
42
+ // ^ { flagKey, value, variant, reason, errorCode, errorMessage, flagMetadata }
43
+
44
+ // All flags for the environment in one request.
45
+ const everything = await client.evaluateAll({ targetingKey: "user-123" })
46
+
47
+ await client.close() // releases the underlying runtime
48
+ ```
49
+
50
+ Getters exist for each flag type: `getBooleanValue` / `getBooleanDetails`,
51
+ `getStringValue` / `…`, `getNumberValue` / `…`, and `getObjectValue<T>` / `…`.
52
+
53
+ ## Effect API
54
+
55
+ ```ts
56
+ import { Effect } from "effect"
57
+ import { ToggldClient, layer } from "@toggld/node/effect"
58
+
59
+ const program = Effect.gen(function* () {
60
+ const flags = yield* ToggldClient
61
+ return yield* flags.getBooleanValue("new-checkout", false, { targetingKey: "user-123" })
62
+ })
63
+
64
+ program.pipe(
65
+ Effect.provide(layer({ sdkKey, endpoint })),
66
+ Effect.runPromise,
67
+ )
68
+ ```
69
+
70
+ The `layer` is self-contained — it wires its own HTTP backend, so you only
71
+ provide this one layer. Lifecycle (the HTTP client) is managed by the enclosing
72
+ scope.
73
+
74
+ ## Options
75
+
76
+ | Option | Type | Default | Notes |
77
+ | ---------------- | --------------------- | ---------------- | ---------------------------------------------------------------- |
78
+ | `sdkKey` | `string` | — | Evaluation (or management) API key; sent as `Bearer`. |
79
+ | `endpoint` | `string` | — | Base URL of the flag API, no trailing path. |
80
+ | `defaultContext` | `EvaluationContext` | `{}` | Merged under per-call context (per-call attributes win). |
81
+ | `timeoutMs` | `number` | `5000` | Per-request timeout. |
82
+ | `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch (tests, proxies, instrumentation). |
83
+
84
+ ## Error semantics
85
+
86
+ Evaluation never throws. On a network failure, timeout, unknown flag, server
87
+ error, or a value whose type doesn't match the requested getter, the call
88
+ resolves to your **default value**. The `*Details` methods carry `reason:
89
+ "ERROR"` and an OpenFeature `errorCode` (`FLAG_NOT_FOUND`, `TYPE_MISMATCH`,
90
+ `TARGETING_KEY_MISSING`, `PARSE_ERROR`, `GENERAL`, …) describing what happened.
@@ -0,0 +1,549 @@
1
+ import { Context, Duration, Effect, Layer, Schema } from "effect";
2
+ import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
3
+ //#region ../spec/src/index.ts
4
+ /** True when `value` is assignable to a flag declared as `type`. */
5
+ const valueMatchesType = (value, type) => {
6
+ switch (type) {
7
+ case "boolean": return typeof value === "boolean";
8
+ case "string": return typeof value === "string";
9
+ case "number": return typeof value === "number" && Number.isFinite(value);
10
+ case "object": return typeof value === "object" && value !== null;
11
+ }
12
+ };
13
+ //#endregion
14
+ //#region ../schema/src/audit.ts
15
+ /**
16
+ * Audit log wire contract (ADR-0009). Every management/control-plane mutation is
17
+ * recorded as one append-only {@link AuditEvent}; a tenant reads its own trail
18
+ * over `GET /api/v1/audit-log`. Evaluation (OFREP) reads are deliberately *not*
19
+ * audited — this is a record of configuration *changes*, not traffic.
20
+ */
21
+ /** Who performed the change. See the server's `Actor` for how each id is sourced. */
22
+ const AuditActor = Schema.Struct({
23
+ type: Schema.Literals([
24
+ "apiKey",
25
+ "user",
26
+ "service"
27
+ ]),
28
+ id: Schema.String
29
+ });
30
+ /**
31
+ * Closed vocabulary of audited actions — a closed set (not free text) so filters
32
+ * and downstream exports stay stable as resources are added. `flag.update` covers
33
+ * both replace (PUT) and patch (PATCH); the before/after states show what moved.
34
+ */
35
+ const AuditAction = Schema.Literals([
36
+ "flag.create",
37
+ "flag.update",
38
+ "flag.delete",
39
+ "environment.create",
40
+ "environment.delete",
41
+ "apiKey.create",
42
+ "apiKey.revoke",
43
+ "tenant.create",
44
+ "tenant.update"
45
+ ]);
46
+ /** The kind of resource an event concerns; pairs with `resourceId`. */
47
+ const AuditResourceType = Schema.Literals([
48
+ "flag",
49
+ "environment",
50
+ "apiKey",
51
+ "tenant"
52
+ ]);
53
+ Schema.Struct({
54
+ id: Schema.String,
55
+ /** Owning tenant; null only for control-plane events (tenant provisioning). */
56
+ tenantId: Schema.NullOr(Schema.String),
57
+ /** The environment touched; null for tenant-wide / definition-level / control-plane events. */
58
+ environmentId: Schema.NullOr(Schema.String),
59
+ actor: AuditActor,
60
+ action: AuditAction,
61
+ resourceType: AuditResourceType,
62
+ /** Flag key, environment id, API-key id, or tenant id. */
63
+ resourceId: Schema.String,
64
+ before: Schema.NullOr(Schema.Unknown),
65
+ after: Schema.NullOr(Schema.Unknown),
66
+ /** Non-authoritative request context (request id, source ip, …); empty in v0. */
67
+ metadata: Schema.Record(Schema.String, Schema.Unknown),
68
+ /** ISO 8601 timestamp the change was recorded. */
69
+ occurredAt: Schema.String
70
+ });
71
+ //#endregion
72
+ //#region ../schema/src/auth.ts
73
+ /**
74
+ * Authorization role carried by an API key.
75
+ *
76
+ * - `management` — full CRUD on the tenant's flags, plus evaluation.
77
+ * - `evaluation` — read-only evaluation (OFREP) of the tenant's flags.
78
+ */
79
+ const Role = Schema.Literals(["management", "evaluation"]);
80
+ Schema.Struct({
81
+ id: Schema.String,
82
+ name: Schema.String,
83
+ createdAt: Schema.String,
84
+ /**
85
+ * Max number of flag *definitions* the tenant may hold; `null` = unlimited.
86
+ * The free tier is 10 (the DB column default). The flag API treats this as an
87
+ * opaque number — the web app owns the plan→limit mapping and pushes changes
88
+ * over the control plane (provision + PATCH). Enforced in `FlagService.create`.
89
+ */
90
+ flagLimit: Schema.NullOr(Schema.Int)
91
+ });
92
+ Schema.Struct({
93
+ id: Schema.String,
94
+ tenantId: Schema.String,
95
+ /** Stable slug, unique within the tenant (e.g. `production`). */
96
+ key: Schema.String,
97
+ name: Schema.String,
98
+ createdAt: Schema.String
99
+ });
100
+ /** Body for creating an environment (POST /admin/v1/tenants/:tenantId/environments). */
101
+ const CreateEnvironmentInput = Schema.Struct({
102
+ key: Schema.String.check(Schema.isMinLength(1)),
103
+ name: Schema.String.check(Schema.isMinLength(1))
104
+ });
105
+ /**
106
+ * Public view of an API key — safe to list. Never includes the secret token or
107
+ * its hash; only a non-secret prefix for human identification.
108
+ */
109
+ const ApiKeyInfo = Schema.Struct({
110
+ id: Schema.String,
111
+ tenantId: Schema.String,
112
+ /** The single environment this key is scoped to. */
113
+ environmentId: Schema.String,
114
+ name: Schema.optionalKey(Schema.String),
115
+ role: Role,
116
+ prefix: Schema.String,
117
+ createdAt: Schema.String
118
+ });
119
+ Schema.Struct({
120
+ ...ApiKeyInfo.fields,
121
+ token: Schema.String
122
+ });
123
+ Schema.Struct({
124
+ id: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1))),
125
+ name: Schema.String.check(Schema.isMinLength(1)),
126
+ environments: Schema.optionalKey(Schema.Array(CreateEnvironmentInput)),
127
+ /** Flag cap for the new tenant; omitted → the free-tier default (10). */
128
+ flagLimit: Schema.optionalKey(Schema.Int)
129
+ });
130
+ Schema.Struct({
131
+ name: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1))),
132
+ flagLimit: Schema.optionalKey(Schema.NullOr(Schema.Int))
133
+ });
134
+ Schema.Struct({
135
+ role: Role,
136
+ name: Schema.optionalKey(Schema.String),
137
+ environment: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1)))
138
+ });
139
+ //#endregion
140
+ //#region ../schema/src/value.ts
141
+ /**
142
+ * The OpenFeature flag value types. Every flag declares one of these; variant
143
+ * values and resolved values are validated against it.
144
+ *
145
+ * @see https://openfeature.dev/specification/types
146
+ */
147
+ const FlagType = Schema.Literals([
148
+ "boolean",
149
+ "string",
150
+ "number",
151
+ "object"
152
+ ]);
153
+ /**
154
+ * A resolved flag value. OpenFeature permits `boolean | string | number |
155
+ * structure`; we store the union as JSON, which also covers arrays and null
156
+ * for "object" typed flags.
157
+ */
158
+ const FlagValue = Schema.Json;
159
+ /**
160
+ * Flag metadata: "a structure supporting the definition of arbitrary
161
+ * properties, with keys of type string, and values of type boolean, string,
162
+ * or number." (Requirement 2.2.10)
163
+ */
164
+ const MetadataValue = Schema.Union([
165
+ Schema.String,
166
+ Schema.Finite,
167
+ Schema.Boolean
168
+ ]);
169
+ const FlagMetadata = Schema.Record(Schema.String, MetadataValue);
170
+ //#endregion
171
+ //#region ../schema/src/context.ts
172
+ /**
173
+ * An OpenFeature evaluation context: an optional `targetingKey` "identifying
174
+ * the subject of the flag evaluation" (Requirement 3.1.1) plus arbitrary
175
+ * custom fields (Requirement 3.1.2). We accept any JSON-valued attributes.
176
+ */
177
+ const EvaluationContext = Schema.Record(Schema.String, FlagValue);
178
+ Schema.ErrorClass("FlagNotFound")({
179
+ _tag: Schema.tag("FlagNotFound"),
180
+ flagKey: Schema.String,
181
+ message: Schema.String
182
+ });
183
+ Schema.ErrorClass("FlagAlreadyExists")({
184
+ _tag: Schema.tag("FlagAlreadyExists"),
185
+ flagKey: Schema.String,
186
+ message: Schema.String
187
+ });
188
+ Schema.ErrorClass("FlagValidationError")({
189
+ _tag: Schema.tag("FlagValidationError"),
190
+ flagKey: Schema.String,
191
+ issues: Schema.Array(Schema.String),
192
+ message: Schema.String
193
+ });
194
+ Schema.ErrorClass("FlagLimitExceeded")({
195
+ _tag: Schema.tag("FlagLimitExceeded"),
196
+ /** The tenant's current flag cap. */
197
+ limit: Schema.Int,
198
+ /** How many flags the tenant has now (>= limit). */
199
+ current: Schema.Int,
200
+ message: Schema.String
201
+ });
202
+ Schema.ErrorClass("Unauthorized")({
203
+ _tag: Schema.tag("Unauthorized"),
204
+ message: Schema.String
205
+ });
206
+ Schema.ErrorClass("Forbidden")({
207
+ _tag: Schema.tag("Forbidden"),
208
+ message: Schema.String
209
+ });
210
+ Schema.ErrorClass("TenantNotFound")({
211
+ _tag: Schema.tag("TenantNotFound"),
212
+ tenantId: Schema.String,
213
+ message: Schema.String
214
+ });
215
+ Schema.ErrorClass("TenantAlreadyExists")({
216
+ _tag: Schema.tag("TenantAlreadyExists"),
217
+ tenantId: Schema.String,
218
+ message: Schema.String
219
+ });
220
+ Schema.ErrorClass("EnvironmentNotFound")({
221
+ _tag: Schema.tag("EnvironmentNotFound"),
222
+ environment: Schema.String,
223
+ message: Schema.String
224
+ });
225
+ Schema.ErrorClass("EnvironmentAlreadyExists")({
226
+ _tag: Schema.tag("EnvironmentAlreadyExists"),
227
+ environment: Schema.String,
228
+ message: Schema.String
229
+ });
230
+ Schema.ErrorClass("ApiKeyNotFound")({
231
+ _tag: Schema.tag("ApiKeyNotFound"),
232
+ keyId: Schema.String,
233
+ message: Schema.String
234
+ });
235
+ //#endregion
236
+ //#region ../schema/src/flag.ts
237
+ /**
238
+ * Operators usable in a targeting condition. Comparisons coerce sensibly:
239
+ * numeric operators require numbers, string operators require strings, and
240
+ * `in`/`notIn` test membership in an array literal.
241
+ */
242
+ const Operator = Schema.Literals([
243
+ "eq",
244
+ "ne",
245
+ "in",
246
+ "notIn",
247
+ "lt",
248
+ "lte",
249
+ "gt",
250
+ "gte",
251
+ "contains",
252
+ "startsWith",
253
+ "endsWith",
254
+ "exists",
255
+ "notExists"
256
+ ]);
257
+ /**
258
+ * A single targeting condition tested against an attribute of the evaluation
259
+ * context (e.g. `targetingKey`, `email`, `plan`). All conditions in a rule are
260
+ * ANDed together.
261
+ */
262
+ const Condition = Schema.Struct({
263
+ attribute: Schema.String,
264
+ operator: Operator,
265
+ /** Comparison operand. Ignored for `exists`/`notExists`. */
266
+ value: Schema.optionalKey(FlagValue)
267
+ });
268
+ /** A weighted slice of a percentage rollout. */
269
+ const Split = Schema.Struct({
270
+ variant: Schema.String,
271
+ /** Relative weight; the engine normalises weights across all splits. */
272
+ weight: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))
273
+ });
274
+ /** Serve a single fixed variant when the rule matches → `TARGETING_MATCH`. */
275
+ const ServeVariant = Schema.Struct({
276
+ type: Schema.Literal("variant"),
277
+ variant: Schema.String
278
+ });
279
+ /**
280
+ * Serve a deterministic percentage rollout when the rule matches → `SPLIT`.
281
+ * Bucketing is consistent for a given subject (`bucketBy`, default
282
+ * `targetingKey`) so a subject always lands in the same slice.
283
+ */
284
+ const ServeRollout = Schema.Struct({
285
+ type: Schema.Literal("rollout"),
286
+ bucketBy: Schema.optionalKey(Schema.String),
287
+ splits: Schema.Array(Split)
288
+ });
289
+ const Serve = Schema.Union([ServeVariant, ServeRollout]);
290
+ /** An ordered targeting rule. The first rule whose conditions all match wins. */
291
+ const Rule = Schema.Struct({
292
+ id: Schema.String,
293
+ description: Schema.optionalKey(Schema.String),
294
+ /** ANDed conditions. An empty list always matches (useful as a catch-all). */
295
+ conditions: Schema.Array(Condition),
296
+ serve: Serve
297
+ });
298
+ /**
299
+ * A feature flag definition.
300
+ *
301
+ * Evaluation order: if `enabled` is false → serve `offVariant` (default
302
+ * `defaultVariant`) with reason `DISABLED`; otherwise walk `targeting` in
303
+ * order and serve the first matching rule (`TARGETING_MATCH`/`SPLIT`); if no
304
+ * rule matches, serve `defaultVariant` with reason `STATIC`.
305
+ */
306
+ const Flag = Schema.Struct({
307
+ key: Schema.String,
308
+ name: Schema.optionalKey(Schema.String),
309
+ description: Schema.optionalKey(Schema.String),
310
+ type: FlagType,
311
+ enabled: Schema.Boolean,
312
+ /** Named values; every served variant name must be a key here. */
313
+ variants: Schema.Record(Schema.String, FlagValue),
314
+ /** Variant served on a normal evaluation with no targeting match. */
315
+ defaultVariant: Schema.String,
316
+ /** Variant served when the flag is disabled. Defaults to `defaultVariant`. */
317
+ offVariant: Schema.optionalKey(Schema.String),
318
+ targeting: Schema.Array(Rule),
319
+ metadata: FlagMetadata,
320
+ createdAt: Schema.String,
321
+ updatedAt: Schema.String
322
+ });
323
+ /**
324
+ * Freeform organization labels for a flag (ADR-0008). A flag may carry any
325
+ * number; they group/filter flags in the dashboard and have **no** effect on
326
+ * evaluation. Deliberately separate from the spec `Flag` (and `metadata`) so
327
+ * they never reach the OFREP wire or the engine.
328
+ */
329
+ const Tags = Schema.Array(Schema.String.check(Schema.isMinLength(1)));
330
+ Schema.Struct({
331
+ ...Flag.fields,
332
+ tags: Tags
333
+ });
334
+ //#endregion
335
+ //#region ../schema/src/resolution.ts
336
+ /**
337
+ * Resolution reasons. The provider "SHOULD populate the resolution details
338
+ * structure's reason field with STATIC, DEFAULT, TARGETING_MATCH, SPLIT,
339
+ * CACHED, DISABLED, UNKNOWN, STALE, ERROR or some other string."
340
+ * (Requirement 2.2.5)
341
+ */
342
+ const Reason = Schema.Literals([
343
+ "STATIC",
344
+ "DEFAULT",
345
+ "TARGETING_MATCH",
346
+ "SPLIT",
347
+ "CACHED",
348
+ "DISABLED",
349
+ "UNKNOWN",
350
+ "STALE",
351
+ "ERROR"
352
+ ]);
353
+ /**
354
+ * OpenFeature error codes.
355
+ * @see https://openfeature.dev/specification/types
356
+ */
357
+ const ErrorCode = Schema.Literals([
358
+ "PROVIDER_NOT_READY",
359
+ "PROVIDER_FATAL",
360
+ "FLAG_NOT_FOUND",
361
+ "PARSE_ERROR",
362
+ "TYPE_MISMATCH",
363
+ "TARGETING_KEY_MISSING",
364
+ "INVALID_CONTEXT",
365
+ "GENERAL"
366
+ ]);
367
+ Schema.Struct({ context: Schema.optionalKey(EvaluationContext) });
368
+ /** A successful single/bulk evaluation result. */
369
+ const OfrepSuccess = Schema.Struct({
370
+ key: Schema.String,
371
+ value: FlagValue,
372
+ reason: Reason,
373
+ variant: Schema.optionalKey(Schema.String),
374
+ metadata: Schema.optionalKey(FlagMetadata)
375
+ });
376
+ /** A per-flag failure embedded in a bulk response. */
377
+ const OfrepFailure = Schema.Struct({
378
+ key: Schema.String,
379
+ errorCode: ErrorCode,
380
+ errorDetails: Schema.optionalKey(Schema.String),
381
+ metadata: Schema.optionalKey(FlagMetadata)
382
+ });
383
+ /** Bulk evaluation response: a mixed list of successes and failures. */
384
+ const OfrepBulkResponse = Schema.Struct({
385
+ flags: Schema.Array(Schema.Union([OfrepSuccess, OfrepFailure])),
386
+ metadata: Schema.optionalKey(FlagMetadata)
387
+ });
388
+ Schema.ErrorClass("OfrepFlagNotFound")({
389
+ key: Schema.String,
390
+ errorCode: Schema.Literal("FLAG_NOT_FOUND"),
391
+ errorDetails: Schema.optionalKey(Schema.String)
392
+ });
393
+ Schema.ErrorClass("OfrepEvaluationError")({
394
+ key: Schema.String,
395
+ errorCode: ErrorCode,
396
+ errorDetails: Schema.optionalKey(Schema.String)
397
+ });
398
+ Schema.Struct({
399
+ key: Schema.String.check(Schema.isMinLength(1)),
400
+ name: Schema.optionalKey(Schema.String),
401
+ description: Schema.optionalKey(Schema.String),
402
+ type: FlagType,
403
+ enabled: Schema.optionalKey(Schema.Boolean),
404
+ variants: Schema.Record(Schema.String, FlagValue),
405
+ defaultVariant: Schema.String,
406
+ offVariant: Schema.optionalKey(Schema.String),
407
+ targeting: Schema.optionalKey(Schema.Array(Rule)),
408
+ metadata: Schema.optionalKey(FlagMetadata),
409
+ /** Freeform organization labels (ADR-0008). Normalized server-side. */
410
+ tags: Schema.optionalKey(Tags)
411
+ });
412
+ Schema.Struct({
413
+ name: Schema.optionalKey(Schema.String),
414
+ description: Schema.optionalKey(Schema.String),
415
+ type: FlagType,
416
+ enabled: Schema.optionalKey(Schema.Boolean),
417
+ variants: Schema.Record(Schema.String, FlagValue),
418
+ defaultVariant: Schema.String,
419
+ offVariant: Schema.optionalKey(Schema.String),
420
+ targeting: Schema.optionalKey(Schema.Array(Rule)),
421
+ metadata: Schema.optionalKey(FlagMetadata),
422
+ tags: Schema.optionalKey(Tags)
423
+ });
424
+ Schema.Struct({
425
+ name: Schema.optionalKey(Schema.String),
426
+ description: Schema.optionalKey(Schema.String),
427
+ type: Schema.optionalKey(FlagType),
428
+ enabled: Schema.optionalKey(Schema.Boolean),
429
+ variants: Schema.optionalKey(Schema.Record(Schema.String, FlagValue)),
430
+ defaultVariant: Schema.optionalKey(Schema.String),
431
+ offVariant: Schema.optionalKey(Schema.String),
432
+ targeting: Schema.optionalKey(Schema.Array(Rule)),
433
+ metadata: Schema.optionalKey(FlagMetadata),
434
+ tags: Schema.optionalKey(Tags)
435
+ });
436
+ //#endregion
437
+ //#region src/internal/core.ts
438
+ /**
439
+ * The Effect core of the Toggld Node SDK — a remote-evaluation client over the
440
+ * server's OFREP endpoints.
441
+ *
442
+ * This is the canonical implementation; `../index.ts` (the plain Promise API) is
443
+ * a thin facade that runs this under a `ManagedRuntime`. The SDK performs **no
444
+ * local evaluation** — every call hits the flag API, which evaluates the flag
445
+ * against the supplied context and returns the resolved value (OpenFeature
446
+ * "remote evaluation"). Local in-process evaluation via `@toggld/engine` is a
447
+ * later milestone (see ADR-0001).
448
+ *
449
+ * OpenFeature semantics: evaluation never throws. Any failure — network error,
450
+ * timeout, unknown flag, a server-reported error, or a value whose type doesn't
451
+ * match the requested getter — resolves to the caller's default value with the
452
+ * details carrying `reason: "ERROR"` and an `errorCode`.
453
+ */
454
+ const DEFAULT_TIMEOUT_MS = 5e3;
455
+ const isBoolean = (v) => typeof v === "boolean";
456
+ const isString = (v) => typeof v === "string";
457
+ const isNumber = (v) => typeof v === "number" && Number.isFinite(v);
458
+ const isObject = (v) => valueMatchesType(v, "object");
459
+ const okDetails = (key, s) => ({
460
+ flagKey: key,
461
+ value: s.value,
462
+ variant: s.variant,
463
+ reason: s.reason,
464
+ errorCode: void 0,
465
+ errorMessage: void 0,
466
+ flagMetadata: s.metadata ?? {}
467
+ });
468
+ const wireErrorDetails = (fallback, e) => ({
469
+ flagKey: e.key,
470
+ value: fallback,
471
+ variant: void 0,
472
+ reason: "ERROR",
473
+ errorCode: e.errorCode,
474
+ errorMessage: e.errorDetails,
475
+ flagMetadata: e.metadata ?? {}
476
+ });
477
+ const errorDetails = (key, value, errorCode, errorMessage, flagMetadata = {}) => ({
478
+ flagKey: key,
479
+ value,
480
+ variant: void 0,
481
+ reason: "ERROR",
482
+ errorCode,
483
+ errorMessage,
484
+ flagMetadata
485
+ });
486
+ /** A readable message for an arbitrary thrown/failed value. */
487
+ const describe = (e) => typeof e === "object" && e !== null && "message" in e && typeof e.message === "string" ? e.message : String(e);
488
+ /** Map a transport/decoding failure to an OpenFeature error code. */
489
+ const codeFor = (e) => typeof e === "object" && e !== null && "_tag" in e && e._tag === "SchemaError" ? "PARSE_ERROR" : "GENERAL";
490
+ /**
491
+ * The Toggld client as an Effect service. Build a {@link layer} from options and
492
+ * compose it into your runtime, then `yield* ToggldClient` to evaluate flags.
493
+ */
494
+ var ToggldClient = class extends Context.Service()("@toggld/node/ToggldClient") {};
495
+ const make = (options) => Effect.gen(function* () {
496
+ const base = yield* HttpClient.HttpClient;
497
+ const timeout = Duration.millis(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
498
+ const http = base.pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl(options.endpoint)), HttpClient.mapRequest(HttpClientRequest.bearerToken(options.sdkKey)));
499
+ const mergedContext = (context) => ({
500
+ ...options.defaultContext,
501
+ ...context
502
+ });
503
+ const decode = HttpClientResponse.schemaBodyJson;
504
+ const evaluate = (key, defaultValue, context) => Effect.gen(function* () {
505
+ const request = HttpClientRequest.post(`/ofrep/v1/evaluate/flags/${encodeURIComponent(key)}`).pipe(HttpClientRequest.bodyJsonUnsafe({ context: mergedContext(context) }));
506
+ const response = yield* http.execute(request);
507
+ return yield* HttpClientResponse.matchStatus(response, {
508
+ "2xx": (r) => Effect.map(decode(OfrepSuccess)(r), (s) => okDetails(key, s)),
509
+ "4xx": (r) => Effect.map(decode(OfrepFailure)(r), (e) => wireErrorDetails(defaultValue, e)),
510
+ orElse: (r) => Effect.succeed(errorDetails(key, defaultValue, "GENERAL", `Unexpected response status ${r.status}`))
511
+ });
512
+ }).pipe(Effect.timeout(timeout), Effect.catch((error) => Effect.succeed(errorDetails(key, defaultValue, codeFor(error), describe(error)))));
513
+ const evaluateAll = (context) => Effect.gen(function* () {
514
+ const request = HttpClientRequest.post("/ofrep/v1/evaluate/flags").pipe(HttpClientRequest.bodyJsonUnsafe({ context: mergedContext(context) }));
515
+ const response = yield* http.execute(request);
516
+ return (yield* HttpClientResponse.matchStatus(response, {
517
+ "2xx": (r) => decode(OfrepBulkResponse)(r),
518
+ orElse: (r) => Effect.fail(/* @__PURE__ */ new Error(`Unexpected response status ${r.status}`))
519
+ })).flags.map((entry) => "errorCode" in entry ? wireErrorDetails(null, entry) : okDetails(entry.key, entry));
520
+ }).pipe(Effect.timeout(timeout), Effect.catch(() => Effect.succeed([])));
521
+ /** Resolve, then enforce the requested value type (else `TYPE_MISMATCH`). */
522
+ const typed = (key, defaultValue, context, type, guard) => Effect.map(evaluate(key, defaultValue, context), (d) => {
523
+ if (d.errorCode !== void 0) return d;
524
+ if (guard(d.value)) return d;
525
+ return errorDetails(key, defaultValue, "TYPE_MISMATCH", `Flag '${key}' value is not of type ${type}`, d.flagMetadata);
526
+ });
527
+ const valueOf = (details) => Effect.map(details, (d) => d.value);
528
+ return {
529
+ evaluate,
530
+ evaluateAll,
531
+ getBooleanDetails: (key, defaultValue, context) => typed(key, defaultValue, context, "boolean", isBoolean),
532
+ getBooleanValue: (key, defaultValue, context) => valueOf(typed(key, defaultValue, context, "boolean", isBoolean)),
533
+ getStringDetails: (key, defaultValue, context) => typed(key, defaultValue, context, "string", isString),
534
+ getStringValue: (key, defaultValue, context) => valueOf(typed(key, defaultValue, context, "string", isString)),
535
+ getNumberDetails: (key, defaultValue, context) => typed(key, defaultValue, context, "number", isNumber),
536
+ getNumberValue: (key, defaultValue, context) => valueOf(typed(key, defaultValue, context, "number", isNumber)),
537
+ getObjectDetails: (key, defaultValue, context) => typed(key, defaultValue, context, "object", isObject),
538
+ getObjectValue: (key, defaultValue, context) => valueOf(typed(key, defaultValue, context, "object", isObject))
539
+ };
540
+ });
541
+ /** The HttpClient layer, optionally backed by a caller-supplied `fetch`. */
542
+ const httpLayer = (fetchImpl) => fetchImpl ? FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchImpl))) : FetchHttpClient.layer;
543
+ /**
544
+ * A self-contained `Layer` providing {@link ToggldClient} — it wires its own
545
+ * HTTP backend, so Effect users need only provide this one layer.
546
+ */
547
+ const layer = (options) => Layer.effect(ToggldClient, make(options)).pipe(Layer.provide(httpLayer(options.fetch)));
548
+ //#endregion
549
+ export { layer as n, ToggldClient as t };
@@ -0,0 +1,32 @@
1
+ import { a as FlagMetadata, i as EvaluationContext, n as ToggldClientOptions, o as FlagValue, r as ErrorCode, s as Reason, t as EvaluationDetails } from "./types-RmWNnA7-.mjs";
2
+ import { Context, Effect, Layer } from "effect";
3
+
4
+ //#region src/internal/core.d.ts
5
+ /** The evaluation surface of a Toggld client. Every method is non-failing. */
6
+ interface ToggldClientShape {
7
+ /** Resolve a flag, returning full details with an untyped (JSON) value. */
8
+ readonly evaluate: (key: string, defaultValue: FlagValue, context?: EvaluationContext) => Effect.Effect<EvaluationDetails<FlagValue>>;
9
+ /** Resolve every flag for the environment in one request (OFREP bulk). */
10
+ readonly evaluateAll: (context?: EvaluationContext) => Effect.Effect<ReadonlyArray<EvaluationDetails<FlagValue>>>;
11
+ readonly getBooleanValue: (key: string, defaultValue: boolean, context?: EvaluationContext) => Effect.Effect<boolean>;
12
+ readonly getBooleanDetails: (key: string, defaultValue: boolean, context?: EvaluationContext) => Effect.Effect<EvaluationDetails<boolean>>;
13
+ readonly getStringValue: (key: string, defaultValue: string, context?: EvaluationContext) => Effect.Effect<string>;
14
+ readonly getStringDetails: (key: string, defaultValue: string, context?: EvaluationContext) => Effect.Effect<EvaluationDetails<string>>;
15
+ readonly getNumberValue: (key: string, defaultValue: number, context?: EvaluationContext) => Effect.Effect<number>;
16
+ readonly getNumberDetails: (key: string, defaultValue: number, context?: EvaluationContext) => Effect.Effect<EvaluationDetails<number>>;
17
+ readonly getObjectValue: <T extends FlagValue>(key: string, defaultValue: T, context?: EvaluationContext) => Effect.Effect<T>;
18
+ readonly getObjectDetails: <T extends FlagValue>(key: string, defaultValue: T, context?: EvaluationContext) => Effect.Effect<EvaluationDetails<T>>;
19
+ }
20
+ declare const ToggldClient_base: Context.ServiceClass<ToggldClient, "@toggld/node/ToggldClient", ToggldClientShape>;
21
+ /**
22
+ * The Toggld client as an Effect service. Build a {@link layer} from options and
23
+ * compose it into your runtime, then `yield* ToggldClient` to evaluate flags.
24
+ */
25
+ declare class ToggldClient extends ToggldClient_base {}
26
+ /**
27
+ * A self-contained `Layer` providing {@link ToggldClient} — it wires its own
28
+ * HTTP backend, so Effect users need only provide this one layer.
29
+ */
30
+ declare const layer: (options: ToggldClientOptions) => Layer.Layer<ToggldClient>;
31
+ //#endregion
32
+ export { type ErrorCode, type EvaluationContext, type EvaluationDetails, type FlagMetadata, type FlagValue, type Reason, ToggldClient, type ToggldClientOptions, type ToggldClientShape, layer };
@@ -0,0 +1,2 @@
1
+ import { n as layer, t as ToggldClient } from "./core-zMjaOru1.mjs";
2
+ export { ToggldClient, layer };
@@ -0,0 +1,30 @@
1
+ import { a as FlagMetadata, i as EvaluationContext, n as ToggldClientOptions, o as FlagValue, r as ErrorCode, s as Reason, t as EvaluationDetails } from "./types-RmWNnA7-.mjs";
2
+
3
+ //#region src/index.d.ts
4
+ /**
5
+ * A Toggld client backed by a private Effect runtime. Create one with {@link
6
+ * ToggldClient.create} and {@link ToggldClient.close} it on shutdown to release
7
+ * the runtime.
8
+ */
9
+ declare class ToggldClient {
10
+ #private;
11
+ private constructor();
12
+ /** Create a client. Resolves once the underlying runtime is ready. */
13
+ static create(options: ToggldClientOptions): Promise<ToggldClient>;
14
+ /** Resolve a flag, returning full details with an untyped (JSON) value. */
15
+ evaluate(key: string, defaultValue: FlagValue, context?: EvaluationContext): Promise<EvaluationDetails<FlagValue>>;
16
+ /** Resolve every flag for the environment in one request (OFREP bulk). */
17
+ evaluateAll(context?: EvaluationContext): Promise<ReadonlyArray<EvaluationDetails<FlagValue>>>;
18
+ getBooleanValue(key: string, defaultValue: boolean, context?: EvaluationContext): Promise<boolean>;
19
+ getBooleanDetails(key: string, defaultValue: boolean, context?: EvaluationContext): Promise<EvaluationDetails<boolean>>;
20
+ getStringValue(key: string, defaultValue: string, context?: EvaluationContext): Promise<string>;
21
+ getStringDetails(key: string, defaultValue: string, context?: EvaluationContext): Promise<EvaluationDetails<string>>;
22
+ getNumberValue(key: string, defaultValue: number, context?: EvaluationContext): Promise<number>;
23
+ getNumberDetails(key: string, defaultValue: number, context?: EvaluationContext): Promise<EvaluationDetails<number>>;
24
+ getObjectValue<T extends FlagValue>(key: string, defaultValue: T, context?: EvaluationContext): Promise<T>;
25
+ getObjectDetails<T extends FlagValue>(key: string, defaultValue: T, context?: EvaluationContext): Promise<EvaluationDetails<T>>;
26
+ /** Dispose the underlying runtime. The client is unusable afterwards. */
27
+ close(): Promise<void>;
28
+ }
29
+ //#endregion
30
+ export { type ErrorCode, type EvaluationContext, type EvaluationDetails, type FlagMetadata, type FlagValue, type Reason, ToggldClient, type ToggldClientOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,77 @@
1
+ import { n as layer, t as ToggldClient$1 } from "./core-zMjaOru1.mjs";
2
+ import { ManagedRuntime } from "effect";
3
+ //#region src/index.ts
4
+ /**
5
+ * `@toggld/node` — the default entry: a plain Promise API.
6
+ *
7
+ * Remote flag evaluation over the server's OFREP endpoints, with **no Effect in
8
+ * any signature**. Internally it runs the Effect implementation from `./effect`
9
+ * under a `ManagedRuntime`.
10
+ *
11
+ * ```ts
12
+ * import { ToggldClient } from "@toggld/node"
13
+ *
14
+ * const client = await ToggldClient.create({ sdkKey, endpoint })
15
+ * const on = await client.getBooleanValue("new-checkout", false, { targetingKey: "user-123" })
16
+ * await client.close()
17
+ * ```
18
+ *
19
+ * Evaluation never throws: any failure resolves to the supplied default value,
20
+ * with the reason/error available via the `*Details` methods.
21
+ */
22
+ /**
23
+ * A Toggld client backed by a private Effect runtime. Create one with {@link
24
+ * ToggldClient.create} and {@link ToggldClient.close} it on shutdown to release
25
+ * the runtime.
26
+ */
27
+ var ToggldClient = class ToggldClient {
28
+ #runtime;
29
+ #client;
30
+ constructor(runtime, client) {
31
+ this.#runtime = runtime;
32
+ this.#client = client;
33
+ }
34
+ /** Create a client. Resolves once the underlying runtime is ready. */
35
+ static async create(options) {
36
+ const runtime = ManagedRuntime.make(layer(options));
37
+ return new ToggldClient(runtime, await runtime.runPromise(ToggldClient$1));
38
+ }
39
+ /** Resolve a flag, returning full details with an untyped (JSON) value. */
40
+ evaluate(key, defaultValue, context) {
41
+ return this.#runtime.runPromise(this.#client.evaluate(key, defaultValue, context));
42
+ }
43
+ /** Resolve every flag for the environment in one request (OFREP bulk). */
44
+ evaluateAll(context) {
45
+ return this.#runtime.runPromise(this.#client.evaluateAll(context));
46
+ }
47
+ getBooleanValue(key, defaultValue, context) {
48
+ return this.#runtime.runPromise(this.#client.getBooleanValue(key, defaultValue, context));
49
+ }
50
+ getBooleanDetails(key, defaultValue, context) {
51
+ return this.#runtime.runPromise(this.#client.getBooleanDetails(key, defaultValue, context));
52
+ }
53
+ getStringValue(key, defaultValue, context) {
54
+ return this.#runtime.runPromise(this.#client.getStringValue(key, defaultValue, context));
55
+ }
56
+ getStringDetails(key, defaultValue, context) {
57
+ return this.#runtime.runPromise(this.#client.getStringDetails(key, defaultValue, context));
58
+ }
59
+ getNumberValue(key, defaultValue, context) {
60
+ return this.#runtime.runPromise(this.#client.getNumberValue(key, defaultValue, context));
61
+ }
62
+ getNumberDetails(key, defaultValue, context) {
63
+ return this.#runtime.runPromise(this.#client.getNumberDetails(key, defaultValue, context));
64
+ }
65
+ getObjectValue(key, defaultValue, context) {
66
+ return this.#runtime.runPromise(this.#client.getObjectValue(key, defaultValue, context));
67
+ }
68
+ getObjectDetails(key, defaultValue, context) {
69
+ return this.#runtime.runPromise(this.#client.getObjectDetails(key, defaultValue, context));
70
+ }
71
+ /** Dispose the underlying runtime. The client is unusable afterwards. */
72
+ close() {
73
+ return this.#runtime.dispose();
74
+ }
75
+ };
76
+ //#endregion
77
+ export { ToggldClient };
@@ -0,0 +1,85 @@
1
+ //#region ../spec/src/index.d.ts
2
+ /**
3
+ * A resolved flag value. OpenFeature permits `boolean | string | number |
4
+ * structure`; we model the union as JSON, which also covers arrays and null for
5
+ * "object" typed flags.
6
+ */
7
+ type FlagValue = null | boolean | number | string | ReadonlyArray<FlagValue> | {
8
+ readonly [key: string]: FlagValue;
9
+ };
10
+ /**
11
+ * Flag metadata: "arbitrary properties, with keys of type string, and values of
12
+ * type boolean, string, or number." (Requirement 2.2.10)
13
+ */
14
+ type MetadataValue = string | number | boolean;
15
+ type FlagMetadata = {
16
+ readonly [key: string]: MetadataValue;
17
+ };
18
+ /**
19
+ * An OpenFeature evaluation context: an optional `targetingKey` identifying the
20
+ * subject (Requirement 3.1.1) plus arbitrary custom JSON-valued attributes
21
+ * (Requirement 3.1.2).
22
+ */
23
+ type EvaluationContext = {
24
+ readonly [attribute: string]: FlagValue;
25
+ };
26
+ /**
27
+ * Resolution reasons. (Requirement 2.2.5)
28
+ */
29
+ type Reason = "STATIC" | "DEFAULT" | "TARGETING_MATCH" | "SPLIT" | "CACHED" | "DISABLED" | "UNKNOWN" | "STALE" | "ERROR";
30
+ /**
31
+ * OpenFeature error codes.
32
+ * @see https://openfeature.dev/specification/types
33
+ */
34
+ type ErrorCode = "PROVIDER_NOT_READY" | "PROVIDER_FATAL" | "FLAG_NOT_FOUND" | "PARSE_ERROR" | "TYPE_MISMATCH" | "TARGETING_KEY_MISSING" | "INVALID_CONTEXT" | "GENERAL";
35
+ //#endregion
36
+ //#region src/internal/types.d.ts
37
+ /** Configuration for a {@link https://toggld.io Toggld} client. */
38
+ interface ToggldClientOptions {
39
+ /**
40
+ * An **evaluation** (or management) API key, sent as `Authorization: Bearer
41
+ * <sdkKey>`. The key is scoped to one tenant + environment server-side, so a
42
+ * client always evaluates against exactly that environment.
43
+ */
44
+ readonly sdkKey: string;
45
+ /**
46
+ * Base URL of the flag API, e.g. `https://toggld-api.example.workers.dev` or
47
+ * `http://localhost:3000` in local development. No trailing path — the client
48
+ * appends the OFREP routes (`/ofrep/v1/...`).
49
+ */
50
+ readonly endpoint: string;
51
+ /**
52
+ * Attributes merged into the evaluation context of **every** request, under
53
+ * any per-call context (per-call attributes win on key collision). Handy for
54
+ * process-wide dimensions such as `region` or `serviceVersion`.
55
+ */
56
+ readonly defaultContext?: EvaluationContext;
57
+ /** Per-request timeout in milliseconds. Default `5000`. */
58
+ readonly timeoutMs?: number;
59
+ /**
60
+ * Custom `fetch` implementation. Defaults to the global `fetch`. Useful for
61
+ * tests, proxies, or injecting retries/instrumentation.
62
+ */
63
+ readonly fetch?: typeof globalThis.fetch;
64
+ }
65
+ /**
66
+ * The outcome of evaluating a single flag — OpenFeature "evaluation details"
67
+ * with a value typed to the requested flag type. Mirrors {@link
68
+ * https://openfeature.dev/specification/sections/evaluation-details}.
69
+ *
70
+ * On any abnormal evaluation (network failure, unknown flag, type mismatch, a
71
+ * server-reported error) the call still resolves: `value` holds the caller's
72
+ * default, `reason` is `"ERROR"`, and `errorCode`/`errorMessage` describe what
73
+ * went wrong. Evaluation never throws.
74
+ */
75
+ interface EvaluationDetails<T extends FlagValue> {
76
+ readonly flagKey: string;
77
+ readonly value: T;
78
+ readonly variant: string | undefined;
79
+ readonly reason: Reason;
80
+ readonly errorCode: ErrorCode | undefined;
81
+ readonly errorMessage: string | undefined;
82
+ readonly flagMetadata: FlagMetadata;
83
+ }
84
+ //#endregion
85
+ export { FlagMetadata as a, EvaluationContext as i, ToggldClientOptions as n, FlagValue as o, ErrorCode as r, Reason as s, EvaluationDetails as t };
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@toggld/node",
3
+ "version": "0.1.0",
4
+ "description": "Toggld SDK for Node.js — local flag evaluation with a background definition sync. Plain Promise API by default; native Effect API via @toggld/node/effect.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://toggld.io",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/toggld/toggld.git",
10
+ "directory": "packages/node"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/toggld/toggld/issues"
14
+ },
15
+ "keywords": [
16
+ "feature-flags",
17
+ "openfeature",
18
+ "toggld",
19
+ "effect"
20
+ ],
21
+ "type": "module",
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "exports": {
26
+ "./package.json": "./package.json",
27
+ ".": {
28
+ "types": "./dist/index.d.mts",
29
+ "default": "./dist/index.mjs"
30
+ },
31
+ "./effect": {
32
+ "types": "./dist/effect.d.mts",
33
+ "default": "./dist/effect.mjs"
34
+ }
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "dependencies": {
40
+ "effect": "4.0.0-beta.78"
41
+ },
42
+ "devDependencies": {
43
+ "tsdown": "^0.22.2",
44
+ "unrun": "^0.3.1",
45
+ "@toggld/schema": "0.1.0",
46
+ "@toggld/spec": "0.1.0"
47
+ },
48
+ "scripts": {
49
+ "build": "tsdown",
50
+ "typecheck": "tsc --noEmit",
51
+ "test": "vitest run",
52
+ "test:watch": "vitest"
53
+ }
54
+ }