Skip to content

Commit

Permalink
Split exports for installation from NPM and CDN
Browse files Browse the repository at this point in the history
Prior to this change, the default exported value, the global singleton, was exported along with the error classes. This caused the global singleton plug to be available at `window.croct.default` instead of `croct`.

With this change, the Javascript code generated for the browser will export only the singleton plug as a global variable `croct` and the NPM package will export an object as a module with the error classes and the singleton plug as its properties.

Co-authored-by: Marcos Passos <[email protected]>
  • Loading branch information
Fryuni and marcospassos authored Apr 7, 2020
1 parent 2c41229 commit 9c9923f
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 141 deletions.
1 change: 0 additions & 1 deletion .github/workflows/deploy-published-releases.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ jobs:
- name: Build bundles
run: |-
npm run rollup
npm run rollup-min
# Clear dependencies from package-lock.json
mv package.json package-full.json
Expand Down
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"lint": "eslint 'src/**/*.ts' 'test/**/*.ts'",
"test": "jest -c jest.config.js --coverage",
"rollup": "rollup -c rollup.config.js",
"rollup-min": "rollup -c rollup.config.js --environment minify"
"rollup-min": "rollup -c rollup.min-config.js"
},
"dependencies": {
"@croct-tech/sdk": "0.0.1-beta1"
Expand Down
26 changes: 6 additions & 20 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,31 @@
import resolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript2';
import tempDir from 'temp-dir';
import {uglify} from 'rollup-plugin-uglify';
import dts from 'rollup-plugin-dts';
import commonjs from 'rollup-plugin-commonjs';

export default () => {
const minify = process.env.minify || false;

return [
{
input: 'src/index.ts',
output: {
file: minify ? 'build/index.min.js' : 'build/index.js',
name: 'croct',
format: 'iife',
file: 'build/index.js',
format: 'commonjs',
sourcemap: true,
},
treeshake: {
propertyReadSideEffects: false
},
plugins: [
resolve(),
commonjs(),
typescript({
cacheRoot: `${tempDir}/.rpt2_cache`,
useTsconfigDeclarationDir: true
useTsconfigDeclarationDir: true,
}),
minify ?
uglify({
compress: {
unused: true,
dead_code: true,
}
}) : {},
]
],
},
{
input: './build/declarations/index.d.ts',
output: [{file: 'build/index.d.ts', format: 'es'}],
output: [{file: 'build/index.d.ts', format: 'commonjs'}],
plugins: [dts({respectExternal: true})],
},
];
};
};
36 changes: 36 additions & 0 deletions rollup.min-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import resolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript2';
import tempDir from 'temp-dir';
import {uglify} from 'rollup-plugin-uglify';
import commonjs from 'rollup-plugin-commonjs';

export default () => {
return [
{
input: 'src/plug.ts',
output: {
file: 'build/plug.min.js',
name: 'croct',
format: 'iife',
sourcemap: false,
},
treeshake: {
propertyReadSideEffects: false,
},
plugins: [
resolve(),
commonjs(),
typescript({
cacheRoot: `${tempDir}/.rpt2_cache`,
useTsconfigDeclarationDir: true,
}),
uglify({
compress: {
unused: true,
dead_code: true,
},
}),
],
},
];
};
116 changes: 1 addition & 115 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,129 +1,15 @@
import {
JsonValue,
SdkFacade,
SdkFacadeConfiguration as Configuration,
EvaluationFacadeOptions as EvaluationOptions,
EvaluationErrorType,
EvaluationError,
ExpressionError,
SessionFacade,
TrackerFacade,
UserFacade,
ExternalEvent,
ExternalEventPayload,
ExternalEventType,
} from '@croct-tech/sdk';

export interface Plug {
readonly tracker: TrackerFacade;
readonly user: UserFacade;
readonly session: SessionFacade;

plug(configuration: Configuration): void;

isAnonymous(): boolean;

getUserId(): string | null;

identify(userId: string): void;

anonymize(): void;

setToken(token: string): void;

unsetToken(): void;

track<T extends ExternalEventType>(type: T, payload: ExternalEventPayload<T>): Promise<ExternalEvent<T>>;

evaluate(expression: string, options?: EvaluationOptions): Promise<JsonValue>;

unplug(): Promise<void>;
}

class SingletonPlug implements Plug {
private facade?: SdkFacade;

public plug(configuration: Configuration): void {
if (this.facade !== undefined) {
const logger = this.facade.getLogger();

logger.info('Croct is already plugged in.');

return;
}

this.facade = SdkFacade.init(configuration);
}

private get instance(): SdkFacade {
if (this.facade === undefined) {
throw new Error('Croct is not plugged in.');
}

return this.facade;
}

public get tracker(): TrackerFacade {
return this.instance.tracker;
}

public get user(): UserFacade {
return this.instance.user;
}

public get session(): SessionFacade {
return this.instance.session;
}

public isAnonymous(): boolean {
return this.instance.context.isAnonymous();
}

public getUserId(): string | null {
return this.instance.context.getUser();
}

public identify(userId: string): void {
this.instance.identify(userId);
}

public anonymize(): void {
this.instance.anonymize();
}

public setToken(token: string): void {
this.instance.setToken(token);
}

public unsetToken(): void {
this.instance.unsetToken();
}

public track<T extends ExternalEventType>(type: T, payload: ExternalEventPayload<T>): Promise<ExternalEvent<T>> {
return this.instance.track(type, payload);
}

public evaluate(expression: string, options: EvaluationOptions = {}): Promise<JsonValue> {
return this.instance.evaluate(expression, options);
}

public async unplug(): Promise<void> {
if (this.facade === undefined) {
return;
}

const logger = this.instance.getLogger();

try {
await this.facade.close();
} finally {
delete this.facade;

logger.info('🔌 Croct has been unplugged.');
}
}
}

export {
Configuration,
ExternalEventType,
Expand All @@ -136,4 +22,4 @@ export {
JsonValue,
};

export default new SingletonPlug();
export {default as croct} from './plug';
124 changes: 124 additions & 0 deletions src/plug.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import {
JsonValue,
SdkFacade,
SdkFacadeConfiguration as Configuration,
EvaluationFacadeOptions as EvaluationOptions,
SessionFacade,
TrackerFacade,
UserFacade,
ExternalEvent,
ExternalEventPayload,
ExternalEventType,
} from '@croct-tech/sdk';

export interface Plug {
readonly tracker: TrackerFacade;
readonly user: UserFacade;
readonly session: SessionFacade;

plug(configuration: Configuration): void;

isAnonymous(): boolean;

getUserId(): string | null;

identify(userId: string): void;

anonymize(): void;

setToken(token: string): void;

unsetToken(): void;

track<T extends ExternalEventType>(type: T, payload: ExternalEventPayload<T>): Promise<ExternalEvent<T>>;

evaluate(expression: string, options?: EvaluationOptions): Promise<JsonValue>;

unplug(): Promise<void>;
}

class GlobalPlug implements Plug {
private facade?: SdkFacade;

public plug(configuration: Configuration): void {
if (this.facade !== undefined) {
const logger = this.facade.getLogger();

logger.info('Croct is already plugged in.');

return;
}

this.facade = SdkFacade.init(configuration);
}

private get instance(): SdkFacade {
if (this.facade === undefined) {
throw new Error('Croct is not plugged in.');
}

return this.facade;
}

public get tracker(): TrackerFacade {
return this.instance.tracker;
}

public get user(): UserFacade {
return this.instance.user;
}

public get session(): SessionFacade {
return this.instance.session;
}

public isAnonymous(): boolean {
return this.instance.context.isAnonymous();
}

public getUserId(): string | null {
return this.instance.context.getUser();
}

public identify(userId: string): void {
this.instance.identify(userId);
}

public anonymize(): void {
this.instance.anonymize();
}

public setToken(token: string): void {
this.instance.setToken(token);
}

public unsetToken(): void {
this.instance.unsetToken();
}

public track<T extends ExternalEventType>(type: T, payload: ExternalEventPayload<T>): Promise<ExternalEvent<T>> {
return this.instance.track(type, payload);
}

public evaluate(expression: string, options: EvaluationOptions = {}): Promise<JsonValue> {
return this.instance.evaluate(expression, options);
}

public async unplug(): Promise<void> {
if (this.facade === undefined) {
return;
}

const logger = this.instance.getLogger();

try {
await this.facade.close();
} finally {
delete this.facade;

logger.info('🔌 Croct has been unplugged.');
}
}
}

export default new GlobalPlug();
2 changes: 1 addition & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {SdkFacade, SdkFacadeConfiguration} from '@croct-tech/sdk';
import croct from '../src/index';
import {croct} from '../src/index';

describe('The Croct plug', () => {
const appId = '7e9d59a9-e4b3-45d4-b1c7-48287f1e5e8a';
Expand Down

0 comments on commit 9c9923f

Please sign in to comment.