@helloleo/plugins 0.1.9 → 0.1.10

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.js CHANGED
@@ -12544,6 +12544,263 @@ var RemovePlugin = async () => {
12544
12544
  // src/tools/scaffold.ts
12545
12545
  import { mkdir } from "fs/promises";
12546
12546
  import path2 from "path";
12547
+
12548
+ // src/tools/scaffold-netsuite.ts
12549
+ function netsuiteTs() {
12550
+ return `/*
12551
+ * NetSuite OAuth client helper (bearer-token-in-fragment).
12552
+ *
12553
+ * Two NetSuite Integration Records back this:
12554
+ * 1. MCP (scope: mcp) -- used by HelloLeo at build time.
12555
+ * 2. Runtime (scope: rest_webservices) -- used here at sign-in time.
12556
+ * Runtime credentials live as HelloLeo Cloud secrets on the project's Worker
12557
+ * (env.NETSUITE_ACCOUNT_ID / _CLIENT_ID / _CLIENT_SECRET). They never reach
12558
+ * the browser. Cookies are NOT used -- frontend \u2194 Worker are cross-site
12559
+ * (e.g. *.helloleo.dev <-> *.workers.dev) and Chrome partitions / drops
12560
+ * third-party cookies in the HelloLeo preview iframe.
12561
+ *
12562
+ * Flow:
12563
+ * 1. User clicks "Sign in with NetSuite".
12564
+ * 2. Browser navigates to the Worker /auth/netsuite/start.
12565
+ * 3. Worker redirects to NetSuite's OAuth UI with PKCE.
12566
+ * 4. NetSuite redirects back to the Worker /auth/netsuite/callback.
12567
+ * 5. Worker exchanges the code, mints a session id, then redirects to
12568
+ * <return_to>#nssid=<sid>. URL fragments stay in the browser only.
12569
+ * 6. This module reads the fragment on load, stashes the sid in
12570
+ * sessionStorage, and sends it as Authorization: Bearer on every
12571
+ * Worker call.
12572
+ *
12573
+ * NEVER use a hardcoded password gate. NEVER use sessionStorage as the
12574
+ * authoritative auth state -- the only acceptable check is /api/me on the
12575
+ * Worker. sessionStorage here is just a cache of the bearer token.
12576
+ */
12577
+
12578
+ export const WORKER_URL = import.meta.env.VITE_WORKER_URL ?? '';
12579
+ const TOKEN_KEY = 'nssid';
12580
+
12581
+ // Capture-and-strip the #nssid=... fragment as early as possible so URLs
12582
+ // shown to the user stay clean. Runs once at module load.
12583
+ (function bootstrapTokenFromHash() {
12584
+ if (typeof window === 'undefined') return;
12585
+ const hash = window.location.hash.replace(/^#/, '');
12586
+ if (!hash) return;
12587
+ const params = new URLSearchParams(hash);
12588
+ const sid = params.get(TOKEN_KEY);
12589
+ if (sid) {
12590
+ try { sessionStorage.setItem(TOKEN_KEY, sid); } catch {}
12591
+ params.delete(TOKEN_KEY);
12592
+ const remaining = params.toString();
12593
+ const newHash = remaining ? '#' + remaining : '';
12594
+ window.history.replaceState(null, '', window.location.pathname + window.location.search + newHash);
12595
+ }
12596
+ })();
12597
+
12598
+ export function getSessionToken(): string | null {
12599
+ try { return sessionStorage.getItem(TOKEN_KEY); } catch { return null; }
12600
+ }
12601
+
12602
+ export function signInWithNetSuite(returnTo: string = window.location.href) {
12603
+ if (!WORKER_URL) {
12604
+ throw new Error(
12605
+ 'VITE_WORKER_URL is not set. HelloLeo Cloud must be provisioned before sign-in works.',
12606
+ );
12607
+ }
12608
+ const url = new URL(\`\${WORKER_URL.replace(/\\/$/, '')}/auth/netsuite/start\`);
12609
+ url.searchParams.set('return_to', returnTo);
12610
+ // The app usually renders inside the HelloLeo preview iframe. NetSuite's
12611
+ // OAuth page sets X-Frame-Options: DENY, so navigating the iframe to the
12612
+ // Worker (which 302s to NetSuite) ends up loading a page the browser
12613
+ // refuses to render -- looks like "nothing happens" to the user. Navigate
12614
+ // the top frame instead so the OAuth flow runs at the top level and the
12615
+ // callback redirect lands on the same top frame, which then reads the
12616
+ // #nssid= fragment. Fallback to same-frame navigation if the top window
12617
+ // is cross-origin and can't be reassigned.
12618
+ try {
12619
+ if (window.top && window.top !== window) {
12620
+ window.top.location.assign(url.toString());
12621
+ return;
12622
+ }
12623
+ } catch {
12624
+ /* top window not accessible \u2014 fall through to same-frame navigation */
12625
+ }
12626
+ window.location.assign(url.toString());
12627
+ }
12628
+
12629
+ export interface NetSuiteSession {
12630
+ authenticated: boolean;
12631
+ account_id?: string;
12632
+ user_id?: string;
12633
+ email?: string;
12634
+ }
12635
+
12636
+ export async function getNetSuiteSession(): Promise<NetSuiteSession> {
12637
+ if (!WORKER_URL) return { authenticated: false };
12638
+ const sid = getSessionToken();
12639
+ if (!sid) return { authenticated: false };
12640
+ const res = await fetch(\`\${WORKER_URL.replace(/\\/$/, '')}/api/me\`, {
12641
+ headers: { Authorization: 'Bearer ' + sid },
12642
+ });
12643
+ if (!res.ok) return { authenticated: false };
12644
+ const data = await res.json();
12645
+ return { authenticated: Boolean(data?.account_id), ...data };
12646
+ }
12647
+
12648
+ export async function signOutNetSuite(): Promise<void> {
12649
+ if (!WORKER_URL) return;
12650
+ const sid = getSessionToken();
12651
+ if (sid) {
12652
+ try {
12653
+ await fetch(\`\${WORKER_URL.replace(/\\/$/, '')}/auth/netsuite/logout\`, {
12654
+ method: 'POST',
12655
+ headers: { Authorization: 'Bearer ' + sid },
12656
+ });
12657
+ } catch {}
12658
+ }
12659
+ try { sessionStorage.removeItem(TOKEN_KEY); } catch {}
12660
+ window.location.reload();
12661
+ }
12662
+
12663
+ /**
12664
+ * Helper for ALL other Worker calls (your dashboard endpoints, etc.).
12665
+ * Always go through this instead of bare fetch -- it injects the bearer
12666
+ * token and routes through the Worker so NetSuite tokens stay server-side.
12667
+ */
12668
+ export async function workerFetch(pathOrUrl: string, init: RequestInit = {}): Promise<Response> {
12669
+ if (!WORKER_URL) throw new Error('VITE_WORKER_URL is not set');
12670
+ const url = pathOrUrl.startsWith('http')
12671
+ ? pathOrUrl
12672
+ : \`\${WORKER_URL.replace(/\\/$/, '')}\${pathOrUrl.startsWith('/') ? '' : '/'}\${pathOrUrl}\`;
12673
+ const sid = getSessionToken();
12674
+ const headers = new Headers(init.headers ?? {});
12675
+ if (sid) headers.set('Authorization', 'Bearer ' + sid);
12676
+ return fetch(url, { ...init, headers });
12677
+ }
12678
+ `;
12679
+ }
12680
+ function signInButtonTsx() {
12681
+ return `import { signInWithNetSuite } from '../../lib/netsuite';
12682
+
12683
+ export function SignInWithNetSuite() {
12684
+ return (
12685
+ <button
12686
+ onClick={() => signInWithNetSuite()}
12687
+ className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
12688
+ >
12689
+ Sign in with NetSuite
12690
+ </button>
12691
+ );
12692
+ }
12693
+ `;
12694
+ }
12695
+ function netsuiteLoginPageTsx() {
12696
+ return `import { SignInWithNetSuite } from './SignInWithNetSuite';
12697
+
12698
+ /**
12699
+ * Default unauthenticated landing page. Replaces any password gate.
12700
+ * Customise copy / imagery freely but keep <SignInWithNetSuite /> as the
12701
+ * only call-to-action -- it points to the Worker's /auth/netsuite/start.
12702
+ */
12703
+ export function LoginPage() {
12704
+ return (
12705
+ <div className="min-h-screen bg-background text-foreground flex">
12706
+ <div className="hidden lg:flex lg:w-1/2 bg-primary text-primary-foreground p-12 flex-col justify-between">
12707
+ <div className="text-xl font-semibold">NetSuite App</div>
12708
+ <div>
12709
+ <h1 className="text-4xl font-bold leading-tight">
12710
+ Connect your NetSuite account
12711
+ </h1>
12712
+ <p className="mt-4 text-primary-foreground/80 max-w-md">
12713
+ Sign in with your NetSuite credentials to access your data securely.
12714
+ Tokens stay server-side on HelloLeo Cloud -- they never reach the
12715
+ browser.
12716
+ </p>
12717
+ </div>
12718
+ <div className="text-xs text-primary-foreground/60">
12719
+ Powered by HelloLeo
12720
+ </div>
12721
+ </div>
12722
+ <div className="flex-1 flex items-center justify-center px-6 py-12">
12723
+ <div className="w-full max-w-sm space-y-6">
12724
+ <div>
12725
+ <h2 className="text-2xl font-semibold">Welcome</h2>
12726
+ <p className="mt-2 text-sm text-muted-foreground">
12727
+ Use the button below to sign in. You'll be redirected to NetSuite
12728
+ to authorise access, then back here.
12729
+ </p>
12730
+ </div>
12731
+ <SignInWithNetSuite />
12732
+ </div>
12733
+ </div>
12734
+ </div>
12735
+ );
12736
+ }
12737
+ `;
12738
+ }
12739
+ function netsuiteAuthGateTsx() {
12740
+ return `import { useEffect, useState } from 'react';
12741
+ import { LoginPage } from './LoginPage';
12742
+ import { getNetSuiteSession, type NetSuiteSession } from '../../lib/netsuite';
12743
+
12744
+ /**
12745
+ * Mandatory auth gate for NetSuite projects. Wrap your real App content with
12746
+ * <AuthGate>...</AuthGate>. Never render NetSuite data without this gate -- it
12747
+ * is the ONLY supported authentication for a NetSuite project (no password
12748
+ * gates, no sessionStorage flags, no shared credential).
12749
+ *
12750
+ * Pattern in src/App.tsx:
12751
+ *
12752
+ * import { AuthGate } from './components/auth/AuthGate';
12753
+ * export default function App() {
12754
+ * return (
12755
+ * <AuthGate>
12756
+ * <Dashboard /> // your authenticated content
12757
+ * </AuthGate>
12758
+ * );
12759
+ * }
12760
+ */
12761
+ export function AuthGate({ children }: { children: React.ReactNode }) {
12762
+ const [session, setSession] = useState<NetSuiteSession | null>(null);
12763
+
12764
+ useEffect(() => { getNetSuiteSession().then(setSession); }, []);
12765
+
12766
+ if (session === null) {
12767
+ return (
12768
+ <div className="min-h-screen flex items-center justify-center bg-background">
12769
+ <div className="h-8 w-8 rounded-full border-2 border-primary border-t-transparent animate-spin" />
12770
+ </div>
12771
+ );
12772
+ }
12773
+
12774
+ if (!session.authenticated) return <LoginPage />;
12775
+
12776
+ return <>{children}</>;
12777
+ }
12778
+ `;
12779
+ }
12780
+ function netsuiteAppTsx() {
12781
+ return `import { AuthGate } from './components/auth/AuthGate';
12782
+
12783
+ /**
12784
+ * NetSuite project entry point. KEEP <AuthGate> as the outermost element --
12785
+ * removing it disables real OAuth and exposes NetSuite data to anonymous
12786
+ * users. Build your dashboard / pages inside the gate.
12787
+ */
12788
+ export default function App() {
12789
+ return (
12790
+ <AuthGate>
12791
+ <div className="min-h-screen bg-background text-foreground p-8">
12792
+ <h1 className="text-2xl font-bold">You are signed in to NetSuite.</h1>
12793
+ <p className="text-muted-foreground mt-2">
12794
+ Replace this placeholder with your dashboard.
12795
+ </p>
12796
+ </div>
12797
+ </AuthGate>
12798
+ );
12799
+ }
12800
+ `;
12801
+ }
12802
+
12803
+ // src/tools/scaffold.ts
12547
12804
  function packageJson(name) {
12548
12805
  return JSON.stringify({
12549
12806
  name,
@@ -12908,243 +13165,6 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
12908
13165
  </React.StrictMode>,
12909
13166
  )`;
12910
13167
  }
12911
- function netsuiteTs() {
12912
- return `/*
12913
- * NetSuite OAuth client helper (bearer-token-in-fragment).
12914
- *
12915
- * Two NetSuite Integration Records back this:
12916
- * 1. MCP (scope: mcp) -- used by HelloLeo at build time.
12917
- * 2. Runtime (scope: rest_webservices) -- used here at sign-in time.
12918
- * Runtime credentials live as HelloLeo Cloud secrets on the project's Worker
12919
- * (env.NETSUITE_ACCOUNT_ID / _CLIENT_ID / _CLIENT_SECRET). They never reach
12920
- * the browser. Cookies are NOT used -- frontend \u2194 Worker are cross-site
12921
- * (e.g. *.helloleo.dev <-> *.workers.dev) and Chrome partitions / drops
12922
- * third-party cookies in the HelloLeo preview iframe.
12923
- *
12924
- * Flow:
12925
- * 1. User clicks "Sign in with NetSuite".
12926
- * 2. Browser navigates to the Worker /auth/netsuite/start.
12927
- * 3. Worker redirects to NetSuite's OAuth UI with PKCE.
12928
- * 4. NetSuite redirects back to the Worker /auth/netsuite/callback.
12929
- * 5. Worker exchanges the code, mints a session id, then redirects to
12930
- * <return_to>#nssid=<sid>. URL fragments stay in the browser only.
12931
- * 6. This module reads the fragment on load, stashes the sid in
12932
- * sessionStorage, and sends it as Authorization: Bearer on every
12933
- * Worker call.
12934
- *
12935
- * NEVER use a hardcoded password gate. NEVER use sessionStorage as the
12936
- * authoritative auth state -- the only acceptable check is /api/me on the
12937
- * Worker. sessionStorage here is just a cache of the bearer token.
12938
- */
12939
-
12940
- export const WORKER_URL = import.meta.env.VITE_WORKER_URL ?? '';
12941
- const TOKEN_KEY = 'nssid';
12942
-
12943
- // Capture-and-strip the #nssid=... fragment as early as possible so URLs
12944
- // shown to the user stay clean. Runs once at module load.
12945
- (function bootstrapTokenFromHash() {
12946
- if (typeof window === 'undefined') return;
12947
- const hash = window.location.hash.replace(/^#/, '');
12948
- if (!hash) return;
12949
- const params = new URLSearchParams(hash);
12950
- const sid = params.get(TOKEN_KEY);
12951
- if (sid) {
12952
- try { sessionStorage.setItem(TOKEN_KEY, sid); } catch {}
12953
- params.delete(TOKEN_KEY);
12954
- const remaining = params.toString();
12955
- const newHash = remaining ? '#' + remaining : '';
12956
- window.history.replaceState(null, '', window.location.pathname + window.location.search + newHash);
12957
- }
12958
- })();
12959
-
12960
- export function getSessionToken(): string | null {
12961
- try { return sessionStorage.getItem(TOKEN_KEY); } catch { return null; }
12962
- }
12963
-
12964
- export function signInWithNetSuite(returnTo: string = window.location.href) {
12965
- if (!WORKER_URL) {
12966
- throw new Error(
12967
- 'VITE_WORKER_URL is not set. HelloLeo Cloud must be provisioned before sign-in works.',
12968
- );
12969
- }
12970
- const url = new URL(\`\${WORKER_URL.replace(/\\/$/, '')}/auth/netsuite/start\`);
12971
- url.searchParams.set('return_to', returnTo);
12972
- window.location.assign(url.toString());
12973
- }
12974
-
12975
- export interface NetSuiteSession {
12976
- authenticated: boolean;
12977
- account_id?: string;
12978
- user_id?: string;
12979
- email?: string;
12980
- }
12981
-
12982
- export async function getNetSuiteSession(): Promise<NetSuiteSession> {
12983
- if (!WORKER_URL) return { authenticated: false };
12984
- const sid = getSessionToken();
12985
- if (!sid) return { authenticated: false };
12986
- const res = await fetch(\`\${WORKER_URL.replace(/\\/$/, '')}/api/me\`, {
12987
- headers: { Authorization: 'Bearer ' + sid },
12988
- });
12989
- if (!res.ok) return { authenticated: false };
12990
- const data = await res.json();
12991
- return { authenticated: Boolean(data?.account_id), ...data };
12992
- }
12993
-
12994
- export async function signOutNetSuite(): Promise<void> {
12995
- if (!WORKER_URL) return;
12996
- const sid = getSessionToken();
12997
- if (sid) {
12998
- try {
12999
- await fetch(\`\${WORKER_URL.replace(/\\/$/, '')}/auth/netsuite/logout\`, {
13000
- method: 'POST',
13001
- headers: { Authorization: 'Bearer ' + sid },
13002
- });
13003
- } catch {}
13004
- }
13005
- try { sessionStorage.removeItem(TOKEN_KEY); } catch {}
13006
- window.location.reload();
13007
- }
13008
-
13009
- /**
13010
- * Helper for ALL other Worker calls (your dashboard endpoints, etc.).
13011
- * Always go through this instead of bare fetch -- it injects the bearer
13012
- * token and routes through the Worker so NetSuite tokens stay server-side.
13013
- */
13014
- export async function workerFetch(pathOrUrl: string, init: RequestInit = {}): Promise<Response> {
13015
- if (!WORKER_URL) throw new Error('VITE_WORKER_URL is not set');
13016
- const url = pathOrUrl.startsWith('http')
13017
- ? pathOrUrl
13018
- : \`\${WORKER_URL.replace(/\\/$/, '')}\${pathOrUrl.startsWith('/') ? '' : '/'}\${pathOrUrl}\`;
13019
- const sid = getSessionToken();
13020
- const headers = new Headers(init.headers ?? {});
13021
- if (sid) headers.set('Authorization', 'Bearer ' + sid);
13022
- return fetch(url, { ...init, headers });
13023
- }
13024
- `;
13025
- }
13026
- function signInButtonTsx() {
13027
- return `import { signInWithNetSuite } from '../../lib/netsuite';
13028
-
13029
- export function SignInWithNetSuite() {
13030
- return (
13031
- <button
13032
- onClick={() => signInWithNetSuite()}
13033
- className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
13034
- >
13035
- Sign in with NetSuite
13036
- </button>
13037
- );
13038
- }
13039
- `;
13040
- }
13041
- function netsuiteLoginPageTsx() {
13042
- return `import { SignInWithNetSuite } from './SignInWithNetSuite';
13043
-
13044
- /**
13045
- * Default unauthenticated landing page. Replaces any password gate.
13046
- * Customise copy / imagery freely but keep <SignInWithNetSuite /> as the
13047
- * only call-to-action -- it points to the Worker's /auth/netsuite/start.
13048
- */
13049
- export function LoginPage() {
13050
- return (
13051
- <div className="min-h-screen bg-background text-foreground flex">
13052
- <div className="hidden lg:flex lg:w-1/2 bg-primary text-primary-foreground p-12 flex-col justify-between">
13053
- <div className="text-xl font-semibold">NetSuite App</div>
13054
- <div>
13055
- <h1 className="text-4xl font-bold leading-tight">
13056
- Connect your NetSuite account
13057
- </h1>
13058
- <p className="mt-4 text-primary-foreground/80 max-w-md">
13059
- Sign in with your NetSuite credentials to access your data securely.
13060
- Tokens stay server-side on HelloLeo Cloud -- they never reach the
13061
- browser.
13062
- </p>
13063
- </div>
13064
- <div className="text-xs text-primary-foreground/60">
13065
- Powered by HelloLeo
13066
- </div>
13067
- </div>
13068
- <div className="flex-1 flex items-center justify-center px-6 py-12">
13069
- <div className="w-full max-w-sm space-y-6">
13070
- <div>
13071
- <h2 className="text-2xl font-semibold">Welcome</h2>
13072
- <p className="mt-2 text-sm text-muted-foreground">
13073
- Use the button below to sign in. You'll be redirected to NetSuite
13074
- to authorise access, then back here.
13075
- </p>
13076
- </div>
13077
- <SignInWithNetSuite />
13078
- </div>
13079
- </div>
13080
- </div>
13081
- );
13082
- }
13083
- `;
13084
- }
13085
- function netsuiteAuthGateTsx() {
13086
- return `import { useEffect, useState } from 'react';
13087
- import { LoginPage } from './LoginPage';
13088
- import { getNetSuiteSession, type NetSuiteSession } from '../../lib/netsuite';
13089
-
13090
- /**
13091
- * Mandatory auth gate for NetSuite projects. Wrap your real App content with
13092
- * <AuthGate>...</AuthGate>. Never render NetSuite data without this gate -- it
13093
- * is the ONLY supported authentication for a NetSuite project (no password
13094
- * gates, no sessionStorage flags, no shared credential).
13095
- *
13096
- * Pattern in src/App.tsx:
13097
- *
13098
- * import { AuthGate } from './components/auth/AuthGate';
13099
- * export default function App() {
13100
- * return (
13101
- * <AuthGate>
13102
- * <Dashboard /> {/* your authenticated content */}
13103
- * </AuthGate>
13104
- * );
13105
- * }
13106
- */
13107
- export function AuthGate({ children }: { children: React.ReactNode }) {
13108
- const [session, setSession] = useState<NetSuiteSession | null>(null);
13109
-
13110
- useEffect(() => { getNetSuiteSession().then(setSession); }, []);
13111
-
13112
- if (session === null) {
13113
- return (
13114
- <div className="min-h-screen flex items-center justify-center bg-background">
13115
- <div className="h-8 w-8 rounded-full border-2 border-primary border-t-transparent animate-spin" />
13116
- </div>
13117
- );
13118
- }
13119
-
13120
- if (!session.authenticated) return <LoginPage />;
13121
-
13122
- return <>{children}</>;
13123
- }
13124
- `;
13125
- }
13126
- function netsuiteAppTsx() {
13127
- return `import { AuthGate } from './components/auth/AuthGate';
13128
-
13129
- /**
13130
- * NetSuite project entry point. KEEP <AuthGate> as the outermost element --
13131
- * removing it disables real OAuth and exposes NetSuite data to anonymous
13132
- * users. Build your dashboard / pages inside the gate.
13133
- */
13134
- export default function App() {
13135
- return (
13136
- <AuthGate>
13137
- <div className="min-h-screen bg-background text-foreground p-8">
13138
- <h1 className="text-2xl font-bold">You are signed in to NetSuite.</h1>
13139
- <p className="text-muted-foreground mt-2">
13140
- Replace this placeholder with your dashboard.
13141
- </p>
13142
- </div>
13143
- </AuthGate>
13144
- );
13145
- }
13146
- `;
13147
- }
13148
13168
  var scaffold = tool({
13149
13169
  description: "Scaffold a new React + Vite + Tailwind CSS project with the HelloLeo design system. " + "Creates all mandatory boilerplate: package.json, index.html (with Google Fonts), " + "vite.config.js, tailwind.config.js, postcss.config.js, src/index.css (CSS variables " + "light+dark), src/lib/utils.ts (cn helper), and src/main.tsx. " + "Call this FIRST for any new project before writing App.tsx and components.",
13150
13170
  args: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@helloleo/plugins",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "OpenCode plugins for HelloLeo",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -0,0 +1,268 @@
1
+ /**
2
+ * NetSuite-specific scaffold templates.
3
+ *
4
+ * Extracted from scaffold.ts so the OAuth bits (client helper, sign-in
5
+ * button, login page, auth gate, gated App.tsx entry point) live in one
6
+ * file. Imported and emitted by scaffold.ts when the caller passes
7
+ * `integrations: ["netsuite"]`. The string contents are byte-for-byte
8
+ * identical to the previous inline versions — splitting is purely
9
+ * organisational and does NOT change scaffold output.
10
+ */
11
+
12
+ export function netsuiteTs(): string {
13
+ return `/*
14
+ * NetSuite OAuth client helper (bearer-token-in-fragment).
15
+ *
16
+ * Two NetSuite Integration Records back this:
17
+ * 1. MCP (scope: mcp) -- used by HelloLeo at build time.
18
+ * 2. Runtime (scope: rest_webservices) -- used here at sign-in time.
19
+ * Runtime credentials live as HelloLeo Cloud secrets on the project's Worker
20
+ * (env.NETSUITE_ACCOUNT_ID / _CLIENT_ID / _CLIENT_SECRET). They never reach
21
+ * the browser. Cookies are NOT used -- frontend ↔ Worker are cross-site
22
+ * (e.g. *.helloleo.dev <-> *.workers.dev) and Chrome partitions / drops
23
+ * third-party cookies in the HelloLeo preview iframe.
24
+ *
25
+ * Flow:
26
+ * 1. User clicks "Sign in with NetSuite".
27
+ * 2. Browser navigates to the Worker /auth/netsuite/start.
28
+ * 3. Worker redirects to NetSuite's OAuth UI with PKCE.
29
+ * 4. NetSuite redirects back to the Worker /auth/netsuite/callback.
30
+ * 5. Worker exchanges the code, mints a session id, then redirects to
31
+ * <return_to>#nssid=<sid>. URL fragments stay in the browser only.
32
+ * 6. This module reads the fragment on load, stashes the sid in
33
+ * sessionStorage, and sends it as Authorization: Bearer on every
34
+ * Worker call.
35
+ *
36
+ * NEVER use a hardcoded password gate. NEVER use sessionStorage as the
37
+ * authoritative auth state -- the only acceptable check is /api/me on the
38
+ * Worker. sessionStorage here is just a cache of the bearer token.
39
+ */
40
+
41
+ export const WORKER_URL = import.meta.env.VITE_WORKER_URL ?? '';
42
+ const TOKEN_KEY = 'nssid';
43
+
44
+ // Capture-and-strip the #nssid=... fragment as early as possible so URLs
45
+ // shown to the user stay clean. Runs once at module load.
46
+ (function bootstrapTokenFromHash() {
47
+ if (typeof window === 'undefined') return;
48
+ const hash = window.location.hash.replace(/^#/, '');
49
+ if (!hash) return;
50
+ const params = new URLSearchParams(hash);
51
+ const sid = params.get(TOKEN_KEY);
52
+ if (sid) {
53
+ try { sessionStorage.setItem(TOKEN_KEY, sid); } catch {}
54
+ params.delete(TOKEN_KEY);
55
+ const remaining = params.toString();
56
+ const newHash = remaining ? '#' + remaining : '';
57
+ window.history.replaceState(null, '', window.location.pathname + window.location.search + newHash);
58
+ }
59
+ })();
60
+
61
+ export function getSessionToken(): string | null {
62
+ try { return sessionStorage.getItem(TOKEN_KEY); } catch { return null; }
63
+ }
64
+
65
+ export function signInWithNetSuite(returnTo: string = window.location.href) {
66
+ if (!WORKER_URL) {
67
+ throw new Error(
68
+ 'VITE_WORKER_URL is not set. HelloLeo Cloud must be provisioned before sign-in works.',
69
+ );
70
+ }
71
+ const url = new URL(\`\${WORKER_URL.replace(/\\/$/, '')}/auth/netsuite/start\`);
72
+ url.searchParams.set('return_to', returnTo);
73
+ // The app usually renders inside the HelloLeo preview iframe. NetSuite's
74
+ // OAuth page sets X-Frame-Options: DENY, so navigating the iframe to the
75
+ // Worker (which 302s to NetSuite) ends up loading a page the browser
76
+ // refuses to render -- looks like "nothing happens" to the user. Navigate
77
+ // the top frame instead so the OAuth flow runs at the top level and the
78
+ // callback redirect lands on the same top frame, which then reads the
79
+ // #nssid= fragment. Fallback to same-frame navigation if the top window
80
+ // is cross-origin and can't be reassigned.
81
+ try {
82
+ if (window.top && window.top !== window) {
83
+ window.top.location.assign(url.toString());
84
+ return;
85
+ }
86
+ } catch {
87
+ /* top window not accessible — fall through to same-frame navigation */
88
+ }
89
+ window.location.assign(url.toString());
90
+ }
91
+
92
+ export interface NetSuiteSession {
93
+ authenticated: boolean;
94
+ account_id?: string;
95
+ user_id?: string;
96
+ email?: string;
97
+ }
98
+
99
+ export async function getNetSuiteSession(): Promise<NetSuiteSession> {
100
+ if (!WORKER_URL) return { authenticated: false };
101
+ const sid = getSessionToken();
102
+ if (!sid) return { authenticated: false };
103
+ const res = await fetch(\`\${WORKER_URL.replace(/\\/$/, '')}/api/me\`, {
104
+ headers: { Authorization: 'Bearer ' + sid },
105
+ });
106
+ if (!res.ok) return { authenticated: false };
107
+ const data = await res.json();
108
+ return { authenticated: Boolean(data?.account_id), ...data };
109
+ }
110
+
111
+ export async function signOutNetSuite(): Promise<void> {
112
+ if (!WORKER_URL) return;
113
+ const sid = getSessionToken();
114
+ if (sid) {
115
+ try {
116
+ await fetch(\`\${WORKER_URL.replace(/\\/$/, '')}/auth/netsuite/logout\`, {
117
+ method: 'POST',
118
+ headers: { Authorization: 'Bearer ' + sid },
119
+ });
120
+ } catch {}
121
+ }
122
+ try { sessionStorage.removeItem(TOKEN_KEY); } catch {}
123
+ window.location.reload();
124
+ }
125
+
126
+ /**
127
+ * Helper for ALL other Worker calls (your dashboard endpoints, etc.).
128
+ * Always go through this instead of bare fetch -- it injects the bearer
129
+ * token and routes through the Worker so NetSuite tokens stay server-side.
130
+ */
131
+ export async function workerFetch(pathOrUrl: string, init: RequestInit = {}): Promise<Response> {
132
+ if (!WORKER_URL) throw new Error('VITE_WORKER_URL is not set');
133
+ const url = pathOrUrl.startsWith('http')
134
+ ? pathOrUrl
135
+ : \`\${WORKER_URL.replace(/\\/$/, '')}\${pathOrUrl.startsWith('/') ? '' : '/'}\${pathOrUrl}\`;
136
+ const sid = getSessionToken();
137
+ const headers = new Headers(init.headers ?? {});
138
+ if (sid) headers.set('Authorization', 'Bearer ' + sid);
139
+ return fetch(url, { ...init, headers });
140
+ }
141
+ `;
142
+ }
143
+
144
+ export function signInButtonTsx(): string {
145
+ return `import { signInWithNetSuite } from '../../lib/netsuite';
146
+
147
+ export function SignInWithNetSuite() {
148
+ return (
149
+ <button
150
+ onClick={() => signInWithNetSuite()}
151
+ className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
152
+ >
153
+ Sign in with NetSuite
154
+ </button>
155
+ );
156
+ }
157
+ `;
158
+ }
159
+
160
+ export function netsuiteLoginPageTsx(): string {
161
+ return `import { SignInWithNetSuite } from './SignInWithNetSuite';
162
+
163
+ /**
164
+ * Default unauthenticated landing page. Replaces any password gate.
165
+ * Customise copy / imagery freely but keep <SignInWithNetSuite /> as the
166
+ * only call-to-action -- it points to the Worker's /auth/netsuite/start.
167
+ */
168
+ export function LoginPage() {
169
+ return (
170
+ <div className="min-h-screen bg-background text-foreground flex">
171
+ <div className="hidden lg:flex lg:w-1/2 bg-primary text-primary-foreground p-12 flex-col justify-between">
172
+ <div className="text-xl font-semibold">NetSuite App</div>
173
+ <div>
174
+ <h1 className="text-4xl font-bold leading-tight">
175
+ Connect your NetSuite account
176
+ </h1>
177
+ <p className="mt-4 text-primary-foreground/80 max-w-md">
178
+ Sign in with your NetSuite credentials to access your data securely.
179
+ Tokens stay server-side on HelloLeo Cloud -- they never reach the
180
+ browser.
181
+ </p>
182
+ </div>
183
+ <div className="text-xs text-primary-foreground/60">
184
+ Powered by HelloLeo
185
+ </div>
186
+ </div>
187
+ <div className="flex-1 flex items-center justify-center px-6 py-12">
188
+ <div className="w-full max-w-sm space-y-6">
189
+ <div>
190
+ <h2 className="text-2xl font-semibold">Welcome</h2>
191
+ <p className="mt-2 text-sm text-muted-foreground">
192
+ Use the button below to sign in. You'll be redirected to NetSuite
193
+ to authorise access, then back here.
194
+ </p>
195
+ </div>
196
+ <SignInWithNetSuite />
197
+ </div>
198
+ </div>
199
+ </div>
200
+ );
201
+ }
202
+ `;
203
+ }
204
+
205
+ export function netsuiteAuthGateTsx(): string {
206
+ return `import { useEffect, useState } from 'react';
207
+ import { LoginPage } from './LoginPage';
208
+ import { getNetSuiteSession, type NetSuiteSession } from '../../lib/netsuite';
209
+
210
+ /**
211
+ * Mandatory auth gate for NetSuite projects. Wrap your real App content with
212
+ * <AuthGate>...</AuthGate>. Never render NetSuite data without this gate -- it
213
+ * is the ONLY supported authentication for a NetSuite project (no password
214
+ * gates, no sessionStorage flags, no shared credential).
215
+ *
216
+ * Pattern in src/App.tsx:
217
+ *
218
+ * import { AuthGate } from './components/auth/AuthGate';
219
+ * export default function App() {
220
+ * return (
221
+ * <AuthGate>
222
+ * <Dashboard /> // your authenticated content
223
+ * </AuthGate>
224
+ * );
225
+ * }
226
+ */
227
+ export function AuthGate({ children }: { children: React.ReactNode }) {
228
+ const [session, setSession] = useState<NetSuiteSession | null>(null);
229
+
230
+ useEffect(() => { getNetSuiteSession().then(setSession); }, []);
231
+
232
+ if (session === null) {
233
+ return (
234
+ <div className="min-h-screen flex items-center justify-center bg-background">
235
+ <div className="h-8 w-8 rounded-full border-2 border-primary border-t-transparent animate-spin" />
236
+ </div>
237
+ );
238
+ }
239
+
240
+ if (!session.authenticated) return <LoginPage />;
241
+
242
+ return <>{children}</>;
243
+ }
244
+ `;
245
+ }
246
+
247
+ export function netsuiteAppTsx(): string {
248
+ return `import { AuthGate } from './components/auth/AuthGate';
249
+
250
+ /**
251
+ * NetSuite project entry point. KEEP <AuthGate> as the outermost element --
252
+ * removing it disables real OAuth and exposes NetSuite data to anonymous
253
+ * users. Build your dashboard / pages inside the gate.
254
+ */
255
+ export default function App() {
256
+ return (
257
+ <AuthGate>
258
+ <div className="min-h-screen bg-background text-foreground p-8">
259
+ <h1 className="text-2xl font-bold">You are signed in to NetSuite.</h1>
260
+ <p className="text-muted-foreground mt-2">
261
+ Replace this placeholder with your dashboard.
262
+ </p>
263
+ </div>
264
+ </AuthGate>
265
+ );
266
+ }
267
+ `;
268
+ }
@@ -2,6 +2,13 @@ import { mkdir } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import type { Plugin } from "@opencode-ai/plugin";
4
4
  import { tool } from "@opencode-ai/plugin";
5
+ import {
6
+ netsuiteAppTsx,
7
+ netsuiteAuthGateTsx,
8
+ netsuiteLoginPageTsx,
9
+ netsuiteTs,
10
+ signInButtonTsx,
11
+ } from "./scaffold-netsuite";
5
12
 
6
13
  function packageJson(name: string) {
7
14
  return JSON.stringify(
@@ -387,248 +394,6 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
387
394
  )`;
388
395
  }
389
396
 
390
- function netsuiteTs() {
391
- return `/*
392
- * NetSuite OAuth client helper (bearer-token-in-fragment).
393
- *
394
- * Two NetSuite Integration Records back this:
395
- * 1. MCP (scope: mcp) -- used by HelloLeo at build time.
396
- * 2. Runtime (scope: rest_webservices) -- used here at sign-in time.
397
- * Runtime credentials live as HelloLeo Cloud secrets on the project's Worker
398
- * (env.NETSUITE_ACCOUNT_ID / _CLIENT_ID / _CLIENT_SECRET). They never reach
399
- * the browser. Cookies are NOT used -- frontend ↔ Worker are cross-site
400
- * (e.g. *.helloleo.dev <-> *.workers.dev) and Chrome partitions / drops
401
- * third-party cookies in the HelloLeo preview iframe.
402
- *
403
- * Flow:
404
- * 1. User clicks "Sign in with NetSuite".
405
- * 2. Browser navigates to the Worker /auth/netsuite/start.
406
- * 3. Worker redirects to NetSuite's OAuth UI with PKCE.
407
- * 4. NetSuite redirects back to the Worker /auth/netsuite/callback.
408
- * 5. Worker exchanges the code, mints a session id, then redirects to
409
- * <return_to>#nssid=<sid>. URL fragments stay in the browser only.
410
- * 6. This module reads the fragment on load, stashes the sid in
411
- * sessionStorage, and sends it as Authorization: Bearer on every
412
- * Worker call.
413
- *
414
- * NEVER use a hardcoded password gate. NEVER use sessionStorage as the
415
- * authoritative auth state -- the only acceptable check is /api/me on the
416
- * Worker. sessionStorage here is just a cache of the bearer token.
417
- */
418
-
419
- export const WORKER_URL = import.meta.env.VITE_WORKER_URL ?? '';
420
- const TOKEN_KEY = 'nssid';
421
-
422
- // Capture-and-strip the #nssid=... fragment as early as possible so URLs
423
- // shown to the user stay clean. Runs once at module load.
424
- (function bootstrapTokenFromHash() {
425
- if (typeof window === 'undefined') return;
426
- const hash = window.location.hash.replace(/^#/, '');
427
- if (!hash) return;
428
- const params = new URLSearchParams(hash);
429
- const sid = params.get(TOKEN_KEY);
430
- if (sid) {
431
- try { sessionStorage.setItem(TOKEN_KEY, sid); } catch {}
432
- params.delete(TOKEN_KEY);
433
- const remaining = params.toString();
434
- const newHash = remaining ? '#' + remaining : '';
435
- window.history.replaceState(null, '', window.location.pathname + window.location.search + newHash);
436
- }
437
- })();
438
-
439
- export function getSessionToken(): string | null {
440
- try { return sessionStorage.getItem(TOKEN_KEY); } catch { return null; }
441
- }
442
-
443
- export function signInWithNetSuite(returnTo: string = window.location.href) {
444
- if (!WORKER_URL) {
445
- throw new Error(
446
- 'VITE_WORKER_URL is not set. HelloLeo Cloud must be provisioned before sign-in works.',
447
- );
448
- }
449
- const url = new URL(\`\${WORKER_URL.replace(/\\/$/, '')}/auth/netsuite/start\`);
450
- url.searchParams.set('return_to', returnTo);
451
- window.location.assign(url.toString());
452
- }
453
-
454
- export interface NetSuiteSession {
455
- authenticated: boolean;
456
- account_id?: string;
457
- user_id?: string;
458
- email?: string;
459
- }
460
-
461
- export async function getNetSuiteSession(): Promise<NetSuiteSession> {
462
- if (!WORKER_URL) return { authenticated: false };
463
- const sid = getSessionToken();
464
- if (!sid) return { authenticated: false };
465
- const res = await fetch(\`\${WORKER_URL.replace(/\\/$/, '')}/api/me\`, {
466
- headers: { Authorization: 'Bearer ' + sid },
467
- });
468
- if (!res.ok) return { authenticated: false };
469
- const data = await res.json();
470
- return { authenticated: Boolean(data?.account_id), ...data };
471
- }
472
-
473
- export async function signOutNetSuite(): Promise<void> {
474
- if (!WORKER_URL) return;
475
- const sid = getSessionToken();
476
- if (sid) {
477
- try {
478
- await fetch(\`\${WORKER_URL.replace(/\\/$/, '')}/auth/netsuite/logout\`, {
479
- method: 'POST',
480
- headers: { Authorization: 'Bearer ' + sid },
481
- });
482
- } catch {}
483
- }
484
- try { sessionStorage.removeItem(TOKEN_KEY); } catch {}
485
- window.location.reload();
486
- }
487
-
488
- /**
489
- * Helper for ALL other Worker calls (your dashboard endpoints, etc.).
490
- * Always go through this instead of bare fetch -- it injects the bearer
491
- * token and routes through the Worker so NetSuite tokens stay server-side.
492
- */
493
- export async function workerFetch(pathOrUrl: string, init: RequestInit = {}): Promise<Response> {
494
- if (!WORKER_URL) throw new Error('VITE_WORKER_URL is not set');
495
- const url = pathOrUrl.startsWith('http')
496
- ? pathOrUrl
497
- : \`\${WORKER_URL.replace(/\\/$/, '')}\${pathOrUrl.startsWith('/') ? '' : '/'}\${pathOrUrl}\`;
498
- const sid = getSessionToken();
499
- const headers = new Headers(init.headers ?? {});
500
- if (sid) headers.set('Authorization', 'Bearer ' + sid);
501
- return fetch(url, { ...init, headers });
502
- }
503
- `;
504
- }
505
-
506
- function signInButtonTsx() {
507
- return `import { signInWithNetSuite } from '../../lib/netsuite';
508
-
509
- export function SignInWithNetSuite() {
510
- return (
511
- <button
512
- onClick={() => signInWithNetSuite()}
513
- className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
514
- >
515
- Sign in with NetSuite
516
- </button>
517
- );
518
- }
519
- `;
520
- }
521
-
522
- function netsuiteLoginPageTsx() {
523
- return `import { SignInWithNetSuite } from './SignInWithNetSuite';
524
-
525
- /**
526
- * Default unauthenticated landing page. Replaces any password gate.
527
- * Customise copy / imagery freely but keep <SignInWithNetSuite /> as the
528
- * only call-to-action -- it points to the Worker's /auth/netsuite/start.
529
- */
530
- export function LoginPage() {
531
- return (
532
- <div className="min-h-screen bg-background text-foreground flex">
533
- <div className="hidden lg:flex lg:w-1/2 bg-primary text-primary-foreground p-12 flex-col justify-between">
534
- <div className="text-xl font-semibold">NetSuite App</div>
535
- <div>
536
- <h1 className="text-4xl font-bold leading-tight">
537
- Connect your NetSuite account
538
- </h1>
539
- <p className="mt-4 text-primary-foreground/80 max-w-md">
540
- Sign in with your NetSuite credentials to access your data securely.
541
- Tokens stay server-side on HelloLeo Cloud -- they never reach the
542
- browser.
543
- </p>
544
- </div>
545
- <div className="text-xs text-primary-foreground/60">
546
- Powered by HelloLeo
547
- </div>
548
- </div>
549
- <div className="flex-1 flex items-center justify-center px-6 py-12">
550
- <div className="w-full max-w-sm space-y-6">
551
- <div>
552
- <h2 className="text-2xl font-semibold">Welcome</h2>
553
- <p className="mt-2 text-sm text-muted-foreground">
554
- Use the button below to sign in. You'll be redirected to NetSuite
555
- to authorise access, then back here.
556
- </p>
557
- </div>
558
- <SignInWithNetSuite />
559
- </div>
560
- </div>
561
- </div>
562
- );
563
- }
564
- `;
565
- }
566
-
567
- function netsuiteAuthGateTsx() {
568
- return `import { useEffect, useState } from 'react';
569
- import { LoginPage } from './LoginPage';
570
- import { getNetSuiteSession, type NetSuiteSession } from '../../lib/netsuite';
571
-
572
- /**
573
- * Mandatory auth gate for NetSuite projects. Wrap your real App content with
574
- * <AuthGate>...</AuthGate>. Never render NetSuite data without this gate -- it
575
- * is the ONLY supported authentication for a NetSuite project (no password
576
- * gates, no sessionStorage flags, no shared credential).
577
- *
578
- * Pattern in src/App.tsx:
579
- *
580
- * import { AuthGate } from './components/auth/AuthGate';
581
- * export default function App() {
582
- * return (
583
- * <AuthGate>
584
- * <Dashboard /> {/* your authenticated content */}
585
- * </AuthGate>
586
- * );
587
- * }
588
- */
589
- export function AuthGate({ children }: { children: React.ReactNode }) {
590
- const [session, setSession] = useState<NetSuiteSession | null>(null);
591
-
592
- useEffect(() => { getNetSuiteSession().then(setSession); }, []);
593
-
594
- if (session === null) {
595
- return (
596
- <div className="min-h-screen flex items-center justify-center bg-background">
597
- <div className="h-8 w-8 rounded-full border-2 border-primary border-t-transparent animate-spin" />
598
- </div>
599
- );
600
- }
601
-
602
- if (!session.authenticated) return <LoginPage />;
603
-
604
- return <>{children}</>;
605
- }
606
- `;
607
- }
608
-
609
- function netsuiteAppTsx() {
610
- return `import { AuthGate } from './components/auth/AuthGate';
611
-
612
- /**
613
- * NetSuite project entry point. KEEP <AuthGate> as the outermost element --
614
- * removing it disables real OAuth and exposes NetSuite data to anonymous
615
- * users. Build your dashboard / pages inside the gate.
616
- */
617
- export default function App() {
618
- return (
619
- <AuthGate>
620
- <div className="min-h-screen bg-background text-foreground p-8">
621
- <h1 className="text-2xl font-bold">You are signed in to NetSuite.</h1>
622
- <p className="text-muted-foreground mt-2">
623
- Replace this placeholder with your dashboard.
624
- </p>
625
- </div>
626
- </AuthGate>
627
- );
628
- }
629
- `;
630
- }
631
-
632
397
  export const scaffold = tool({
633
398
  description:
634
399
  "Scaffold a new React + Vite + Tailwind CSS project with the HelloLeo design system. " +