@helloleo/plugins 0.2.17 → 0.2.19

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
@@ -24904,13 +24904,19 @@ var SCAFFOLD_TEMPLATES = {
24904
24904
  "tanstack-start": "tanstack-start-2026-07-30",
24905
24905
  "tanstack-router": "tanstack-router-2026-06-15"
24906
24906
  };
24907
+ var LEGACY_TEMPLATES = ["tanstack-start-2026-06-18"];
24907
24908
  var SCAFFOLD_VERSION = SCAFFOLD_TEMPLATES["tanstack-start"];
24908
- function resolveTemplateId() {
24909
+ function resolveTemplateId(type) {
24909
24910
  const version3 = process.env.PLUGINS_SCAFFOLD_VERSION;
24910
- const known = Object.values(SCAFFOLD_TEMPLATES);
24911
- if (version3 && known.includes(version3))
24912
- return version3;
24913
- return SCAFFOLD_TEMPLATES["tanstack-router"];
24911
+ const known = [
24912
+ ...Object.values(SCAFFOLD_TEMPLATES),
24913
+ ...LEGACY_TEMPLATES
24914
+ ];
24915
+ const pinned = version3 && known.includes(version3) ? version3 : undefined;
24916
+ if (type) {
24917
+ return pinned?.startsWith(type) ? pinned : SCAFFOLD_TEMPLATES[type];
24918
+ }
24919
+ return pinned ?? SCAFFOLD_TEMPLATES["tanstack-router"];
24914
24920
  }
24915
24921
  function projectUuidFromDir(dir) {
24916
24922
  return path3.basename(dir);
@@ -24921,13 +24927,14 @@ function integrationProxyUrl(projectUuid) {
24921
24927
  }
24922
24928
  var scaffoldOptionsSchema = exports_external2.object({
24923
24929
  name: exports_external2.string().describe("Human-readable name for SEO, e.g. 'Shipping Platform'"),
24924
- description: exports_external2.string().describe("One sentence describing the app. Used as the meta description.")
24930
+ description: exports_external2.string().describe("One sentence describing the app. Used as the meta description."),
24931
+ type: exports_external2.enum(["tanstack-start", "tanstack-router"]).optional().describe("Project type. 'tanstack-start': SSR app with API routes and a " + "database, KV and bucket \u2014 use it whenever the app needs to " + "persist data or run server-side code, and always for " + "setup_authentication (it needs server routes). " + "'tanstack-router': client-only SPA with no server and no database " + "\u2014 use it only for pure frontends that talk to external APIs. " + "Omit to use the deployment's default.")
24925
24932
  });
24926
24933
  function slugify(name) {
24927
24934
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "leo-project";
24928
24935
  }
24929
- async function writeBaseScaffold({ name, description }, dir) {
24930
- const templateId = resolveTemplateId();
24936
+ async function writeBaseScaffold({ name, description, type }, dir) {
24937
+ const templateId = resolveTemplateId(type);
24931
24938
  const projectUuid = projectUuidFromDir(dir);
24932
24939
  const created = await renderTemplate(templateId, {
24933
24940
  LEO_NAME: name,
@@ -24942,13 +24949,14 @@ async function writeBaseScaffold({ name, description }, dir) {
24942
24949
  return [...created, leoPath];
24943
24950
  }
24944
24951
  var scaffold = tool({
24945
- description: "Scaffold a new project with React 19, file-based routing (TanStack), " + "Tailwind v4, shadcn/ui, and react-query. Call this first for any new" + " project, before writing routes or components.",
24952
+ description: "Scaffold a new project with React 19, file-based routing (TanStack), " + "Tailwind v4, shadcn/ui, and react-query. Two types: 'tanstack-start' " + "(SSR, API routes, and a database, KV and bucket via @helloleo/runtime) " + "or 'tanstack-router' (client-only SPA, no server, no database). Call " + "this first for any new project, before writing routes or components.",
24946
24953
  args: {
24947
24954
  name: scaffoldOptionsSchema.shape.name,
24948
- description: scaffoldOptionsSchema.shape.description
24955
+ description: scaffoldOptionsSchema.shape.description,
24956
+ type: scaffoldOptionsSchema.shape.type
24949
24957
  },
24950
24958
  async execute(args, context) {
24951
- const isStart = resolveTemplateId() === SCAFFOLD_TEMPLATES["tanstack-start"];
24959
+ const isStart = resolveTemplateId(args.type).startsWith("tanstack-start");
24952
24960
  const created = await writeBaseScaffold(args, context.directory);
24953
24961
  const uiComponents = created.filter((f) => f.startsWith("src/components/ui/"));
24954
24962
  const rest = created.filter((f) => !f.startsWith("src/components/ui/"));
@@ -25543,9 +25551,745 @@ var SetupAuthenticationPlugin = async () => {
25543
25551
  };
25544
25552
  };
25545
25553
  // src/tools/setup-netsuite.ts
25546
- import { mkdir as mkdir2 } from "fs/promises";
25554
+ import { mkdir as mkdir2, readFile as readFile3 } from "fs/promises";
25547
25555
  import path7 from "path";
25548
- function netsuiteTs() {
25556
+ async function readScaffoldId2(dir) {
25557
+ try {
25558
+ const meta = await Bun.file(path7.join(dir, ".leo", "project.json")).json();
25559
+ return typeof meta?.scaffold === "string" ? meta.scaffold : null;
25560
+ } catch {
25561
+ return null;
25562
+ }
25563
+ }
25564
+ function schemaAppend() {
25565
+ return `
25566
+ // --- NetSuite OAuth (added by setup_netsuite) ---
25567
+ // Short-lived PKCE + return-to state between /auth/netsuite/start and its
25568
+ // callback. Single-use: the callback deletes the row after reading it.
25569
+ export const netsuiteFlows = sqliteTable('netsuite_flows', {
25570
+ flowId: text('flow_id').primaryKey(),
25571
+ codeVerifier: text('code_verifier').notNull(),
25572
+ returnTo: text('return_to').notNull(),
25573
+ createdAt: integer('created_at')
25574
+ .notNull()
25575
+ .default(sql\`(unixepoch())\`),
25576
+ })
25577
+
25578
+ // Opaque session id -> NetSuite tokens. Tokens stay server-side; the browser
25579
+ // only ever holds the sid (sent as a bearer).
25580
+ export const netsuiteSessions = sqliteTable('netsuite_sessions', {
25581
+ sid: text('sid').primaryKey(),
25582
+ accountId: text('account_id').notNull(),
25583
+ accessToken: text('access_token').notNull(),
25584
+ refreshToken: text('refresh_token'),
25585
+ expiresAt: integer('expires_at'),
25586
+ userId: text('user_id'),
25587
+ email: text('email'),
25588
+ createdAt: integer('created_at')
25589
+ .notNull()
25590
+ .default(sql\`(unixepoch())\`),
25591
+ })
25592
+ `;
25593
+ }
25594
+ function netsuiteServerTs() {
25595
+ return `/*
25596
+ * NetSuite runtime OAuth -- server side (TanStack Start server routes).
25597
+ *
25598
+ * Runs wherever the app runs: \`vite dev\` (workerd) in the Fly preview machine
25599
+ * in dev, and the published Cloudflare Worker in prod. There is no separate
25600
+ * backend Worker -- these helpers back the /auth/netsuite/* + /api/me routes.
25601
+ *
25602
+ * Config is read from the Cloudflare env binding via @helloleo/runtime.
25603
+ * Set NETSUITE_ACCOUNT_ID / _CLIENT_ID / _CLIENT_SECRET (secret optional for a
25604
+ * PKCE public client) and optional PUBLIC_APP_URL as HelloLeo Cloud secrets
25605
+ * (prod) or dev vars (preview). They never reach the browser.
25606
+ */
25607
+ import { eq } from 'drizzle-orm'
25608
+ import { env as runtimeEnv } from '@helloleo/runtime'
25609
+ import { db } from '#/db'
25610
+ import { netsuiteSessions } from '#/db/schema'
25611
+
25612
+ interface NsEnv {
25613
+ NETSUITE_ACCOUNT_ID?: string
25614
+ NETSUITE_CLIENT_ID?: string
25615
+ NETSUITE_CLIENT_SECRET?: string
25616
+ PUBLIC_APP_URL?: string
25617
+ HELLOLEO_URL?: string
25618
+ }
25619
+ const nsEnv = runtimeEnv as unknown as NsEnv
25620
+
25621
+ // Runtime record scope. The app signs end-users in for REST/SuiteQL.
25622
+ export const SCOPE = 'rest_webservices'
25623
+ const REFRESH_LEEWAY_SECONDS = 60
25624
+
25625
+ export function requireConfig() {
25626
+ const accountId = nsEnv.NETSUITE_ACCOUNT_ID
25627
+ const clientId = nsEnv.NETSUITE_CLIENT_ID
25628
+ if (!accountId || !clientId) {
25629
+ throw new Error(
25630
+ 'NetSuite not configured: set NETSUITE_ACCOUNT_ID and NETSUITE_CLIENT_ID (and NETSUITE_CLIENT_SECRET for a confidential client) as HelloLeo Cloud secrets / dev vars.',
25631
+ )
25632
+ }
25633
+ return { accountId, clientId, clientSecret: nsEnv.NETSUITE_CLIENT_SECRET || '' }
25634
+ }
25635
+
25636
+ // Account id -> DNS host form: lowercase, underscores to hyphens.
25637
+ function host(accountId: string) {
25638
+ return accountId.trim().toLowerCase().replace(/_/g, '-')
25639
+ }
25640
+ export function authorizeUrl(accountId: string) {
25641
+ return \`https://\${host(accountId)}.app.netsuite.com/app/login/oauth2/authorize.nl\`
25642
+ }
25643
+ export function tokenUrl(accountId: string) {
25644
+ return \`https://\${host(accountId)}.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token\`
25645
+ }
25646
+ export function restBase(accountId: string) {
25647
+ return \`https://\${host(accountId)}.suitetalk.api.netsuite.com\`
25648
+ }
25649
+
25650
+ function stripTrailingSlash(s: string) {
25651
+ return s.endsWith('/') ? s.slice(0, -1) : s
25652
+ }
25653
+
25654
+ // Public origin of THIS app, used to build the redirect URI. Prefer an explicit
25655
+ // PUBLIC_APP_URL; else derive from the request (honouring the preview proxy's
25656
+ // forwarded headers). Must match a redirect URI registered on the NetSuite
25657
+ // Integration Record exactly.
25658
+ export function appOrigin(request: Request) {
25659
+ // 1) Explicit override wins (set by the platform per environment).
25660
+ if (nsEnv.PUBLIC_APP_URL) return stripTrailingSlash(nsEnv.PUBLIC_APP_URL)
25661
+ // 2) HELLOLEO_URL is injected on every deploy (the app's canonical origin,
25662
+ // a bare host with no scheme), so it's set even when the NetSuite
25663
+ // wizard's PUBLIC_APP_URL pin wasn't.
25664
+ if (nsEnv.HELLOLEO_URL) return \`https://\${stripTrailingSlash(nsEnv.HELLOLEO_URL)}\`
25665
+ // 3) Preview/prod proxies rewrite Host, so trust the forwarded/original host
25666
+ // they set (HelloLeo's nginx sends X-Original-Host) \u2014 that's the public URL
25667
+ // the browser loaded, not an internal upstream host.
25668
+ const url = new URL(request.url)
25669
+ const proto = request.headers.get('x-forwarded-proto') || url.protocol.replace(':', '')
25670
+ const hostHeader =
25671
+ request.headers.get('x-forwarded-host') ||
25672
+ request.headers.get('x-original-host') ||
25673
+ url.host
25674
+ return \`\${proto}://\${hostHeader}\`
25675
+ }
25676
+ export function redirectUri(request: Request) {
25677
+ return \`\${appOrigin(request)}/auth/netsuite/callback\`
25678
+ }
25679
+
25680
+ // Coerce ?return_to= to our OWN origin. The callback appends the session bearer
25681
+ // as a #nssid=... fragment; an off-origin return_to would leak that live
25682
+ // credential to an attacker-controlled page (open-redirect -> token theft).
25683
+ export function safeReturnTo(request: Request, raw: string | null): string {
25684
+ const origin = appOrigin(request)
25685
+ if (!raw) return origin
25686
+ try {
25687
+ const u = new URL(raw, origin)
25688
+ return u.origin === origin ? u.toString() : origin
25689
+ } catch {
25690
+ return origin
25691
+ }
25692
+ }
25693
+
25694
+ // --- PKCE (Web Crypto: works on workerd and Node) ---
25695
+ function b64url(bytes: Uint8Array) {
25696
+ let s = ''
25697
+ for (const b of bytes) s += String.fromCharCode(b)
25698
+ return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')
25699
+ }
25700
+ export async function pkce() {
25701
+ const verifier = b64url(crypto.getRandomValues(new Uint8Array(48)))
25702
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))
25703
+ const challenge = b64url(new Uint8Array(digest))
25704
+ return { verifier, challenge }
25705
+ }
25706
+
25707
+ interface TokenResponse {
25708
+ access_token?: string
25709
+ refresh_token?: string
25710
+ expires_in?: number
25711
+ error?: string
25712
+ error_description?: string
25713
+ }
25714
+
25715
+ // Confidential client -> HTTP Basic. Public (PKCE-only) -> client_id in body.
25716
+ function authHeaders(clientId: string, clientSecret: string, params: Record<string, string>) {
25717
+ const headers: Record<string, string> = { 'Content-Type': 'application/x-www-form-urlencoded' }
25718
+ if (clientSecret) headers.Authorization = 'Basic ' + btoa(\`\${clientId}:\${clientSecret}\`)
25719
+ else params.client_id = clientId
25720
+ return headers
25721
+ }
25722
+
25723
+ // POST the token endpoint and parse tolerantly. NetSuite returns JSON for both
25724
+ // success and OAuth errors, but a gateway (502/504) can return HTML -- never let
25725
+ // res.json() throw into the route handler (that would surface as an opaque 500
25726
+ // instead of a clean "token exchange failed").
25727
+ async function postToken(
25728
+ accountId: string,
25729
+ params: Record<string, string>,
25730
+ headers: Record<string, string>,
25731
+ ): Promise<TokenResponse> {
25732
+ let res: Response
25733
+ try {
25734
+ res = await fetch(tokenUrl(accountId), { method: 'POST', headers, body: new URLSearchParams(params) })
25735
+ } catch (e) {
25736
+ return { error: 'network_error', error_description: String(e) }
25737
+ }
25738
+ const text = await res.text()
25739
+ let data: TokenResponse = {}
25740
+ try {
25741
+ data = JSON.parse(text) as TokenResponse
25742
+ } catch {
25743
+ // non-JSON body (e.g. gateway HTML) -- leave data empty, fall through
25744
+ }
25745
+ if (!res.ok && !data.error) {
25746
+ data = { error: 'token_request_failed', error_description: 'HTTP ' + res.status }
25747
+ }
25748
+ return data
25749
+ }
25750
+
25751
+ export async function exchangeCode(request: Request, code: string, verifier: string) {
25752
+ const { accountId, clientId, clientSecret } = requireConfig()
25753
+ const params: Record<string, string> = {
25754
+ grant_type: 'authorization_code',
25755
+ code,
25756
+ redirect_uri: redirectUri(request),
25757
+ code_verifier: verifier,
25758
+ }
25759
+ return postToken(accountId, params, authHeaders(clientId, clientSecret, params))
25760
+ }
25761
+
25762
+ async function refreshToken(refresh: string) {
25763
+ const { accountId, clientId, clientSecret } = requireConfig()
25764
+ const params: Record<string, string> = { grant_type: 'refresh_token', refresh_token: refresh }
25765
+ return postToken(accountId, params, authHeaders(clientId, clientSecret, params))
25766
+ }
25767
+
25768
+ export interface NsSession {
25769
+ sid: string
25770
+ accountId: string
25771
+ accessToken: string
25772
+ refreshToken: string | null
25773
+ expiresAt: number | null
25774
+ userId: string | null
25775
+ email: string | null
25776
+ }
25777
+
25778
+ // Load a session by sid, transparently refreshing the access token when it's
25779
+ // within the leeway of expiry. Returns null if unknown or unrefreshable.
25780
+ export async function getSession(sid: string): Promise<NsSession | null> {
25781
+ if (!sid) return null
25782
+ const rows = await db.select().from(netsuiteSessions).where(eq(netsuiteSessions.sid, sid)).limit(1)
25783
+ const s = rows[0]
25784
+ if (!s) return null
25785
+ const now = Math.floor(Date.now() / 1000)
25786
+ // A missing expiry is treated as EXPIRED (force a refresh) rather than trusting
25787
+ // the token forever -- NetSuite normally sends expires_in, so this is defensive.
25788
+ const expired = s.expiresAt == null ? true : now + REFRESH_LEEWAY_SECONDS >= s.expiresAt
25789
+ if (expired) {
25790
+ // Token expired (or about to). It MUST refresh; if it can't, the session is
25791
+ // dead \u2014 delete it and return null so /api/me reports signed-out and the user
25792
+ // re-auths, rather than a "logged in" app whose every NetSuite call 401s.
25793
+ if (!s.refreshToken) { await deleteSession(sid); return null }
25794
+ const tok = await refreshToken(s.refreshToken)
25795
+ if (!tok.access_token) { await deleteSession(sid); return null }
25796
+ const expiresAt = now + (tok.expires_in || 3600)
25797
+ const refreshTok = tok.refresh_token ?? s.refreshToken
25798
+ await db
25799
+ .update(netsuiteSessions)
25800
+ .set({ accessToken: tok.access_token, refreshToken: refreshTok, expiresAt })
25801
+ .where(eq(netsuiteSessions.sid, sid))
25802
+ return { ...s, accessToken: tok.access_token, refreshToken: refreshTok, expiresAt }
25803
+ }
25804
+ return s
25805
+ }
25806
+
25807
+ export async function deleteSession(sid: string) {
25808
+ if (sid) await db.delete(netsuiteSessions).where(eq(netsuiteSessions.sid, sid))
25809
+ }
25810
+
25811
+ export function bearer(request: Request) {
25812
+ const h = request.headers.get('authorization') || ''
25813
+ return h.startsWith('Bearer ') ? h.slice(7) : ''
25814
+ }
25815
+
25816
+ /**
25817
+ * Call NetSuite REST / SuiteQL for the signed-in session. Use this from your
25818
+ * data routes (src/routes/api/*). \`path\` is relative to the account's
25819
+ * suitetalk host, e.g. '/services/rest/query/v1/suiteql'. Returns the raw
25820
+ * fetch Response (401 if the sid is unknown). Access token is auto-refreshed.
25821
+ */
25822
+ export async function netsuiteFetch(sid: string, path: string, init: RequestInit = {}): Promise<Response> {
25823
+ const session = await getSession(sid)
25824
+ if (!session) return new Response(JSON.stringify({ error: 'unauthorized' }), { status: 401 })
25825
+ const url = path.startsWith('http') ? path : \`\${restBase(session.accountId)}\${path}\`
25826
+ const headers = new Headers(init.headers)
25827
+ headers.set('Authorization', \`Bearer \${session.accessToken}\`)
25828
+ if (init.body && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json')
25829
+ return fetch(url, { ...init, headers })
25830
+ }
25831
+ `;
25832
+ }
25833
+ function startRouteTs() {
25834
+ return `import { createFileRoute } from '@tanstack/react-router'
25835
+ import { db } from '#/db'
25836
+ import { netsuiteFlows } from '#/db/schema'
25837
+ import {
25838
+ authorizeUrl,
25839
+ pkce,
25840
+ redirectUri,
25841
+ requireConfig,
25842
+ safeReturnTo,
25843
+ SCOPE,
25844
+ } from '#/lib/netsuite-server'
25845
+
25846
+ // GET /auth/netsuite/start -- begin the NetSuite OAuth (PKCE) flow.
25847
+ export const Route = createFileRoute('/auth/netsuite/start')({
25848
+ server: {
25849
+ handlers: {
25850
+ GET: async ({ request }) => {
25851
+ const { accountId, clientId } = requireConfig()
25852
+ const url = new URL(request.url)
25853
+ // Same-origin only: the callback returns the bearer in a URL fragment.
25854
+ const returnTo = safeReturnTo(request, url.searchParams.get('return_to'))
25855
+
25856
+ const { verifier, challenge } = await pkce()
25857
+ const flowId = crypto.randomUUID()
25858
+ await db.insert(netsuiteFlows).values({ flowId, codeVerifier: verifier, returnTo })
25859
+
25860
+ const authorize = new URL(authorizeUrl(accountId))
25861
+ authorize.searchParams.set('response_type', 'code')
25862
+ authorize.searchParams.set('client_id', clientId)
25863
+ authorize.searchParams.set('redirect_uri', redirectUri(request))
25864
+ authorize.searchParams.set('scope', SCOPE)
25865
+ authorize.searchParams.set('state', flowId)
25866
+ authorize.searchParams.set('code_challenge', challenge)
25867
+ authorize.searchParams.set('code_challenge_method', 'S256')
25868
+
25869
+ return new Response(null, { status: 302, headers: { Location: authorize.toString() } })
25870
+ },
25871
+ },
25872
+ },
25873
+ })
25874
+ `;
25875
+ }
25876
+ function callbackRouteTs() {
25877
+ return `import { createFileRoute } from '@tanstack/react-router'
25878
+ import { eq } from 'drizzle-orm'
25879
+ import { db } from '#/db'
25880
+ import { netsuiteFlows, netsuiteSessions } from '#/db/schema'
25881
+ import { exchangeCode, requireConfig } from '#/lib/netsuite-server'
25882
+
25883
+ // GET /auth/netsuite/callback -- exchange the code, mint a session, hand the
25884
+ // bearer back to the SPA via the URL fragment (#nssid=...). The fragment
25885
+ // survives the HelloLeo preview iframe, where third-party cookies are dropped.
25886
+ export const Route = createFileRoute('/auth/netsuite/callback')({
25887
+ server: {
25888
+ handlers: {
25889
+ GET: async ({ request }) => {
25890
+ const url = new URL(request.url)
25891
+ const err = url.searchParams.get('error')
25892
+ if (err) return new Response(\`NetSuite authorization failed: \${err}\`, { status: 400 })
25893
+
25894
+ const code = url.searchParams.get('code')
25895
+ const state = url.searchParams.get('state')
25896
+ if (!code || !state) return new Response('Missing code or state', { status: 400 })
25897
+
25898
+ const rows = await db
25899
+ .select()
25900
+ .from(netsuiteFlows)
25901
+ .where(eq(netsuiteFlows.flowId, state))
25902
+ .limit(1)
25903
+ const flow = rows[0]
25904
+ if (!flow) return new Response('Unknown or expired flow -- start again', { status: 400 })
25905
+ // Single-use: burn the flow row immediately.
25906
+ await db.delete(netsuiteFlows).where(eq(netsuiteFlows.flowId, state))
25907
+ // Reject stale flows: the PKCE verifier must not stay valid indefinitely
25908
+ // for an abandoned or leaked authorize URL (createdAt is unixepoch seconds).
25909
+ const nowSec = Math.floor(Date.now() / 1000)
25910
+ if (flow.createdAt && nowSec - flow.createdAt > 600) {
25911
+ return new Response('Flow expired -- start again', { status: 400 })
25912
+ }
25913
+
25914
+ const tok = await exchangeCode(request, code, flow.codeVerifier)
25915
+ if (!tok.access_token) {
25916
+ return new Response(
25917
+ \`Token exchange failed: \${tok.error_description || tok.error || 'unknown error'}\`,
25918
+ { status: 400 },
25919
+ )
25920
+ }
25921
+
25922
+ const sid = crypto.randomUUID()
25923
+ const now = Math.floor(Date.now() / 1000)
25924
+ await db.insert(netsuiteSessions).values({
25925
+ sid,
25926
+ accountId: requireConfig().accountId,
25927
+ accessToken: tok.access_token,
25928
+ refreshToken: tok.refresh_token ?? null,
25929
+ expiresAt: now + (tok.expires_in || 3600),
25930
+ })
25931
+
25932
+ const dest = new URL(flow.returnTo)
25933
+ dest.hash = \`nssid=\${sid}\`
25934
+ return new Response(null, { status: 302, headers: { Location: dest.toString() } })
25935
+ },
25936
+ },
25937
+ },
25938
+ })
25939
+ `;
25940
+ }
25941
+ function logoutRouteTs() {
25942
+ return `import { createFileRoute } from '@tanstack/react-router'
25943
+ import { bearer, deleteSession } from '#/lib/netsuite-server'
25944
+
25945
+ // POST /auth/netsuite/logout -- destroy the current session.
25946
+ export const Route = createFileRoute('/auth/netsuite/logout')({
25947
+ server: {
25948
+ handlers: {
25949
+ POST: async ({ request }) => {
25950
+ await deleteSession(bearer(request))
25951
+ return Response.json({ ok: true })
25952
+ },
25953
+ },
25954
+ },
25955
+ })
25956
+ `;
25957
+ }
25958
+ function meRouteTs() {
25959
+ return `import { createFileRoute } from '@tanstack/react-router'
25960
+ import { bearer, getSession } from '#/lib/netsuite-server'
25961
+
25962
+ // GET /api/me -- resolve the bearer sid to a session. The ONLY authoritative
25963
+ // auth check; the client must never trust sessionStorage on its own.
25964
+ export const Route = createFileRoute('/api/me')({
25965
+ server: {
25966
+ handlers: {
25967
+ GET: async ({ request }) => {
25968
+ const session = await getSession(bearer(request))
25969
+ if (!session) return Response.json({ authenticated: false })
25970
+ return Response.json({
25971
+ authenticated: true,
25972
+ account_id: session.accountId,
25973
+ })
25974
+ },
25975
+ },
25976
+ },
25977
+ })
25978
+ `;
25979
+ }
25980
+ function configRouteTs() {
25981
+ return `import { createFileRoute } from '@tanstack/react-router'
25982
+ import { env as runtimeEnv } from '@helloleo/runtime'
25983
+ import { appOrigin, redirectUri } from '#/lib/netsuite-server'
25984
+
25985
+ // GET /auth/netsuite/config -- single source of truth for the redirect URI.
25986
+ // Whatever this returns is EXACTLY what /auth/netsuite/start sends NetSuite, so
25987
+ // show the user THIS value to register on their Integration Record. Never
25988
+ // hardcode or guess a callback URL.
25989
+ export const Route = createFileRoute('/auth/netsuite/config')({
25990
+ server: {
25991
+ handlers: {
25992
+ GET: async ({ request }) => {
25993
+ const e = runtimeEnv as unknown as {
25994
+ NETSUITE_ACCOUNT_ID?: string
25995
+ NETSUITE_CLIENT_ID?: string
25996
+ }
25997
+ return Response.json({
25998
+ redirect_uri: redirectUri(request),
25999
+ origin: appOrigin(request),
26000
+ configured: Boolean(e.NETSUITE_ACCOUNT_ID && e.NETSUITE_CLIENT_ID),
26001
+ })
26002
+ },
26003
+ },
26004
+ },
26005
+ })
26006
+ `;
26007
+ }
26008
+ function netsuiteClientTs() {
26009
+ return `/*
26010
+ * NetSuite auth -- client (same-origin). The OAuth backend is THIS app's own
26011
+ * server routes (src/routes/auth/netsuite/* + src/routes/api/me.ts), so every
26012
+ * call is relative -- no separate Worker, no VITE_WORKER_URL.
26013
+ *
26014
+ * The browser only ever holds an opaque session id (sid), handed back in the
26015
+ * callback's URL fragment (#nssid=...) so it survives the HelloLeo preview
26016
+ * iframe (third-party cookies are partitioned/dropped there). The sid rides as
26017
+ * Authorization: Bearer on every call; NetSuite tokens stay server-side. The
26018
+ * only authoritative auth check is GET /api/me.
26019
+ *
26020
+ * NEVER use a password gate. NEVER trust sessionStorage as the auth state --
26021
+ * it's just a cache of the bearer.
26022
+ */
26023
+ const TOKEN_KEY = 'nssid'
26024
+
26025
+ // Capture-and-strip #nssid=... as early as possible so URLs stay clean.
26026
+ ;(function bootstrapTokenFromHash() {
26027
+ if (typeof window === 'undefined') return
26028
+ const hash = window.location.hash.replace(/^#/, '')
26029
+ if (!hash) return
26030
+ const params = new URLSearchParams(hash)
26031
+ const sid = params.get(TOKEN_KEY)
26032
+ if (sid) {
26033
+ try {
26034
+ sessionStorage.setItem(TOKEN_KEY, sid)
26035
+ } catch {}
26036
+ params.delete(TOKEN_KEY)
26037
+ const rest = params.toString()
26038
+ window.history.replaceState(
26039
+ null,
26040
+ '',
26041
+ window.location.pathname + window.location.search + (rest ? '#' + rest : ''),
26042
+ )
26043
+ }
26044
+ })()
26045
+
26046
+ export function getSessionToken(): string | null {
26047
+ try {
26048
+ return sessionStorage.getItem(TOKEN_KEY)
26049
+ } catch {
26050
+ return null
26051
+ }
26052
+ }
26053
+
26054
+ export function signInWithNetSuite(returnTo: string = window.location.href) {
26055
+ const url = new URL('/auth/netsuite/start', window.location.origin)
26056
+ url.searchParams.set('return_to', returnTo)
26057
+ // The app renders inside the HelloLeo preview iframe; /start 302s to
26058
+ // NetSuite, whose OAuth page sends X-Frame-Options: DENY. Navigate the TOP
26059
+ // frame so the flow runs at top level and the callback lands there to read
26060
+ // #nssid=. Assign .href (NOT .assign(): reading .assign off a cross-origin
26061
+ // window.top.location throws, dropping us into the iframe fallback ->
26062
+ // "refused to connect").
26063
+ try {
26064
+ if (window.top && window.top !== window) {
26065
+ window.top.location.href = url.toString()
26066
+ return
26067
+ }
26068
+ } catch {
26069
+ /* top window unreachable -- fall through to same-frame navigation */
26070
+ }
26071
+ window.location.href = url.toString()
26072
+ }
26073
+
26074
+ export interface NetSuiteSession {
26075
+ authenticated: boolean
26076
+ account_id?: string
26077
+ }
26078
+
26079
+ export async function getNetSuiteSession(): Promise<NetSuiteSession> {
26080
+ const sid = getSessionToken()
26081
+ if (!sid) return { authenticated: false }
26082
+ const res = await fetch('/api/me', { headers: { Authorization: 'Bearer ' + sid } })
26083
+ if (!res.ok) return { authenticated: false }
26084
+ // res.json() is \`unknown\` under workers-types -- assert the /api/me shape.
26085
+ const data = (await res.json()) as NetSuiteSession
26086
+ return { ...data, authenticated: Boolean(data?.authenticated) }
26087
+ }
26088
+
26089
+ export async function signOutNetSuite(): Promise<void> {
26090
+ const sid = getSessionToken()
26091
+ if (sid) {
26092
+ try {
26093
+ await fetch('/auth/netsuite/logout', {
26094
+ method: 'POST',
26095
+ headers: { Authorization: 'Bearer ' + sid },
26096
+ })
26097
+ } catch {}
26098
+ }
26099
+ try {
26100
+ sessionStorage.removeItem(TOKEN_KEY)
26101
+ } catch {}
26102
+ window.location.reload()
26103
+ }
26104
+
26105
+ /**
26106
+ * Fetch YOUR data routes (src/routes/api/*) with the bearer attached. Use this
26107
+ * instead of bare fetch for authenticated calls.
26108
+ */
26109
+ export async function apiFetch(path: string, init: RequestInit = {}): Promise<Response> {
26110
+ const sid = getSessionToken()
26111
+ const headers = new Headers(init.headers)
26112
+ if (sid) headers.set('Authorization', 'Bearer ' + sid)
26113
+ return fetch(path, { ...init, headers })
26114
+ }
26115
+
26116
+ /**
26117
+ * The exact redirect URI this app will send NetSuite, read from the server so
26118
+ * it can never drift from what /auth/netsuite/start actually uses. Show it to
26119
+ * whoever registers the Integration Record; never hardcode a callback URL.
26120
+ */
26121
+ export async function getNetSuiteRedirectUri(): Promise<string | null> {
26122
+ try {
26123
+ const res = await fetch('/auth/netsuite/config')
26124
+ if (!res.ok) return null
26125
+ const data = (await res.json()) as { redirect_uri?: string }
26126
+ return data?.redirect_uri ?? null
26127
+ } catch {
26128
+ return null
26129
+ }
26130
+ }
26131
+ `;
26132
+ }
26133
+ function startAuthTsx() {
26134
+ return `import * as React from 'react'
26135
+ import {
26136
+ getNetSuiteSession,
26137
+ signInWithNetSuite,
26138
+ signOutNetSuite,
26139
+ type NetSuiteSession,
26140
+ } from './netsuite'
26141
+
26142
+ /**
26143
+ * NetSuite auth context. Holds the session (resolved client-side from /api/me
26144
+ * via getNetSuiteSession) and exposes sign-in / sign-out. /api/me is the only
26145
+ * authoritative check -- never trust sessionStorage directly.
26146
+ */
26147
+ export interface NetSuiteAuthContextValue {
26148
+ pending: boolean
26149
+ isAuthenticated: boolean
26150
+ session: NetSuiteSession | null
26151
+ signIn: () => void
26152
+ signOut: () => Promise<void>
26153
+ refresh: () => Promise<void>
26154
+ }
26155
+
26156
+ const NetSuiteAuthContext = React.createContext<NetSuiteAuthContextValue | null>(null)
26157
+
26158
+ export function NetSuiteAuthProvider({ children }: { children: React.ReactNode }) {
26159
+ const [session, setSession] = React.useState<NetSuiteSession | null>(null)
26160
+ // Start pending on BOTH server and client render so SSR and first paint match
26161
+ // (a spinner), avoiding a hydration mismatch. The effect (client-only)
26162
+ // resolves it.
26163
+ const [pending, setPending] = React.useState(true)
26164
+
26165
+ const refresh = React.useCallback(async () => {
26166
+ setPending(true)
26167
+ try {
26168
+ setSession(await getNetSuiteSession())
26169
+ } finally {
26170
+ setPending(false)
26171
+ }
26172
+ }, [])
26173
+
26174
+ React.useEffect(() => {
26175
+ refresh()
26176
+ }, [refresh])
26177
+
26178
+ const value: NetSuiteAuthContextValue = {
26179
+ pending,
26180
+ isAuthenticated: Boolean(session?.authenticated),
26181
+ session,
26182
+ signIn: () => signInWithNetSuite(),
26183
+ signOut: signOutNetSuite,
26184
+ refresh,
26185
+ }
26186
+
26187
+ return <NetSuiteAuthContext.Provider value={value}>{children}</NetSuiteAuthContext.Provider>
26188
+ }
26189
+
26190
+ export function useNetSuiteAuth(): NetSuiteAuthContextValue {
26191
+ const ctx = React.useContext(NetSuiteAuthContext)
26192
+ if (!ctx) {
26193
+ throw new Error('useNetSuiteAuth must be used within <NetSuiteAuthProvider>')
26194
+ }
26195
+ return ctx
26196
+ }
26197
+ `;
26198
+ }
26199
+ function startAuthLayoutTsx() {
26200
+ return `import type { ReactNode } from 'react'
26201
+ import { NetSuiteAuthProvider, useNetSuiteAuth } from '../../lib/auth'
26202
+ import { LoginPage } from './LoginPage'
26203
+
26204
+ /**
26205
+ * NetSuite auth layout. The ONE manual wiring step: wrap the root route's
26206
+ * <Outlet /> with it in src/routes/__root.tsx:
26207
+ *
26208
+ * import { AuthLayout } from '../components/auth/AuthLayout'
26209
+ * ...
26210
+ * function RootComponent() {
26211
+ * return (
26212
+ * <RootDocument>
26213
+ * <AuthLayout>
26214
+ * <Outlet />
26215
+ * </AuthLayout>
26216
+ * </RootDocument>
26217
+ * )
26218
+ * }
26219
+ *
26220
+ * It provides auth context and gates rendering: a spinner while the session
26221
+ * resolves, <LoginPage /> for signed-out users, your routes once signed in.
26222
+ * NEVER swap this for a password gate -- real OAuth is the only login.
26223
+ */
26224
+ export function AuthLayout({ children }: { children: ReactNode }) {
26225
+ return (
26226
+ <NetSuiteAuthProvider>
26227
+ <Gate>{children}</Gate>
26228
+ </NetSuiteAuthProvider>
26229
+ )
26230
+ }
26231
+
26232
+ function Gate({ children }: { children: ReactNode }) {
26233
+ const { pending, isAuthenticated } = useNetSuiteAuth()
26234
+
26235
+ if (pending) {
26236
+ return (
26237
+ <div className="min-h-screen flex items-center justify-center bg-background">
26238
+ <div className="h-8 w-8 rounded-full border-2 border-primary border-t-transparent animate-spin" />
26239
+ </div>
26240
+ )
26241
+ }
26242
+
26243
+ if (!isAuthenticated) return <LoginPage />
26244
+
26245
+ return <>{children}</>
26246
+ }
26247
+ `;
26248
+ }
26249
+ function startLoginPageTsx() {
26250
+ return `import { SignInWithNetSuite } from './SignInWithNetSuite'
26251
+
26252
+ /**
26253
+ * Unauthenticated gate -- a deliberately bare placeholder. DESIGN THIS PAGE
26254
+ * to match the app you are building: its real name, its brand, its layout
26255
+ * language. Do NOT ship this default as-is.
26256
+ *
26257
+ * The only hard requirements:
26258
+ * - keep <SignInWithNetSuite /> as the ONLY call-to-action (it starts the
26259
+ * OAuth flow at /auth/netsuite/start)
26260
+ * - never add a password form -- real OAuth is the only login
26261
+ */
26262
+ export function LoginPage() {
26263
+ return (
26264
+ <main className="min-h-screen flex items-center justify-center bg-background text-foreground p-4">
26265
+ <div className="flex flex-col items-center gap-4 text-center">
26266
+ <h1 className="text-2xl font-semibold">Sign in</h1>
26267
+ <p className="text-sm text-muted-foreground">
26268
+ Connect your NetSuite account to continue.
26269
+ </p>
26270
+ <SignInWithNetSuite />
26271
+ </div>
26272
+ </main>
26273
+ )
26274
+ }
26275
+ `;
26276
+ }
26277
+ function startSignInButtonTsx() {
26278
+ return `import { signInWithNetSuite } from '../../lib/netsuite'
26279
+
26280
+ export function SignInWithNetSuite() {
26281
+ return (
26282
+ <button
26283
+ onClick={() => signInWithNetSuite()}
26284
+ 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"
26285
+ >
26286
+ Sign in with NetSuite
26287
+ </button>
26288
+ )
26289
+ }
26290
+ `;
26291
+ }
26292
+ function spaNetsuiteTs() {
25549
26293
  return `/*
25550
26294
  * NetSuite OAuth client helper (bearer-token-in-fragment).
25551
26295
  *
@@ -25702,7 +26446,7 @@ export async function workerFetch(pathOrUrl: string, init: RequestInit = {}): Pr
25702
26446
  }
25703
26447
  `;
25704
26448
  }
25705
- function signInButtonTsx() {
26449
+ function spaSignInButtonTsx() {
25706
26450
  return `import { signInWithNetSuite } from '../../lib/netsuite';
25707
26451
 
25708
26452
  export function SignInWithNetSuite() {
@@ -25717,51 +26461,35 @@ export function SignInWithNetSuite() {
25717
26461
  }
25718
26462
  `;
25719
26463
  }
25720
- function netsuiteLoginPageTsx() {
26464
+ function spaLoginPageTsx() {
25721
26465
  return `import { SignInWithNetSuite } from './SignInWithNetSuite';
25722
26466
 
25723
26467
  /**
25724
- * Default unauthenticated landing page. Replaces any password gate.
25725
- * Customise copy / imagery freely but keep <SignInWithNetSuite /> as the
25726
- * only call-to-action -- it points to the Worker's /auth/netsuite/start.
26468
+ * Unauthenticated gate -- a deliberately bare placeholder. DESIGN THIS PAGE
26469
+ * to match the app you are building: its real name, its brand, its layout
26470
+ * language. Do NOT ship this default as-is.
26471
+ *
26472
+ * The only hard requirements:
26473
+ * - keep <SignInWithNetSuite /> as the ONLY call-to-action (it starts the
26474
+ * OAuth flow on the Worker's /auth/netsuite/start)
26475
+ * - never add a password form -- real OAuth is the only login
25727
26476
  */
25728
26477
  export function LoginPage() {
25729
26478
  return (
25730
- <div className="min-h-screen bg-background text-foreground flex">
25731
- <div className="hidden lg:flex lg:w-1/2 bg-primary text-primary-foreground p-12 flex-col justify-between">
25732
- <div className="text-xl font-semibold">NetSuite App</div>
25733
- <div>
25734
- <h1 className="text-4xl font-bold leading-tight">
25735
- Connect your NetSuite account
25736
- </h1>
25737
- <p className="mt-4 text-primary-foreground/80 max-w-md">
25738
- Sign in with your NetSuite credentials to access your data securely.
25739
- Tokens stay server-side on HelloLeo Cloud -- they never reach the
25740
- browser.
25741
- </p>
25742
- </div>
25743
- <div className="text-xs text-primary-foreground/60">
25744
- Powered by HelloLeo
25745
- </div>
25746
- </div>
25747
- <div className="flex-1 flex items-center justify-center px-6 py-12">
25748
- <div className="w-full max-w-sm space-y-6">
25749
- <div>
25750
- <h2 className="text-2xl font-semibold">Welcome</h2>
25751
- <p className="mt-2 text-sm text-muted-foreground">
25752
- Use the button below to sign in. You'll be redirected to NetSuite
25753
- to authorise access, then back here.
25754
- </p>
25755
- </div>
25756
- <SignInWithNetSuite />
25757
- </div>
26479
+ <main className="min-h-screen flex items-center justify-center bg-background text-foreground p-4">
26480
+ <div className="flex flex-col items-center gap-4 text-center">
26481
+ <h1 className="text-2xl font-semibold">Sign in</h1>
26482
+ <p className="text-sm text-muted-foreground">
26483
+ Connect your NetSuite account to continue.
26484
+ </p>
26485
+ <SignInWithNetSuite />
25758
26486
  </div>
25759
- </div>
26487
+ </main>
25760
26488
  );
25761
26489
  }
25762
26490
  `;
25763
26491
  }
25764
- function authTsx() {
26492
+ function spaAuthTsx() {
25765
26493
  return `import * as React from 'react';
25766
26494
  import {
25767
26495
  getNetSuiteSession,
@@ -25833,7 +26561,7 @@ export function useNetSuiteAuth(): NetSuiteAuthContextValue {
25833
26561
  }
25834
26562
  `;
25835
26563
  }
25836
- function authLayoutTsx() {
26564
+ function spaAuthLayoutTsx() {
25837
26565
  return `import type { ReactNode } from 'react';
25838
26566
  import { NetSuiteAuthProvider, useNetSuiteAuth } from '../../lib/auth';
25839
26567
  import { LoginPage } from './LoginPage';
@@ -25887,57 +26615,174 @@ function Gate({ children }: { children: ReactNode }) {
25887
26615
  }
25888
26616
  `;
25889
26617
  }
26618
+ async function executeStart(dir) {
26619
+ await mkdir2(path7.join(dir, "src", "lib"), { recursive: true });
26620
+ await mkdir2(path7.join(dir, "src", "components", "auth"), {
26621
+ recursive: true
26622
+ });
26623
+ await mkdir2(path7.join(dir, "src", "routes", "auth", "netsuite"), {
26624
+ recursive: true
26625
+ });
26626
+ await mkdir2(path7.join(dir, "src", "routes", "api"), { recursive: true });
26627
+ const schemaImports = `import { sql } from 'drizzle-orm'
26628
+ import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'
26629
+ `;
26630
+ const schemaPath = path7.join(dir, "src", "db", "schema.ts");
26631
+ let schemaAppended = false;
26632
+ try {
26633
+ const current = await readFile3(schemaPath, "utf8");
26634
+ if (!current.includes("netsuite_flows")) {
26635
+ const hasImports = /^import .*drizzle-orm/m.test(current);
26636
+ await Bun.write(schemaPath, (hasImports ? current : schemaImports + current) + schemaAppend());
26637
+ schemaAppended = true;
26638
+ }
26639
+ } catch {
26640
+ await Bun.write(schemaPath, schemaImports + schemaAppend());
26641
+ schemaAppended = true;
26642
+ }
26643
+ const files = [
26644
+ [path7.join("src", "lib", "netsuite-server.ts"), netsuiteServerTs()],
26645
+ [
26646
+ path7.join("src", "routes", "auth", "netsuite", "start.ts"),
26647
+ startRouteTs()
26648
+ ],
26649
+ [
26650
+ path7.join("src", "routes", "auth", "netsuite", "callback.ts"),
26651
+ callbackRouteTs()
26652
+ ],
26653
+ [
26654
+ path7.join("src", "routes", "auth", "netsuite", "logout.ts"),
26655
+ logoutRouteTs()
26656
+ ],
26657
+ [
26658
+ path7.join("src", "routes", "auth", "netsuite", "config.ts"),
26659
+ configRouteTs()
26660
+ ],
26661
+ [path7.join("src", "routes", "api", "me.ts"), meRouteTs()],
26662
+ [path7.join("src", "lib", "netsuite.ts"), netsuiteClientTs()],
26663
+ [path7.join("src", "lib", "auth.tsx"), startAuthTsx()],
26664
+ [
26665
+ path7.join("src", "components", "auth", "AuthLayout.tsx"),
26666
+ startAuthLayoutTsx()
26667
+ ],
26668
+ [
26669
+ path7.join("src", "components", "auth", "LoginPage.tsx"),
26670
+ startLoginPageTsx()
26671
+ ],
26672
+ [
26673
+ path7.join("src", "components", "auth", "SignInWithNetSuite.tsx"),
26674
+ startSignInButtonTsx()
26675
+ ]
26676
+ ];
26677
+ for (const [filePath, content] of files) {
26678
+ await Bun.write(path7.join(dir, filePath), content);
26679
+ }
26680
+ return [
26681
+ `Wrote ${files.length} NetSuite files${schemaAppended ? " + appended src/db/schema.ts" : ""}:`,
26682
+ "DOCS -- the authoritative setup guide is https://docs.helloleo.dev/integrations/netsuite . When you tell the user what to do in NetSuite, follow and link these steps verbatim; do not invent steps.",
26683
+ " - Record #2 (runtime): https://docs.helloleo.dev/integrations/netsuite#step-4-%E2%80%94-create-integration-record-2-runtime",
26684
+ " - Send runtime creds to Leo: https://docs.helloleo.dev/integrations/netsuite#step-5-%E2%80%94-send-the-runtime-credentials-to-leo",
26685
+ "",
26686
+ " server (OAuth backend lives in the app -- no separate Worker):",
26687
+ " - src/lib/netsuite-server.ts (env, PKCE, token exchange, session refresh, netsuiteFetch)",
26688
+ " - src/routes/auth/netsuite/start.ts GET begin PKCE flow",
26689
+ " - src/routes/auth/netsuite/callback.ts GET code -> tokens -> session",
26690
+ " - src/routes/auth/netsuite/logout.ts POST destroy session",
26691
+ " - src/routes/auth/netsuite/config.ts GET the exact redirect URI to register",
26692
+ " - src/routes/api/me.ts GET bearer -> session (auth check)",
26693
+ " - src/db/schema.ts += netsuite_flows + netsuite_sessions",
26694
+ " client:",
26695
+ " - src/lib/netsuite.ts (same-origin: signIn, session, apiFetch)",
26696
+ " - src/lib/auth.tsx (NetSuiteAuthProvider + useNetSuiteAuth)",
26697
+ " - src/components/auth/{AuthLayout,LoginPage,SignInWithNetSuite}.tsx",
26698
+ "",
26699
+ "WIRE IT UP (one manual step): in src/routes/__root.tsx, wrap <Outlet /> with <AuthLayout>:",
26700
+ "",
26701
+ " import { AuthLayout } from '../components/auth/AuthLayout'",
26702
+ "",
26703
+ " <AuthLayout>",
26704
+ " <Outlet />",
26705
+ " </AuthLayout>",
26706
+ "",
26707
+ "Then:",
26708
+ "- DESIGN THE LOGIN PAGE: src/components/auth/LoginPage.tsx is a bare placeholder on purpose. Restyle it to match THIS app (name, brand, layout) as part of building the UI -- do not ship the default. Keep <SignInWithNetSuite /> as the only call-to-action; never add a password form.",
26709
+ "- Build your dashboard inside <AuthLayout>. Read the session with useNetSuiteAuth().",
26710
+ "- Data routes: add src/routes/api/*.ts and call netsuiteFetch(bearer(request), '/services/rest/query/v1/suiteql', {...}) from the handler.",
26711
+ "- MIGRATIONS: schema.ts changed (netsuite_flows + netsuite_sessions). Migrations are generated and applied automatically; if the dev server complains about missing tables, run `bun run db:generate` once (never hand-edit files under drizzle/).",
26712
+ "",
26713
+ "TWO INTEGRATION RECORDS -- do not confuse them:",
26714
+ "- Record #1 (scope: mcp): already connected, used ONLY to build the app (schema discovery). This login does NOT use it.",
26715
+ "- Record #2 (scope: rest_webservices): THIS login uses it -- the end user signs into NetSuite through it, and the redirect URI is registered on THIS record. If it doesn't exist yet, tell the user to create it (a second Integration Record, scope rest_webservices only).",
26716
+ "",
26717
+ "CONFIG -- NETSUITE_ACCOUNT_ID, NETSUITE_CLIENT_ID, NETSUITE_CLIENT_SECRET (secret optional for PKCE public clients). Never hardcode; never put in code. Same var names in every environment, different SOURCE:",
26718
+ "- DEV (Fly preview): read from the project .env. HelloLeo writes them there (the setup wizard, or the env tooling). In dev the app uses .env -- do NOT tell the user to use HelloLeo Cloud here.",
26719
+ "- PROD (published Worker): the SAME names live as HelloLeo Cloud secrets; the publish step promotes them from .env onto the Worker automatically. Same code path (@helloleo/runtime env), just a different source per environment.",
26720
+ "- PUBLIC_APP_URL / HELLOLEO_URL are set by the platform per environment; don't hardcode them.",
26721
+ "- REDIRECT URI -- never guess or hardcode it. It is derived server-side and auto-corrects behind the preview proxy. Read the exact value from GET /auth/netsuite/config (or getNetSuiteRedirectUri() on the client) and tell the user to register THAT on Integration Record #2 (scope: rest_webservices). ONE redirect URI per record: register exactly the value /auth/netsuite/config returns for the environment the user signs into. If login must work in BOTH the preview and the published app, use a separate Integration Record per environment (same env var names, different NETSUITE_CLIENT_ID/_SECRET values per environment) -- do not stack URLs on one record.",
26722
+ "- Never replace <AuthLayout> with a password gate. Real OAuth is the only supported login."
26723
+ ].join(`
26724
+ `);
26725
+ }
26726
+ async function executeSpa(dir) {
26727
+ await mkdir2(path7.join(dir, "src", "components", "auth"), {
26728
+ recursive: true
26729
+ });
26730
+ const nsFiles = [
26731
+ [path7.join("src", "lib", "netsuite.ts"), spaNetsuiteTs()],
26732
+ [path7.join("src", "lib", "auth.tsx"), spaAuthTsx()],
26733
+ [
26734
+ path7.join("src", "components", "auth", "AuthLayout.tsx"),
26735
+ spaAuthLayoutTsx()
26736
+ ],
26737
+ [
26738
+ path7.join("src", "components", "auth", "LoginPage.tsx"),
26739
+ spaLoginPageTsx()
26740
+ ],
26741
+ [
26742
+ path7.join("src", "components", "auth", "SignInWithNetSuite.tsx"),
26743
+ spaSignInButtonTsx()
26744
+ ]
26745
+ ];
26746
+ for (const [filePath, content] of nsFiles) {
26747
+ await Bun.write(path7.join(dir, filePath), content);
26748
+ }
26749
+ return [
26750
+ `Wrote ${nsFiles.length} NetSuite OAuth files (all additive, nothing overwritten):`,
26751
+ " - src/lib/netsuite.ts (OAuth client: signIn, session, workerFetch)",
26752
+ " - src/lib/auth.tsx (NetSuiteAuthProvider and useNetSuiteAuth)",
26753
+ " - src/components/auth/AuthLayout.tsx (provider and auth gate)",
26754
+ " - src/components/auth/LoginPage.tsx (unauthenticated view)",
26755
+ " - src/components/auth/SignInWithNetSuite.tsx (sign-in button)",
26756
+ "",
26757
+ "Notes:",
26758
+ "- DESIGN THE LOGIN PAGE: src/components/auth/LoginPage.tsx is a bare placeholder on purpose. Restyle it to match THIS app (name, brand, layout) as part of building the UI -- do not ship the default. Keep <SignInWithNetSuite /> as the only call-to-action; never add a password form.",
26759
+ "- AuthLayout shows LoginPage to signed-out users and renders the app's routes once they sign in with NetSuite.",
26760
+ "- Read the session anywhere with useNetSuiteAuth() from src/lib/auth.tsx.",
26761
+ "- Never replace AuthLayout with a password gate. Real OAuth is the only supported login.",
26762
+ "- The auth worker (deployed via the cloudflare-backend MCP) serves /auth/netsuite/start, /auth/netsuite/callback, /api/me and /auth/netsuite/logout. It reads env.NETSUITE_ACCOUNT_ID, _CLIENT_ID and _CLIENT_SECRET. VITE_WORKER_URL must be set (HelloLeo Cloud seeds it).",
26763
+ "- POPUP FLOW (required so login works inside the HelloLeo preview iframe): the client opens /auth/netsuite/start in a popup with ?popup=1. The worker MUST carry that flag through OAuth (persist it on the flow row in /start, read it back in /callback via state). In /auth/netsuite/callback, when the flow was popup, DO NOT redirect to return_to#nssid \u2014 instead return an HTML page whose script does: window.opener.postMessage({ type: 'netsuite-auth', nssid: SID }, '*'); window.close(); (fall back to the return_to#nssid redirect only when there is no opener / not a popup). Without this, the preview iframe (partitioned sessionStorage) keeps showing the login after sign-in.",
26764
+ "",
26765
+ "Next: in src/routes/__root.tsx, import AuthLayout and wrap <Outlet /> with it. Keep any existing providers.",
26766
+ "",
26767
+ " import { AuthLayout } from '../components/auth/AuthLayout'",
26768
+ "",
26769
+ " <AuthLayout>",
26770
+ " <Outlet />",
26771
+ " </AuthLayout>"
26772
+ ].join(`
26773
+ `);
26774
+ }
25890
26775
  var setupNetsuite = tool({
25891
- description: "Add NetSuite OAuth wiring to an existing project. Call scaffold first, " + "then this. Writes the OAuth client, auth provider and login components. " + "All files are additive, nothing is overwritten. Real OAuth is wired " + "from day one, never replace <AuthLayout> with a password placeholder.",
26776
+ description: "Add NetSuite runtime OAuth (end-user LOGIN) to an existing project. " + "Call scaffold first, then this. Works on both scaffold types: it " + "writes the client + auth components, and the OAuth backend is the " + "project's HelloLeo Cloud Worker (VITE_WORKER_URL) -- the platform " + "wizard registers the Worker's fixed /auth/netsuite/callback on the " + "Integration Record, so the app never hosts the OAuth routes itself. " + "This login uses NetSuite Integration Record #2 " + "(scope: rest_webservices) -- a SEPARATE record from the MCP one " + "(scope: mcp) that was used only to BUILD the app; do not confuse " + "them. Real OAuth from day one -- never replace <AuthLayout> with a " + "password placeholder. Setup guide (link the user to it): " + "https://docs.helloleo.dev/integrations/netsuite",
25892
26777
  args: {},
25893
26778
  async execute(_args, context) {
25894
26779
  const dir = context.directory;
25895
- await mkdir2(path7.join(dir, "src", "components", "auth"), {
25896
- recursive: true
25897
- });
25898
- const nsFiles = [
25899
- [path7.join("src", "lib", "netsuite.ts"), netsuiteTs()],
25900
- [path7.join("src", "lib", "auth.tsx"), authTsx()],
25901
- [
25902
- path7.join("src", "components", "auth", "AuthLayout.tsx"),
25903
- authLayoutTsx()
25904
- ],
25905
- [
25906
- path7.join("src", "components", "auth", "LoginPage.tsx"),
25907
- netsuiteLoginPageTsx()
25908
- ],
25909
- [
25910
- path7.join("src", "components", "auth", "SignInWithNetSuite.tsx"),
25911
- signInButtonTsx()
25912
- ]
25913
- ];
25914
- for (const [filePath, content] of nsFiles) {
25915
- await Bun.write(path7.join(dir, filePath), content);
26780
+ const scaffoldId = await readScaffoldId2(dir);
26781
+ const inAppOptIn = process.env.PLUGINS_NETSUITE_IN_APP === "1";
26782
+ if (inAppOptIn && scaffoldId?.startsWith("tanstack-start")) {
26783
+ return executeStart(dir);
25916
26784
  }
25917
- return [
25918
- `Wrote ${nsFiles.length} NetSuite OAuth files (all additive, nothing overwritten):`,
25919
- " - src/lib/netsuite.ts (OAuth client: signIn, session, workerFetch)",
25920
- " - src/lib/auth.tsx (NetSuiteAuthProvider and useNetSuiteAuth)",
25921
- " - src/components/auth/AuthLayout.tsx (provider and auth gate)",
25922
- " - src/components/auth/LoginPage.tsx (unauthenticated view)",
25923
- " - src/components/auth/SignInWithNetSuite.tsx (sign-in button)",
25924
- "",
25925
- "Notes:",
25926
- "- AuthLayout shows LoginPage to signed-out users and renders the app's routes once they sign in with NetSuite.",
25927
- "- Read the session anywhere with useNetSuiteAuth() from src/lib/auth.tsx.",
25928
- "- Never replace AuthLayout with a password gate. Real OAuth is the only supported login.",
25929
- "- The auth worker (deployed via the cloudflare-backend MCP) serves /auth/netsuite/start, /auth/netsuite/callback, /api/me and /auth/netsuite/logout. It reads env.NETSUITE_ACCOUNT_ID, _CLIENT_ID and _CLIENT_SECRET. VITE_WORKER_URL must be set (HelloLeo Cloud seeds it).",
25930
- "- POPUP FLOW (required so login works inside the HelloLeo preview iframe): the client opens /auth/netsuite/start in a popup with ?popup=1. The worker MUST carry that flag through OAuth (persist it on the flow row in /start, read it back in /callback via state). In /auth/netsuite/callback, when the flow was popup, DO NOT redirect to return_to#nssid \u2014 instead return an HTML page whose script does: window.opener.postMessage({ type: 'netsuite-auth', nssid: SID }, '*'); window.close(); (fall back to the return_to#nssid redirect only when there is no opener / not a popup). Without this, the preview iframe (partitioned sessionStorage) keeps showing the login after sign-in.",
25931
- "",
25932
- "Next: in src/routes/__root.tsx, import AuthLayout and wrap <Outlet /> with it. Keep any existing providers.",
25933
- "",
25934
- " import { AuthLayout } from '../components/auth/AuthLayout'",
25935
- "",
25936
- " <AuthLayout>",
25937
- " <Outlet />",
25938
- " </AuthLayout>"
25939
- ].join(`
25940
- `);
26785
+ return executeSpa(dir);
25941
26786
  }
25942
26787
  });
25943
26788
  var SetupNetsuitePlugin = async () => {