@hyphen/sdk 1.12.0 → 1.12.1

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/dist/index.cjs CHANGED
@@ -39,506 +39,529 @@ __export(index_exports, {
39
39
  });
40
40
  module.exports = __toCommonJS(index_exports);
41
41
 
42
- // src/toggle.ts
42
+ // src/env.ts
43
+ var import_node_fs = __toESM(require("fs"), 1);
44
+ var import_node_path = __toESM(require("path"), 1);
43
45
  var import_node_process = __toESM(require("process"), 1);
46
+ var import_dotenv = require("dotenv");
47
+ function env(options) {
48
+ const local = options?.local ?? true;
49
+ const currentWorkingDirectory = options?.path ?? import_node_process.default.cwd();
50
+ const envPath = import_node_path.default.resolve(currentWorkingDirectory, ".env");
51
+ if (import_node_fs.default.existsSync(envPath)) {
52
+ (0, import_dotenv.config)({
53
+ path: envPath,
54
+ quiet: true,
55
+ debug: false
56
+ });
57
+ }
58
+ if (local) {
59
+ const localEnvPath = import_node_path.default.resolve(currentWorkingDirectory, ".env.local");
60
+ if (import_node_fs.default.existsSync(localEnvPath)) {
61
+ (0, import_dotenv.config)({
62
+ path: localEnvPath,
63
+ override: true,
64
+ quiet: true,
65
+ debug: false
66
+ });
67
+ }
68
+ }
69
+ const environment = options?.environment ?? import_node_process.default.env.NODE_ENV;
70
+ if (environment) {
71
+ const envSpecificPath = import_node_path.default.resolve(currentWorkingDirectory, `.env.${environment}`);
72
+ if (import_node_fs.default.existsSync(envSpecificPath)) {
73
+ (0, import_dotenv.config)({
74
+ path: envSpecificPath,
75
+ override: true,
76
+ quiet: true,
77
+ debug: false
78
+ });
79
+ }
80
+ if (local) {
81
+ const envLocalPath = import_node_path.default.resolve(currentWorkingDirectory, `.env.${environment}.local`);
82
+ if (import_node_fs.default.existsSync(envLocalPath)) {
83
+ (0, import_dotenv.config)({
84
+ path: envLocalPath,
85
+ override: true,
86
+ quiet: true,
87
+ debug: false
88
+ });
89
+ }
90
+ }
91
+ }
92
+ }
93
+ __name(env, "env");
94
+ var loadEnv = env;
95
+
96
+ // src/hyphen.ts
97
+ var import_hookified3 = require("hookified");
98
+
99
+ // src/link.ts
100
+ var import_node_buffer = require("buffer");
101
+ var import_node_process2 = __toESM(require("process"), 1);
102
+
103
+ // src/base-service.ts
104
+ var import_axios = __toESM(require("axios"), 1);
105
+ var import_cacheable = require("cacheable");
44
106
  var import_hookified = require("hookified");
45
- var import_dotenv = __toESM(require("dotenv"), 1);
46
- var import_server_sdk = require("@openfeature/server-sdk");
47
- var import_openfeature_server_provider = require("@hyphen/openfeature-server-provider");
48
- import_dotenv.default.config();
49
- var ToggleHooks = /* @__PURE__ */ function(ToggleHooks2) {
50
- ToggleHooks2["beforeGetBoolean"] = "beforeGetBoolean";
51
- ToggleHooks2["afterGetBoolean"] = "afterGetBoolean";
52
- ToggleHooks2["beforeGetString"] = "beforeGetString";
53
- ToggleHooks2["afterGetString"] = "afterGetString";
54
- ToggleHooks2["beforeGetNumber"] = "beforeGetNumber";
55
- ToggleHooks2["afterGetNumber"] = "afterGetNumber";
56
- ToggleHooks2["beforeGetObject"] = "beforeGetObject";
57
- ToggleHooks2["afterGetObject"] = "afterGetObject";
58
- return ToggleHooks2;
107
+ var import_pino = __toESM(require("pino"), 1);
108
+ var ErrorMessages = /* @__PURE__ */ function(ErrorMessages2) {
109
+ ErrorMessages2["API_KEY_REQUIRED"] = "API key is required. Please provide it via options or set the HYPHEN_API_KEY environment variable.";
110
+ ErrorMessages2["PUBLIC_API_KEY_SHOULD_NOT_BE_USED"] = "The provided API key is a public API key. Please provide a valid non public API key for authentication.";
111
+ return ErrorMessages2;
59
112
  }({});
60
- var Toggle = class extends import_hookified.Hookified {
113
+ var BaseService = class extends import_hookified.Hookified {
61
114
  static {
62
- __name(this, "Toggle");
115
+ __name(this, "BaseService");
63
116
  }
64
- _applicationId = import_node_process.default.env.HYPHEN_APPLICATION_ID;
65
- _publicApiKey = import_node_process.default.env.HYPHEN_PUBLIC_API_KEY;
66
- _environment;
67
- _client;
68
- _context;
117
+ _log = (0, import_pino.default)();
118
+ _cache = new import_cacheable.Cacheable();
69
119
  _throwErrors = false;
70
- _uris;
71
- _caching;
72
- /*
73
- * Create a new Toggle instance. This will create a new client and set the options.
74
- * @param {ToggleOptions}
75
- */
76
120
  constructor(options) {
77
- super();
78
- this._throwErrors = options?.throwErrors ?? false;
79
- this._applicationId = options?.applicationId;
80
- if (options?.publicApiKey) {
81
- this.setPublicApiKey(options.publicApiKey);
121
+ super(options);
122
+ if (options && options.throwErrors !== void 0) {
123
+ this._throwErrors = options.throwErrors;
82
124
  }
83
- this._environment = options?.environment ?? import_node_process.default.env.NODE_ENV ?? "development";
84
- this._context = options?.context;
85
- this._uris = options?.uris;
86
- this._caching = options?.caching;
87
- }
88
- /**
89
- * Get the application ID
90
- * @returns {string | undefined}
91
- */
92
- get applicationId() {
93
- return this._applicationId;
94
- }
95
- /**
96
- * Set the application ID
97
- * @param {string | undefined} value
98
- */
99
- set applicationId(value) {
100
- this._applicationId = value;
101
125
  }
102
- /**
103
- * Get the public API key
104
- * @returns {string}
105
- */
106
- get publicApiKey() {
107
- return this._publicApiKey;
126
+ get log() {
127
+ return this._log;
108
128
  }
109
- /**
110
- * Set the public API key
111
- * @param {string} value
112
- */
113
- set publicApiKey(value) {
114
- if (!value) {
115
- this._publicApiKey = void 0;
116
- this._client = void 0;
117
- return;
118
- }
119
- this.setPublicApiKey(value);
129
+ set log(value) {
130
+ this._log = value;
120
131
  }
121
- /**
122
- * Get the environment
123
- * @returns {string}
124
- */
125
- get environment() {
126
- return this._environment;
132
+ get cache() {
133
+ return this._cache;
127
134
  }
128
- /**
129
- * Set the environment
130
- * @param {string} value
131
- */
132
- set environment(value) {
133
- this._environment = value;
135
+ set cache(value) {
136
+ this._cache = value;
134
137
  }
135
- /**
136
- * Get the throwErrors. If true, errors will be thrown in addition to being emitted.
137
- * @returns {boolean}
138
- */
139
138
  get throwErrors() {
140
139
  return this._throwErrors;
141
140
  }
142
- /**
143
- * Set the throwErrors. If true, errors will be thrown in addition to being emitted.
144
- * @param {boolean} value
145
- */
146
141
  set throwErrors(value) {
147
142
  this._throwErrors = value;
148
143
  }
149
- /**
150
- * Get the current context. This is the default context used. You can override this at the get function level.
151
- * @returns {ToggleContext}
152
- */
153
- get context() {
154
- return this._context;
144
+ error(message, ...args) {
145
+ this._log.error(message, ...args);
146
+ this.emit("error", message, ...args);
147
+ if (this.throwErrors) {
148
+ throw new Error(message);
149
+ }
155
150
  }
156
- /**
157
- * Set the context. This is the default context used. You can override this at the get function level.
158
- * @param {ToggleContext} value
159
- */
160
- set context(value) {
161
- this._context = value;
151
+ warn(message, ...args) {
152
+ this._log.warn(message, ...args);
153
+ this.emit("warn", message, ...args);
154
+ }
155
+ info(message, ...args) {
156
+ this._log.info(message, ...args);
157
+ this.emit("info", message, ...args);
158
+ }
159
+ async get(url, config2) {
160
+ return import_axios.default.get(url, config2);
161
+ }
162
+ async post(url, data, config2) {
163
+ return import_axios.default.post(url, data, config2);
164
+ }
165
+ async put(url, data, config2) {
166
+ return import_axios.default.put(url, data, config2);
167
+ }
168
+ async delete(url, config2) {
169
+ if (config2?.headers) {
170
+ delete config2.headers["content-type"];
171
+ }
172
+ return import_axios.default.delete(url, config2);
173
+ }
174
+ async patch(url, data, config2) {
175
+ return import_axios.default.patch(url, data, config2);
176
+ }
177
+ createHeaders(apiKey) {
178
+ const headers = {
179
+ "content-type": "application/json",
180
+ accept: "application/json"
181
+ };
182
+ if (apiKey) {
183
+ headers["x-api-key"] = apiKey;
184
+ }
185
+ return headers;
186
+ }
187
+ };
188
+
189
+ // src/link.ts
190
+ env();
191
+ var defaultLinkUris = [
192
+ "https://api.hyphen.ai/api/organizations/{organizationId}/link/codes/"
193
+ ];
194
+ var Link = class extends BaseService {
195
+ static {
196
+ __name(this, "Link");
197
+ }
198
+ _uris = defaultLinkUris;
199
+ _organizationId;
200
+ _apiKey;
201
+ constructor(options) {
202
+ super(options);
203
+ this._uris = options?.uris ?? defaultLinkUris;
204
+ this._organizationId = options?.organizationId;
205
+ if (options?.apiKey) {
206
+ this.setApiKey(options.apiKey);
207
+ }
208
+ if (!this._apiKey && import_node_process2.default.env.HYPHEN_API_KEY) {
209
+ this.setApiKey(import_node_process2.default.env.HYPHEN_API_KEY);
210
+ }
211
+ if (!this._organizationId && import_node_process2.default.env.HYPHEN_ORGANIZATION_ID) {
212
+ this._organizationId = import_node_process2.default.env.HYPHEN_ORGANIZATION_ID;
213
+ }
162
214
  }
163
215
  /**
164
- * Get the URIs. This is used to override the default URIs for testing or if you are using a self-hosted version.
165
- * @returns {Array<string>}
216
+ * Get the URIs for the link service. The default is `["https://api.hyphen.ai/api/organizations/{organizationId}/link/codes/"]`.
217
+ * @returns {string[]} The URIs for the link service.
166
218
  */
167
219
  get uris() {
168
220
  return this._uris;
169
221
  }
170
222
  /**
171
- * Set the URIs. This is used to override the default URIs for testing or if you are using a self-hosted version.
172
- * @param {Array<string>} value
223
+ * Set the URIs for the link service. The default is `["https://api.hyphen.ai/api/organizations/{organizationId}/link/codes/"]`.
224
+ * @param {string[]} uris - The URIs to set.
173
225
  */
174
- set uris(value) {
175
- this._uris = value;
226
+ set uris(uris) {
227
+ this._uris = uris;
176
228
  }
177
229
  /**
178
- * Get the caching options.
179
- * @returns {ToggleCachingOptions | undefined}
230
+ * Get the organization ID for the link service. This is required to access the link service.
231
+ * @returns {string | undefined} The organization ID.
180
232
  */
181
- get caching() {
182
- return this._caching;
233
+ get organizationId() {
234
+ return this._organizationId;
183
235
  }
184
236
  /**
185
- * Set the caching options.
186
- * @param {ToggleCachingOptions | undefined} value
237
+ * Set the organization ID for the link service. This is required to access the link service.
238
+ * @param {string | undefined} organizationId - The organization ID to set.
187
239
  */
188
- set caching(value) {
189
- this._caching = value;
240
+ set organizationId(organizationId) {
241
+ this._organizationId = organizationId;
190
242
  }
191
243
  /**
192
- * This is a helper function to set the public API key. It will check if the key starts with public_ and set it. If it
193
- * does set it will also set the client to undefined to force a new one to be created. If it does not,
194
- * it will emit an error and console warning and not set the key. Used by the constructor and publicApiKey setter.
195
- * @param key
196
- * @returns
244
+ * Get the API key for the link service. This is required to access the link service.
245
+ * @returns {string | undefined} The API key.
197
246
  */
198
- setPublicApiKey(key) {
199
- if (!key.startsWith("public_")) {
200
- this.emit("error", new Error("Public API key should start with public_"));
201
- if (import_node_process.default.env.NODE_ENV !== "production") {
202
- console.error("Public API key should start with public_");
203
- }
204
- return;
205
- }
206
- this._publicApiKey = key;
207
- this._client = void 0;
247
+ get apiKey() {
248
+ return this._apiKey;
208
249
  }
209
250
  /**
210
- * Set the context. This is the default context used. You can override this at the get function level.
211
- * @param {ToggleContext} context
251
+ * Set the API key for the link service. This is required to access the link service.
252
+ * @param {string | undefined} apiKey - The API key to set.
212
253
  */
213
- setContext(context) {
214
- this._context = context;
215
- this._client = void 0;
254
+ set apiKey(apiKey) {
255
+ this.setApiKey(apiKey);
216
256
  }
217
257
  /**
218
- * Helper function to get the client. This will create a new client if one does not exist. It will also set the
219
- * application ID, environment, and URIs if they are not set. This is used by the get function to get the client.
220
- * This is normally only used internally.
221
- * @returns {Promise<Client>}
258
+ * Set the API key for the link service. If the API key starts with 'public_', an error is thrown.
259
+ * This is to ensure that the API key is not a public key, which should not be used for authenticated requests.
260
+ * @param {string} apiKey
222
261
  */
223
- async getClient() {
224
- if (!this._client) {
225
- if (this._applicationId === void 0 || this._applicationId.length === 0) {
226
- const errorMessage = "Application ID is not set. You must set it before using the client or have the HYPHEN_APPLICATION_ID environment variable set.";
227
- this.emit("error", new Error(errorMessage));
228
- if (this._throwErrors) {
229
- throw new Error(errorMessage);
230
- }
231
- }
232
- const options = {
233
- application: this._applicationId,
234
- environment: this._environment,
235
- horizonUrls: this._uris,
236
- cache: this._caching
237
- };
238
- if (this._publicApiKey && this._publicApiKey.length > 0) {
239
- await import_server_sdk.OpenFeature.setProviderAndWait(new import_openfeature_server_provider.HyphenProvider(this._publicApiKey, options));
240
- } else {
241
- this.emit("error", new Error("Public API key is not set. You must set it before using the client or have the HYPHEN_PUBLIC_API_KEY environment variable set."));
242
- if (this._throwErrors) {
243
- throw new Error("Public API key is not set");
244
- }
245
- }
246
- this._client = import_server_sdk.OpenFeature.getClient(this._context);
262
+ setApiKey(apiKey) {
263
+ if (apiKey?.startsWith("public_")) {
264
+ throw new Error('API key cannot start with "public_"');
265
+ }
266
+ if (apiKey) {
267
+ this._apiKey = apiKey;
247
268
  }
248
- return this._client;
249
269
  }
250
270
  /**
251
- * This is the main function to get a feature flag value. It will check the type of the default value and call the
252
- * appropriate function. It will also set the context if it is not set.
253
- * @param {string} key - The key of the feature flag
254
- * @param {T} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
255
- * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
256
- * @returns {Promise<T>}
271
+ * Get the URI for a specific organization and code. This is used internally to construct the URI for the link service.
272
+ * @param {string} organizationId The ID of the organization.
273
+ * @param {string} code The code to include in the URI.
274
+ * @returns {string} The constructed URI.
257
275
  */
258
- async get(key, defaultValue, options) {
259
- switch (typeof defaultValue) {
260
- case "boolean": {
261
- return this.getBoolean(key, defaultValue, options);
262
- }
263
- case "string": {
264
- return this.getString(key, defaultValue, options);
265
- }
266
- case "number": {
267
- return this.getNumber(key, defaultValue, options);
268
- }
269
- default: {
270
- return this.getObject(key, defaultValue, options);
271
- }
276
+ getUri(organizationId, prefix1, prefix2, prefix3) {
277
+ if (!organizationId) {
278
+ throw new Error("Organization ID is required to get the URI.");
279
+ }
280
+ let url = this._uris[0].replace("{organizationId}", organizationId);
281
+ if (prefix1) {
282
+ url = url.endsWith("/") ? `${url}${prefix1}/` : `${url}/${prefix1}`;
283
+ }
284
+ if (prefix2) {
285
+ url = url.endsWith("/") ? `${url}${prefix2}/` : `${url}/${prefix2}`;
286
+ }
287
+ if (prefix3) {
288
+ url = url.endsWith("/") ? `${url}${prefix3}/` : `${url}/${prefix3}`;
289
+ }
290
+ if (url.endsWith("/")) {
291
+ url = url.slice(0, -1);
272
292
  }
293
+ return url;
273
294
  }
274
295
  /**
275
- * Get a boolean value from the feature flag. This will check the type of the default value and call the
276
- * appropriate function. It will also set the context if it is not set.
277
- * @param {string} key - The key of the feature flag
278
- * @param {boolean} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
279
- * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
280
- * @returns {Promise<boolean>} - The value of the feature flag
296
+ * Create a short code for a long URL.
297
+ * @param {string} longUrl The long URL to shorten.
298
+ * @param {string} domain The domain to use for the short code.
299
+ * @param {CreateShortCodeOptions} options Optional parameters for creating the short code.
300
+ * @returns {Promise<CreateShortCodeResponse>} A promise that resolves to the created short code details.
281
301
  */
282
- async getBoolean(key, defaultValue, options) {
283
- try {
284
- const data = {
285
- key,
286
- defaultValue,
287
- options
288
- };
289
- await this.hook("beforeGetBoolean", data);
290
- const client = await this.getClient();
291
- const result = await client.getBooleanValue(data.key, data.defaultValue, data.options?.context);
292
- const resultData = {
293
- key,
294
- defaultValue,
295
- options,
296
- result
297
- };
298
- await this.hook("afterGetBoolean", resultData);
299
- return resultData.result;
300
- } catch (error) {
301
- this.emit("error", error);
302
- if (this._throwErrors) {
303
- throw error;
304
- }
302
+ async createShortCode(longUrl, domain, options) {
303
+ if (!this._organizationId) {
304
+ throw new Error("Organization ID is required to create a short code.");
305
305
  }
306
- return defaultValue;
306
+ const url = this.getUri(this._organizationId);
307
+ const body = {
308
+ long_url: longUrl,
309
+ domain,
310
+ code: options?.code,
311
+ title: options?.title,
312
+ tags: options?.tags
313
+ };
314
+ const headers = this.createHeaders(this._apiKey);
315
+ const response = await this.post(url, body, {
316
+ headers
317
+ });
318
+ if (response.status === 201) {
319
+ return response.data;
320
+ }
321
+ throw new Error(`Failed to create short code: ${response.statusText}`);
307
322
  }
308
323
  /**
309
- * Get a string value from the feature flag.
310
- * @param {string} key - The key of the feature flag
311
- * @param {string} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
312
- * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
313
- * @returns {Promise<string>} - The value of the feature flag
324
+ * Get a short code by its code.
325
+ * @param {string} code The short code to retrieve. Example: 'code_686bed403c3991bd676bba4d'
326
+ * @returns {Promise<GetShortCodeResponse>} A promise that resolves to the short code details.
314
327
  */
315
- async getString(key, defaultValue, options) {
316
- try {
317
- const data = {
318
- key,
319
- defaultValue,
320
- options
321
- };
322
- await this.hook("beforeGetString", data);
323
- const client = await this.getClient();
324
- const result = await client.getStringValue(data.key, data.defaultValue, data.options?.context);
325
- const resultData = {
326
- key,
327
- defaultValue,
328
- options,
329
- result
330
- };
331
- await this.hook("afterGetString", resultData);
332
- return resultData.result;
333
- } catch (error) {
334
- this.emit("error", error);
335
- if (this._throwErrors) {
336
- throw error;
337
- }
328
+ async getShortCode(code) {
329
+ if (!this._organizationId) {
330
+ throw new Error("Organization ID is required to get a short code.");
338
331
  }
339
- return defaultValue;
340
- }
341
- async getNumber(key, defaultValue, options) {
342
- try {
343
- const data = {
344
- key,
345
- defaultValue,
346
- options
347
- };
348
- await this.hook("beforeGetNumber", data);
349
- const client = await this.getClient();
350
- const result = await client.getNumberValue(data.key, data.defaultValue, data.options?.context);
351
- const resultData = {
352
- key,
353
- defaultValue,
354
- options,
355
- result
356
- };
357
- await this.hook("afterGetNumber", resultData);
358
- return resultData.result;
359
- } catch (error) {
360
- this.emit("error", error);
361
- if (this._throwErrors) {
362
- throw error;
363
- }
332
+ const url = this.getUri(this._organizationId, code);
333
+ const headers = this.createHeaders(this._apiKey);
334
+ const response = await this.get(url, {
335
+ headers
336
+ });
337
+ if (response.status === 200) {
338
+ return response.data;
364
339
  }
365
- return defaultValue;
340
+ throw new Error(`Failed to get short code: ${response.statusText}`);
366
341
  }
367
342
  /**
368
- * Get an object value from the feature flag. This will check the type of the default value and call the
369
- * appropriate function. It will also set the context if it is not set.
370
- * @param {string} key - The key of the feature flag
371
- * @param {T} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
372
- * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
373
- * @returns {Promise<T>} - The value of the feature flag
343
+ * Get all short codes for the organization.
344
+ * @param {string} titleSearch Optional search term to filter short codes by title.
345
+ * @param {string[]} tags Optional tags to filter short codes.
346
+ * @param {number} pageNumber The page number to retrieve. Default is 1.
347
+ * @param {number} pageSize The number of short codes per page. Default is 100.
348
+ * @returns {Promise<GetShortCodesResponse>} A promise that resolves to the list of short codes.
374
349
  */
375
- async getObject(key, defaultValue, options) {
376
- try {
377
- const data = {
378
- key,
379
- defaultValue,
380
- options
381
- };
382
- await this.hook("beforeGetObject", data);
383
- const client = await this.getClient();
384
- const result = await client.getObjectValue(key, defaultValue, data.options?.context);
385
- const resultData = {
386
- key,
387
- defaultValue,
388
- options,
389
- result
390
- };
391
- await this.hook("afterGetObject", resultData);
392
- return resultData.result;
393
- } catch (error) {
394
- this.emit("error", error);
395
- if (this._throwErrors) {
396
- throw error;
397
- }
398
- }
399
- return defaultValue;
400
- }
401
- };
402
-
403
- // src/env.ts
404
- var import_node_process2 = __toESM(require("process"), 1);
405
- var import_node_fs = __toESM(require("fs"), 1);
406
- var import_node_path = __toESM(require("path"), 1);
407
- var import_dotenv2 = require("dotenv");
408
- function env(options) {
409
- const local = options?.local ?? true;
410
- const currentWorkingDirectory = options?.path ?? import_node_process2.default.cwd();
411
- const envPath = import_node_path.default.resolve(currentWorkingDirectory, ".env");
412
- if (import_node_fs.default.existsSync(envPath)) {
413
- (0, import_dotenv2.config)({
414
- path: envPath
350
+ async getShortCodes(titleSearch, tags, pageNumber = 1, pageSize = 100) {
351
+ if (!this._organizationId) {
352
+ throw new Error("Organization ID is required to get short codes.");
353
+ }
354
+ const url = this.getUri(this._organizationId);
355
+ const headers = this.createHeaders(this._apiKey);
356
+ const parameters = {};
357
+ if (titleSearch) {
358
+ parameters.title = titleSearch;
359
+ }
360
+ if (tags && tags.length > 0) {
361
+ parameters.tags = tags.join(",");
362
+ }
363
+ parameters.pageNum = pageNumber.toString();
364
+ parameters.pageSize = pageSize.toString();
365
+ const response = await this.get(url, {
366
+ headers,
367
+ params: parameters
415
368
  });
416
- }
417
- if (local) {
418
- const localEnvPath = import_node_path.default.resolve(currentWorkingDirectory, ".env.local");
419
- if (import_node_fs.default.existsSync(localEnvPath)) {
420
- (0, import_dotenv2.config)({
421
- path: localEnvPath,
422
- override: true
423
- });
369
+ if (response.status === 200) {
370
+ return response.data;
424
371
  }
372
+ throw new Error(`Failed to get short codes: ${response.statusText}`);
425
373
  }
426
- const environment = options?.environment ?? import_node_process2.default.env.NODE_ENV;
427
- if (environment) {
428
- const envSpecificPath = import_node_path.default.resolve(currentWorkingDirectory, `.env.${environment}`);
429
- if (import_node_fs.default.existsSync(envSpecificPath)) {
430
- (0, import_dotenv2.config)({
431
- path: envSpecificPath,
432
- override: true
433
- });
374
+ /**
375
+ * Get all tags associated with the organization's short codes.
376
+ * @returns {Promise<string[]>} A promise that resolves to an array of tags.
377
+ */
378
+ async getTags() {
379
+ if (!this._organizationId) {
380
+ throw new Error("Organization ID is required to get tags.");
434
381
  }
435
- if (local) {
436
- const envLocalPath = import_node_path.default.resolve(currentWorkingDirectory, `.env.${environment}.local`);
437
- if (import_node_fs.default.existsSync(envLocalPath)) {
438
- (0, import_dotenv2.config)({
439
- path: envLocalPath,
440
- override: true
441
- });
442
- }
382
+ const url = this.getUri(this._organizationId, "tags");
383
+ const headers = this.createHeaders(this._apiKey);
384
+ const response = await this.get(url, {
385
+ headers
386
+ });
387
+ if (response.status === 200) {
388
+ return response.data;
443
389
  }
390
+ throw new Error(`Failed to get tags: ${response.statusText}`);
444
391
  }
445
- }
446
- __name(env, "env");
447
- var loadEnv = env;
448
-
449
- // src/hyphen.ts
450
- var import_hookified3 = require("hookified");
451
-
452
- // src/net-info.ts
453
- var import_node_process3 = __toESM(require("process"), 1);
454
-
455
- // src/base-service.ts
456
- var import_hookified2 = require("hookified");
457
- var import_cacheable = require("cacheable");
458
- var import_axios = __toESM(require("axios"), 1);
459
- var import_pino = __toESM(require("pino"), 1);
460
- var ErrorMessages = /* @__PURE__ */ function(ErrorMessages2) {
461
- ErrorMessages2["API_KEY_REQUIRED"] = "API key is required. Please provide it via options or set the HYPHEN_API_KEY environment variable.";
462
- ErrorMessages2["PUBLIC_API_KEY_SHOULD_NOT_BE_USED"] = "The provided API key is a public API key. Please provide a valid non public API key for authentication.";
463
- return ErrorMessages2;
464
- }({});
465
- var BaseService = class extends import_hookified2.Hookified {
466
- static {
467
- __name(this, "BaseService");
468
- }
469
- _log = (0, import_pino.default)();
470
- _cache = new import_cacheable.Cacheable();
471
- _throwErrors = false;
472
- constructor(options) {
473
- super(options);
474
- if (options && options.throwErrors !== void 0) {
475
- this._throwErrors = options.throwErrors;
392
+ /**
393
+ * Get statistics for a specific short code.
394
+ * @param code The short code to retrieve statistics for.
395
+ * @returns {Promise<GetCodeStatsResponse>} A promise that resolves to the code statistics.
396
+ */
397
+ async getCodeStats(code, startDate, endDate) {
398
+ if (!this._organizationId) {
399
+ throw new Error("Organization ID is required to get code stats.");
476
400
  }
477
- }
478
- get log() {
479
- return this._log;
480
- }
481
- set log(value) {
482
- this._log = value;
483
- }
484
- get cache() {
485
- return this._cache;
486
- }
487
- set cache(value) {
488
- this._cache = value;
489
- }
490
- get throwErrors() {
491
- return this._throwErrors;
492
- }
493
- set throwErrors(value) {
494
- this._throwErrors = value;
495
- }
496
- error(message, ...args) {
497
- this._log.error(message, ...args);
498
- this.emit("error", message, ...args);
499
- if (this.throwErrors) {
500
- throw new Error(message);
401
+ const url = this.getUri(this._organizationId, code, "stats");
402
+ const headers = this.createHeaders(this._apiKey);
403
+ const parameters = {
404
+ startDate: startDate.toISOString(),
405
+ endDate: endDate.toISOString()
406
+ };
407
+ const response = await this.get(url, {
408
+ headers,
409
+ params: parameters
410
+ });
411
+ if (response.status === 200) {
412
+ return response.data;
501
413
  }
414
+ throw new Error(`Failed to get code stats: ${response.statusText}`);
502
415
  }
503
- warn(message, ...args) {
504
- this._log.warn(message, ...args);
505
- this.emit("warn", message, ...args);
506
- }
507
- info(message, ...args) {
508
- this._log.info(message, ...args);
509
- this.emit("info", message, ...args);
510
- }
511
- async get(url, config2) {
512
- return import_axios.default.get(url, config2);
416
+ /**
417
+ * Update a short code.
418
+ * @param {string} code The short code to update. Example: 'code_686bed403c3991bd676bba4d'
419
+ * @param {UpdateShortCodeOptions} options The options to update the short code with.
420
+ * @returns {Promise<UpdateShortCodeResponse>} A promise that resolves to the updated short code details.
421
+ */
422
+ async updateShortCode(code, options) {
423
+ if (!this._organizationId) {
424
+ throw new Error("Organization ID is required to update a short code.");
425
+ }
426
+ const url = this.getUri(this._organizationId, code);
427
+ const headers = this.createHeaders(this._apiKey);
428
+ const response = await this.patch(url, options, {
429
+ headers
430
+ });
431
+ if (response.status === 200) {
432
+ return response.data;
433
+ }
434
+ throw new Error(`Failed to update short code: ${response.statusText}`);
513
435
  }
514
- async post(url, data, config2) {
515
- return import_axios.default.post(url, data, config2);
436
+ /**
437
+ * Delete a short code.
438
+ * @param {string} code The short code to delete. Example: 'code_686bed403c3991bd676bba4d'
439
+ * @returns {Promise<boolean>} A promise that resolves to true if the short code was deleted successfully, or false if it was not.
440
+ */
441
+ async deleteShortCode(code) {
442
+ if (!this._organizationId) {
443
+ throw new Error("Organization ID is required to delete a short code.");
444
+ }
445
+ const url = this.getUri(this._organizationId, code);
446
+ const headers = this.createHeaders(this._apiKey);
447
+ const response = await this.delete(url, {
448
+ headers
449
+ });
450
+ if (response.status === 204) {
451
+ return true;
452
+ }
453
+ throw new Error(`Failed to delete short code: ${response.statusText}`);
516
454
  }
517
- async put(url, data, config2) {
518
- return import_axios.default.put(url, data, config2);
455
+ /**
456
+ * Create a QR code for a specific short code.
457
+ * @param {string} code The short code to create a QR code for.
458
+ * @param {CreateQrCodeOptions} options The options for creating the QR code.
459
+ * @returns {Promise<CreateQrCodeResponse>} A promise that resolves to the created QR code details.
460
+ */
461
+ async createQrCode(code, options) {
462
+ if (!this._organizationId) {
463
+ throw new Error("Organization ID is required to create a QR code.");
464
+ }
465
+ const url = this.getUri(this._organizationId, code, "qrs");
466
+ const headers = this.createHeaders(this._apiKey);
467
+ const body = {
468
+ title: options?.title,
469
+ backgroundColor: options?.backgroundColor,
470
+ color: options?.color,
471
+ size: options?.size,
472
+ logo: options?.logo
473
+ };
474
+ const response = await this.post(url, body, {
475
+ headers
476
+ });
477
+ if (response.status === 201) {
478
+ const result = response.data;
479
+ if (result.qrCode) {
480
+ const buffer = import_node_buffer.Buffer.from(result.qrCode, "base64");
481
+ result.qrCodeBytes = new Uint16Array(buffer);
482
+ }
483
+ return result;
484
+ }
485
+ throw new Error(`Failed to create QR code: ${response.statusText}`);
519
486
  }
520
- async delete(url, config2) {
521
- if (config2 && config2.headers) {
522
- delete config2.headers["content-type"];
487
+ /**
488
+ * Get a QR code by its ID.
489
+ * @param code The short code associated with the QR code.
490
+ * @param qr The ID of the QR code to retrieve.
491
+ * @returns The details of the requested QR code.
492
+ */
493
+ async getQrCode(code, qr) {
494
+ if (!this._organizationId) {
495
+ throw new Error("Organization ID is required to get a QR code.");
523
496
  }
524
- return import_axios.default.delete(url, config2);
497
+ const url = this.getUri(this._organizationId, code, "qrs", qr);
498
+ const headers = this.createHeaders(this._apiKey);
499
+ const response = await this.get(url, {
500
+ headers
501
+ });
502
+ if (response.status === 200) {
503
+ const result = response.data;
504
+ if (result.qrCode) {
505
+ const buffer = import_node_buffer.Buffer.from(result.qrCode, "base64");
506
+ result.qrCodeBytes = new Uint16Array(buffer);
507
+ }
508
+ return result;
509
+ }
510
+ throw new Error(`Failed to get QR code: ${response.statusText}`);
525
511
  }
526
- async patch(url, data, config2) {
527
- return import_axios.default.patch(url, data, config2);
512
+ async getQrCodes(code, pageNumber, pageSize) {
513
+ if (!this._organizationId) {
514
+ throw new Error("Organization ID is required to get QR codes.");
515
+ }
516
+ const url = this.getUri(this._organizationId, code, "qrs");
517
+ const headers = this.createHeaders(this._apiKey);
518
+ const parameters = {};
519
+ if (pageNumber) {
520
+ parameters.pageNum = pageNumber.toString();
521
+ }
522
+ if (pageSize) {
523
+ parameters.pageSize = pageSize.toString();
524
+ }
525
+ const response = await this.get(url, {
526
+ headers,
527
+ params: parameters
528
+ });
529
+ if (response.status === 200) {
530
+ const result = response.data;
531
+ for (const qrCode of result.data) {
532
+ if (qrCode.qrCode) {
533
+ const buffer = import_node_buffer.Buffer.from(qrCode.qrCode, "base64");
534
+ qrCode.qrCodeBytes = new Uint16Array(buffer);
535
+ }
536
+ }
537
+ return result;
538
+ }
539
+ throw new Error(`Failed to get QR codes: ${response.statusText}`);
528
540
  }
529
- createHeaders(apiKey) {
530
- const headers = {
531
- "content-type": "application/json",
532
- accept: "application/json"
533
- };
534
- if (apiKey) {
535
- headers["x-api-key"] = apiKey;
541
+ /**
542
+ * Delete a QR code by its ID.
543
+ * @param {string} code The short code associated with the QR code.
544
+ * @param {string} qr The ID of the QR code to delete.
545
+ * @returns {Promise<boolean>} A promise that resolves to true if the QR code was deleted successfully, or false if it was not.
546
+ */
547
+ async deleteQrCode(code, qr) {
548
+ if (!this._organizationId) {
549
+ throw new Error("Organization ID is required to delete a QR code.");
536
550
  }
537
- return headers;
551
+ const url = this.getUri(this._organizationId, code, "qrs", qr);
552
+ const headers = this.createHeaders(this._apiKey);
553
+ const response = await this.delete(url, {
554
+ headers
555
+ });
556
+ if (response.status === 204) {
557
+ return true;
558
+ }
559
+ throw new Error(`Failed to delete QR code: ${response.statusText}`);
538
560
  }
539
561
  };
540
562
 
541
563
  // src/net-info.ts
564
+ var import_node_process3 = __toESM(require("process"), 1);
542
565
  env();
543
566
  var NetInfo = class extends BaseService {
544
567
  static {
@@ -560,31 +583,31 @@ var NetInfo = class extends BaseService {
560
583
  }
561
584
  }
562
585
  /**
563
- * Gets or sets the API key for authentication.
564
- * If not set, it will try to use the `HYPHEN_API_KEY` environment variable.
565
- * @type {string | undefined}
566
- */
586
+ * Gets or sets the API key for authentication.
587
+ * If not set, it will try to use the `HYPHEN_API_KEY` environment variable.
588
+ * @type {string | undefined}
589
+ */
567
590
  get apiKey() {
568
591
  return this._apiKey;
569
592
  }
570
593
  /**
571
- * Sets the API key for authentication.
572
- * @param {string | undefined} value - The API key to set.
573
- */
594
+ * Sets the API key for authentication.
595
+ * @param {string | undefined} value - The API key to set.
596
+ */
574
597
  set apiKey(value) {
575
598
  this.setApiKey(value);
576
599
  }
577
600
  /**
578
- * Gets or sets the base URI for the API.
579
- * @type {string}
580
- */
601
+ * Gets or sets the base URI for the API.
602
+ * @type {string}
603
+ */
581
604
  get baseUri() {
582
605
  return this._baseUri;
583
606
  }
584
607
  /**
585
- * Sets the base URI for the API.
586
- * @param {string} value - The base URI to set.
587
- */
608
+ * Sets the base URI for the API.
609
+ * @param {string} value - The base URI to set.
610
+ */
588
611
  set baseUri(value) {
589
612
  this._baseUri = value;
590
613
  }
@@ -596,10 +619,10 @@ var NetInfo = class extends BaseService {
596
619
  this._apiKey = value;
597
620
  }
598
621
  /**
599
- * Fetches GeoIP information for a given IP address.
600
- * @param {string} ip - The IP address to fetch GeoIP information for.
601
- * @returns {Promise<ipInfo | ipInfoError>} - A promise that resolves to the ip information or an error.
602
- */
622
+ * Fetches GeoIP information for a given IP address.
623
+ * @param {string} ip - The IP address to fetch GeoIP information for.
624
+ * @returns {Promise<ipInfo | ipInfoError>} - A promise that resolves to the ip information or an error.
625
+ */
603
626
  async getIpInfo(ip) {
604
627
  try {
605
628
  if (!this._apiKey) {
@@ -666,380 +689,364 @@ var NetInfo = class extends BaseService {
666
689
  }
667
690
  };
668
691
 
669
- // src/link.ts
692
+ // src/toggle.ts
670
693
  var import_node_process4 = __toESM(require("process"), 1);
671
- var import_node_buffer = require("buffer");
672
- env();
673
- var defaultLinkUris = [
674
- "https://api.hyphen.ai/api/organizations/{organizationId}/link/codes/"
675
- ];
676
- var Link = class extends BaseService {
694
+ var import_openfeature_server_provider = require("@hyphen/openfeature-server-provider");
695
+ var import_server_sdk = require("@openfeature/server-sdk");
696
+ var import_dotenv2 = __toESM(require("dotenv"), 1);
697
+ var import_hookified2 = require("hookified");
698
+ import_dotenv2.default.config();
699
+ var ToggleHooks = /* @__PURE__ */ function(ToggleHooks2) {
700
+ ToggleHooks2["beforeGetBoolean"] = "beforeGetBoolean";
701
+ ToggleHooks2["afterGetBoolean"] = "afterGetBoolean";
702
+ ToggleHooks2["beforeGetString"] = "beforeGetString";
703
+ ToggleHooks2["afterGetString"] = "afterGetString";
704
+ ToggleHooks2["beforeGetNumber"] = "beforeGetNumber";
705
+ ToggleHooks2["afterGetNumber"] = "afterGetNumber";
706
+ ToggleHooks2["beforeGetObject"] = "beforeGetObject";
707
+ ToggleHooks2["afterGetObject"] = "afterGetObject";
708
+ return ToggleHooks2;
709
+ }({});
710
+ var Toggle = class extends import_hookified2.Hookified {
677
711
  static {
678
- __name(this, "Link");
712
+ __name(this, "Toggle");
679
713
  }
680
- _uris = defaultLinkUris;
681
- _organizationId;
682
- _apiKey;
714
+ _applicationId = import_node_process4.default.env.HYPHEN_APPLICATION_ID;
715
+ _publicApiKey = import_node_process4.default.env.HYPHEN_PUBLIC_API_KEY;
716
+ _environment;
717
+ _client;
718
+ _context;
719
+ _throwErrors = false;
720
+ _uris;
721
+ _caching;
722
+ /*
723
+ * Create a new Toggle instance. This will create a new client and set the options.
724
+ * @param {ToggleOptions}
725
+ */
683
726
  constructor(options) {
684
- super(options);
685
- this._uris = options?.uris ?? defaultLinkUris;
686
- this._organizationId = options?.organizationId;
687
- if (options?.apiKey) {
688
- this.setApiKey(options.apiKey);
689
- }
690
- if (!this._apiKey && import_node_process4.default.env.HYPHEN_API_KEY) {
691
- this.setApiKey(import_node_process4.default.env.HYPHEN_API_KEY);
692
- }
693
- if (!this._organizationId && import_node_process4.default.env.HYPHEN_ORGANIZATION_ID) {
694
- this._organizationId = import_node_process4.default.env.HYPHEN_ORGANIZATION_ID;
727
+ super();
728
+ this._throwErrors = options?.throwErrors ?? false;
729
+ this._applicationId = options?.applicationId;
730
+ if (options?.publicApiKey) {
731
+ this.setPublicApiKey(options.publicApiKey);
695
732
  }
733
+ this._environment = options?.environment ?? import_node_process4.default.env.NODE_ENV ?? "development";
734
+ this._context = options?.context;
735
+ this._uris = options?.uris;
736
+ this._caching = options?.caching;
737
+ }
738
+ /**
739
+ * Get the application ID
740
+ * @returns {string | undefined}
741
+ */
742
+ get applicationId() {
743
+ return this._applicationId;
744
+ }
745
+ /**
746
+ * Set the application ID
747
+ * @param {string | undefined} value
748
+ */
749
+ set applicationId(value) {
750
+ this._applicationId = value;
751
+ }
752
+ /**
753
+ * Get the public API key
754
+ * @returns {string}
755
+ */
756
+ get publicApiKey() {
757
+ return this._publicApiKey;
696
758
  }
697
759
  /**
698
- * Get the URIs for the link service. The default is `["https://api.hyphen.ai/api/organizations/{organizationId}/link/codes/"]`.
699
- * @returns {string[]} The URIs for the link service.
760
+ * Set the public API key
761
+ * @param {string} value
700
762
  */
701
- get uris() {
702
- return this._uris;
763
+ set publicApiKey(value) {
764
+ if (!value) {
765
+ this._publicApiKey = void 0;
766
+ this._client = void 0;
767
+ return;
768
+ }
769
+ this.setPublicApiKey(value);
703
770
  }
704
771
  /**
705
- * Set the URIs for the link service. The default is `["https://api.hyphen.ai/api/organizations/{organizationId}/link/codes/"]`.
706
- * @param {string[]} uris - The URIs to set.
772
+ * Get the environment
773
+ * @returns {string}
707
774
  */
708
- set uris(uris) {
709
- this._uris = uris;
775
+ get environment() {
776
+ return this._environment;
710
777
  }
711
778
  /**
712
- * Get the organization ID for the link service. This is required to access the link service.
713
- * @returns {string | undefined} The organization ID.
779
+ * Set the environment
780
+ * @param {string} value
714
781
  */
715
- get organizationId() {
716
- return this._organizationId;
782
+ set environment(value) {
783
+ this._environment = value;
717
784
  }
718
785
  /**
719
- * Set the organization ID for the link service. This is required to access the link service.
720
- * @param {string | undefined} organizationId - The organization ID to set.
786
+ * Get the throwErrors. If true, errors will be thrown in addition to being emitted.
787
+ * @returns {boolean}
721
788
  */
722
- set organizationId(organizationId) {
723
- this._organizationId = organizationId;
789
+ get throwErrors() {
790
+ return this._throwErrors;
724
791
  }
725
792
  /**
726
- * Get the API key for the link service. This is required to access the link service.
727
- * @returns {string | undefined} The API key.
793
+ * Set the throwErrors. If true, errors will be thrown in addition to being emitted.
794
+ * @param {boolean} value
728
795
  */
729
- get apiKey() {
730
- return this._apiKey;
796
+ set throwErrors(value) {
797
+ this._throwErrors = value;
731
798
  }
732
799
  /**
733
- * Set the API key for the link service. This is required to access the link service.
734
- * @param {string | undefined} apiKey - The API key to set.
800
+ * Get the current context. This is the default context used. You can override this at the get function level.
801
+ * @returns {ToggleContext}
735
802
  */
736
- set apiKey(apiKey) {
737
- this.setApiKey(apiKey);
803
+ get context() {
804
+ return this._context;
738
805
  }
739
806
  /**
740
- * Set the API key for the link service. If the API key starts with 'public_', an error is thrown.
741
- * This is to ensure that the API key is not a public key, which should not be used for authenticated requests.
742
- * @param {string} apiKey
807
+ * Set the context. This is the default context used. You can override this at the get function level.
808
+ * @param {ToggleContext} value
743
809
  */
744
- setApiKey(apiKey) {
745
- if (apiKey?.startsWith("public_")) {
746
- throw new Error('API key cannot start with "public_"');
747
- }
748
- if (apiKey) {
749
- this._apiKey = apiKey;
750
- }
810
+ set context(value) {
811
+ this._context = value;
751
812
  }
752
813
  /**
753
- * Get the URI for a specific organization and code. This is used internally to construct the URI for the link service.
754
- * @param {string} organizationId The ID of the organization.
755
- * @param {string} code The code to include in the URI.
756
- * @returns {string} The constructed URI.
814
+ * Get the URIs. This is used to override the default URIs for testing or if you are using a self-hosted version.
815
+ * @returns {Array<string>}
757
816
  */
758
- getUri(organizationId, prefix1, prefix2, prefix3) {
759
- if (!organizationId) {
760
- throw new Error("Organization ID is required to get the URI.");
761
- }
762
- let url = this._uris[0].replace("{organizationId}", organizationId);
763
- if (prefix1) {
764
- url = url.endsWith("/") ? `${url}${prefix1}/` : `${url}/${prefix1}`;
765
- }
766
- if (prefix2) {
767
- url = url.endsWith("/") ? `${url}${prefix2}/` : `${url}/${prefix2}`;
768
- }
769
- if (prefix3) {
770
- url = url.endsWith("/") ? `${url}${prefix3}/` : `${url}/${prefix3}`;
771
- }
772
- if (url.endsWith("/")) {
773
- url = url.slice(0, -1);
774
- }
775
- return url;
817
+ get uris() {
818
+ return this._uris;
776
819
  }
777
820
  /**
778
- * Create a short code for a long URL.
779
- * @param {string} longUrl The long URL to shorten.
780
- * @param {string} domain The domain to use for the short code.
781
- * @param {CreateShortCodeOptions} options Optional parameters for creating the short code.
782
- * @returns {Promise<CreateShortCodeResponse>} A promise that resolves to the created short code details.
821
+ * Set the URIs. This is used to override the default URIs for testing or if you are using a self-hosted version.
822
+ * @param {Array<string>} value
783
823
  */
784
- async createShortCode(longUrl, domain, options) {
785
- if (!this._organizationId) {
786
- throw new Error("Organization ID is required to create a short code.");
787
- }
788
- const url = this.getUri(this._organizationId);
789
- const body = {
790
- // eslint-disable-next-line @typescript-eslint/naming-convention
791
- long_url: longUrl,
792
- domain,
793
- code: options?.code,
794
- title: options?.title,
795
- tags: options?.tags
796
- };
797
- const headers = this.createHeaders(this._apiKey);
798
- const response = await this.post(url, body, {
799
- headers
800
- });
801
- if (response.status === 201) {
802
- return response.data;
803
- }
804
- throw new Error(`Failed to create short code: ${response.statusText}`);
824
+ set uris(value) {
825
+ this._uris = value;
805
826
  }
806
827
  /**
807
- * Get a short code by its code.
808
- * @param {string} code The short code to retrieve. Example: 'code_686bed403c3991bd676bba4d'
809
- * @returns {Promise<GetShortCodeResponse>} A promise that resolves to the short code details.
828
+ * Get the caching options.
829
+ * @returns {ToggleCachingOptions | undefined}
810
830
  */
811
- async getShortCode(code) {
812
- if (!this._organizationId) {
813
- throw new Error("Organization ID is required to get a short code.");
814
- }
815
- const url = this.getUri(this._organizationId, code);
816
- const headers = this.createHeaders(this._apiKey);
817
- const response = await this.get(url, {
818
- headers
819
- });
820
- if (response.status === 200) {
821
- return response.data;
822
- }
823
- throw new Error(`Failed to get short code: ${response.statusText}`);
831
+ get caching() {
832
+ return this._caching;
824
833
  }
825
834
  /**
826
- * Get all short codes for the organization.
827
- * @param {string} titleSearch Optional search term to filter short codes by title.
828
- * @param {string[]} tags Optional tags to filter short codes.
829
- * @param {number} pageNumber The page number to retrieve. Default is 1.
830
- * @param {number} pageSize The number of short codes per page. Default is 100.
831
- * @returns {Promise<GetShortCodesResponse>} A promise that resolves to the list of short codes.
835
+ * Set the caching options.
836
+ * @param {ToggleCachingOptions | undefined} value
832
837
  */
833
- async getShortCodes(titleSearch, tags, pageNumber = 1, pageSize = 100) {
834
- if (!this._organizationId) {
835
- throw new Error("Organization ID is required to get short codes.");
836
- }
837
- const url = this.getUri(this._organizationId);
838
- const headers = this.createHeaders(this._apiKey);
839
- const parameters = {};
840
- if (titleSearch) {
841
- parameters.title = titleSearch;
842
- }
843
- if (tags && tags.length > 0) {
844
- parameters.tags = tags.join(",");
845
- }
846
- parameters.pageNum = pageNumber.toString();
847
- parameters.pageSize = pageSize.toString();
848
- const response = await this.get(url, {
849
- headers,
850
- params: parameters
851
- });
852
- if (response.status === 200) {
853
- return response.data;
854
- }
855
- throw new Error(`Failed to get short codes: ${response.statusText}`);
838
+ set caching(value) {
839
+ this._caching = value;
856
840
  }
857
841
  /**
858
- * Get all tags associated with the organization's short codes.
859
- * @returns {Promise<string[]>} A promise that resolves to an array of tags.
842
+ * This is a helper function to set the public API key. It will check if the key starts with public_ and set it. If it
843
+ * does set it will also set the client to undefined to force a new one to be created. If it does not,
844
+ * it will emit an error and console warning and not set the key. Used by the constructor and publicApiKey setter.
845
+ * @param key
846
+ * @returns
860
847
  */
861
- async getTags() {
862
- if (!this._organizationId) {
863
- throw new Error("Organization ID is required to get tags.");
864
- }
865
- const url = this.getUri(this._organizationId, "tags");
866
- const headers = this.createHeaders(this._apiKey);
867
- const response = await this.get(url, {
868
- headers
869
- });
870
- if (response.status === 200) {
871
- return response.data;
848
+ setPublicApiKey(key) {
849
+ if (!key.startsWith("public_")) {
850
+ this.emit("error", new Error("Public API key should start with public_"));
851
+ if (import_node_process4.default.env.NODE_ENV !== "production") {
852
+ console.error("Public API key should start with public_");
853
+ }
854
+ return;
872
855
  }
873
- throw new Error(`Failed to get tags: ${response.statusText}`);
856
+ this._publicApiKey = key;
857
+ this._client = void 0;
874
858
  }
875
859
  /**
876
- * Get statistics for a specific short code.
877
- * @param code The short code to retrieve statistics for.
878
- * @returns {Promise<GetCodeStatsResponse>} A promise that resolves to the code statistics.
860
+ * Set the context. This is the default context used. You can override this at the get function level.
861
+ * @param {ToggleContext} context
879
862
  */
880
- async getCodeStats(code, startDate, endDate) {
881
- if (!this._organizationId) {
882
- throw new Error("Organization ID is required to get code stats.");
883
- }
884
- const url = this.getUri(this._organizationId, code, "stats");
885
- const headers = this.createHeaders(this._apiKey);
886
- const parameters = {
887
- startDate: startDate.toISOString(),
888
- endDate: endDate.toISOString()
889
- };
890
- const response = await this.get(url, {
891
- headers,
892
- params: parameters
893
- });
894
- if (response.status === 200) {
895
- return response.data;
896
- }
897
- throw new Error(`Failed to get code stats: ${response.statusText}`);
863
+ setContext(context) {
864
+ this._context = context;
865
+ this._client = void 0;
898
866
  }
899
867
  /**
900
- * Update a short code.
901
- * @param {string} code The short code to update. Example: 'code_686bed403c3991bd676bba4d'
902
- * @param {UpdateShortCodeOptions} options The options to update the short code with.
903
- * @returns {Promise<UpdateShortCodeResponse>} A promise that resolves to the updated short code details.
868
+ * Helper function to get the client. This will create a new client if one does not exist. It will also set the
869
+ * application ID, environment, and URIs if they are not set. This is used by the get function to get the client.
870
+ * This is normally only used internally.
871
+ * @returns {Promise<Client>}
904
872
  */
905
- async updateShortCode(code, options) {
906
- if (!this._organizationId) {
907
- throw new Error("Organization ID is required to update a short code.");
908
- }
909
- const url = this.getUri(this._organizationId, code);
910
- const headers = this.createHeaders(this._apiKey);
911
- const response = await this.patch(url, options, {
912
- headers
913
- });
914
- if (response.status === 200) {
915
- return response.data;
873
+ async getClient() {
874
+ if (!this._client) {
875
+ if (this._applicationId === void 0 || this._applicationId.length === 0) {
876
+ const errorMessage = "Application ID is not set. You must set it before using the client or have the HYPHEN_APPLICATION_ID environment variable set.";
877
+ this.emit("error", new Error(errorMessage));
878
+ if (this._throwErrors) {
879
+ throw new Error(errorMessage);
880
+ }
881
+ }
882
+ const options = {
883
+ application: this._applicationId,
884
+ environment: this._environment,
885
+ horizonUrls: this._uris,
886
+ cache: this._caching
887
+ };
888
+ if (this._publicApiKey && this._publicApiKey.length > 0) {
889
+ await import_server_sdk.OpenFeature.setProviderAndWait(new import_openfeature_server_provider.HyphenProvider(this._publicApiKey, options));
890
+ } else {
891
+ this.emit("error", new Error("Public API key is not set. You must set it before using the client or have the HYPHEN_PUBLIC_API_KEY environment variable set."));
892
+ if (this._throwErrors) {
893
+ throw new Error("Public API key is not set");
894
+ }
895
+ }
896
+ this._client = import_server_sdk.OpenFeature.getClient(this._context);
916
897
  }
917
- throw new Error(`Failed to update short code: ${response.statusText}`);
898
+ return this._client;
918
899
  }
919
900
  /**
920
- * Delete a short code.
921
- * @param {string} code The short code to delete. Example: 'code_686bed403c3991bd676bba4d'
922
- * @returns {Promise<boolean>} A promise that resolves to true if the short code was deleted successfully, or false if it was not.
901
+ * This is the main function to get a feature flag value. It will check the type of the default value and call the
902
+ * appropriate function. It will also set the context if it is not set.
903
+ * @param {string} key - The key of the feature flag
904
+ * @param {T} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
905
+ * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
906
+ * @returns {Promise<T>}
923
907
  */
924
- async deleteShortCode(code) {
925
- if (!this._organizationId) {
926
- throw new Error("Organization ID is required to delete a short code.");
927
- }
928
- const url = this.getUri(this._organizationId, code);
929
- const headers = this.createHeaders(this._apiKey);
930
- const response = await this.delete(url, {
931
- headers
932
- });
933
- if (response.status === 204) {
934
- return true;
908
+ async get(key, defaultValue, options) {
909
+ switch (typeof defaultValue) {
910
+ case "boolean": {
911
+ return this.getBoolean(key, defaultValue, options);
912
+ }
913
+ case "string": {
914
+ return this.getString(key, defaultValue, options);
915
+ }
916
+ case "number": {
917
+ return this.getNumber(key, defaultValue, options);
918
+ }
919
+ default: {
920
+ return this.getObject(key, defaultValue, options);
921
+ }
935
922
  }
936
- throw new Error(`Failed to delete short code: ${response.statusText}`);
937
923
  }
938
924
  /**
939
- * Create a QR code for a specific short code.
940
- * @param {string} code The short code to create a QR code for.
941
- * @param {CreateQrCodeOptions} options The options for creating the QR code.
942
- * @returns {Promise<CreateQrCodeResponse>} A promise that resolves to the created QR code details.
925
+ * Get a boolean value from the feature flag. This will check the type of the default value and call the
926
+ * appropriate function. It will also set the context if it is not set.
927
+ * @param {string} key - The key of the feature flag
928
+ * @param {boolean} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
929
+ * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
930
+ * @returns {Promise<boolean>} - The value of the feature flag
943
931
  */
944
- async createQrCode(code, options) {
945
- if (!this._organizationId) {
946
- throw new Error("Organization ID is required to create a QR code.");
947
- }
948
- const url = this.getUri(this._organizationId, code, "qrs");
949
- const headers = this.createHeaders(this._apiKey);
950
- const body = {
951
- title: options?.title,
952
- backgroundColor: options?.backgroundColor,
953
- color: options?.color,
954
- size: options?.size,
955
- logo: options?.logo
956
- };
957
- const response = await this.post(url, body, {
958
- headers
959
- });
960
- if (response.status === 201) {
961
- const result = response.data;
962
- if (result.qrCode) {
963
- const buffer = import_node_buffer.Buffer.from(result.qrCode, "base64");
964
- result.qrCodeBytes = new Uint16Array(buffer);
932
+ async getBoolean(key, defaultValue, options) {
933
+ try {
934
+ const data = {
935
+ key,
936
+ defaultValue,
937
+ options
938
+ };
939
+ await this.hook("beforeGetBoolean", data);
940
+ const client = await this.getClient();
941
+ const result = await client.getBooleanValue(data.key, data.defaultValue, data.options?.context);
942
+ const resultData = {
943
+ key,
944
+ defaultValue,
945
+ options,
946
+ result
947
+ };
948
+ await this.hook("afterGetBoolean", resultData);
949
+ return resultData.result;
950
+ } catch (error) {
951
+ this.emit("error", error);
952
+ if (this._throwErrors) {
953
+ throw error;
965
954
  }
966
- return result;
967
955
  }
968
- throw new Error(`Failed to create QR code: ${response.statusText}`);
956
+ return defaultValue;
969
957
  }
970
958
  /**
971
- * Get a QR code by its ID.
972
- * @param code The short code associated with the QR code.
973
- * @param qr The ID of the QR code to retrieve.
974
- * @returns The details of the requested QR code.
959
+ * Get a string value from the feature flag.
960
+ * @param {string} key - The key of the feature flag
961
+ * @param {string} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
962
+ * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
963
+ * @returns {Promise<string>} - The value of the feature flag
975
964
  */
976
- async getQrCode(code, qr) {
977
- if (!this._organizationId) {
978
- throw new Error("Organization ID is required to get a QR code.");
979
- }
980
- const url = this.getUri(this._organizationId, code, "qrs", qr);
981
- const headers = this.createHeaders(this._apiKey);
982
- const response = await this.get(url, {
983
- headers
984
- });
985
- if (response.status === 200) {
986
- const result = response.data;
987
- if (result.qrCode) {
988
- const buffer = import_node_buffer.Buffer.from(result.qrCode, "base64");
989
- result.qrCodeBytes = new Uint16Array(buffer);
965
+ async getString(key, defaultValue, options) {
966
+ try {
967
+ const data = {
968
+ key,
969
+ defaultValue,
970
+ options
971
+ };
972
+ await this.hook("beforeGetString", data);
973
+ const client = await this.getClient();
974
+ const result = await client.getStringValue(data.key, data.defaultValue, data.options?.context);
975
+ const resultData = {
976
+ key,
977
+ defaultValue,
978
+ options,
979
+ result
980
+ };
981
+ await this.hook("afterGetString", resultData);
982
+ return resultData.result;
983
+ } catch (error) {
984
+ this.emit("error", error);
985
+ if (this._throwErrors) {
986
+ throw error;
990
987
  }
991
- return result;
992
988
  }
993
- throw new Error(`Failed to get QR code: ${response.statusText}`);
989
+ return defaultValue;
994
990
  }
995
- async getQrCodes(code, pageNumber, pageSize) {
996
- if (!this._organizationId) {
997
- throw new Error("Organization ID is required to get QR codes.");
998
- }
999
- const url = this.getUri(this._organizationId, code, "qrs");
1000
- const headers = this.createHeaders(this._apiKey);
1001
- const parameters = {};
1002
- if (pageNumber) {
1003
- parameters.pageNum = pageNumber.toString();
1004
- }
1005
- if (pageSize) {
1006
- parameters.pageSize = pageSize.toString();
1007
- }
1008
- const response = await this.get(url, {
1009
- headers,
1010
- params: parameters
1011
- });
1012
- if (response.status === 200) {
1013
- const result = response.data;
1014
- for (const qrCode of result.data) {
1015
- if (qrCode.qrCode) {
1016
- const buffer = import_node_buffer.Buffer.from(qrCode.qrCode, "base64");
1017
- qrCode.qrCodeBytes = new Uint16Array(buffer);
1018
- }
991
+ async getNumber(key, defaultValue, options) {
992
+ try {
993
+ const data = {
994
+ key,
995
+ defaultValue,
996
+ options
997
+ };
998
+ await this.hook("beforeGetNumber", data);
999
+ const client = await this.getClient();
1000
+ const result = await client.getNumberValue(data.key, data.defaultValue, data.options?.context);
1001
+ const resultData = {
1002
+ key,
1003
+ defaultValue,
1004
+ options,
1005
+ result
1006
+ };
1007
+ await this.hook("afterGetNumber", resultData);
1008
+ return resultData.result;
1009
+ } catch (error) {
1010
+ this.emit("error", error);
1011
+ if (this._throwErrors) {
1012
+ throw error;
1019
1013
  }
1020
- return result;
1021
1014
  }
1022
- throw new Error(`Failed to get QR codes: ${response.statusText}`);
1015
+ return defaultValue;
1023
1016
  }
1024
1017
  /**
1025
- * Delete a QR code by its ID.
1026
- * @param {string} code The short code associated with the QR code.
1027
- * @param {string} qr The ID of the QR code to delete.
1028
- * @returns {Promise<boolean>} A promise that resolves to true if the QR code was deleted successfully, or false if it was not.
1018
+ * Get an object value from the feature flag. This will check the type of the default value and call the
1019
+ * appropriate function. It will also set the context if it is not set.
1020
+ * @param {string} key - The key of the feature flag
1021
+ * @param {T} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
1022
+ * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
1023
+ * @returns {Promise<T>} - The value of the feature flag
1029
1024
  */
1030
- async deleteQrCode(code, qr) {
1031
- if (!this._organizationId) {
1032
- throw new Error("Organization ID is required to delete a QR code.");
1033
- }
1034
- const url = this.getUri(this._organizationId, code, "qrs", qr);
1035
- const headers = this.createHeaders(this._apiKey);
1036
- const response = await this.delete(url, {
1037
- headers
1038
- });
1039
- if (response.status === 204) {
1040
- return true;
1025
+ async getObject(key, defaultValue, options) {
1026
+ try {
1027
+ const data = {
1028
+ key,
1029
+ defaultValue,
1030
+ options
1031
+ };
1032
+ await this.hook("beforeGetObject", data);
1033
+ const client = await this.getClient();
1034
+ const result = await client.getObjectValue(key, defaultValue, data.options?.context);
1035
+ const resultData = {
1036
+ key,
1037
+ defaultValue,
1038
+ options,
1039
+ result
1040
+ };
1041
+ await this.hook("afterGetObject", resultData);
1042
+ return resultData.result;
1043
+ } catch (error) {
1044
+ this.emit("error", error);
1045
+ if (this._throwErrors) {
1046
+ throw error;
1047
+ }
1041
1048
  }
1042
- throw new Error(`Failed to delete QR code: ${response.statusText}`);
1049
+ return defaultValue;
1043
1050
  }
1044
1051
  };
1045
1052