@croct/plug 0.10.1 → 0.11.0-alpha

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/constants.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  export declare const CDN_URL = "https://cdn.croct.io/js/v1/lib/plug.js";
2
2
  export declare const PLAYGROUND_ORIGIN = "https://play.croct.com";
3
3
  export declare const PLAYGROUND_CONNECT_URL = "https://play.croct.com/connect.html";
4
+ export declare const PREVIEW_WIDGET_ORIGIN = "https://cdn.croct.io";
5
+ export declare const PREVIEW_WIDGET_URL = "https://cdn.croct.io/js/v1/lib/plug/widget-0.11.0-alpha.html";
package/constants.js CHANGED
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PLAYGROUND_CONNECT_URL = exports.PLAYGROUND_ORIGIN = exports.CDN_URL = void 0;
3
+ exports.PREVIEW_WIDGET_URL = exports.PREVIEW_WIDGET_ORIGIN = exports.PLAYGROUND_CONNECT_URL = exports.PLAYGROUND_ORIGIN = exports.CDN_URL = void 0;
4
4
  exports.CDN_URL = 'https://cdn.croct.io/js/v1/lib/plug.js';
5
5
  exports.PLAYGROUND_ORIGIN = 'https://play.croct.com';
6
6
  exports.PLAYGROUND_CONNECT_URL = 'https://play.croct.com/connect.html';
7
+ exports.PREVIEW_WIDGET_ORIGIN = 'https://cdn.croct.io';
8
+ exports.PREVIEW_WIDGET_URL = 'https://cdn.croct.io/js/v1/lib/plug/widget-0.11.0-alpha.html';
package/eap.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { SlotId, FetchResponse } from './fetch';
2
- import { NullableJsonObject } from './sdk/json';
3
- import { Plug } from './plug';
1
+ import { VersionedSlotId } from './slot';
2
+ import { JsonObject } from './sdk/json';
3
+ import { LegacyFetchResponse, Plug } from './plug';
4
4
  export interface EapFeatures {
5
- fetch<P extends NullableJsonObject, I extends SlotId = SlotId>(this: Plug, slotId: I): Promise<FetchResponse<I, P>>;
5
+ fetch<P extends JsonObject, I extends VersionedSlotId>(this: Plug, slotId: I): Promise<LegacyFetchResponse<I, P>>;
6
6
  }
7
7
  interface EapHooks extends EapFeatures {
8
8
  initialize(this: Plug): void;
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var plug_1 = require("./plug");
4
- /* eslint-disable-next-line import/no-default-export */
3
+ const plug_1 = require("./plug");
4
+ /* eslint-disable-next-line import/no-default-export -- Should be default export */
5
5
  exports.default = new plug_1.GlobalPlug();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@croct/plug",
3
- "version": "0.10.1",
3
+ "version": "0.11.0-alpha",
4
4
  "description": "A fully-featured devkit for building natively personalized applications.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -29,35 +29,29 @@
29
29
  "lint": "eslint 'src/**/*.ts' 'test/**/*.ts'",
30
30
  "test": "jest -c jest.config.js --coverage",
31
31
  "validate": "tsc --noEmit",
32
- "build": "tsc",
32
+ "build": "tsc -p tsconfig.build.json",
33
33
  "bundle": "rollup -c"
34
34
  },
35
35
  "dependencies": {
36
36
  "@croct/json": "^1.1.0",
37
- "@croct/sdk": "^0.9.1",
37
+ "@croct/sdk": "^0.11.0-alpha",
38
38
  "tslib": "^2.2.0"
39
39
  },
40
40
  "devDependencies": {
41
- "@babel/core": "^7.14.3",
42
- "@babel/preset-env": "^7.14.2",
43
- "@babel/preset-typescript": "^7.13.0",
44
- "@rollup/plugin-commonjs": "^19.0.0",
45
- "@rollup/plugin-node-resolve": "^13.0.0",
46
- "@rollup/plugin-replace": "^2.4.2",
47
- "@rollup/plugin-typescript": "^8.2.1",
48
- "@types/jest": "^26.0.23",
49
- "@typescript-eslint/eslint-plugin": "^4.24.0",
50
- "@typescript-eslint/parser": "^4.24.0",
51
- "babel-jest": "^26.6.3",
52
- "eslint": "^7.27.0",
53
- "eslint-config-airbnb-base": "^14.2.1",
54
- "eslint-plugin-import": "^2.23.3",
55
- "eslint-plugin-jest": "^24.3.6",
56
- "jest": "^26.6.3",
57
- "rollup": "^2.48.0",
58
- "rollup-plugin-terser": "^7.0.2",
59
- "ts-jest": "^26.5.6",
60
- "typescript": "^4.2.4"
41
+ "@croct/eslint-plugin": "^0.6.3",
42
+ "@rollup/plugin-commonjs": "^23.0.2",
43
+ "@rollup/plugin-node-resolve": "^15.0.1",
44
+ "@rollup/plugin-replace": "^5.0.1",
45
+ "@rollup/plugin-terser": "^0.1.0",
46
+ "@rollup/plugin-typescript": "^9.0.2",
47
+ "@types/jest": "^29.2.2",
48
+ "@typescript-eslint/parser": "^5.30.0",
49
+ "eslint": "^8.27.0",
50
+ "jest": "^29.3.1",
51
+ "jest-environment-jsdom": "^29.3.1",
52
+ "rollup": "^3.3.0",
53
+ "ts-jest": "^29.0.3",
54
+ "typescript": "^4.9.3"
61
55
  },
62
56
  "browserslist": [
63
57
  "last 1 version"
package/playground.d.ts CHANGED
@@ -4,11 +4,7 @@ import { Campaign, Page } from '@croct/sdk/evaluator';
4
4
  import { Plugin, PluginFactory } from './plugin';
5
5
  import { Logger, SdkEventSubscriber, Tab } from './sdk';
6
6
  import { TokenProvider } from './sdk/token';
7
- export declare type Options = {
8
- connectionId?: string;
9
- };
10
- export declare const factory: PluginFactory<Options>;
11
- export declare type Configuration = {
7
+ export type Configuration = {
12
8
  appId: string;
13
9
  connectionId?: string;
14
10
  sdkVersion: string;
@@ -20,7 +16,7 @@ export declare type Configuration = {
20
16
  tokenProvider: TokenProvider;
21
17
  logger: Logger;
22
18
  };
23
- export declare type SyncPayload = {
19
+ export type SyncPayload = {
24
20
  appId: string;
25
21
  connectionId: string;
26
22
  sdkVersion: string;
@@ -52,3 +48,7 @@ export declare class PlaygroundPlugin implements Plugin {
52
48
  private syncToken;
53
49
  private createContext;
54
50
  }
51
+ export type Options = {
52
+ connectionId?: string;
53
+ };
54
+ export declare const factory: PluginFactory<Options>;
package/playground.js CHANGED
@@ -1,28 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PlaygroundPlugin = exports.factory = void 0;
4
- var error_1 = require("@croct/sdk/error");
5
- var evaluatorFacade_1 = require("@croct/sdk/facade/evaluatorFacade");
6
- var constants_1 = require("./constants");
7
- var factory = function (_a) {
8
- var sdk = _a.sdk, options = _a.options;
9
- return new PlaygroundPlugin({
10
- sdkVersion: sdk.version,
11
- appId: sdk.appId,
12
- connectionId: options.connectionId,
13
- tab: sdk.tab,
14
- storage: sdk.getTabStorage(),
15
- tokenProvider: sdk.tokenStore,
16
- cidAssigner: sdk.cidAssigner,
17
- contextFactory: new evaluatorFacade_1.TabContextFactory(sdk.tab),
18
- eventSubscriber: sdk.eventManager,
19
- logger: sdk.getLogger(),
20
- });
21
- };
22
- exports.factory = factory;
23
- var CONNECTION_PARAMETER = '__cplay';
24
- var PlaygroundPlugin = /** @class */ (function () {
25
- function PlaygroundPlugin(configuration) {
3
+ exports.factory = exports.PlaygroundPlugin = void 0;
4
+ const error_1 = require("@croct/sdk/error");
5
+ const evaluatorFacade_1 = require("@croct/sdk/facade/evaluatorFacade");
6
+ const constants_1 = require("./constants");
7
+ const CONNECTION_PARAMETER = '__cplay';
8
+ class PlaygroundPlugin {
9
+ constructor(configuration) {
26
10
  this.sdkVersion = configuration.sdkVersion;
27
11
  this.appId = configuration.appId;
28
12
  this.connectionId = configuration.connectionId;
@@ -34,32 +18,30 @@ var PlaygroundPlugin = /** @class */ (function () {
34
18
  this.tokenProvider = configuration.tokenProvider;
35
19
  this.logger = configuration.logger;
36
20
  }
37
- PlaygroundPlugin.prototype.enable = function () {
38
- var _this = this;
39
- var connectionId = this.resolveConnectionId();
21
+ enable() {
22
+ const connectionId = this.resolveConnectionId();
40
23
  if (connectionId === null) {
41
24
  return;
42
25
  }
43
- this.syncListener = function () {
44
- return _this.cidAssigner.assignCid()
45
- .then(function (cid) {
46
- _this.syncToken(connectionId, cid);
47
- })
48
- .catch(function (error) {
49
- _this.logger.warn("Sync failed: " + error_1.formatCause(error));
50
- });
51
- };
26
+ this.syncListener = () => this.cidAssigner
27
+ .assignCid()
28
+ .then(cid => {
29
+ this.syncToken(connectionId, cid);
30
+ })
31
+ .catch(error => {
32
+ this.logger.warn(`Sync failed: ${(0, error_1.formatCause)(error)}`);
33
+ });
52
34
  this.eventSubscriber.addListener('tokenChanged', this.syncListener);
53
35
  this.tab.addListener('urlChange', this.syncListener);
54
36
  return this.syncListener();
55
- };
56
- PlaygroundPlugin.prototype.resolveConnectionId = function () {
37
+ }
38
+ resolveConnectionId() {
57
39
  if (this.connectionId !== undefined) {
58
40
  this.logger.debug('Connection ID passed in configuration');
59
41
  return this.connectionId;
60
42
  }
61
- var url = new URL(this.tab.url);
62
- var connectionId = url.searchParams.get(CONNECTION_PARAMETER);
43
+ const url = new URL(this.tab.url);
44
+ let connectionId = url.searchParams.get(CONNECTION_PARAMETER);
63
45
  if (connectionId === null || connectionId === '') {
64
46
  this.logger.debug('No connection ID found in URL');
65
47
  connectionId = this.storage.getItem('connectionId');
@@ -71,17 +53,16 @@ var PlaygroundPlugin = /** @class */ (function () {
71
53
  this.logger.debug('Connection ID found in URL');
72
54
  this.storage.setItem('connectionId', connectionId);
73
55
  return connectionId;
74
- };
75
- PlaygroundPlugin.prototype.disable = function () {
56
+ }
57
+ disable() {
76
58
  if (this.syncListener !== undefined) {
77
59
  this.eventSubscriber.removeListener('tokenChanged', this.syncListener);
78
60
  this.tab.removeListener('urlChange', this.syncListener);
79
61
  delete this.syncListener;
80
62
  }
81
- };
82
- PlaygroundPlugin.prototype.syncToken = function (connectionId, cid) {
83
- var _this = this;
84
- var iframe = document.createElement('iframe');
63
+ }
64
+ syncToken(connectionId, cid) {
65
+ const iframe = document.createElement('iframe');
85
66
  iframe.setAttribute('src', constants_1.PLAYGROUND_CONNECT_URL);
86
67
  iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin');
87
68
  iframe.style.visibility = 'hidden';
@@ -89,17 +70,17 @@ var PlaygroundPlugin = /** @class */ (function () {
89
70
  iframe.style.border = '0';
90
71
  iframe.style.width = '0';
91
72
  iframe.style.height = '0';
92
- var context = this.createContext();
93
- iframe.onload = function () {
73
+ const context = this.createContext();
74
+ iframe.onload = () => {
94
75
  var _a, _b;
95
76
  if (iframe.contentWindow === null) {
96
77
  if (document.body.contains(iframe)) {
97
78
  document.body.removeChild(iframe);
98
79
  }
99
- _this.logger.warn('Sync handshake failed');
80
+ this.logger.warn('Sync handshake failed');
100
81
  return;
101
82
  }
102
- var listener = function (event) {
83
+ const listener = (event) => {
103
84
  if (event.origin !== constants_1.PLAYGROUND_ORIGIN || event.data !== connectionId) {
104
85
  return;
105
86
  }
@@ -107,23 +88,24 @@ var PlaygroundPlugin = /** @class */ (function () {
107
88
  if (document.body.contains(iframe)) {
108
89
  document.body.removeChild(iframe);
109
90
  }
110
- _this.logger.debug('Sync completed');
91
+ this.logger.debug('Sync completed');
111
92
  };
112
93
  window.addEventListener('message', listener);
113
- var payload = {
114
- appId: _this.appId,
94
+ const payload = {
95
+ appId: this.appId,
115
96
  connectionId: connectionId,
116
- sdkVersion: _this.sdkVersion,
117
- tabId: _this.tab.id,
97
+ sdkVersion: this.sdkVersion,
98
+ tabId: this.tab.id,
118
99
  cid: cid,
119
- token: (_b = (_a = _this.tokenProvider.getToken()) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null,
100
+ token: (_b = (_a = this.tokenProvider
101
+ .getToken()) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null,
120
102
  context: context,
121
103
  };
122
104
  iframe.contentWindow.postMessage(payload, constants_1.PLAYGROUND_ORIGIN);
123
- _this.logger.debug('Waiting for sync acknowledgment...');
105
+ this.logger.debug('Waiting for sync acknowledgment...');
124
106
  };
125
107
  this.logger.debug('Sync started');
126
- var connect = function () {
108
+ const connect = () => {
127
109
  document.body.appendChild(iframe);
128
110
  };
129
111
  if (document.body === null) {
@@ -132,21 +114,36 @@ var PlaygroundPlugin = /** @class */ (function () {
132
114
  else {
133
115
  connect();
134
116
  }
135
- };
136
- PlaygroundPlugin.prototype.createContext = function () {
137
- var _a = this.contextFactory.createContext(), page = _a.page, campaign = _a.campaign, timezone = _a.timezone;
138
- var context = {};
117
+ }
118
+ createContext() {
119
+ const { page, campaign, timeZone } = this.contextFactory.createContext();
120
+ const context = {};
139
121
  if (page !== undefined) {
140
122
  context.page = page;
141
123
  }
142
124
  if (campaign !== undefined) {
143
125
  context.campaign = campaign;
144
126
  }
145
- if (timezone !== undefined) {
146
- context.timezone = timezone;
127
+ if (timeZone !== undefined) {
128
+ context.timeZone = timeZone;
147
129
  }
148
130
  return context;
149
- };
150
- return PlaygroundPlugin;
151
- }());
131
+ }
132
+ }
152
133
  exports.PlaygroundPlugin = PlaygroundPlugin;
134
+ const factory = (props) => {
135
+ const { sdk, options } = props;
136
+ return new PlaygroundPlugin({
137
+ sdkVersion: sdk.version,
138
+ appId: sdk.appId,
139
+ connectionId: options.connectionId,
140
+ tab: sdk.tab,
141
+ storage: sdk.getTabStorage(),
142
+ tokenProvider: sdk.userTokenStore,
143
+ cidAssigner: sdk.cidAssigner,
144
+ contextFactory: new evaluatorFacade_1.TabContextFactory(sdk.tab),
145
+ eventSubscriber: sdk.eventManager,
146
+ logger: sdk.getLogger(),
147
+ });
148
+ };
149
+ exports.factory = factory;
package/plug.d.ts CHANGED
@@ -1,20 +1,34 @@
1
1
  import { SessionFacade } from '@croct/sdk/facade/sessionFacade';
2
2
  import { UserFacade } from '@croct/sdk/facade/userFacade';
3
3
  import { TrackerFacade } from '@croct/sdk/facade/trackerFacade';
4
- import { EvaluatorFacade, EvaluationOptions } from '@croct/sdk/facade/evaluatorFacade';
4
+ import { EvaluationOptions, EvaluatorFacade } from '@croct/sdk/facade/evaluatorFacade';
5
5
  import { Configuration as SdkFacadeConfiguration } from '@croct/sdk/facade/sdkFacade';
6
6
  import { Optional } from '@croct/sdk/utilityTypes';
7
7
  import { ExternalTrackingEvent as ExternalEvent, ExternalTrackingEventPayload as ExternalEventPayload, ExternalTrackingEventType as ExternalEventType } from '@croct/sdk/trackingEvents';
8
+ import { FetchOptions as BaseFetchOptions } from '@croct/sdk/facade/contentFetcherFacade';
8
9
  import { PluginFactory } from './plugin';
9
10
  import { EapFeatures } from './eap';
10
- import { SlotId, FetchResponse, FetchOptions } from './fetch';
11
- import { NullableJsonObject, JsonValue } from './sdk/json';
11
+ import { VersionedSlotId, SlotContent } from './slot';
12
+ import { JsonValue, JsonObject } from './sdk/json';
12
13
  export interface PluginConfigurations {
13
14
  [key: string]: any;
14
15
  }
15
- export declare type Configuration = Optional<SdkFacadeConfiguration, 'appId'> & {
16
+ export type Configuration = Optional<SdkFacadeConfiguration, 'appId'> & {
16
17
  plugins?: PluginConfigurations;
17
18
  };
19
+ export type FetchOptions = Omit<BaseFetchOptions, 'version'>;
20
+ export type FetchResponse<I extends VersionedSlotId, C extends JsonObject = JsonObject> = {
21
+ content: SlotContent<I, C>;
22
+ };
23
+ /**
24
+ * @internal
25
+ */
26
+ export type LegacyFetchResponse<I extends VersionedSlotId, C extends JsonObject = JsonObject> = FetchResponse<I, C> & {
27
+ /**
28
+ * @deprecated Use `content` instead.
29
+ */
30
+ payload: SlotContent<I, C>;
31
+ };
18
32
  export interface Plug extends EapFeatures {
19
33
  readonly tracker: TrackerFacade;
20
34
  readonly user: UserFacade;
@@ -31,6 +45,7 @@ export interface Plug extends EapFeatures {
31
45
  unsetToken(): void;
32
46
  track<T extends ExternalEventType>(type: T, payload: ExternalEventPayload<T>): Promise<ExternalEvent<T>>;
33
47
  evaluate<T extends JsonValue>(expression: string, options?: EvaluationOptions): Promise<T>;
48
+ fetch<P extends JsonObject, I extends VersionedSlotId>(slotId: I, options?: FetchOptions): Promise<LegacyFetchResponse<I, P>>;
34
49
  unplug(): Promise<void>;
35
50
  }
36
51
  export declare class GlobalPlug implements Plug {
@@ -59,10 +74,7 @@ export declare class GlobalPlug implements Plug {
59
74
  track<T extends ExternalEventType>(type: T, payload: ExternalEventPayload<T>): Promise<ExternalEvent<T>>;
60
75
  evaluate<T extends JsonValue>(expression: string, options?: EvaluationOptions): Promise<T>;
61
76
  test(expression: string, options?: EvaluationOptions): Promise<boolean>;
62
- /**
63
- * This API is unstable and subject to change in future releases.
64
- */
65
- fetch<P extends NullableJsonObject, I extends SlotId = SlotId>(slotId: I, options?: FetchOptions): Promise<FetchResponse<I, P>>;
77
+ get fetch(): Plug['fetch'];
66
78
  unplug(): Promise<void>;
67
79
  private eap;
68
80
  }
package/plug.js CHANGED
@@ -1,87 +1,92 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GlobalPlug = void 0;
4
- var tslib_1 = require("tslib");
5
- var sdkFacade_1 = require("@croct/sdk/facade/sdkFacade");
6
- var error_1 = require("@croct/sdk/error");
7
- var validation_1 = require("@croct/sdk/validation");
8
- var token_1 = require("@croct/sdk/token");
9
- var sdk_1 = require("@croct/sdk");
10
- var constants_1 = require("./constants");
11
- var playground_1 = require("./playground");
12
- var PLUGIN_NAMESPACE = 'Plugin';
4
+ const sdkFacade_1 = require("@croct/sdk/facade/sdkFacade");
5
+ const error_1 = require("@croct/sdk/error");
6
+ const validation_1 = require("@croct/sdk/validation");
7
+ const token_1 = require("@croct/sdk/token");
8
+ const sdk_1 = require("@croct/sdk");
9
+ const constants_1 = require("./constants");
10
+ const playground_1 = require("./playground");
11
+ const preview_1 = require("./preview");
12
+ const PLUGIN_NAMESPACE = 'Plugin';
13
13
  function detectAppId() {
14
- var script = window.document.querySelector("script[src^='" + constants_1.CDN_URL + "']");
14
+ const script = window.document.querySelector(`script[src^='${constants_1.CDN_URL}']`);
15
15
  if (!(script instanceof HTMLScriptElement)) {
16
16
  return null;
17
17
  }
18
18
  return (new URL(script.src)).searchParams.get('appId');
19
19
  }
20
- var GlobalPlug = /** @class */ (function () {
21
- function GlobalPlug() {
22
- var _this = this;
23
- this.pluginFactories = { playground: playground_1.factory };
20
+ class GlobalPlug {
21
+ constructor() {
22
+ this.pluginFactories = {
23
+ playground: playground_1.factory,
24
+ preview: preview_1.factory,
25
+ };
24
26
  this.plugins = {};
25
- this.ready = new Promise(function (resolve) {
26
- _this.initialize = resolve;
27
+ this.ready = new Promise(resolve => {
28
+ this.initialize = resolve;
27
29
  });
28
30
  }
29
- GlobalPlug.prototype.extend = function (name, plugin) {
31
+ extend(name, plugin) {
30
32
  if (this.pluginFactories[name] !== undefined) {
31
- throw new Error("Another plugin is already registered with name \"" + name + "\".");
33
+ throw new Error(`Another plugin is already registered with name "${name}".`);
32
34
  }
33
35
  this.pluginFactories[name] = plugin;
34
- };
35
- GlobalPlug.prototype.plug = function (configuration) {
36
- var e_1, _a;
37
- var _this = this;
38
- var _b, _c, _d, _e;
39
- if (configuration === void 0) { configuration = {}; }
36
+ }
37
+ plug(configuration = {}) {
38
+ var _a, _b, _c, _d;
40
39
  if (this.instance !== undefined) {
41
- var logger_1 = this.instance.getLogger();
42
- logger_1.info('Croct is already plugged in.');
40
+ const logger = this.instance.getLogger();
41
+ logger.info('Croct is already plugged in.');
43
42
  return;
44
43
  }
45
- var detectedAppId = detectAppId();
46
- var configuredAppId = (_b = configuration.appId) !== null && _b !== void 0 ? _b : null;
44
+ const detectedAppId = detectAppId();
45
+ const configuredAppId = (_a = configuration.appId) !== null && _a !== void 0 ? _a : null;
47
46
  if (detectedAppId !== null && configuredAppId !== null && detectedAppId !== configuredAppId) {
48
47
  throw new Error('The specified app ID and the auto-detected app ID are conflicting. '
49
48
  + 'There is no need to specify an app ID when using an application-specific tag. '
50
49
  + 'Please try again omitting the "appId" option.');
51
50
  }
52
- var appId = detectedAppId !== null && detectedAppId !== void 0 ? detectedAppId : configuredAppId;
51
+ const appId = detectedAppId !== null && detectedAppId !== void 0 ? detectedAppId : configuredAppId;
53
52
  if (appId === null) {
54
53
  throw new Error('The app ID must be specified when it cannot be auto-detected. '
55
54
  + 'Please try again specifying the "appId" option.');
56
55
  }
57
- var plugins = configuration.plugins, test = configuration.test, sdkConfiguration = tslib_1.__rest(configuration, ["plugins", "test"]);
58
- var sdk = sdkFacade_1.SdkFacade.init(tslib_1.__assign(tslib_1.__assign({}, sdkConfiguration), { appId: appId, test: test !== null && test !== void 0 ? test : (typeof process === 'object' && (((_c = process.env) === null || _c === void 0 ? void 0 : _c.CROCT_TEST_MODE) !== undefined
56
+ const { plugins, test, ...sdkConfiguration } = configuration;
57
+ const sdk = sdkFacade_1.SdkFacade.init({
58
+ ...sdkConfiguration,
59
+ appId: appId,
60
+ test: test !== null && test !== void 0 ? test : (typeof process === 'object' && (((_b = process.env) === null || _b === void 0 ? void 0 : _b.CROCT_TEST_MODE) !== undefined
59
61
  ? process.env.CROCT_TEST_MODE === 'true'
60
- : ((_d = process.env) === null || _d === void 0 ? void 0 : _d.NODE_ENV) === 'test')) }));
62
+ : ((_c = process.env) === null || _c === void 0 ? void 0 : _c.NODE_ENV) === 'test')),
63
+ });
61
64
  this.instance = sdk;
62
- var logger = this.instance.getLogger();
65
+ const logger = this.instance.getLogger();
63
66
  if (detectedAppId === configuredAppId) {
64
67
  logger.warn('It is strongly recommended omitting the "appId" option when using '
65
68
  + 'the application-specific tag as it is detected automatically.');
66
69
  }
67
- var pending = [];
68
- var _loop_1 = function (name_1, options) {
69
- logger.debug("Initializing plugin \"" + name_1 + "\"...");
70
- var factory = this_1.pluginFactories[name_1];
70
+ const pending = [];
71
+ const defaultEnabledPlugins = Object.fromEntries(Object.keys(this.pluginFactories)
72
+ .map(name => [name, true]));
73
+ for (const [name, options] of Object.entries({ ...defaultEnabledPlugins, ...plugins })) {
74
+ logger.debug(`Initializing plugin "${name}"...`);
75
+ const factory = this.pluginFactories[name];
71
76
  if (factory === undefined) {
72
- logger.error("Plugin \"" + name_1 + "\" is not registered.");
73
- return "continue";
77
+ logger.error(`Plugin "${name}" is not registered.`);
78
+ continue;
74
79
  }
75
80
  if (typeof options !== 'boolean' && (options === null || typeof options !== 'object')) {
76
- logger.error("Invalid options for plugin \"" + name_1 + "\", "
77
- + ("expected either boolean or object but got " + validation_1.describe(options)));
78
- return "continue";
81
+ logger.error(`Invalid options for plugin "${name}", `
82
+ + `expected either boolean or object but got ${(0, validation_1.describe)(options)}`);
83
+ continue;
79
84
  }
80
85
  if (options === false) {
81
- logger.warn("Plugin \"" + name_1 + "\" is declared but not enabled");
82
- return "continue";
86
+ logger.warn(`Plugin "${name}" is declared but not enabled`);
87
+ continue;
83
88
  }
84
- var args = {
89
+ const args = {
85
90
  options: options === true ? {} : options,
86
91
  sdk: {
87
92
  version: sdk_1.VERSION,
@@ -91,258 +96,185 @@ var GlobalPlug = /** @class */ (function () {
91
96
  user: sdk.user,
92
97
  session: sdk.session,
93
98
  tab: sdk.context.getTab(),
94
- tokenStore: {
99
+ userTokenStore: {
95
100
  getToken: sdk.getToken.bind(sdk),
96
101
  setToken: sdk.setToken.bind(sdk),
97
102
  },
103
+ previewTokenStore: sdk.previewTokenStore,
98
104
  cidAssigner: sdk.cidAssigner,
99
105
  eventManager: sdk.eventManager,
100
- getLogger: function () {
101
- var namespace = [];
102
- for (var _i = 0; _i < arguments.length; _i++) {
103
- namespace[_i] = arguments[_i];
104
- }
105
- return sdk.getLogger.apply(sdk, tslib_1.__spreadArray([PLUGIN_NAMESPACE, name_1], tslib_1.__read(namespace)));
106
- },
107
- getTabStorage: function () {
108
- var namespace = [];
109
- for (var _i = 0; _i < arguments.length; _i++) {
110
- namespace[_i] = arguments[_i];
111
- }
112
- return sdk.getTabStorage.apply(sdk, tslib_1.__spreadArray([PLUGIN_NAMESPACE, name_1], tslib_1.__read(namespace)));
113
- },
114
- getBrowserStorage: function () {
115
- var namespace = [];
116
- for (var _i = 0; _i < arguments.length; _i++) {
117
- namespace[_i] = arguments[_i];
118
- }
119
- return sdk.getBrowserStorage.apply(sdk, tslib_1.__spreadArray([PLUGIN_NAMESPACE, name_1], tslib_1.__read(namespace)));
120
- },
106
+ getLogger: (...namespace) => sdk.getLogger(PLUGIN_NAMESPACE, name, ...namespace),
107
+ getTabStorage: (...namespace) => (sdk.getTabStorage(PLUGIN_NAMESPACE, name, ...namespace)),
108
+ getBrowserStorage: (...namespace) => (sdk.getBrowserStorage(PLUGIN_NAMESPACE, name, ...namespace)),
121
109
  },
122
110
  };
123
- var plugin = void 0;
111
+ let plugin;
124
112
  try {
125
113
  plugin = factory(args);
126
114
  }
127
115
  catch (error) {
128
- logger.error("Failed to initialize plugin \"" + name_1 + "\": " + error_1.formatCause(error));
129
- return "continue";
116
+ logger.error(`Failed to initialize plugin "${name}": ${(0, error_1.formatCause)(error)}`);
117
+ continue;
130
118
  }
131
- logger.debug("Plugin \"" + name_1 + "\" initialized");
119
+ logger.debug(`Plugin "${name}" initialized`);
132
120
  if (typeof plugin !== 'object') {
133
- return "continue";
121
+ continue;
134
122
  }
135
- this_1.plugins[name_1] = plugin;
136
- var promise = plugin.enable();
123
+ this.plugins[name] = plugin;
124
+ const promise = plugin.enable();
137
125
  if (!(promise instanceof Promise)) {
138
- logger.debug("Plugin \"" + name_1 + "\" enabled");
139
- return "continue";
140
- }
141
- pending.push(promise
142
- .then(function () { return logger.debug("Plugin \"" + name_1 + "\" enabled"); })
143
- .catch(function (error) { return logger.error("Failed to enable plugin \"" + name_1 + "\": " + error_1.formatCause(error)); }));
144
- };
145
- var this_1 = this;
146
- try {
147
- for (var _f = tslib_1.__values(Object.entries(tslib_1.__assign({ playground: true }, plugins))), _g = _f.next(); !_g.done; _g = _f.next()) {
148
- var _h = tslib_1.__read(_g.value, 2), name_1 = _h[0], options = _h[1];
149
- _loop_1(name_1, options);
150
- }
151
- }
152
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
153
- finally {
154
- try {
155
- if (_g && !_g.done && (_a = _f.return)) _a.call(_f);
126
+ logger.debug(`Plugin "${name}" enabled`);
127
+ continue;
156
128
  }
157
- finally { if (e_1) throw e_1.error; }
129
+ pending.push(promise.then(() => logger.debug(`Plugin "${name}" enabled`))
130
+ .catch(error => logger.error(`Failed to enable plugin "${name}": ${(0, error_1.formatCause)(error)}`)));
158
131
  }
159
- var initializeEap = (_e = window.croctEap) === null || _e === void 0 ? void 0 : _e.initialize;
132
+ const initializeEap = (_d = window.croctEap) === null || _d === void 0 ? void 0 : _d.initialize;
160
133
  if (typeof initializeEap === 'function') {
161
134
  initializeEap.call(this);
162
135
  }
163
- Promise.all(pending).then(function () {
164
- _this.initialize();
136
+ Promise.all(pending)
137
+ .then(() => {
138
+ this.initialize();
165
139
  logger.debug('Initialization complete');
166
140
  });
167
- };
168
- Object.defineProperty(GlobalPlug.prototype, "initialized", {
169
- get: function () {
170
- return this.instance !== undefined;
171
- },
172
- enumerable: false,
173
- configurable: true
174
- });
175
- Object.defineProperty(GlobalPlug.prototype, "plugged", {
176
- get: function () {
177
- var _this = this;
178
- return this.ready.then(function () { return _this; });
179
- },
180
- enumerable: false,
181
- configurable: true
182
- });
183
- Object.defineProperty(GlobalPlug.prototype, "flushed", {
184
- get: function () {
185
- var _this = this;
186
- return this.tracker.flushed.then(function () { return _this; });
187
- },
188
- enumerable: false,
189
- configurable: true
190
- });
191
- Object.defineProperty(GlobalPlug.prototype, "sdk", {
192
- get: function () {
193
- if (this.instance === undefined) {
194
- throw new Error('Croct is not plugged in.');
195
- }
196
- return this.instance;
197
- },
198
- enumerable: false,
199
- configurable: true
200
- });
201
- Object.defineProperty(GlobalPlug.prototype, "tracker", {
202
- get: function () {
203
- return this.sdk.tracker;
204
- },
205
- enumerable: false,
206
- configurable: true
207
- });
208
- Object.defineProperty(GlobalPlug.prototype, "evaluator", {
209
- get: function () {
210
- return this.sdk.evaluator;
211
- },
212
- enumerable: false,
213
- configurable: true
214
- });
215
- Object.defineProperty(GlobalPlug.prototype, "user", {
216
- get: function () {
217
- return this.sdk.user;
218
- },
219
- enumerable: false,
220
- configurable: true
221
- });
222
- Object.defineProperty(GlobalPlug.prototype, "session", {
223
- get: function () {
224
- return this.sdk.session;
225
- },
226
- enumerable: false,
227
- configurable: true
228
- });
229
- GlobalPlug.prototype.isAnonymous = function () {
230
- return this.sdk.context.isAnonymous();
231
- };
232
- GlobalPlug.prototype.getUserId = function () {
233
- return this.sdk.context.getUser();
234
- };
235
- GlobalPlug.prototype.identify = function (userId) {
141
+ }
142
+ get initialized() {
143
+ return this.instance !== undefined;
144
+ }
145
+ get plugged() {
146
+ return this.ready.then(() => this);
147
+ }
148
+ get flushed() {
149
+ return this.tracker
150
+ .flushed
151
+ .then(() => this);
152
+ }
153
+ get sdk() {
154
+ if (this.instance === undefined) {
155
+ throw new Error('Croct is not plugged in.');
156
+ }
157
+ return this.instance;
158
+ }
159
+ get tracker() {
160
+ return this.sdk.tracker;
161
+ }
162
+ get evaluator() {
163
+ return this.sdk.evaluator;
164
+ }
165
+ get user() {
166
+ return this.sdk.user;
167
+ }
168
+ get session() {
169
+ return this.sdk.session;
170
+ }
171
+ isAnonymous() {
172
+ return this.sdk
173
+ .context
174
+ .isAnonymous();
175
+ }
176
+ getUserId() {
177
+ return this.sdk
178
+ .context
179
+ .getUser();
180
+ }
181
+ identify(userId) {
236
182
  if (typeof userId !== 'string') {
237
183
  throw new Error('The user ID must be a string. Read more on https://croct.help/plug-js/id-conversion');
238
184
  }
239
185
  this.sdk.identify(userId);
240
- };
241
- GlobalPlug.prototype.anonymize = function () {
186
+ }
187
+ anonymize() {
242
188
  this.sdk.anonymize();
243
- };
244
- GlobalPlug.prototype.setToken = function (token) {
189
+ }
190
+ setToken(token) {
245
191
  this.sdk.setToken(token_1.Token.parse(token));
246
- };
247
- GlobalPlug.prototype.unsetToken = function () {
192
+ }
193
+ unsetToken() {
248
194
  this.sdk.unsetToken();
249
- };
250
- GlobalPlug.prototype.track = function (type, payload) {
251
- return this.sdk.tracker.track(type, payload);
252
- };
253
- GlobalPlug.prototype.evaluate = function (expression, options) {
254
- if (options === void 0) { options = {}; }
255
- return this.sdk.evaluator.evaluate(expression, options);
256
- };
257
- GlobalPlug.prototype.test = function (expression, options) {
258
- if (options === void 0) { options = {}; }
195
+ }
196
+ track(type, payload) {
197
+ return this.sdk
198
+ .tracker
199
+ .track(type, payload);
200
+ }
201
+ evaluate(expression, options = {}) {
202
+ return this.sdk
203
+ .evaluator
204
+ .evaluate(expression, options);
205
+ }
206
+ test(expression, options = {}) {
259
207
  return this.evaluate(expression, options)
260
- .then(function (result) { return result === true; });
261
- };
262
- /**
263
- * This API is unstable and subject to change in future releases.
264
- */
265
- GlobalPlug.prototype.fetch = function (slotId, options) {
266
- if (options === void 0) { options = {}; }
267
- return this.eap('fetch').call(this, slotId, options);
268
- };
269
- GlobalPlug.prototype.unplug = function () {
270
- return tslib_1.__awaiter(this, void 0, void 0, function () {
271
- var _a, instance, plugins, logger, pending, _loop_2, _b, _c, _d, pluginName, controller;
272
- var e_2, _e;
273
- var _this = this;
274
- return tslib_1.__generator(this, function (_f) {
275
- switch (_f.label) {
276
- case 0:
277
- if (this.instance === undefined) {
278
- return [2 /*return*/];
279
- }
280
- _a = this, instance = _a.instance, plugins = _a.plugins;
281
- logger = this.sdk.getLogger();
282
- pending = [];
283
- _loop_2 = function (pluginName, controller) {
284
- if (typeof controller.disable !== 'function') {
285
- return "continue";
286
- }
287
- logger.debug("Disabling plugin \"" + pluginName + "\"...");
288
- var promise = controller.disable();
289
- if (!(promise instanceof Promise)) {
290
- logger.debug("Plugin \"" + pluginName + "\" disabled");
291
- return "continue";
292
- }
293
- pending.push(promise
294
- .then(function () { return logger.debug("Plugin \"" + pluginName + "\" disabled"); })
295
- .catch(function (error) { return logger.error("Failed to disable \"" + pluginName + "\": " + error_1.formatCause(error)); }));
296
- };
297
- try {
298
- for (_b = tslib_1.__values(Object.entries(plugins)), _c = _b.next(); !_c.done; _c = _b.next()) {
299
- _d = tslib_1.__read(_c.value, 2), pluginName = _d[0], controller = _d[1];
300
- _loop_2(pluginName, controller);
301
- }
302
- }
303
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
304
- finally {
305
- try {
306
- if (_c && !_c.done && (_e = _b.return)) _e.call(_b);
307
- }
308
- finally { if (e_2) throw e_2.error; }
309
- }
310
- // Reset
311
- delete this.instance;
312
- this.plugins = {};
313
- this.ready = new Promise(function (resolve) {
314
- _this.initialize = resolve;
315
- });
316
- return [4 /*yield*/, Promise.all(pending)];
317
- case 1:
318
- _f.sent();
319
- _f.label = 2;
320
- case 2:
321
- _f.trys.push([2, , 4, 5]);
322
- return [4 /*yield*/, instance.close()];
323
- case 3:
324
- _f.sent();
325
- return [3 /*break*/, 5];
326
- case 4:
327
- logger.info('🔌 Croct has been unplugged.');
328
- return [7 /*endfinally*/];
329
- case 5: return [2 /*return*/];
330
- }
331
- });
208
+ .then(result => result === true);
209
+ }
210
+ get fetch() {
211
+ const logger = this.sdk.getLogger();
212
+ return this.eap('fetch', (slotId, options = {}) => {
213
+ const [id, version] = slotId.split('@');
214
+ return this.sdk
215
+ .contentFetcher
216
+ .fetch(id, {
217
+ ...options,
218
+ version: version === 'latest' ? undefined : version,
219
+ })
220
+ .then(response => ({
221
+ get payload() {
222
+ logger.warn('Accessing the "payload" property of the fetch response is deprecated'
223
+ + ' and will be removed in a future version. Use the "content" property instead.');
224
+ return response.content;
225
+ },
226
+ content: response.content,
227
+ }));
228
+ });
229
+ }
230
+ async unplug() {
231
+ if (this.instance === undefined) {
232
+ return;
233
+ }
234
+ const { instance, plugins } = this;
235
+ const logger = this.sdk.getLogger();
236
+ const pending = [];
237
+ for (const [pluginName, controller] of Object.entries(plugins)) {
238
+ if (typeof controller.disable !== 'function') {
239
+ continue;
240
+ }
241
+ logger.debug(`Disabling plugin "${pluginName}"...`);
242
+ const promise = controller.disable();
243
+ if (!(promise instanceof Promise)) {
244
+ logger.debug(`Plugin "${pluginName}" disabled`);
245
+ continue;
246
+ }
247
+ pending.push(promise.then(() => logger.debug(`Plugin "${pluginName}" disabled`))
248
+ .catch(error => logger.error(`Failed to disable "${pluginName}": ${(0, error_1.formatCause)(error)}`)));
249
+ }
250
+ // Reset
251
+ delete this.instance;
252
+ this.plugins = {};
253
+ this.ready = new Promise(resolve => {
254
+ this.initialize = resolve;
332
255
  });
333
- };
334
- GlobalPlug.prototype.eap = function (feature) {
335
- var logger = this.sdk.getLogger();
336
- var eap = window.croctEap;
337
- var method = typeof eap === 'object' ? eap[feature] : undefined;
256
+ await Promise.all(pending);
257
+ try {
258
+ await instance.close();
259
+ }
260
+ finally {
261
+ logger.info('🔌 Croct has been unplugged.');
262
+ }
263
+ }
264
+ eap(feature, api) {
265
+ const eap = window.croctEap;
266
+ const method = typeof eap === 'object' ? eap[feature] : undefined;
338
267
  if (typeof method !== 'function') {
339
- throw new Error("The " + feature + " feature is currently available only to accounts participating in our "
340
- + 'Early-Access Program (EAP). Please contact your Customer Success Manager or email eap@croct.com '
341
- + 'to check your account eligibility.');
268
+ return api;
342
269
  }
343
- logger.warn("The " + feature + " API is still unstable and subject to change in future releases.");
344
- return method;
345
- };
346
- return GlobalPlug;
347
- }());
270
+ return method.bind(new Proxy(this, {
271
+ get: (plug, property) => {
272
+ if (property === feature) {
273
+ return api;
274
+ }
275
+ return plug[property];
276
+ },
277
+ }));
278
+ }
279
+ }
348
280
  exports.GlobalPlug = GlobalPlug;
package/plugin.d.ts CHANGED
@@ -10,7 +10,8 @@ export interface PluginSdk {
10
10
  readonly user: UserFacade;
11
11
  readonly session: SessionFacade;
12
12
  readonly tab: Tab;
13
- readonly tokenStore: TokenStore;
13
+ readonly userTokenStore: TokenStore;
14
+ readonly previewTokenStore: TokenStore;
14
15
  readonly cidAssigner: CidAssigner;
15
16
  readonly eventManager: SdkEventManager;
16
17
  getLogger(...namespace: string[]): Logger;
package/preview.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { Logger } from './sdk';
2
+ import { Plugin, PluginFactory } from './plugin';
3
+ import { TokenStore } from './sdk/token';
4
+ export type Configuration = {
5
+ tokenStore: TokenStore;
6
+ logger: Logger;
7
+ };
8
+ export declare class PreviewPlugin implements Plugin {
9
+ private static readonly PREVIEW_PARAMS;
10
+ private readonly tokenStore;
11
+ private readonly logger;
12
+ private readonly widgetId;
13
+ constructor(configuration: Configuration);
14
+ enable(): void;
15
+ disable(): void;
16
+ private updateToken;
17
+ private getWidgetUrl;
18
+ private getWidgetParams;
19
+ private insertWidget;
20
+ private createWidget;
21
+ }
22
+ export declare const factory: PluginFactory;
package/preview.js ADDED
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.factory = exports.PreviewPlugin = void 0;
4
+ const error_1 = require("@croct/sdk/error");
5
+ const uuid_1 = require("@croct/sdk/uuid");
6
+ const token_1 = require("./sdk/token");
7
+ const constants_1 = require("./constants");
8
+ const PREVIEW_PARAMETER = 'croct-preview';
9
+ const PREVIEW_EXIT = 'exit';
10
+ class PreviewPlugin {
11
+ constructor(configuration) {
12
+ this.widgetId = `croct-preview:${(0, uuid_1.uuid4)()}`;
13
+ this.tokenStore = configuration.tokenStore;
14
+ this.logger = configuration.logger;
15
+ }
16
+ enable() {
17
+ const url = new URL(window.location.href);
18
+ const previewData = url.searchParams.get(PREVIEW_PARAMETER);
19
+ if (previewData !== null) {
20
+ this.updateToken(previewData);
21
+ // Remove the token from the URL
22
+ url.searchParams.delete(PREVIEW_PARAMETER);
23
+ window.history.replaceState({}, '', url.toString());
24
+ }
25
+ const token = this.tokenStore.getToken();
26
+ if (token !== null) {
27
+ this.insertWidget(this.getWidgetUrl(token));
28
+ }
29
+ }
30
+ disable() {
31
+ var _a;
32
+ (_a = document.getElementById(this.widgetId)) === null || _a === void 0 ? void 0 : _a.remove();
33
+ }
34
+ updateToken(data) {
35
+ if (data === PREVIEW_EXIT) {
36
+ this.tokenStore.setToken(null);
37
+ return;
38
+ }
39
+ try {
40
+ let token = token_1.Token.parse(data);
41
+ const { exp } = token.getPayload();
42
+ if (exp !== undefined && exp <= Date.now() / 1000) {
43
+ token = null;
44
+ }
45
+ this.tokenStore.setToken(token);
46
+ }
47
+ catch (error) {
48
+ this.tokenStore.setToken(null);
49
+ this.logger.warn(`Invalid preview token: ${(0, error_1.formatCause)(error)}`);
50
+ }
51
+ }
52
+ getWidgetUrl(token) {
53
+ const params = this.getWidgetParams(token);
54
+ let queryString = params.toString();
55
+ if (queryString !== '') {
56
+ queryString = `?${queryString}`;
57
+ }
58
+ return `${constants_1.PREVIEW_WIDGET_URL}${queryString}`;
59
+ }
60
+ getWidgetParams(token) {
61
+ const { metadata = {} } = token.getPayload();
62
+ const params = new URLSearchParams();
63
+ if (metadata === null || typeof metadata !== 'object' || Array.isArray(metadata)) {
64
+ return params;
65
+ }
66
+ for (const [key, param] of Object.entries(PreviewPlugin.PREVIEW_PARAMS)) {
67
+ const value = metadata[key];
68
+ if (typeof value === 'string') {
69
+ params.set(param, value);
70
+ }
71
+ }
72
+ return params;
73
+ }
74
+ insertWidget(url) {
75
+ const widget = this.createWidget(url);
76
+ window.addEventListener('message', event => {
77
+ if (event.origin !== constants_1.PREVIEW_WIDGET_ORIGIN) {
78
+ return;
79
+ }
80
+ switch (event.data.type) {
81
+ case 'croct:preview:leave': {
82
+ this.tokenStore.setToken(null);
83
+ const exitUrl = new URL(window.location.href);
84
+ exitUrl.searchParams.set(PREVIEW_PARAMETER, PREVIEW_EXIT);
85
+ window.location.replace(exitUrl.toString());
86
+ break;
87
+ }
88
+ case 'croct:preview:resize':
89
+ widget.style.width = `${event.data.width}px`;
90
+ widget.style.height = `${event.data.height}px`;
91
+ break;
92
+ }
93
+ });
94
+ document.body.prepend(widget);
95
+ }
96
+ createWidget(url) {
97
+ const widget = document.createElement('iframe');
98
+ widget.setAttribute('id', this.widgetId);
99
+ widget.setAttribute('src', url);
100
+ widget.setAttribute('sandbox', 'allow-scripts allow-same-origin');
101
+ widget.style.position = 'fixed';
102
+ widget.style.width = '0px';
103
+ widget.style.height = '0px';
104
+ widget.style.right = '0';
105
+ widget.style.bottom = '0';
106
+ widget.style.border = '0';
107
+ widget.style.overflow = 'hidden';
108
+ widget.style.zIndex = '2147483647';
109
+ return widget;
110
+ }
111
+ }
112
+ exports.PreviewPlugin = PreviewPlugin;
113
+ PreviewPlugin.PREVIEW_PARAMS = {
114
+ experienceName: 'experience',
115
+ experimentName: 'experiment',
116
+ audienceName: 'audience',
117
+ variantName: 'variant',
118
+ };
119
+ const factory = (props) => {
120
+ const { sdk } = props;
121
+ return new PreviewPlugin({
122
+ tokenStore: props.sdk.previewTokenStore,
123
+ logger: sdk.getLogger(),
124
+ });
125
+ };
126
+ exports.factory = factory;
@@ -1,2 +1,2 @@
1
1
  export { EvaluatorFacade, EvaluationOptions } from '@croct/sdk/facade/evaluatorFacade';
2
- export { EvaluationError, EvaluationErrorType, ExpressionError } from '@croct/sdk/evaluator';
2
+ export { EvaluationError, EvaluationErrorType, QueryError } from '@croct/sdk/evaluator';
package/sdk/evaluation.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ExpressionError = exports.EvaluationErrorType = exports.EvaluationError = exports.EvaluatorFacade = void 0;
3
+ exports.QueryError = exports.EvaluationErrorType = exports.EvaluationError = exports.EvaluatorFacade = void 0;
4
4
  var evaluatorFacade_1 = require("@croct/sdk/facade/evaluatorFacade");
5
5
  Object.defineProperty(exports, "EvaluatorFacade", { enumerable: true, get: function () { return evaluatorFacade_1.EvaluatorFacade; } });
6
6
  var evaluator_1 = require("@croct/sdk/evaluator");
7
7
  Object.defineProperty(exports, "EvaluationError", { enumerable: true, get: function () { return evaluator_1.EvaluationError; } });
8
8
  Object.defineProperty(exports, "EvaluationErrorType", { enumerable: true, get: function () { return evaluator_1.EvaluationErrorType; } });
9
- Object.defineProperty(exports, "ExpressionError", { enumerable: true, get: function () { return evaluator_1.ExpressionError; } });
9
+ Object.defineProperty(exports, "QueryError", { enumerable: true, get: function () { return evaluator_1.QueryError; } });
package/sdk/index.d.ts CHANGED
@@ -6,7 +6,7 @@ export { UserFacade } from '@croct/sdk/facade/userFacade';
6
6
  export { Tab } from '@croct/sdk/tab';
7
7
  export { CidAssigner } from '@croct/sdk/cid';
8
8
  export { SdkEventType, SdkEvent } from '@croct/sdk/sdkEvents';
9
- export declare type SdkEventListener<T extends SdkEventType> = EventListener<SdkEventMap[T]>;
10
- export declare type SdkEventDispatcher = EventDispatcher<Record<string, Record<string, any>>>;
11
- export declare type SdkEventSubscriber = EventSubscriber<SdkEventMap>;
12
- export declare type SdkEventManager = EventManager<SdkEventMap, Record<string, Record<string, any>>>;
9
+ export type SdkEventListener<T extends SdkEventType> = EventListener<SdkEventMap[T]>;
10
+ export type SdkEventDispatcher = EventDispatcher<Record<string, Record<string, any>>>;
11
+ export type SdkEventSubscriber = EventSubscriber<SdkEventMap>;
12
+ export type SdkEventManager = EventManager<SdkEventMap, Record<string, Record<string, any>>>;
package/sdk/json.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { JsonObject } from '@croct/json';
2
2
  export * from '@croct/json/mutable';
3
- export declare type NullableJsonObject = JsonObject | null;
3
+ export type NullableJsonObject = JsonObject | null;
package/sdk/json.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var tslib_1 = require("tslib");
3
+ const tslib_1 = require("tslib");
4
4
  tslib_1.__exportStar(require("@croct/json/mutable"), exports);
package/sdk/token.d.ts CHANGED
@@ -1 +1 @@
1
- export { Token, Claims, Headers, TokenProvider, TokenStore } from '@croct/sdk/token';
1
+ export { Token, TokenPayload, Headers, TokenProvider, TokenStore } from '@croct/sdk/token';
package/sdk/tracking.d.ts CHANGED
@@ -3,4 +3,4 @@ import { TrackingEvent, TrackingEventType } from '@croct/sdk/trackingEvents';
3
3
  export { TrackerFacade } from '@croct/sdk/facade/trackerFacade';
4
4
  export { EventListener } from '@croct/sdk/tracker';
5
5
  export { TrackingEvent, TrackingEventType, ExternalTrackingEvent, ExternalTrackingEventPayload, ExternalTrackingEventType, } from '@croct/sdk/trackingEvents';
6
- export declare type EventInfo<T extends TrackingEventType> = SdkEventInfo<TrackingEvent<T>>;
6
+ export type EventInfo<T extends TrackingEventType> = SdkEventInfo<TrackingEvent<T>>;
package/sdk/validation.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var tslib_1 = require("tslib");
3
+ const tslib_1 = require("tslib");
4
4
  tslib_1.__exportStar(require("@croct/sdk/validation"), exports);
5
5
  tslib_1.__exportStar(require("@croct/sdk/error"), exports);
package/slot.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { JsonObject } from '@croct/json';
2
+ export interface SlotMap {
3
+ }
4
+ type LatestSlotVersionMap = {
5
+ [K in keyof SlotMap]: {
6
+ latest: SlotMap[K];
7
+ };
8
+ };
9
+ export interface VersionedSlotMap extends LatestSlotVersionMap {
10
+ }
11
+ type LatestAlias = 'latest';
12
+ export type SlotId = keyof VersionedSlotMap extends never ? string : keyof VersionedSlotMap;
13
+ export type SlotVersion<I extends SlotId = SlotId> = LatestAlias | (I extends keyof VersionedSlotMap ? keyof VersionedSlotMap[I] : never);
14
+ export type VersionedSlotId<I extends SlotId = SlotId> = I | {
15
+ [K in SlotId]: `${K}@${SlotVersion<K> & string}`;
16
+ }[I];
17
+ type VersionedSlotContent<I extends SlotId, V extends string = LatestAlias, C extends JsonObject = JsonObject> = I extends keyof VersionedSlotMap ? (V extends keyof VersionedSlotMap[I] ? VersionedSlotMap[I][V] : C) : C;
18
+ export type ExtractSlotVersion<I extends string> = I extends `${string}@${infer V}` ? (LatestAlias extends V ? LatestAlias : (V extends `${number}` ? V : never)) : LatestAlias;
19
+ export type ExtractSlotId<I extends string> = I extends `${infer V}@${string}` ? V : I;
20
+ export type SlotContent<I extends VersionedSlotId, C extends JsonObject = JsonObject> = VersionedSlotContent<ExtractSlotId<I>, ExtractSlotVersion<I>, C>;
21
+ export {};
File without changes
package/fetch.d.ts DELETED
@@ -1,12 +0,0 @@
1
- import { NullableJsonObject, JsonObject } from './sdk/json';
2
- export interface SlotMap {
3
- }
4
- export declare type FetchOptions = {
5
- timeout?: number;
6
- attributes?: JsonObject;
7
- };
8
- export declare type SlotId = keyof SlotMap extends never ? string : keyof SlotMap;
9
- export declare type SlotContent<I extends SlotId> = I extends keyof SlotMap ? SlotMap[I] : NullableJsonObject;
10
- export declare type FetchResponse<I extends SlotId, P extends NullableJsonObject = NullableJsonObject> = {
11
- payload: SlotContent<I> & P;
12
- };