starpro-plugin-sdk 0.0.0-stage → 1.0.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/README.md CHANGED
@@ -1,3 +1,110 @@
1
- # Temporary Holding Version
1
+ # StarPro Plugin SDK (`starpro-plugin-sdk`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ SDK resmi untuk mengubah aplikasi web apa pun (**Next.js**, **React**, **Vue**, **Svelte**, atau **JavaScript biasa**) menjadi **Plugin Native StarPro (No-Iframe)** dengan sinkronisasi token autentikasi dan auto-bypass login.
4
+
5
+ ---
6
+
7
+ ## 🚀 Cara Instalasi
8
+
9
+ ```bash
10
+ # Menggunakan npm
11
+ npm install starpro-plugin-sdk
12
+
13
+ # Menggunakan yarn
14
+ yarn add starpro-plugin-sdk
15
+
16
+ # Menggunakan pnpm
17
+ pnpm add starpro-plugin-sdk
18
+ ```
19
+
20
+ ---
21
+
22
+ ## 🛠️ Cara Penggunaan di Proyek Anda
23
+
24
+ ### 1. Di Aplikasi Next.js / React
25
+
26
+ Cukup buat file entry point plugin Anda (misal `src/plugin-entry.tsx`):
27
+
28
+ ```tsx
29
+ import React from "react";
30
+ import { createRoot } from "react-dom/client";
31
+ import { defineStarProPlugin, StarProPluginWrapper } from "starpro-plugin-sdk";
32
+ import TenantDashboard from "./app/(app)/dashboard/page"; // Halaman Dashboard Anda
33
+
34
+ defineStarProPlugin({
35
+ pluginId: "star-tenant-access", // ID Plugin Anda
36
+ onMount: (container, payload) => {
37
+ const root = createRoot(container);
38
+
39
+ // Langsung render Dashboard!
40
+ // Login otomatis dilewati (di-bypass) & token otomatis disuntikkan ke Axios & fetch()
41
+ root.render(
42
+ <StarProPluginWrapper payload={payload}>
43
+ <TenantDashboard />
44
+ </StarProPluginWrapper>,
45
+ );
46
+
47
+ // Cleanup unmount saat tab plugin ditutup di StarPro
48
+ return () => {
49
+ root.unmount();
50
+ };
51
+ },
52
+ });
53
+ ```
54
+
55
+ Di dalam komponen React apa pun pada aplikasi Anda, Anda juga bisa mengakses data login StarPro menggunakan hook:
56
+
57
+ ```tsx
58
+ import { useStarProAuth } from "starpro-plugin-sdk";
59
+
60
+ export function ProfileWidget() {
61
+ const { accessToken, user, isPlugin } = useStarProAuth();
62
+
63
+ return (
64
+ <div>{isPlugin && <p>Berjalan di StarPro sebagai: {user?.email}</p>}</div>
65
+ );
66
+ }
67
+ ```
68
+
69
+ ---
70
+
71
+ ### 2. Di Aplikasi Vue.js
72
+
73
+ ```javascript
74
+ import { createApp } from "vue";
75
+ import { defineStarProPlugin } from "starpro-plugin-sdk";
76
+ import AppDashboard from "./views/AppDashboard.vue";
77
+
78
+ defineStarProPlugin({
79
+ pluginId: "my-vue-plugin",
80
+ onMount: (container, payload) => {
81
+ const app = createApp(AppDashboard, { user: payload.user });
82
+ app.mount(container);
83
+ return () => app.unmount();
84
+ },
85
+ });
86
+ ```
87
+
88
+ ---
89
+
90
+ ### 3. Di Vanilla JavaScript / HTML
91
+
92
+ ```javascript
93
+ import { defineStarProPlugin } from "starpro-plugin-sdk";
94
+
95
+ defineStarProPlugin({
96
+ pluginId: "my-js-plugin",
97
+ onMount: (container, { user }) => {
98
+ container.innerHTML = `<h1>Halo, ${user?.name || user?.email}!</h1>`;
99
+ },
100
+ });
101
+ ```
102
+
103
+ ---
104
+
105
+ ## ⚙️ Fitur yang Dijalankan Otomatis oleh SDK:
106
+
107
+ 1. **Auto Storage Sync**: Menyimpan `accessToken` dan `refreshToken` ke `localStorage` dan `sessionStorage`.
108
+ 2. **Auto Axios Interceptor**: Menyuntikkan `Authorization: Bearer <accessToken>` ke semua request Axios.
109
+ 3. **Auto Fetch Interceptor**: Menyuntikkan header `Authorization` ke fungsi `fetch()` native browser.
110
+ 4. **Auto-Bypass Flag**: Menyimpan flag `is_starpro_plugin: true` agar halaman sign-in tidak perlu ditampilkan.
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "starpro-plugin-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Universal SDK to turn any React, Next.js, Vue, or JavaScript web app into a native StarPro plugin with automatic authentication & login bypass.",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ },
14
+ "./react": {
15
+ "types": "./dist/react.d.ts",
16
+ "import": "./dist/react.mjs",
17
+ "require": "./dist/react.js"
18
+ }
19
+ },
20
+ "scripts": {
21
+ "build": "tsup src/index.ts src/react.tsx --dts --format cjs,esm --clean"
22
+ },
23
+ "keywords": [
24
+ "starpro",
25
+ "plugin",
26
+ "micro-frontend",
27
+ "sdk",
28
+ "react",
29
+ "nextjs",
30
+ "auth-bypass"
31
+ ],
32
+ "author": "StarPro Engineering Team",
33
+ "license": "MIT",
34
+ "peerDependencies": {
35
+ "react": ">=18.0.0",
36
+ "react-dom": ">=18.0.0"
37
+ },
38
+ "peerDependenciesMeta": {
39
+ "react": {
40
+ "optional": true
41
+ },
42
+ "react-dom": {
43
+ "optional": true
44
+ }
45
+ },
46
+ "devDependencies": {
47
+ "tsup": "^8.3.5",
48
+ "typescript": "^5.0.0"
49
+ }
50
+ }
package/src/bridge.ts ADDED
@@ -0,0 +1,94 @@
1
+ import { StarProAuthPayload } from "./types";
2
+
3
+ /**
4
+ * Injects StarPro authentication tokens across all standard channels:
5
+ * - localStorage & sessionStorage
6
+ * - Global Axios default headers & interceptors
7
+ * - Browser native window.fetch() interceptor
8
+ */
9
+ export function setupStarProAuthBridge(payload: StarProAuthPayload): void {
10
+ if (typeof window === "undefined") return;
11
+
12
+ const { accessToken, refreshToken, user } = payload || {};
13
+ if (!accessToken) return;
14
+
15
+ console.log("⚡ [StarPro Plugin SDK] Auto-syncing auth tokens across storage & HTTP clients...");
16
+
17
+ // 1. Storage Injection
18
+ const tokenKeys = ["accessToken", "access_token", "token", "starpro_token", "authToken"];
19
+ tokenKeys.forEach((key) => {
20
+ try {
21
+ localStorage.setItem(key, accessToken);
22
+ sessionStorage.setItem(key, accessToken);
23
+ } catch (e) {
24
+ // Ignore storage quota or access issues
25
+ }
26
+ });
27
+
28
+ if (refreshToken) {
29
+ try {
30
+ localStorage.setItem("refreshToken", refreshToken);
31
+ localStorage.setItem("refresh_token", refreshToken);
32
+ sessionStorage.setItem("refreshToken", refreshToken);
33
+ } catch (e) {}
34
+ }
35
+
36
+ if (user) {
37
+ try {
38
+ localStorage.setItem("user", JSON.stringify(user));
39
+ localStorage.setItem("user_email", user.email || "");
40
+ } catch (e) {}
41
+ }
42
+
43
+ try {
44
+ localStorage.setItem("is_starpro_plugin", "true");
45
+ sessionStorage.setItem("is_starpro_plugin", "true");
46
+ } catch (e) {}
47
+
48
+ // 2. Global Axios Injection (if window.axios exists)
49
+ if (window.axios) {
50
+ try {
51
+ window.axios.defaults.headers.common["Authorization"] = `Bearer ${accessToken}`;
52
+ } catch (e) {}
53
+ }
54
+
55
+ // 3. Global Native fetch() Interceptor
56
+ if (typeof window.fetch === "function") {
57
+ const originalFetch = window.fetch;
58
+ window.fetch = function (input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
59
+ const options: RequestInit = init || {};
60
+ options.headers = options.headers || {};
61
+
62
+ if (options.headers instanceof Headers) {
63
+ if (!options.headers.has("Authorization")) {
64
+ options.headers.set("Authorization", `Bearer ${accessToken}`);
65
+ }
66
+ } else if (Array.isArray(options.headers)) {
67
+ const hasAuth = options.headers.some(([k]) => k.toLowerCase() === "authorization");
68
+ if (!hasAuth) {
69
+ options.headers.push(["Authorization", `Bearer ${accessToken}`]);
70
+ }
71
+ } else {
72
+ const headersRecord = options.headers as Record<string, string>;
73
+ if (!headersRecord["Authorization"] && !headersRecord["authorization"]) {
74
+ headersRecord["Authorization"] = `Bearer ${accessToken}`;
75
+ }
76
+ }
77
+
78
+ return originalFetch.call(this, input, options);
79
+ };
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Returns true if the current application is currently running as a StarPro plugin.
85
+ */
86
+ export function isStarProPlugin(): boolean {
87
+ if (typeof window === "undefined") return false;
88
+ return (
89
+ localStorage.getItem("is_starpro_plugin") === "true" ||
90
+ sessionStorage.getItem("is_starpro_plugin") === "true" ||
91
+ Boolean(window.StarProPlugins)
92
+ );
93
+ }
94
+
@@ -0,0 +1,79 @@
1
+ import { DefinePluginOptions, StarProAuthPayload } from "./types";
2
+ import { setupStarProAuthBridge } from "./bridge";
3
+
4
+ /**
5
+ * Universal registration function to define a StarPro plugin in any JavaScript web.
6
+ * Supports React, Next.js, Vue, Svelte, and Vanilla JS.
7
+ */
8
+ export function defineStarProPlugin(options: DefinePluginOptions): void {
9
+ if (typeof window === "undefined") return;
10
+
11
+ const {
12
+ pluginId = "default",
13
+ onMount,
14
+ onUnmount,
15
+ autoInjectAuth = true,
16
+ } = options;
17
+
18
+ window.StarProPlugins = window.StarProPlugins || {};
19
+
20
+ const pluginModule = {
21
+ mount: function (
22
+ container: HTMLElement | string,
23
+ payload: StarProAuthPayload,
24
+ ) {
25
+ const targetElement =
26
+ typeof container === "string"
27
+ ? document.getElementById(container)
28
+ : container;
29
+
30
+ if (!targetElement) {
31
+ console.error(
32
+ `[StarPro Plugin: ${pluginId}] Target container element not found!`,
33
+ );
34
+ return;
35
+ }
36
+
37
+ // Automatically setup bridge & inject tokens if enabled
38
+ if (autoInjectAuth) {
39
+ setupStarProAuthBridge(payload);
40
+ }
41
+
42
+ // Execute user mount function
43
+ let cleanup: (() => void) | void = undefined;
44
+ if (typeof onMount === "function") {
45
+ cleanup = onMount(targetElement, payload);
46
+ }
47
+
48
+ // Return cleanup function for StarPro to call when unmounting
49
+ return function unmount() {
50
+ if (typeof cleanup === "function") {
51
+ try {
52
+ cleanup();
53
+ } catch (err) {
54
+ console.warn(`[StarPro Plugin: ${pluginId}] Error in cleanup:`, err);
55
+ }
56
+ }
57
+ if (typeof onUnmount === "function") {
58
+ try {
59
+ onUnmount();
60
+ } catch (err) {
61
+ console.warn(
62
+ `[StarPro Plugin: ${pluginId}] Error in onUnmount:`,
63
+ err,
64
+ );
65
+ }
66
+ }
67
+ targetElement.innerHTML = "";
68
+ };
69
+ },
70
+ };
71
+
72
+ // Register under specific plugin ID and default fallback
73
+ window.StarProPlugins[pluginId] = pluginModule;
74
+ window.StarProPlugins["default"] = pluginModule;
75
+ window.mountStarProPlugin = pluginModule.mount;
76
+
77
+ console.log(`✓ [StarPro Plugin SDK] Registered plugin "${pluginId}"`);
78
+ }
79
+
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ // Public API for starpro-plugin-sdk
2
+ export * from "./types";
3
+ export * from "./bridge";
4
+ export * from "./define-plugin";
5
+ export * from "./react";
6
+
package/src/react.tsx ADDED
@@ -0,0 +1,94 @@
1
+ import React, { useState, useEffect } from "react";
2
+ import { StarProAuthPayload, StarProUser } from "./types";
3
+ import { isStarProPlugin } from "./bridge";
4
+
5
+ export interface StarProAuthState {
6
+ accessToken: string | null;
7
+ refreshToken: string | null;
8
+ user: StarProUser | null;
9
+ isPlugin: boolean;
10
+ isLoading: boolean;
11
+ }
12
+
13
+ /**
14
+ * React Hook to access StarPro authentication state anywhere in your React/Next.js app.
15
+ */
16
+ export function useStarProAuth(): StarProAuthState {
17
+ const [authState, setAuthState] = useState<StarProAuthState>(() => {
18
+ if (typeof window === "undefined") {
19
+ return {
20
+ accessToken: null,
21
+ refreshToken: null,
22
+ user: null,
23
+ isPlugin: false,
24
+ isLoading: true,
25
+ };
26
+ }
27
+
28
+ const token = localStorage.getItem("accessToken") || localStorage.getItem("token");
29
+ const refresh = localStorage.getItem("refreshToken");
30
+ let userObj: StarProUser | null = null;
31
+ try {
32
+ const storedUser = localStorage.getItem("user");
33
+ if (storedUser) userObj = JSON.parse(storedUser);
34
+ } catch (e) {}
35
+
36
+ return {
37
+ accessToken: token,
38
+ refreshToken: refresh,
39
+ user: userObj,
40
+ isPlugin: isStarProPlugin(),
41
+ isLoading: false,
42
+ };
43
+ });
44
+
45
+ return authState;
46
+ }
47
+
48
+ export interface StarProPluginWrapperProps {
49
+ payload?: StarProAuthPayload;
50
+ children: React.ReactNode;
51
+ fallback?: React.ReactNode;
52
+ banner?: boolean;
53
+ }
54
+
55
+ /**
56
+ * React Wrapper Component that handles auto-bypass of the login screen.
57
+ * Displays a connected banner and directly renders your main dashboard component.
58
+ */
59
+ export const StarProPluginWrapper: React.FC<StarProPluginWrapperProps> = ({
60
+ payload,
61
+ children,
62
+ banner = true,
63
+ }) => {
64
+ const user = payload?.user;
65
+
66
+ return (
67
+ <div className="starpro-plugin-root">
68
+ {banner && user && (
69
+ <div
70
+ style={{
71
+ background: "#f0fdf4",
72
+ border: "1px solid #bbf7d0",
73
+ color: "#166534",
74
+ padding: "8px 14px",
75
+ fontSize: "12px",
76
+ borderRadius: "8px",
77
+ marginBottom: "16px",
78
+ display: "flex",
79
+ justifyContent: "space-between",
80
+ alignItems: "center",
81
+ fontFamily: "system-ui, -apple-system, sans-serif",
82
+ }}
83
+ >
84
+ <span>
85
+ ✓ Terhubung ke StarPro sebagai: <strong>{user.name || user.email}</strong>
86
+ </span>
87
+ <span style={{ fontSize: "11px", opacity: 0.8 }}>Login Otomatis Aktif</span>
88
+ </div>
89
+ )}
90
+ {children}
91
+ </div>
92
+ );
93
+ };
94
+
package/src/types.ts ADDED
@@ -0,0 +1,66 @@
1
+ export interface StarProUser {
2
+ name?: string | null;
3
+ email?: string | null;
4
+ id?: string | null;
5
+ [key: string]: any;
6
+ }
7
+
8
+ export interface StarProAuthPayload {
9
+ accessToken: string;
10
+ refreshToken?: string;
11
+ user?: StarProUser;
12
+ [key: string]: any;
13
+ }
14
+
15
+ export type MountCleanupFn = () => void;
16
+
17
+ export type PluginMountHandler = (
18
+ container: HTMLElement,
19
+ payload: StarProAuthPayload,
20
+ ) => MountCleanupFn | void;
21
+
22
+ export interface DefinePluginOptions {
23
+ /**
24
+ * The identifier for this plugin (e.g. "star-tenant-access" or "subkon-progress").
25
+ * Defaults to "default".
26
+ */
27
+ pluginId?: string;
28
+
29
+ /**
30
+ * Callback executed when StarPro mounts the plugin.
31
+ * Receives target DOM element and the authentication payload.
32
+ * Return an optional cleanup function to be called on unmount.
33
+ */
34
+ onMount: PluginMountHandler;
35
+
36
+ /**
37
+ * Optional callback executed when StarPro unmounts the plugin.
38
+ */
39
+ onUnmount?: () => void;
40
+
41
+ /**
42
+ * Whether to automatically inject auth tokens into localStorage, sessionStorage,
43
+ * Axios defaults, and native fetch() calls. Defaults to true.
44
+ */
45
+ autoInjectAuth?: boolean;
46
+ }
47
+
48
+ declare global {
49
+ interface Window {
50
+ StarProPlugins?: Record<
51
+ string,
52
+ {
53
+ mount: (
54
+ container: HTMLElement | string,
55
+ payload: StarProAuthPayload,
56
+ ) => MountCleanupFn | void;
57
+ }
58
+ >;
59
+ mountStarProPlugin?: (
60
+ container: HTMLElement | string,
61
+ payload: StarProAuthPayload,
62
+ ) => MountCleanupFn | void;
63
+ axios?: any;
64
+ }
65
+ }
66
+
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "jsx": "react-jsx",
7
+ "declaration": true,
8
+ "declarationMap": true,
9
+ "strict": true,
10
+ "esModuleInterop": true,
11
+ "skipLibCheck": true,
12
+ "forceConsistentCasingInFileNames": true,
13
+ "outDir": "./dist"
14
+ },
15
+ "include": ["src/**/*"]
16
+ }
17
+