Skip to content

Commit

Permalink
fix: type generation with direct import from packages (#63)
Browse files Browse the repository at this point in the history
* fix: type generation with direct import from packages

* chore: readme updated

* chore: readme updated

* chore: doc link updated

* chore: minor refactor and command name updated
  • Loading branch information
MoumitaM authored Sep 9, 2024
1 parent 32b31ef commit b4c68c2
Show file tree
Hide file tree
Showing 24 changed files with 358 additions and 625 deletions.
8 changes: 5 additions & 3 deletions examples/js-cdn-typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ This is a basic web application written in TypeScript that uses RudderTyper clie
## Steps to run the sample app

1. Run `npm run setup` to install the required dependencies.
2. Replace `__WRITE_KEY__` and `__DATAPLANE_URL__` values in `./public/index.html` file.
2. Replace all `__WRITE_KEY__` and `__DATAPLANE_URL__` values in `./public/index.html` file.
3. Run the command `npm start`. The app will run in development mode. Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
4. Click on the track button to fire event.

![Alt text](app.png?raw=true 'Sample Site')

> Note: If you are building your own sample app, `@rudderstack/analytics-js` npm package must be added as a dev dependency of the package.json.
## Regenerate client libraries

1. Run the command `npx rudder-typer`. This will generate new `index.ts` and `rudder.ts` file based on the ruddertyper.yml.
Expand Down Expand Up @@ -40,15 +42,15 @@ Execute the following steps to regenerate the client library based on your track
Note: Ensure that you have setup the repository for development.

```
npm run ruddertyper:dev init
npm run rudder-typer:dev init
```

This will build the RudderTyper module locally and regenerates the client library based on the tracking plan.

You can further execute various RudderTyper commands like,

```
npm run ruddertyper:dev <command>
npm run rudder-typer:dev <command>
```

To re-generate the browserify bundle run the below command
Expand Down
3 changes: 2 additions & 1 deletion examples/js-cdn-typescript/package-lock.json

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

4 changes: 2 additions & 2 deletions examples/js-cdn-typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@rudderstack/analytics-js": "*",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
Expand All @@ -12,6 +11,7 @@
"web-vitals": "^2.1.4"
},
"devDependencies": {
"@rudderstack/analytics-js": "*",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.96",
"@types/react": "^18.2.79",
Expand All @@ -33,7 +33,7 @@
"setup": "npm ci",
"start": "react-scripts start",
"build": "react-scripts build",
"ruddertyper:dev": "chmod +x ./rt_script.sh && ./rt_script.sh"
"rudder-typer:dev": "chmod +x ./rt_script.sh && ./rt_script.sh"
},
"eslintConfig": {
"extends": [
Expand Down
137 changes: 95 additions & 42 deletions examples/js-cdn-typescript/public/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
Expand All @@ -23,53 +23,71 @@
-->
<title>React App</title>
<script>
(function() {
"use strict";
window.RudderSnippetVersion = "3.0.24";
var identifier = "rudderanalytics";
(function () {
'use strict';
window.RudderSnippetVersion = '3.0.24';
var identifier = 'rudderanalytics';
if (!window[identifier]) {
window[identifier] = [];
}
var rudderanalytics = window[identifier];
if (Array.isArray(rudderanalytics)) {
if (rudderanalytics.snippetExecuted === true && window.console && console.error) {
console.error("RudderStack JavaScript SDK snippet included more than once.");
console.error('RudderStack JavaScript SDK snippet included more than once.');
} else {
rudderanalytics.snippetExecuted = true;
window.rudderAnalyticsBuildType = "legacy";
var sdkBaseUrl = "https://cdn.rudderlabs.com/v3";
var sdkName = "rsa.min.js";
var scriptLoadingMode = "async";
var methods = [ "setDefaultInstanceKey", "load", "ready", "page", "track", "identify", "alias", "group", "reset", "setAnonymousId", "startSession", "endSession", "consent" ];
window.rudderAnalyticsBuildType = 'legacy';
var sdkBaseUrl = 'https://cdn.rudderlabs.com/v3';
var sdkName = 'rsa.min.js';
var scriptLoadingMode = 'async';
var methods = [
'setDefaultInstanceKey',
'load',
'ready',
'page',
'track',
'identify',
'alias',
'group',
'reset',
'setAnonymousId',
'startSession',
'endSession',
'consent',
];
for (var i = 0; i < methods.length; i++) {
var method = methods[i];
rudderanalytics[method] = function(methodName) {
return function() {
rudderanalytics[method] = (function (methodName) {
return function () {
if (Array.isArray(window[identifier])) {
rudderanalytics.push([ methodName ].concat(Array.prototype.slice.call(arguments)));
rudderanalytics.push(
[methodName].concat(Array.prototype.slice.call(arguments)),
);
} else {
var _methodName;
(_methodName = window[identifier][methodName]) === null || _methodName === void 0 || _methodName.apply(window[identifier], arguments);
(_methodName = window[identifier][methodName]) === null ||
_methodName === void 0 ||
_methodName.apply(window[identifier], arguments);
}
};
}(method);
})(method);
}
try {
new Function('return import("")');
window.rudderAnalyticsBuildType = "modern";
window.rudderAnalyticsBuildType = 'modern';
} catch (e) {}
var head = document.head || document.getElementsByTagName("head")[0];
var body = document.body || document.getElementsByTagName("body")[0];
window.rudderAnalyticsAddScript = function(url, extraAttributeKey, extraAttributeVal) {
var scriptTag = document.createElement("script");
var head = document.head || document.getElementsByTagName('head')[0];
var body = document.body || document.getElementsByTagName('body')[0];
window.rudderAnalyticsAddScript = function (url, extraAttributeKey, extraAttributeVal) {
var scriptTag = document.createElement('script');
scriptTag.src = url;
scriptTag.setAttribute("data-loader", "RS_JS_SDK");
scriptTag.setAttribute('data-loader', 'RS_JS_SDK');
if (extraAttributeKey && extraAttributeVal) {
scriptTag.setAttribute(extraAttributeKey, extraAttributeVal);
}
if (scriptLoadingMode === "async") {
if (scriptLoadingMode === 'async') {
scriptTag.async = true;
} else if (scriptLoadingMode === "defer") {
} else if (scriptLoadingMode === 'defer') {
scriptTag.defer = true;
}
if (head) {
Expand All @@ -78,31 +96,40 @@
body.insertBefore(scriptTag, body.firstChild);
}
};
window.rudderAnalyticsMount = function() {
(function() {
if (typeof globalThis === "undefined") {
window.rudderAnalyticsMount = function () {
(function () {
if (typeof globalThis === 'undefined') {
var getGlobal = function getGlobal() {
if (typeof self !== "undefined") {
if (typeof self !== 'undefined') {
return self;
}
if (typeof window !== "undefined") {
if (typeof window !== 'undefined') {
return window;
}
return null;
};
var global = getGlobal();
if (global) {
Object.defineProperty(global, "globalThis", {
Object.defineProperty(global, 'globalThis', {
value: global,
configurable: true
configurable: true,
});
}
}
})();
window.rudderAnalyticsAddScript("".concat(sdkBaseUrl, "/").concat(window.rudderAnalyticsBuildType, "/").concat(sdkName), "data-rsa-write-key", "__WRITE_KEY__");
window.rudderAnalyticsAddScript(
''
.concat(sdkBaseUrl, '/')
.concat(window.rudderAnalyticsBuildType, '/')
.concat(sdkName),
'data-rsa-write-key',
'__WRITE_KEY__',
);
};
if (typeof Promise === "undefined" || typeof globalThis === "undefined") {
window.rudderAnalyticsAddScript("https://polyfill-fastly.io/v3/polyfill.min.js?version=3.111.0&features=Symbol%2CPromise&callback=rudderAnalyticsMount");
if (typeof Promise === 'undefined' || typeof globalThis === 'undefined') {
window.rudderAnalyticsAddScript(
'https://polyfill-fastly.io/v3/polyfill.min.js?version=3.111.0&features=Symbol%2CPromise&callback=rudderAnalyticsMount',
);
} else {
window.rudderAnalyticsMount();
}
Expand All @@ -126,24 +153,50 @@
</script>
<script>
function track() {
rudderTyper.sampleEvent1({
'Sample property 1': 'Sample value 1',
});
rudderTyper.sampleEvent1(
{
'Sample property 1': 'Sample value 1',
},
{
integrations: {
All: false,
'Google Analytics': true,
},
context: {
active: true,
app: {
name: 'RudderStack',
version: '1.0.0',
build: '100',
},
device: {
id: 'device_id',
manufacturer: 'Samsung',
model: 'Galaxy S20',
name: 'Samsung Galaxy S20',
type: 'Android',
},
timestamp: new Date(),
extraKey1: 'value1',
},
},
() => {
console.log('callback called from sampleEvent1 event');
},
);
}
</script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div style="margin-left: 10%;">
<div style="margin-left: 10%">
<h1>Test HTML file</h1>
<br />
<button data-testid="track-btn" onclick="track()">Track</button>
</div>


<div id="root">
</div>

<div id="root"></div>

<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
Expand Down
2 changes: 1 addition & 1 deletion examples/js-cdn-typescript/public/rudderTyperBundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -8388,7 +8388,7 @@
ruddertyper: {
sdk: 'analytics.js',
language: 'typescript',
rudderTyperVersion: '1.0.0-beta.8',
rudderTyperVersion: '1.0.0-beta.11',
trackingPlanId: 'tp_2kKI0i514th5OEuYi5AdsRwNlXC',
trackingPlanVersion: 2,
},
Expand Down
37 changes: 31 additions & 6 deletions examples/js-cdn-typescript/src/analytics/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,34 @@
*/
import Ajv, { ErrorObject } from 'ajv';
import AjvDraft4 from 'ajv-draft-04';
import * as Rudder from './rudder';

import type {
RudderAnalytics,
RudderAnalyticsPreloader,
ApiOptions,
ApiObject,
} from '@rudderstack/analytics-js';
/**
* The analytics instance should be available via window.rudderanalytics.
* You can install it by following instructions at: https://www.rudderstack.com/docs/sources/event-streams/sdks/rudderstack-javascript-sdk/installation/
*/
declare global {
interface Window {
rudderanalytics: RudderAnalytics | RudderAnalyticsPreloader | undefined;
}
}

type apiCallback = (data?: any) => void;

/** The Schema object which is being used by Ajv to validate the message */
export interface Schema {
$schema?: string;
description?: string;
properties?: object;
title?: string;
type?: string;
}

export interface SampleEvent1 {
/**
* Sample property 1
Expand Down Expand Up @@ -94,7 +119,7 @@ export function setRudderTyperOptions(options: RudderTyperOptions) {
* Validates a message against a JSON Schema using Ajv. If the message
* is invalid, the `onViolation` handler will be called.
*/
async function validateAgainstSchema(message: Record<string, any>, schema: Rudder.Schema) {
async function validateAgainstSchema(message: Record<string, any>, schema: Schema) {
let ajv;
if (schema['$schema'] && schema['$schema'].includes('draft-04')) {
ajv = new AjvDraft4({
Expand All @@ -118,15 +143,15 @@ async function validateAgainstSchema(message: Record<string, any>, schema: Rudde
* Helper to attach metadata on RudderTyper to outbound requests.
* This is used for attribution and debugging by the RudderStack team.
*/
function withRudderTyperContext(message: Rudder.Options = {}): Rudder.Options {
function withRudderTyperContext(message: ApiOptions = {}): ApiOptions {
return {
...message,
context: {
...(message.context || {}),
...((message.context as ApiObject) || {}),
ruddertyper: {
sdk: 'analytics.js',
language: 'typescript',
rudderTyperVersion: '1.0.0-beta.8',
rudderTyperVersion: '1.0.0-beta.11',
trackingPlanId: 'tp_2kKI0i514th5OEuYi5AdsRwNlXC',
trackingPlanVersion: 2,
},
Expand All @@ -149,7 +174,7 @@ function withRudderTyperContext(message: Rudder.Options = {}): Rudder.Options {
*/
export function sampleEvent1(
props?: SampleEvent1,
options?: Rudder.Options,
options?: ApiOptions,
callback?: apiCallback,
): void {
const a = analytics();
Expand Down
Loading

0 comments on commit b4c68c2

Please sign in to comment.