@ops-ai/toggly-fastify 0.4.0 → 0.5.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/README.md +5 -6
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/package.json +13 -13
package/README.md
CHANGED
|
@@ -11,16 +11,15 @@ npm install @ops-ai/toggly-fastify
|
|
|
11
11
|
## Compatibility
|
|
12
12
|
|
|
13
13
|
The adapter retains its `fastify` peer range of `^4.0.0 || ^5.0.0` and its
|
|
14
|
-
Node.js package floor of
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
itself can run on Node 18.
|
|
14
|
+
Node.js package floor of 22. Upstream still publishes Fastify 4 (`four`
|
|
15
|
+
dist-tag, currently 4.29.1) and Fastify 5 (`latest`, currently 5.12.7); CI
|
|
16
|
+
proves both majors on Node 22, 24, and 26.
|
|
18
17
|
|
|
19
18
|
The compatibility harness packs the release artifact, resolves its core
|
|
20
19
|
dependency from npm, type-checks its public declarations, exercises ESM and
|
|
21
20
|
CommonJS exports, and starts real HTTP listeners. To provide exact Node
|
|
22
|
-
binaries in a local matrix, set `
|
|
23
|
-
`
|
|
21
|
+
binaries in a local matrix, set `TOGGLY_FASTIFY_NODE_FASTIFY4` and
|
|
22
|
+
`TOGGLY_FASTIFY_NODE_FASTIFY5` before `pnpm test:hosts`.
|
|
24
23
|
|
|
25
24
|
## Documentation
|
|
26
25
|
|
package/dist/index.cjs
CHANGED
|
@@ -115,15 +115,15 @@ var togglyPluginAsync = async (fastify, config) => {
|
|
|
115
115
|
isFeatureOn: (featureKey) => fastifyClient.isFeatureOn(featureKey, context),
|
|
116
116
|
isFeatureOff: (featureKey) => fastifyClient.isFeatureOff(featureKey, context),
|
|
117
117
|
evaluateFeatureGate: (featureKeys, requirement, negate) => fastifyClient.evaluateFeatureGate(featureKeys, requirement, negate, context),
|
|
118
|
-
|
|
118
|
+
getVariant(featureKey) {
|
|
119
119
|
return fastifyClient.getVariant(featureKey, context);
|
|
120
120
|
},
|
|
121
|
-
|
|
121
|
+
getVariantValue(featureKey) {
|
|
122
122
|
return fastifyClient.getVariantValue(featureKey, context);
|
|
123
123
|
}
|
|
124
124
|
};
|
|
125
125
|
});
|
|
126
|
-
fastify.addHook("onClose",
|
|
126
|
+
fastify.addHook("onClose", () => {
|
|
127
127
|
closeFastifyToggly();
|
|
128
128
|
});
|
|
129
129
|
};
|
|
@@ -175,7 +175,7 @@ function featureRoutes(routes) {
|
|
|
175
175
|
const gate = featureGate(route);
|
|
176
176
|
return gate(request, reply);
|
|
177
177
|
}
|
|
178
|
-
return;
|
|
178
|
+
return void 0;
|
|
179
179
|
};
|
|
180
180
|
}
|
|
181
181
|
function withFeature(featureKey, options = {}) {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/plugin.ts"],"sourcesContent":["// Plugin\nexport {\n togglyPlugin,\n featureGate,\n featureRoutes,\n withFeature,\n featuresHandler,\n getFastifyToggly,\n closeFastifyToggly,\n} from './plugin.js'\n\n// Types\nexport type {\n TogglyFastifyConfig,\n TogglyRequestData,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Re-export core types for convenience\nexport type {\n TogglyClient,\n TogglyConfig,\n TogglyServerConfig,\n TogglyState,\n FeatureDefinitions,\n FeatureRequirement,\n EvaluationContext,\n Hook,\n HookMetadata,\n VariantResult,\n} from '@ops-ai/toggly-node-core'\n\n// Re-export core utilities\nexport {\n createTogglyClient,\n initToggly,\n getToggly,\n useToggly,\n closeToggly,\n createLoggingHook,\n createMemoryCache,\n createFileCache,\n} from '@ops-ai/toggly-node-core'\n","import type {\n FastifyInstance,\n FastifyRequest,\n FastifyReply,\n FastifyPluginAsync,\n} from 'fastify'\n\n// Custom type for preHandler hooks (simpler than Fastify's complex generic type)\ntype PreHandlerHook = (\n request: FastifyRequest,\n reply: FastifyReply\n) => Promise<unknown>\nimport fp from 'fastify-plugin'\nimport {\n createTogglyClient,\n normalizeFeatureKeys,\n fromHttpRequest,\n type TogglyClient,\n type EvaluationContext,\n} from '@ops-ai/toggly-node-core'\nimport type {\n TogglyFastifyConfig,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Module-level client singleton\nlet fastifyClient: TogglyClient | null = null\n\n/**\n * Get the Fastify Toggly client\n */\nexport function getFastifyToggly(): TogglyClient | null {\n return fastifyClient\n}\n\n/**\n * Get identity from request\n */\nasync function extractIdentity(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<string | undefined> {\n // Use custom extractor if provided\n if (config.getIdentity) {\n return config.getIdentity(request)\n }\n\n // Default: check header\n const headerIdentity = request.headers['x-toggly-identity']\n if (typeof headerIdentity === 'string') {\n return headerIdentity\n }\n\n return undefined\n}\n\n/**\n * Get evaluation context from request\n */\nasync function extractContext(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<EvaluationContext> {\n const headers = request.headers as Record<string, string | string[] | undefined>\n const headerRequest = fromHttpRequest(headers).request\n\n // Custom full context: use returned fields, fill missing request from headers\n if (config.getContext) {\n const custom = await config.getContext(request)\n return {\n ...custom,\n // Field-level merge: custom wins; missing keys filled from headers\n request: {\n ...headerRequest,\n ...custom.request,\n },\n }\n }\n\n // Default: identity / groups / claims providers + segment request headers\n const identity = await extractIdentity(request, config)\n const groups = config.getGroups ? await config.getGroups(request) : undefined\n const claims = config.getClaims ? await config.getClaims(request) : undefined\n const fromReq = fromHttpRequest(headers, { identity, groups, claims })\n\n return {\n identity: fromReq.identity,\n groups: fromReq.groups,\n claims: fromReq.claims,\n request: fromReq.request,\n traits: {\n ip: request.ip,\n userAgent: request.headers['user-agent'],\n path: request.url,\n method: request.method,\n },\n }\n}\n\n/**\n * Toggly Fastify plugin\n *\n * This plugin:\n * 1. Initializes the Toggly client\n * 2. Attaches feature flag helpers to the request object\n * 3. Extracts identity and context from the request\n */\nconst togglyPluginAsync: FastifyPluginAsync<TogglyFastifyConfig> = async (\n fastify: FastifyInstance,\n config: TogglyFastifyConfig\n) => {\n // Initialize client\n if (!fastifyClient) {\n fastifyClient = createTogglyClient(config)\n await fastifyClient.init()\n }\n\n // Add hook to attach toggly to request\n fastify.addHook('preHandler', async (request: FastifyRequest) => {\n if (!fastifyClient) {\n throw new Error('Toggly client not initialized')\n }\n\n // Extract context from request\n const context = await extractContext(request, config)\n const identity = context.identity\n\n // Attach Toggly helpers to request\n request.toggly = {\n client: fastifyClient,\n features: fastifyClient.state.features,\n identity,\n context,\n isFeatureOn: (featureKey: string) => fastifyClient!.isFeatureOn(featureKey, context),\n isFeatureOff: (featureKey: string) => fastifyClient!.isFeatureOff(featureKey, context),\n evaluateFeatureGate: (featureKeys, requirement, negate) =>\n fastifyClient!.evaluateFeatureGate(featureKeys, requirement, negate, context),\n async getVariant(featureKey: string) {\n return fastifyClient!.getVariant(featureKey, context)\n },\n async getVariantValue(featureKey: string) {\n return fastifyClient!.getVariantValue(featureKey, context)\n },\n }\n })\n\n // Close client when fastify closes\n fastify.addHook('onClose', async () => {\n closeFastifyToggly()\n })\n}\n\n/**\n * Toggly Fastify plugin with proper encapsulation\n */\nexport const togglyPlugin = fp(togglyPluginAsync, {\n name: '@ops-ai/toggly-fastify',\n fastify: '>=4.0.0',\n})\n\n/**\n * Create a feature gate preHandler hook\n *\n * Protects routes by checking if specified features are enabled\n */\nexport function featureGate(options: FeatureGateOptions): PreHandlerHook {\n const {\n featureKey,\n requirement = 'all',\n negate = false,\n onDisabled,\n redirectTo,\n redirectStatus = 302,\n } = options\n\n const featureKeys = normalizeFeatureKeys(featureKey)\n\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!request.toggly) {\n throw new Error('Toggly plugin must be registered before using featureGate')\n }\n\n const isEnabled = await request.toggly.evaluateFeatureGate(featureKeys, requirement, negate)\n\n if (isEnabled) {\n return // Continue to handler\n }\n\n // Feature is disabled\n if (redirectTo) {\n return reply.redirect(redirectTo, redirectStatus)\n }\n\n if (onDisabled) {\n await onDisabled(request)\n return\n }\n\n // Default: 404\n return reply.status(404).send({\n error: 'Not Found',\n message: 'The requested resource is not available',\n })\n }\n}\n\n/**\n * Create preHandler that applies feature gates based on route patterns\n */\nexport function featureRoutes(routes: FeatureRouteOptions[]): PreHandlerHook {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n for (const route of routes) {\n // Check if route matches\n const pathMatches =\n typeof route.path === 'string'\n ? request.url === route.path || request.url.startsWith(route.path)\n : route.path.test(request.url)\n\n if (!pathMatches) {\n continue\n }\n\n // Check if method matches\n if (route.methods && !route.methods.includes(request.method.toUpperCase())) {\n continue\n }\n\n // Apply feature gate\n const gate = featureGate(route)\n return gate(request, reply)\n }\n\n // No matching route, continue\n return\n }\n}\n\n/**\n * Create a decorated route handler that checks features\n */\nexport function withFeature(\n featureKey: string | string[],\n options: Omit<FeatureGateOptions, 'featureKey'> = {}\n): PreHandlerHook {\n return featureGate({ featureKey, ...options })\n}\n\n/**\n * Get features route handler\n */\nexport async function featuresHandler(\n request: FastifyRequest,\n reply: FastifyReply\n): Promise<void> {\n if (!request.toggly) {\n return reply.status(500).send({\n error: 'Internal Server Error',\n message: 'Toggly plugin not configured',\n })\n }\n\n return reply.send({\n features: request.toggly.features,\n identity: request.toggly.identity,\n })\n}\n\n/**\n * Close the Fastify Toggly client\n */\nexport function closeFastifyToggly(): void {\n if (fastifyClient) {\n fastifyClient.close()\n fastifyClient = null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYA,4BAAe;AACf,8BAMO;AAQP,IAAI,gBAAqC;AAKlC,SAAS,mBAAwC;AACtD,SAAO;AACT;AAKA,eAAe,gBACb,SACA,QAC6B;AAE7B,MAAI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,MAC5B,OAAO;AAAA,MACP,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AACF;AAKO,SAAS,cAAc,QAA+C;AAC3E,SAAO,OAAO,SAAyB,UAAwB;AAC7D,eAAW,SAAS,QAAQ;AAE1B,YAAM,cACJ,OAAO,MAAM,SAAS,WAClB,QAAQ,QAAQ,MAAM,QAAQ,QAAQ,IAAI,WAAW,MAAM,IAAI,IAC/D,MAAM,KAAK,KAAK,QAAQ,GAAG;AAEjC,UAAI,CAAC,aAAa;AAChB;AAAA,MACF;AAGA,UAAI,MAAM,WAAW,CAAC,MAAM,QAAQ,SAAS,QAAQ,OAAO,YAAY,CAAC,GAAG;AAC1E;AAAA,MACF;AAGA,YAAM,OAAO,YAAY,KAAK;AAC9B,aAAO,KAAK,SAAS,KAAK;AAAA,IAC5B;AAGA;AAAA,EACF;AACF;AAKO,SAAS,YACd,YACA,UAAkD,CAAC,GACnC;AAChB,SAAO,YAAY,EAAE,YAAY,GAAG,QAAQ,CAAC;AAC/C;AAKA,eAAsB,gBACpB,SACA,OACe;AACf,MAAI,CAAC,QAAQ,QAAQ;AACnB,WAAO,MAAM,OAAO,GAAG,EAAE,KAAK;AAAA,MAC5B,OAAO;AAAA,MACP,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,SAAO,MAAM,KAAK;AAAA,IAChB,UAAU,QAAQ,OAAO;AAAA,IACzB,UAAU,QAAQ,OAAO;AAAA,EAC3B,CAAC;AACH;AAKO,SAAS,qBAA2B;AACzC,MAAI,eAAe;AACjB,kBAAc,MAAM;AACpB,oBAAgB;AAAA,EAClB;AACF;;;ADlPA,IAAAC,2BASO;","names":["fp","import_toggly_node_core"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/plugin.ts"],"sourcesContent":["// Plugin\nexport {\n togglyPlugin,\n featureGate,\n featureRoutes,\n withFeature,\n featuresHandler,\n getFastifyToggly,\n closeFastifyToggly,\n} from './plugin.js'\n\n// Types\nexport type {\n TogglyFastifyConfig,\n TogglyRequestData,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Re-export core types for convenience\nexport type {\n TogglyClient,\n TogglyConfig,\n TogglyServerConfig,\n TogglyState,\n FeatureDefinitions,\n FeatureRequirement,\n EvaluationContext,\n Hook,\n HookMetadata,\n VariantResult,\n} from '@ops-ai/toggly-node-core'\n\n// Re-export core utilities\nexport {\n createTogglyClient,\n initToggly,\n getToggly,\n useToggly,\n closeToggly,\n createLoggingHook,\n createMemoryCache,\n createFileCache,\n} from '@ops-ai/toggly-node-core'\n","import type {\n FastifyInstance,\n FastifyRequest,\n FastifyReply,\n FastifyPluginAsync,\n} from 'fastify'\n\n// Custom type for preHandler hooks (simpler than Fastify's complex generic type)\ntype PreHandlerHook = (\n request: FastifyRequest,\n reply: FastifyReply\n) => Promise<unknown>\nimport fp from 'fastify-plugin'\nimport {\n createTogglyClient,\n normalizeFeatureKeys,\n fromHttpRequest,\n type TogglyClient,\n type EvaluationContext,\n} from '@ops-ai/toggly-node-core'\nimport type {\n TogglyFastifyConfig,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Module-level client singleton\nlet fastifyClient: TogglyClient | null = null\n\n/**\n * Get the Fastify Toggly client\n */\nexport function getFastifyToggly(): TogglyClient | null {\n return fastifyClient\n}\n\n/**\n * Get identity from request\n */\nasync function extractIdentity(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<string | undefined> {\n // Use custom extractor if provided\n if (config.getIdentity) {\n return config.getIdentity(request)\n }\n\n // Default: check header\n const headerIdentity = request.headers['x-toggly-identity']\n if (typeof headerIdentity === 'string') {\n return headerIdentity\n }\n\n return undefined\n}\n\n/**\n * Get evaluation context from request\n */\nasync function extractContext(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<EvaluationContext> {\n const headers = request.headers as Record<string, string | string[] | undefined>\n const headerRequest = fromHttpRequest(headers).request\n\n // Custom full context: use returned fields, fill missing request from headers\n if (config.getContext) {\n const custom = await config.getContext(request)\n return {\n ...custom,\n // Field-level merge: custom wins; missing keys filled from headers\n request: {\n ...headerRequest,\n ...custom.request,\n },\n }\n }\n\n // Default: identity / groups / claims providers + segment request headers\n const identity = await extractIdentity(request, config)\n const groups = config.getGroups ? await config.getGroups(request) : undefined\n const claims = config.getClaims ? await config.getClaims(request) : undefined\n const fromReq = fromHttpRequest(headers, { identity, groups, claims })\n\n return {\n identity: fromReq.identity,\n groups: fromReq.groups,\n claims: fromReq.claims,\n request: fromReq.request,\n traits: {\n ip: request.ip,\n userAgent: request.headers['user-agent'],\n path: request.url,\n method: request.method,\n },\n }\n}\n\n/**\n * Toggly Fastify plugin\n *\n * This plugin:\n * 1. Initializes the Toggly client\n * 2. Attaches feature flag helpers to the request object\n * 3. Extracts identity and context from the request\n */\nconst togglyPluginAsync: FastifyPluginAsync<TogglyFastifyConfig> = async (\n fastify: FastifyInstance,\n config: TogglyFastifyConfig\n) => {\n // Initialize client\n if (!fastifyClient) {\n fastifyClient = createTogglyClient(config)\n await fastifyClient.init()\n }\n\n // Add hook to attach toggly to request\n fastify.addHook('preHandler', async (request: FastifyRequest) => {\n if (!fastifyClient) {\n throw new Error('Toggly client not initialized')\n }\n\n // Extract context from request\n const context = await extractContext(request, config)\n const identity = context.identity\n\n // Attach Toggly helpers to request\n request.toggly = {\n client: fastifyClient,\n features: fastifyClient.state.features,\n identity,\n context,\n isFeatureOn: (featureKey: string) => fastifyClient!.isFeatureOn(featureKey, context),\n isFeatureOff: (featureKey: string) => fastifyClient!.isFeatureOff(featureKey, context),\n evaluateFeatureGate: (featureKeys, requirement, negate) =>\n fastifyClient!.evaluateFeatureGate(featureKeys, requirement, negate, context),\n getVariant(featureKey: string) {\n return fastifyClient!.getVariant(featureKey, context)\n },\n getVariantValue(featureKey: string) {\n return fastifyClient!.getVariantValue(featureKey, context)\n },\n }\n })\n\n // Close client when fastify closes\n fastify.addHook('onClose', () => {\n closeFastifyToggly()\n })\n}\n\n/**\n * Toggly Fastify plugin with proper encapsulation\n */\nexport const togglyPlugin = fp(togglyPluginAsync, {\n name: '@ops-ai/toggly-fastify',\n fastify: '>=4.0.0',\n})\n\n/**\n * Create a feature gate preHandler hook\n *\n * Protects routes by checking if specified features are enabled\n */\nexport function featureGate(options: FeatureGateOptions): PreHandlerHook {\n const {\n featureKey,\n requirement = 'all',\n negate = false,\n onDisabled,\n redirectTo,\n redirectStatus = 302,\n } = options\n\n const featureKeys = normalizeFeatureKeys(featureKey)\n\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!request.toggly) {\n throw new Error('Toggly plugin must be registered before using featureGate')\n }\n\n const isEnabled = await request.toggly.evaluateFeatureGate(featureKeys, requirement, negate)\n\n if (isEnabled) {\n return // Continue to handler\n }\n\n // Feature is disabled\n if (redirectTo) {\n return reply.redirect(redirectTo, redirectStatus)\n }\n\n if (onDisabled) {\n await onDisabled(request)\n return\n }\n\n // Default: 404\n return reply.status(404).send({\n error: 'Not Found',\n message: 'The requested resource is not available',\n })\n }\n}\n\n/**\n * Create preHandler that applies feature gates based on route patterns\n */\nexport function featureRoutes(routes: FeatureRouteOptions[]): PreHandlerHook {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n for (const route of routes) {\n // Check if route matches\n const pathMatches =\n typeof route.path === 'string'\n ? request.url === route.path || request.url.startsWith(route.path)\n : route.path.test(request.url)\n\n if (!pathMatches) {\n continue\n }\n\n // Check if method matches\n if (route.methods && !route.methods.includes(request.method.toUpperCase())) {\n continue\n }\n\n // Apply feature gate\n const gate = featureGate(route)\n return gate(request, reply)\n }\n\n // No matching route, continue.\n return undefined\n }\n}\n\n/**\n * Create a decorated route handler that checks features\n */\nexport function withFeature(\n featureKey: string | string[],\n options: Omit<FeatureGateOptions, 'featureKey'> = {}\n): PreHandlerHook {\n return featureGate({ featureKey, ...options })\n}\n\n/**\n * Get features route handler\n */\nexport async function featuresHandler(\n request: FastifyRequest,\n reply: FastifyReply\n): Promise<void> {\n if (!request.toggly) {\n return reply.status(500).send({\n error: 'Internal Server Error',\n message: 'Toggly plugin not configured',\n })\n }\n\n return reply.send({\n features: request.toggly.features,\n identity: request.toggly.identity,\n })\n}\n\n/**\n * Close the Fastify Toggly client\n */\nexport function closeFastifyToggly(): void {\n if (fastifyClient) {\n fastifyClient.close()\n fastifyClient = null\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYA,4BAAe;AACf,8BAMO;AAQP,IAAI,gBAAqC;AAKlC,SAAS,mBAAwC;AACtD,SAAO;AACT;AAKA,eAAe,gBACb,SACA,QAC6B;AAE7B,MAAI,OAAO,aAAa;AACtB,WAAO,OAAO,YAAY,OAAO;AAAA,EACnC;AAGA,QAAM,iBAAiB,QAAQ,QAAQ,mBAAmB;AAC1D,MAAI,OAAO,mBAAmB,UAAU;AACtC,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAKA,eAAe,eACb,SACA,QAC4B;AAC5B,QAAM,UAAU,QAAQ;AACxB,QAAM,oBAAgB,yCAAgB,OAAO,EAAE;AAG/C,MAAI,OAAO,YAAY;AACrB,UAAM,SAAS,MAAM,OAAO,WAAW,OAAO;AAC9C,WAAO;AAAA,MACL,GAAG;AAAA;AAAA,MAEH,SAAS;AAAA,QACP,GAAG;AAAA,QACH,GAAG,OAAO;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AAGA,QAAM,WAAW,MAAM,gBAAgB,SAAS,MAAM;AACtD,QAAM,SAAS,OAAO,YAAY,MAAM,OAAO,UAAU,OAAO,IAAI;AACpE,QAAM,SAAS,OAAO,YAAY,MAAM,OAAO,UAAU,OAAO,IAAI;AACpE,QAAM,cAAU,yCAAgB,SAAS,EAAE,UAAU,QAAQ,OAAO,CAAC;AAErE,SAAO;AAAA,IACL,UAAU,QAAQ;AAAA,IAClB,QAAQ,Q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,MACP,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,SAAO,MAAM,KAAK;AAAA,IAChB,UAAU,QAAQ,OAAO;AAAA,IACzB,UAAU,QAAQ,OAAO;AAAA,EAC3B,CAAC;AACH;AAKO,SAAS,qBAA2B;AACzC,MAAI,eAAe;AACjB,kBAAc,MAAM;AACpB,oBAAgB;AAAA,EAClB;AACF;;;ADlPA,IAAAC,2BASO;","names":["fp","import_toggly_node_core"]}
|
package/dist/index.js
CHANGED
|
@@ -69,15 +69,15 @@ var togglyPluginAsync = async (fastify, config) => {
|
|
|
69
69
|
isFeatureOn: (featureKey) => fastifyClient.isFeatureOn(featureKey, context),
|
|
70
70
|
isFeatureOff: (featureKey) => fastifyClient.isFeatureOff(featureKey, context),
|
|
71
71
|
evaluateFeatureGate: (featureKeys, requirement, negate) => fastifyClient.evaluateFeatureGate(featureKeys, requirement, negate, context),
|
|
72
|
-
|
|
72
|
+
getVariant(featureKey) {
|
|
73
73
|
return fastifyClient.getVariant(featureKey, context);
|
|
74
74
|
},
|
|
75
|
-
|
|
75
|
+
getVariantValue(featureKey) {
|
|
76
76
|
return fastifyClient.getVariantValue(featureKey, context);
|
|
77
77
|
}
|
|
78
78
|
};
|
|
79
79
|
});
|
|
80
|
-
fastify.addHook("onClose",
|
|
80
|
+
fastify.addHook("onClose", () => {
|
|
81
81
|
closeFastifyToggly();
|
|
82
82
|
});
|
|
83
83
|
};
|
|
@@ -129,7 +129,7 @@ function featureRoutes(routes) {
|
|
|
129
129
|
const gate = featureGate(route);
|
|
130
130
|
return gate(request, reply);
|
|
131
131
|
}
|
|
132
|
-
return;
|
|
132
|
+
return void 0;
|
|
133
133
|
};
|
|
134
134
|
}
|
|
135
135
|
function withFeature(featureKey, options = {}) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/plugin.ts","../src/index.ts"],"sourcesContent":["import type {\n FastifyInstance,\n FastifyRequest,\n FastifyReply,\n FastifyPluginAsync,\n} from 'fastify'\n\n// Custom type for preHandler hooks (simpler than Fastify's complex generic type)\ntype PreHandlerHook = (\n request: FastifyRequest,\n reply: FastifyReply\n) => Promise<unknown>\nimport fp from 'fastify-plugin'\nimport {\n createTogglyClient,\n normalizeFeatureKeys,\n fromHttpRequest,\n type TogglyClient,\n type EvaluationContext,\n} from '@ops-ai/toggly-node-core'\nimport type {\n TogglyFastifyConfig,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Module-level client singleton\nlet fastifyClient: TogglyClient | null = null\n\n/**\n * Get the Fastify Toggly client\n */\nexport function getFastifyToggly(): TogglyClient | null {\n return fastifyClient\n}\n\n/**\n * Get identity from request\n */\nasync function extractIdentity(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<string | undefined> {\n // Use custom extractor if provided\n if (config.getIdentity) {\n return config.getIdentity(request)\n }\n\n // Default: check header\n const headerIdentity = request.headers['x-toggly-identity']\n if (typeof headerIdentity === 'string') {\n return headerIdentity\n }\n\n return undefined\n}\n\n/**\n * Get evaluation context from request\n */\nasync function extractContext(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<EvaluationContext> {\n const headers = request.headers as Record<string, string | string[] | undefined>\n const headerRequest = fromHttpRequest(headers).request\n\n // Custom full context: use returned fields, fill missing request from headers\n if (config.getContext) {\n const custom = await config.getContext(request)\n return {\n ...custom,\n // Field-level merge: custom wins; missing keys filled from headers\n request: {\n ...headerRequest,\n ...custom.request,\n },\n }\n }\n\n // Default: identity / groups / claims providers + segment request headers\n const identity = await extractIdentity(request, config)\n const groups = config.getGroups ? await config.getGroups(request) : undefined\n const claims = config.getClaims ? await config.getClaims(request) : undefined\n const fromReq = fromHttpRequest(headers, { identity, groups, claims })\n\n return {\n identity: fromReq.identity,\n groups: fromReq.groups,\n claims: fromReq.claims,\n request: fromReq.request,\n traits: {\n ip: request.ip,\n userAgent: request.headers['user-agent'],\n path: request.url,\n method: request.method,\n },\n }\n}\n\n/**\n * Toggly Fastify plugin\n *\n * This plugin:\n * 1. Initializes the Toggly client\n * 2. Attaches feature flag helpers to the request object\n * 3. Extracts identity and context from the request\n */\nconst togglyPluginAsync: FastifyPluginAsync<TogglyFastifyConfig> = async (\n fastify: FastifyInstance,\n config: TogglyFastifyConfig\n) => {\n // Initialize client\n if (!fastifyClient) {\n fastifyClient = createTogglyClient(config)\n await fastifyClient.init()\n }\n\n // Add hook to attach toggly to request\n fastify.addHook('preHandler', async (request: FastifyRequest) => {\n if (!fastifyClient) {\n throw new Error('Toggly client not initialized')\n }\n\n // Extract context from request\n const context = await extractContext(request, config)\n const identity = context.identity\n\n // Attach Toggly helpers to request\n request.toggly = {\n client: fastifyClient,\n features: fastifyClient.state.features,\n identity,\n context,\n isFeatureOn: (featureKey: string) => fastifyClient!.isFeatureOn(featureKey, context),\n isFeatureOff: (featureKey: string) => fastifyClient!.isFeatureOff(featureKey, context),\n evaluateFeatureGate: (featureKeys, requirement, negate) =>\n fastifyClient!.evaluateFeatureGate(featureKeys, requirement, negate, context),\n async getVariant(featureKey: string) {\n return fastifyClient!.getVariant(featureKey, context)\n },\n async getVariantValue(featureKey: string) {\n return fastifyClient!.getVariantValue(featureKey, context)\n },\n }\n })\n\n // Close client when fastify closes\n fastify.addHook('onClose', async () => {\n closeFastifyToggly()\n })\n}\n\n/**\n * Toggly Fastify plugin with proper encapsulation\n */\nexport const togglyPlugin = fp(togglyPluginAsync, {\n name: '@ops-ai/toggly-fastify',\n fastify: '>=4.0.0',\n})\n\n/**\n * Create a feature gate preHandler hook\n *\n * Protects routes by checking if specified features are enabled\n */\nexport function featureGate(options: FeatureGateOptions): PreHandlerHook {\n const {\n featureKey,\n requirement = 'all',\n negate = false,\n onDisabled,\n redirectTo,\n redirectStatus = 302,\n } = options\n\n const featureKeys = normalizeFeatureKeys(featureKey)\n\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!request.toggly) {\n throw new Error('Toggly plugin must be registered before using featureGate')\n }\n\n const isEnabled = await request.toggly.evaluateFeatureGate(featureKeys, requirement, negate)\n\n if (isEnabled) {\n return // Continue to handler\n }\n\n // Feature is disabled\n if (redirectTo) {\n return reply.redirect(redirectTo, redirectStatus)\n }\n\n if (onDisabled) {\n await onDisabled(request)\n return\n }\n\n // Default: 404\n return reply.status(404).send({\n error: 'Not Found',\n message: 'The requested resource is not available',\n })\n }\n}\n\n/**\n * Create preHandler that applies feature gates based on route patterns\n */\nexport function featureRoutes(routes: FeatureRouteOptions[]): PreHandlerHook {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n for (const route of routes) {\n // Check if route matches\n const pathMatches =\n typeof route.path === 'string'\n ? request.url === route.path || request.url.startsWith(route.path)\n : route.path.test(request.url)\n\n if (!pathMatches) {\n continue\n }\n\n // Check if method matches\n if (route.methods && !route.methods.includes(request.method.toUpperCase())) {\n continue\n }\n\n // Apply feature gate\n const gate = featureGate(route)\n return gate(request, reply)\n }\n\n // No matching route, continue\n return\n }\n}\n\n/**\n * Create a decorated route handler that checks features\n */\nexport function withFeature(\n featureKey: string | string[],\n options: Omit<FeatureGateOptions, 'featureKey'> = {}\n): PreHandlerHook {\n return featureGate({ featureKey, ...options })\n}\n\n/**\n * Get features route handler\n */\nexport async function featuresHandler(\n request: FastifyRequest,\n reply: FastifyReply\n): Promise<void> {\n if (!request.toggly) {\n return reply.status(500).send({\n error: 'Internal Server Error',\n message: 'Toggly plugin not configured',\n })\n }\n\n return reply.send({\n features: request.toggly.features,\n identity: request.toggly.identity,\n })\n}\n\n/**\n * Close the Fastify Toggly client\n */\nexport function closeFastifyToggly(): void {\n if (fastifyClient) {\n fastifyClient.close()\n fastifyClient = null\n }\n}\n","// Plugin\nexport {\n togglyPlugin,\n featureGate,\n featureRoutes,\n withFeature,\n featuresHandler,\n getFastifyToggly,\n closeFastifyToggly,\n} from './plugin.js'\n\n// Types\nexport type {\n TogglyFastifyConfig,\n TogglyRequestData,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Re-export core types for convenience\nexport type {\n TogglyClient,\n TogglyConfig,\n TogglyServerConfig,\n TogglyState,\n FeatureDefinitions,\n FeatureRequirement,\n EvaluationContext,\n Hook,\n HookMetadata,\n VariantResult,\n} from '@ops-ai/toggly-node-core'\n\n// Re-export core utilities\nexport {\n createTogglyClient,\n initToggly,\n getToggly,\n useToggly,\n closeToggly,\n createLoggingHook,\n createMemoryCache,\n createFileCache,\n} from '@ops-ai/toggly-node-core'\n"],"mappings":";AAYA,OAAO,QAAQ;AACf;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAQP,IAAI,gBAAqC;AAKlC,SAAS,mBAAwC;AACtD,SAAO;AACT;AAKA,eAAe,gBACb,SACA,QAC6B;AAE7B,MAAI,OAAO,aAAa;AACtB,WAAO,OAAO,YAAY,OAAO;AAAA,EACnC;AAGA,QAAM,iBAAiB,QAAQ,QAAQ,mBAAmB;AAC1D,MAAI,OAAO,mBAAmB,UAAU;AACtC,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAKA,eAAe,eACb,SACA,QAC4B;AAC5B,QAAM,UAAU,QAAQ;AACxB,QAAM,gBAAgB,gBAAgB,OAAO,EAAE;AAG/C,MAAI,OAAO,YAAY;AACrB,UAAM,SAAS,MAAM,OAAO,WAAW,OAAO;AAC9C,WAAO;AAAA,MACL,GAAG;AAAA;AAAA,MAEH,SAAS;AAAA,QACP,GAAG;AAAA,QACH,GAAG,OAAO;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AAGA,QAAM,WAAW,MAAM,gBAAgB,SAAS,MAAM;AACtD,QAAM,SAAS,OAAO,YAAY,MAAM,OAAO,UAAU,OAAO,IAAI;AACpE,QAAM,SAAS,OAAO,YAAY,MAAM,OAAO,UAAU,OAAO,IAAI;AACpE,QAAM,UAAU,gBAAgB,SAAS,EAAE,UAAU,QAAQ,OAAO,CAAC;AAErE,SAAO;AAAA,IACL,UAAU,QAAQ;AAAA,IAClB,QAAQ,QAAQ;AAAA,IAChB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AAC;AAAA,EACH;AAEA,SAAO,MAAM,KAAK;AAAA,IAChB,UAAU,QAAQ,OAAO;AAAA,IACzB,UAAU,QAAQ,OAAO;AAAA,EAC3B,CAAC;AACH;AAKO,SAAS,qBAA2B;AACzC,MAAI,eAAe;AACjB,kBAAc,MAAM;AACpB,oBAAgB;AAAA,EAClB;AACF;;;AClPA;AAAA,EACE,sBAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["createTogglyClient"]}
|
|
1
|
+
{"version":3,"sources":["../src/plugin.ts","../src/index.ts"],"sourcesContent":["import type {\n FastifyInstance,\n FastifyRequest,\n FastifyReply,\n FastifyPluginAsync,\n} from 'fastify'\n\n// Custom type for preHandler hooks (simpler than Fastify's complex generic type)\ntype PreHandlerHook = (\n request: FastifyRequest,\n reply: FastifyReply\n) => Promise<unknown>\nimport fp from 'fastify-plugin'\nimport {\n createTogglyClient,\n normalizeFeatureKeys,\n fromHttpRequest,\n type TogglyClient,\n type EvaluationContext,\n} from '@ops-ai/toggly-node-core'\nimport type {\n TogglyFastifyConfig,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Module-level client singleton\nlet fastifyClient: TogglyClient | null = null\n\n/**\n * Get the Fastify Toggly client\n */\nexport function getFastifyToggly(): TogglyClient | null {\n return fastifyClient\n}\n\n/**\n * Get identity from request\n */\nasync function extractIdentity(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<string | undefined> {\n // Use custom extractor if provided\n if (config.getIdentity) {\n return config.getIdentity(request)\n }\n\n // Default: check header\n const headerIdentity = request.headers['x-toggly-identity']\n if (typeof headerIdentity === 'string') {\n return headerIdentity\n }\n\n return undefined\n}\n\n/**\n * Get evaluation context from request\n */\nasync function extractContext(\n request: FastifyRequest,\n config: TogglyFastifyConfig\n): Promise<EvaluationContext> {\n const headers = request.headers as Record<string, string | string[] | undefined>\n const headerRequest = fromHttpRequest(headers).request\n\n // Custom full context: use returned fields, fill missing request from headers\n if (config.getContext) {\n const custom = await config.getContext(request)\n return {\n ...custom,\n // Field-level merge: custom wins; missing keys filled from headers\n request: {\n ...headerRequest,\n ...custom.request,\n },\n }\n }\n\n // Default: identity / groups / claims providers + segment request headers\n const identity = await extractIdentity(request, config)\n const groups = config.getGroups ? await config.getGroups(request) : undefined\n const claims = config.getClaims ? await config.getClaims(request) : undefined\n const fromReq = fromHttpRequest(headers, { identity, groups, claims })\n\n return {\n identity: fromReq.identity,\n groups: fromReq.groups,\n claims: fromReq.claims,\n request: fromReq.request,\n traits: {\n ip: request.ip,\n userAgent: request.headers['user-agent'],\n path: request.url,\n method: request.method,\n },\n }\n}\n\n/**\n * Toggly Fastify plugin\n *\n * This plugin:\n * 1. Initializes the Toggly client\n * 2. Attaches feature flag helpers to the request object\n * 3. Extracts identity and context from the request\n */\nconst togglyPluginAsync: FastifyPluginAsync<TogglyFastifyConfig> = async (\n fastify: FastifyInstance,\n config: TogglyFastifyConfig\n) => {\n // Initialize client\n if (!fastifyClient) {\n fastifyClient = createTogglyClient(config)\n await fastifyClient.init()\n }\n\n // Add hook to attach toggly to request\n fastify.addHook('preHandler', async (request: FastifyRequest) => {\n if (!fastifyClient) {\n throw new Error('Toggly client not initialized')\n }\n\n // Extract context from request\n const context = await extractContext(request, config)\n const identity = context.identity\n\n // Attach Toggly helpers to request\n request.toggly = {\n client: fastifyClient,\n features: fastifyClient.state.features,\n identity,\n context,\n isFeatureOn: (featureKey: string) => fastifyClient!.isFeatureOn(featureKey, context),\n isFeatureOff: (featureKey: string) => fastifyClient!.isFeatureOff(featureKey, context),\n evaluateFeatureGate: (featureKeys, requirement, negate) =>\n fastifyClient!.evaluateFeatureGate(featureKeys, requirement, negate, context),\n getVariant(featureKey: string) {\n return fastifyClient!.getVariant(featureKey, context)\n },\n getVariantValue(featureKey: string) {\n return fastifyClient!.getVariantValue(featureKey, context)\n },\n }\n })\n\n // Close client when fastify closes\n fastify.addHook('onClose', () => {\n closeFastifyToggly()\n })\n}\n\n/**\n * Toggly Fastify plugin with proper encapsulation\n */\nexport const togglyPlugin = fp(togglyPluginAsync, {\n name: '@ops-ai/toggly-fastify',\n fastify: '>=4.0.0',\n})\n\n/**\n * Create a feature gate preHandler hook\n *\n * Protects routes by checking if specified features are enabled\n */\nexport function featureGate(options: FeatureGateOptions): PreHandlerHook {\n const {\n featureKey,\n requirement = 'all',\n negate = false,\n onDisabled,\n redirectTo,\n redirectStatus = 302,\n } = options\n\n const featureKeys = normalizeFeatureKeys(featureKey)\n\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!request.toggly) {\n throw new Error('Toggly plugin must be registered before using featureGate')\n }\n\n const isEnabled = await request.toggly.evaluateFeatureGate(featureKeys, requirement, negate)\n\n if (isEnabled) {\n return // Continue to handler\n }\n\n // Feature is disabled\n if (redirectTo) {\n return reply.redirect(redirectTo, redirectStatus)\n }\n\n if (onDisabled) {\n await onDisabled(request)\n return\n }\n\n // Default: 404\n return reply.status(404).send({\n error: 'Not Found',\n message: 'The requested resource is not available',\n })\n }\n}\n\n/**\n * Create preHandler that applies feature gates based on route patterns\n */\nexport function featureRoutes(routes: FeatureRouteOptions[]): PreHandlerHook {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n for (const route of routes) {\n // Check if route matches\n const pathMatches =\n typeof route.path === 'string'\n ? request.url === route.path || request.url.startsWith(route.path)\n : route.path.test(request.url)\n\n if (!pathMatches) {\n continue\n }\n\n // Check if method matches\n if (route.methods && !route.methods.includes(request.method.toUpperCase())) {\n continue\n }\n\n // Apply feature gate\n const gate = featureGate(route)\n return gate(request, reply)\n }\n\n // No matching route, continue.\n return undefined\n }\n}\n\n/**\n * Create a decorated route handler that checks features\n */\nexport function withFeature(\n featureKey: string | string[],\n options: Omit<FeatureGateOptions, 'featureKey'> = {}\n): PreHandlerHook {\n return featureGate({ featureKey, ...options })\n}\n\n/**\n * Get features route handler\n */\nexport async function featuresHandler(\n request: FastifyRequest,\n reply: FastifyReply\n): Promise<void> {\n if (!request.toggly) {\n return reply.status(500).send({\n error: 'Internal Server Error',\n message: 'Toggly plugin not configured',\n })\n }\n\n return reply.send({\n features: request.toggly.features,\n identity: request.toggly.identity,\n })\n}\n\n/**\n * Close the Fastify Toggly client\n */\nexport function closeFastifyToggly(): void {\n if (fastifyClient) {\n fastifyClient.close()\n fastifyClient = null\n }\n}\n","// Plugin\nexport {\n togglyPlugin,\n featureGate,\n featureRoutes,\n withFeature,\n featuresHandler,\n getFastifyToggly,\n closeFastifyToggly,\n} from './plugin.js'\n\n// Types\nexport type {\n TogglyFastifyConfig,\n TogglyRequestData,\n FeatureGateOptions,\n FeatureRouteOptions,\n} from './types.js'\n\n// Re-export core types for convenience\nexport type {\n TogglyClient,\n TogglyConfig,\n TogglyServerConfig,\n TogglyState,\n FeatureDefinitions,\n FeatureRequirement,\n EvaluationContext,\n Hook,\n HookMetadata,\n VariantResult,\n} from '@ops-ai/toggly-node-core'\n\n// Re-export core utilities\nexport {\n createTogglyClient,\n initToggly,\n getToggly,\n useToggly,\n closeToggly,\n createLoggingHook,\n createMemoryCache,\n createFileCache,\n} from '@ops-ai/toggly-node-core'\n"],"mappings":";AAYA,OAAO,QAAQ;AACf;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAQP,IAAI,gBAAqC;AAKlC,SAAS,mBAAwC;AACtD,SAAO;AACT;AAKA,eAAe,gBACb,SACA,QAC6B;AAE7B,MAAI,OAAO,aAAa;AACtB,WAAO,OAAO,YAAY,OAAO;AAAA,EACnC;AAGA,QAAM,iBAAiB,QAAQ,QAAQ,mBAAmB;AAC1D,MAAI,OAAO,mBAAmB,UAAU;AACtC,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAKA,eAAe,eACb,SACA,QAC4B;AAC5B,QAAM,UAAU,QAAQ;AACxB,QAAM,gBAAgB,gBAAgB,OAAO,EAAE;AAG/C,MAAI,OAAO,YAAY;AACrB,UAAM,SAAS,MAA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A,UAAI,MAAM,WAAW,CAAC,MAAM,QAAQ,SAAS,QAAQ,OAAO,YAAY,CAAC,GAAG;AAC1E;AAAA,MACF;AAGA,YAAM,OAAO,YAAY,KAAK;AAC9B,aAAO,KAAK,SAAS,KAAK;AAAA,IAC5B;AAGA,WAAO;AAAA,EACT;AACF;AAKO,SAAS,YACd,YACA,UAAkD,CAAC,GACnC;AAChB,SAAO,YAAY,EAAE,YAAY,GAAG,QAAQ,CAAC;AAC/C;AAKA,eAAsB,gBACpB,SACA,OACe;AACf,MAAI,CAAC,QAAQ,QAAQ;AACnB,WAAO,MAAM,OAAO,GAAG,EAAE,KAAK;AAAA,MAC5B,OAAO;AAAA,MACP,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,SAAO,MAAM,KAAK;AAAA,IAChB,UAAU,QAAQ,OAAO;AAAA,IACzB,UAAU,QAAQ,OAAO;AAAA,EAC3B,CAAC;AACH;AAKO,SAAS,qBAA2B;AACzC,MAAI,eAAe;AACjB,kBAAc,MAAM;AACpB,oBAAgB;AAAA,EAClB;AACF;;;AClPA;AAAA,EACE,sBAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["createTogglyClient"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ops-ai/toggly-fastify",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Toggly feature flags Fastify plugin",
|
|
5
5
|
"main": "./dist/index.cjs",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -45,26 +45,26 @@
|
|
|
45
45
|
"url": "https://github.com/ops-ai/Toggly.FeatureManagement/issues"
|
|
46
46
|
},
|
|
47
47
|
"engines": {
|
|
48
|
-
"node": ">=
|
|
48
|
+
"node": ">=22.0.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
51
|
"fastify": "^4.0.0 || ^5.0.0"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"fastify-plugin": "^5.0
|
|
55
|
-
"@ops-ai/toggly-node-core": "^0.
|
|
54
|
+
"fastify-plugin": "^5.1.0",
|
|
55
|
+
"@ops-ai/toggly-node-core": "^0.14.0"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
|
-
"@eslint/js": "^9.39.
|
|
59
|
-
"@types/node": "^22.
|
|
60
|
-
"@vitest/coverage-v8": "^3.2.
|
|
61
|
-
"eslint": "^9.
|
|
62
|
-
"fastify": "^5.
|
|
58
|
+
"@eslint/js": "^9.39.5",
|
|
59
|
+
"@types/node": "^22.20.5",
|
|
60
|
+
"@vitest/coverage-v8": "^3.2.7",
|
|
61
|
+
"eslint": "^9.39.5",
|
|
62
|
+
"fastify": "^5.12.7",
|
|
63
63
|
"globals": "^15.15.0",
|
|
64
|
-
"tsup": "^8.5.
|
|
65
|
-
"typescript": "^5.
|
|
66
|
-
"typescript-eslint": "^8.
|
|
67
|
-
"vitest": "^3.2.
|
|
64
|
+
"tsup": "^8.5.1",
|
|
65
|
+
"typescript": "^5.9.3",
|
|
66
|
+
"typescript-eslint": "^8.72.1",
|
|
67
|
+
"vitest": "^3.2.7"
|
|
68
68
|
},
|
|
69
69
|
"publishConfig": {
|
|
70
70
|
"access": "public"
|