@infaris/flags 0.0.0-stage → 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Infaris
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # @infaris/flags
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Edge Config and feature flags for **Hosting by Infaris**: the EU alternative to Vercel Edge Config and Flags, and a
4
+ light LaunchDarkly. Bundled shared error contract; Node 18+, Bun, Deno, Cloudflare Workers and Vercel's edge runtime.
5
+
6
+ - **Server** (`@infaris/flags`): the whole snapshot in memory, evaluated locally (no request per flag), refreshed when
7
+ Hosting pushes a new version and at most every 30 seconds otherwise.
8
+ - **Browser** (`@infaris/flags/client`) and **React** (`@infaris/flags/react`): only flags and values marked
9
+ *client-visible*, already evaluated by Hosting. Targeting rules never reach the browser.
10
+ - **Vercel flags SDK** (`@infaris/flags/adapter`): `flag({ key, adapter: infarisAdapter() })`.
11
+
12
+ ## Set up
13
+
14
+ ```bash
15
+ infaris-guard hosting config enable --site shop.example.nl # writes INFARIS_FLAGS_* on the site
16
+ infaris-guard hosting flags set new-checkout --env production --on --rollout 10
17
+ ```
18
+
19
+ Hosting sets four variables on the site (the next deploy has them):
20
+
21
+ | Variable | Where | What |
22
+ | --- | --- | --- |
23
+ | `INFARIS_FLAGS_URL`, `INFARIS_FLAGS_SECRET_KEY` | server only | the snapshot, also server-only flags |
24
+ | `NEXT_PUBLIC_INFARIS_FLAGS_URL`, `NEXT_PUBLIC_INFARIS_FLAGS_KEY` | browser | client-visible flags only |
25
+
26
+ A site without environment variables (own server, Webbie) gets its keys once with
27
+ `infaris-guard hosting config keys rotate`.
28
+
29
+ ## Server
30
+
31
+ ```ts
32
+ import { createFlagsClient } from '@infaris/flags';
33
+
34
+ const flags = createFlagsClient(); // reads INFARIS_FLAGS_URL and INFARIS_FLAGS_SECRET_KEY
35
+
36
+ if (await flags.getFlag('new-checkout', { userId: user.id, email: user.email, org: user.orgId, role: user.role })) {
37
+ // ...
38
+ }
39
+ const banner = await flags.getConfig('banner', { text: '' });
40
+ ```
41
+
42
+ The environment comes from `INFARIS_ENV`, `VERCEL_ENV` or `NODE_ENV` (`production`, `preview`, `development`).
43
+
44
+ ## Browser and React
45
+
46
+ ```tsx
47
+ import { createBrowserFlags } from '@infaris/flags/client';
48
+ import { FlagsProvider, useFlag } from '@infaris/flags/react';
49
+
50
+ const flags = createBrowserFlags({ getAccessToken: () => session?.access_token });
51
+
52
+ export function App() {
53
+ return <FlagsProvider client={flags}><Checkout /></FlagsProvider>;
54
+ }
55
+
56
+ function Checkout() {
57
+ return useFlag('new-checkout') ? <NewCheckout /> : <OldCheckout />;
58
+ }
59
+ ```
60
+
61
+ Targeting on Infaris Auth claims (e-mail address, `app_metadata.org`, `app_metadata.role`) needs the access token;
62
+ Hosting verifies it. Without a token only the percentage rollout applies, on `anonymousId`.
63
+
64
+ ## Vercel flags SDK
65
+
66
+ ```ts
67
+ import { flag } from 'flags/next';
68
+ import { infarisAdapter } from '@infaris/flags/adapter';
69
+
70
+ export const newCheckout = flag<boolean>({
71
+ key: 'new-checkout',
72
+ adapter: infarisAdapter(),
73
+ identify: async () => ({ user: { id: session.user.id, email: session.user.email } }),
74
+ });
75
+ ```
76
+
77
+ ## How a flag is evaluated
78
+
79
+ 1. Kill switch on: `false` everywhere.
80
+ 2. Off in this environment: `false`.
81
+ 3. Rules, in order (the first match wins): `userId`, `email`, `emailDomain`, `org`, `role` with `in`, `not_in` or
82
+ `ends_with`.
83
+ 4. Rollout: `null` or 100% is everyone; otherwise that share of users, sticky per user id
84
+ (`fnv1a32("<flag>:<userId>") % 10000`). Someone in at 10% stays in at 25%.
85
+
86
+ The same code runs in Hosting and in this package, so the server, the browser and the Guard app agree.
87
+
88
+ ## Runtime and modules
89
+
90
+ Node.js 22.12 or newer, Bun, modern browsers and edge runtimes with `fetch`. ES modules and CommonJS are both supported. Server credentials must stay on the server.
91
+
92
+ Licensed under MIT. See [LICENSE](./LICENSE).
93
+
94
+ All API errors extend `InfarisError` (also exported here), with `code`, `status` and `message`. Existing error classes remain supported.
95
+
96
+ ## Client factory
97
+
98
+ Every Hosting SDK exports `createClient(options)`. Existing named factories and positional Auth/Data arguments remain available.
99
+
100
+ ```ts
101
+ import { createClient } from '@infaris/flags';
102
+ const client = createClient();
103
+ ```
104
+
105
+ The common error implementation is bundled; installing this SDK does not require a private workspace package.
@@ -0,0 +1,388 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ try {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ } catch (e) {
12
+ throw mod = 0, e;
13
+ }
14
+ };
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (let key of __getOwnPropNames(from))
22
+ if (!__hasOwnProp.call(to, key) && key !== except)
23
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
+ }
25
+ return to;
26
+ };
27
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
28
+ // If the importer is in node compatibility mode or this is not an ESM
29
+ // file that has been converted to a CommonJS file using a Babel-
30
+ // compatible transform (i.e. "__esModule" has not been set), then set
31
+ // "default" to the CommonJS "module.exports" for node compatibility.
32
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
33
+ mod
34
+ ));
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+
37
+ // ../hosting-sdk/dist/index.cjs
38
+ var require_dist = __commonJS({
39
+ "../hosting-sdk/dist/index.cjs"(exports2, module2) {
40
+ "use strict";
41
+ var __defProp2 = Object.defineProperty;
42
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
43
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
44
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
45
+ var __export2 = (target, all) => {
46
+ for (var name in all)
47
+ __defProp2(target, name, { get: all[name], enumerable: true });
48
+ };
49
+ var __copyProps2 = (to, from, except, desc) => {
50
+ if (from && typeof from === "object" || typeof from === "function") {
51
+ for (let key of __getOwnPropNames2(from))
52
+ if (!__hasOwnProp2.call(to, key) && key !== except)
53
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
54
+ }
55
+ return to;
56
+ };
57
+ var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
58
+ var index_exports = {};
59
+ __export2(index_exports, {
60
+ InfarisError: () => InfarisError2
61
+ });
62
+ module2.exports = __toCommonJS2(index_exports);
63
+ var errorBrand = /* @__PURE__ */ Symbol.for("@infaris/hosting-sdk/error");
64
+ var InfarisError2 = class _InfarisError extends Error {
65
+ // SDK bundles contain separate copies; catch the shared base across bundles and module formats.
66
+ static [Symbol.hasInstance](value) {
67
+ if (this !== _InfarisError) return Function.prototype[Symbol.hasInstance].call(this, value);
68
+ return value instanceof Error && errorBrand in value && value[errorBrand] === true;
69
+ }
70
+ code;
71
+ status;
72
+ constructor(message, code = "sdk_error", status = null) {
73
+ super(message);
74
+ Object.defineProperty(this, errorBrand, { value: true });
75
+ this.name = "InfarisError";
76
+ this.code = code;
77
+ this.status = status;
78
+ }
79
+ };
80
+ }
81
+ });
82
+
83
+ // src/adapter.ts
84
+ var adapter_exports = {};
85
+ __export(adapter_exports, {
86
+ contextFromEntities: () => contextFromEntities,
87
+ createInfarisAdapter: () => createInfarisAdapter,
88
+ infarisAdapter: () => infarisAdapter
89
+ });
90
+ module.exports = __toCommonJS(adapter_exports);
91
+
92
+ // src/evaluate.ts
93
+ function fnv1a32(input) {
94
+ const bytes = new TextEncoder().encode(input);
95
+ let hash = 2166136261;
96
+ for (const byte of bytes) {
97
+ hash ^= byte;
98
+ hash = Math.imul(hash, 16777619) >>> 0;
99
+ }
100
+ return hash >>> 0;
101
+ }
102
+ function rolloutBucket(flagKey, userId) {
103
+ return fnv1a32(`${flagKey}:${userId}`) % 1e4;
104
+ }
105
+ function attributeOf(ctx, attribute) {
106
+ switch (attribute) {
107
+ case "email":
108
+ return ctx.email ? ctx.email.trim().toLowerCase() : void 0;
109
+ case "emailDomain": {
110
+ const at = ctx.email ? ctx.email.lastIndexOf("@") : -1;
111
+ return at >= 0 ? ctx.email.slice(at + 1).trim().toLowerCase() : void 0;
112
+ }
113
+ case "userId":
114
+ return ctx.userId || void 0;
115
+ case "org":
116
+ return ctx.org || void 0;
117
+ case "role":
118
+ return ctx.role || void 0;
119
+ }
120
+ }
121
+ var caseless = (attribute) => attribute === "email" || attribute === "emailDomain";
122
+ function ruleMatches(rule, ctx) {
123
+ const actual = attributeOf(ctx, rule.attribute);
124
+ if (actual === void 0) return false;
125
+ const values = caseless(rule.attribute) ? rule.values.map((v) => v.trim().toLowerCase()) : rule.values;
126
+ switch (rule.operator) {
127
+ case "in":
128
+ return values.includes(actual);
129
+ case "not_in":
130
+ return !values.includes(actual);
131
+ case "ends_with":
132
+ return values.some((v) => v.length > 0 && actual.endsWith(v));
133
+ }
134
+ }
135
+ function evaluateFlag(flag, environment, ctx) {
136
+ if (flag.killed) return { value: false, reason: "killed" };
137
+ const env = flag.environments[environment];
138
+ if (!env || !env.enabled) return { value: false, reason: "off" };
139
+ for (const rule of env.rules) {
140
+ if (ruleMatches(rule, ctx)) return { value: rule.serve, reason: "rule" };
141
+ }
142
+ if (env.rollout === null || env.rollout >= 100) return { value: true, reason: "fallthrough" };
143
+ if (env.rollout <= 0) return { value: false, reason: "rollout" };
144
+ if (!ctx.userId) return { value: false, reason: "no_user" };
145
+ return { value: rolloutBucket(flag.key, ctx.userId) < Math.round(env.rollout * 100), reason: "rollout" };
146
+ }
147
+
148
+ // src/types.ts
149
+ var import_hosting_sdk = __toESM(require_dist(), 1);
150
+ var FlagsError = class extends import_hosting_sdk.InfarisError {
151
+ constructor(message, status, code) {
152
+ super(message, code, status);
153
+ this.status = status;
154
+ this.code = code;
155
+ this.name = "FlagsError";
156
+ }
157
+ status;
158
+ code;
159
+ };
160
+ function detectEnvironment(env = readEnv()) {
161
+ const raw = (env?.INFARIS_ENV ?? env?.VERCEL_ENV ?? env?.NODE_ENV ?? "production").toLowerCase();
162
+ if (raw === "preview") return "preview";
163
+ if (raw === "development" || raw === "dev" || raw === "test" || raw === "local") return "development";
164
+ return "production";
165
+ }
166
+ function readEnv() {
167
+ const p = globalThis.process;
168
+ return p?.env;
169
+ }
170
+ function parseSseVersions(buffer) {
171
+ const versions = [];
172
+ const events = buffer.split(/\r?\n\r?\n/);
173
+ const rest = events.pop() ?? "";
174
+ for (const event of events) {
175
+ let name = "message";
176
+ let data = "";
177
+ for (const line of event.split(/\r?\n/)) {
178
+ if (line.startsWith("event:")) name = line.slice(6).trim();
179
+ else if (line.startsWith("data:")) data += line.slice(5).trim();
180
+ }
181
+ if (name !== "version" || !data) continue;
182
+ try {
183
+ const parsed = JSON.parse(data);
184
+ if (typeof parsed.version === "number") versions.push(parsed.version);
185
+ } catch {
186
+ }
187
+ }
188
+ return { versions, rest };
189
+ }
190
+ function trimSlash(url) {
191
+ return url.replace(/\/+$/, "");
192
+ }
193
+
194
+ // src/server.ts
195
+ var FlagsClient = class {
196
+ environment;
197
+ url;
198
+ key;
199
+ fetchImpl;
200
+ refreshMs;
201
+ onError;
202
+ snapshot = null;
203
+ etag = null;
204
+ checkedAt = 0;
205
+ loading = null;
206
+ streamAbort = null;
207
+ streaming = false;
208
+ closed = false;
209
+ listeners = /* @__PURE__ */ new Set();
210
+ constructor(options = {}) {
211
+ const env = readEnv();
212
+ const url = options.url ?? env?.INFARIS_FLAGS_URL;
213
+ const key = options.secretKey ?? env?.INFARIS_FLAGS_SECRET_KEY;
214
+ if (!url) throw new FlagsError("Missing url (set INFARIS_FLAGS_URL)", null, "missing_url");
215
+ if (!key) throw new FlagsError("Missing secret key (set INFARIS_FLAGS_SECRET_KEY)", null, "missing_key");
216
+ if (!key.startsWith("ifr_fsk_")) throw new FlagsError("The server client needs the secret key (ifr_fsk_\u2026)", null, "wrong_key");
217
+ this.url = trimSlash(url);
218
+ this.key = key;
219
+ this.environment = options.environment ?? detectEnvironment(env);
220
+ this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
221
+ this.refreshMs = options.refreshIntervalMs ?? 3e4;
222
+ this.onError = options.onError ?? (() => void 0);
223
+ if (options.stream ?? true) this.streaming = true;
224
+ }
225
+ /** The version in memory (0 before the first load). */
226
+ get version() {
227
+ return this.snapshot?.version ?? 0;
228
+ }
229
+ /** Loads the first snapshot (and opens the stream). Every getter calls it, so calling it yourself is optional. */
230
+ async ready() {
231
+ if (this.snapshot) {
232
+ if (Date.now() - this.checkedAt > this.refreshMs && !this.loading) void this.refresh().catch(this.onError);
233
+ return;
234
+ }
235
+ await this.refresh();
236
+ if (this.streaming && !this.streamAbort) this.openStream();
237
+ }
238
+ /** Fetches the snapshot when it changed (`If-None-Match`). */
239
+ async refresh() {
240
+ if (this.loading) return this.loading;
241
+ this.loading = (async () => {
242
+ try {
243
+ const res = await this.fetchImpl(`${this.url}/snapshot`, {
244
+ headers: { authorization: `Bearer ${this.key}`, ...this.etag ? { "if-none-match": this.etag } : {} }
245
+ });
246
+ this.checkedAt = Date.now();
247
+ if (res.status === 304 && this.snapshot) return;
248
+ if (!res.ok) throw new FlagsError(`Flags snapshot failed (HTTP ${res.status})`, res.status, "http_error");
249
+ const next = await res.json();
250
+ const changed = next.version !== this.snapshot?.version;
251
+ this.snapshot = next;
252
+ this.etag = res.headers.get("etag");
253
+ if (changed) for (const listener of this.listeners) listener(next.version);
254
+ } finally {
255
+ this.loading = null;
256
+ }
257
+ })();
258
+ return this.loading;
259
+ }
260
+ /** The value of a flag for this user; `defaultValue` for an unknown flag or before Hosting answered once. */
261
+ async getFlag(key, context = {}, defaultValue = false) {
262
+ try {
263
+ await this.ready();
264
+ } catch (error) {
265
+ this.onError(error);
266
+ if (!this.snapshot) return defaultValue;
267
+ }
268
+ return this.getFlagSync(key, context, defaultValue);
269
+ }
270
+ /** From memory only (no request): for hot paths once `ready()` resolved. */
271
+ getFlagSync(key, context = {}, defaultValue = false) {
272
+ const result = this.evaluate(key, context);
273
+ return result ? result.value : defaultValue;
274
+ }
275
+ /** Value and reason, or null for an unknown flag. */
276
+ evaluate(key, context = {}) {
277
+ const flag = this.snapshot?.flags.find((f) => f.key === key);
278
+ return flag ? evaluateFlag(flag, this.environment, context) : null;
279
+ }
280
+ /** Every flag for this user. */
281
+ async getAll(context = {}) {
282
+ await this.ready().catch(this.onError);
283
+ const out = {};
284
+ for (const flag of this.snapshot?.flags ?? []) out[flag.key] = evaluateFlag(flag, this.environment, context).value;
285
+ return out;
286
+ }
287
+ /** An Edge Config value. */
288
+ async getConfig(key, defaultValue) {
289
+ await this.ready().catch(this.onError);
290
+ const items = this.snapshot?.items ?? {};
291
+ return Object.prototype.hasOwnProperty.call(items, key) ? items[key] : defaultValue;
292
+ }
293
+ /** Called with the new version after every change that reached this process. */
294
+ onChange(listener) {
295
+ this.listeners.add(listener);
296
+ return () => this.listeners.delete(listener);
297
+ }
298
+ close() {
299
+ this.closed = true;
300
+ this.streamAbort?.abort();
301
+ this.streamAbort = null;
302
+ }
303
+ openStream() {
304
+ if (this.closed) return;
305
+ const abort = new AbortController();
306
+ this.streamAbort = abort;
307
+ void (async () => {
308
+ let delay = 1e3;
309
+ while (!abort.signal.aborted) {
310
+ try {
311
+ const res = await this.fetchImpl(`${this.url}/stream`, {
312
+ headers: { authorization: `Bearer ${this.key}`, accept: "text/event-stream" },
313
+ signal: abort.signal
314
+ });
315
+ if (!res.ok || !res.body) throw new FlagsError(`Flags stream failed (HTTP ${res.status})`, res.status, "stream_failed");
316
+ delay = 1e3;
317
+ const reader = res.body.getReader();
318
+ const decoder = new TextDecoder();
319
+ let buffer = "";
320
+ for (; ; ) {
321
+ const { done, value } = await reader.read();
322
+ if (done) break;
323
+ buffer += decoder.decode(value, { stream: true });
324
+ const parsed = parseSseVersions(buffer);
325
+ buffer = parsed.rest;
326
+ if (parsed.versions.some((v) => v > this.version)) await this.refresh().catch(this.onError);
327
+ else this.checkedAt = Date.now();
328
+ }
329
+ } catch (error) {
330
+ if (abort.signal.aborted) return;
331
+ this.onError(error);
332
+ }
333
+ await new Promise((resolve) => setTimeout(resolve, delay));
334
+ delay = Math.min(delay * 2, 3e4);
335
+ }
336
+ })();
337
+ }
338
+ };
339
+ function createFlagsClient(options = {}) {
340
+ return new FlagsClient(options);
341
+ }
342
+
343
+ // src/adapter.ts
344
+ var pick = (source, name) => {
345
+ if (!source || typeof source !== "object") return void 0;
346
+ const value = source[name];
347
+ return typeof value === "string" && value ? value : void 0;
348
+ };
349
+ function contextFromEntities(entities) {
350
+ const user = entities && typeof entities === "object" ? entities.user ?? entities : void 0;
351
+ const context = {};
352
+ const userId = pick(user, "userId") ?? pick(user, "id") ?? pick(user, "sub");
353
+ const email = pick(user, "email");
354
+ const org = pick(user, "org") ?? pick(user, "organizationId") ?? pick(entities, "org");
355
+ const role = pick(user, "role");
356
+ if (userId) context.userId = userId;
357
+ if (email) context.email = email;
358
+ if (org) context.org = org;
359
+ if (role) context.role = role;
360
+ return context;
361
+ }
362
+ var shared = null;
363
+ function createInfarisAdapter(options = {}) {
364
+ const client = options.client ?? createFlagsClient(options);
365
+ return function adapter() {
366
+ return {
367
+ ...options.origin ? { origin: options.origin } : {},
368
+ async decide({ key, entities, defaultValue }) {
369
+ await client.ready().catch(() => void 0);
370
+ const context = contextFromEntities(entities);
371
+ const evaluated = client.evaluate(key, context);
372
+ if (evaluated) return evaluated.value;
373
+ const value = await client.getConfig(key);
374
+ return value === void 0 ? defaultValue : value;
375
+ }
376
+ };
377
+ };
378
+ }
379
+ function infarisAdapter() {
380
+ shared ??= createFlagsClient();
381
+ return createInfarisAdapter({ client: shared })();
382
+ }
383
+ // Annotate the CommonJS export names for ESM import in node:
384
+ 0 && (module.exports = {
385
+ contextFromEntities,
386
+ createInfarisAdapter,
387
+ infarisAdapter
388
+ });
@@ -0,0 +1,38 @@
1
+ import { FlagsClientOptions, FlagsClient } from './index.cjs';
2
+ import { F as FlagContext } from './types-DMIusvFt.cjs';
3
+
4
+ /**
5
+ * An adapter for the Vercel `flags` SDK (`flags/next`, `flags/sveltekit`): `@infaris/flags/adapter`.
6
+ *
7
+ * import { flag } from 'flags/next';
8
+ * import { infarisAdapter } from '@infaris/flags/adapter';
9
+ *
10
+ * export const newCheckout = flag({ key: 'new-checkout', adapter: infarisAdapter(), identify: ... });
11
+ *
12
+ * The adapter evaluates on the server with the in-memory `FlagsClient` (secret key). `identify` returns the entities;
13
+ * `userId`, `email`, `org` and `role` (top level or under `user`) are used for targeting and the rollout. A key that is
14
+ * not a flag reads an Edge Config value. This file does not import `flags`: the shape is structural, so any version
15
+ * of the SDK with `decide({ key, entities, defaultValue })` works.
16
+ */
17
+
18
+ interface InfarisFlagsAdapter<ValueType, EntitiesType> {
19
+ origin?: string | ((key: string) => string | undefined);
20
+ decide(params: {
21
+ key: string;
22
+ entities?: EntitiesType;
23
+ defaultValue?: ValueType;
24
+ headers?: unknown;
25
+ cookies?: unknown;
26
+ }): Promise<ValueType>;
27
+ }
28
+ /** Reads `userId`/`id`/`sub`, `email`, `org`/`organizationId` and `role` from the entities (or `entities.user`). */
29
+ declare function contextFromEntities(entities: unknown): FlagContext;
30
+ /** Makes adapters that share one client (create it once per process). */
31
+ declare function createInfarisAdapter(options?: FlagsClientOptions & {
32
+ client?: FlagsClient;
33
+ origin?: string;
34
+ }): <ValueType = boolean, EntitiesType = unknown>() => InfarisFlagsAdapter<ValueType, EntitiesType>;
35
+ /** The adapter with the client from `INFARIS_FLAGS_URL` and `INFARIS_FLAGS_SECRET_KEY`. */
36
+ declare function infarisAdapter<ValueType = boolean, EntitiesType = unknown>(): InfarisFlagsAdapter<ValueType, EntitiesType>;
37
+
38
+ export { type InfarisFlagsAdapter, contextFromEntities, createInfarisAdapter, infarisAdapter };
@@ -0,0 +1,38 @@
1
+ import { FlagsClientOptions, FlagsClient } from './index.js';
2
+ import { F as FlagContext } from './types-DMIusvFt.js';
3
+
4
+ /**
5
+ * An adapter for the Vercel `flags` SDK (`flags/next`, `flags/sveltekit`): `@infaris/flags/adapter`.
6
+ *
7
+ * import { flag } from 'flags/next';
8
+ * import { infarisAdapter } from '@infaris/flags/adapter';
9
+ *
10
+ * export const newCheckout = flag({ key: 'new-checkout', adapter: infarisAdapter(), identify: ... });
11
+ *
12
+ * The adapter evaluates on the server with the in-memory `FlagsClient` (secret key). `identify` returns the entities;
13
+ * `userId`, `email`, `org` and `role` (top level or under `user`) are used for targeting and the rollout. A key that is
14
+ * not a flag reads an Edge Config value. This file does not import `flags`: the shape is structural, so any version
15
+ * of the SDK with `decide({ key, entities, defaultValue })` works.
16
+ */
17
+
18
+ interface InfarisFlagsAdapter<ValueType, EntitiesType> {
19
+ origin?: string | ((key: string) => string | undefined);
20
+ decide(params: {
21
+ key: string;
22
+ entities?: EntitiesType;
23
+ defaultValue?: ValueType;
24
+ headers?: unknown;
25
+ cookies?: unknown;
26
+ }): Promise<ValueType>;
27
+ }
28
+ /** Reads `userId`/`id`/`sub`, `email`, `org`/`organizationId` and `role` from the entities (or `entities.user`). */
29
+ declare function contextFromEntities(entities: unknown): FlagContext;
30
+ /** Makes adapters that share one client (create it once per process). */
31
+ declare function createInfarisAdapter(options?: FlagsClientOptions & {
32
+ client?: FlagsClient;
33
+ origin?: string;
34
+ }): <ValueType = boolean, EntitiesType = unknown>() => InfarisFlagsAdapter<ValueType, EntitiesType>;
35
+ /** The adapter with the client from `INFARIS_FLAGS_URL` and `INFARIS_FLAGS_SECRET_KEY`. */
36
+ declare function infarisAdapter<ValueType = boolean, EntitiesType = unknown>(): InfarisFlagsAdapter<ValueType, EntitiesType>;
37
+
38
+ export { type InfarisFlagsAdapter, contextFromEntities, createInfarisAdapter, infarisAdapter };
@@ -0,0 +1,51 @@
1
+ import {
2
+ createFlagsClient
3
+ } from "./chunk-RZ6DL2QZ.js";
4
+ import "./chunk-LLGINDZS.js";
5
+ import "./chunk-TRTQSARU.js";
6
+
7
+ // src/adapter.ts
8
+ var pick = (source, name) => {
9
+ if (!source || typeof source !== "object") return void 0;
10
+ const value = source[name];
11
+ return typeof value === "string" && value ? value : void 0;
12
+ };
13
+ function contextFromEntities(entities) {
14
+ const user = entities && typeof entities === "object" ? entities.user ?? entities : void 0;
15
+ const context = {};
16
+ const userId = pick(user, "userId") ?? pick(user, "id") ?? pick(user, "sub");
17
+ const email = pick(user, "email");
18
+ const org = pick(user, "org") ?? pick(user, "organizationId") ?? pick(entities, "org");
19
+ const role = pick(user, "role");
20
+ if (userId) context.userId = userId;
21
+ if (email) context.email = email;
22
+ if (org) context.org = org;
23
+ if (role) context.role = role;
24
+ return context;
25
+ }
26
+ var shared = null;
27
+ function createInfarisAdapter(options = {}) {
28
+ const client = options.client ?? createFlagsClient(options);
29
+ return function adapter() {
30
+ return {
31
+ ...options.origin ? { origin: options.origin } : {},
32
+ async decide({ key, entities, defaultValue }) {
33
+ await client.ready().catch(() => void 0);
34
+ const context = contextFromEntities(entities);
35
+ const evaluated = client.evaluate(key, context);
36
+ if (evaluated) return evaluated.value;
37
+ const value = await client.getConfig(key);
38
+ return value === void 0 ? defaultValue : value;
39
+ }
40
+ };
41
+ };
42
+ }
43
+ function infarisAdapter() {
44
+ shared ??= createFlagsClient();
45
+ return createInfarisAdapter({ client: shared })();
46
+ }
47
+ export {
48
+ contextFromEntities,
49
+ createInfarisAdapter,
50
+ infarisAdapter
51
+ };