@cosmoops/connect-sdk 0.2.0 → 0.6.0
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/CHANGELOG.md +125 -0
- package/README.md +284 -7
- package/dist/cjs/cli/doctor.js +209 -0
- package/dist/cjs/cli/init.js +20 -8
- package/dist/cjs/client/components/access-gate.js +162 -0
- package/dist/cjs/client/components/account-sessions.js +21 -19
- package/dist/cjs/client/components/app-shell.js +157 -0
- package/dist/cjs/client/components/apps-grid.js +2 -1
- package/dist/cjs/client/components/integrations-modal.js +95 -0
- package/dist/cjs/client/components/motion.js +27 -0
- package/dist/cjs/client/components/nav.js +97 -0
- package/dist/cjs/client/components/plans.js +39 -37
- package/dist/cjs/client/components/readiness.js +3 -1
- package/dist/cjs/client/components/side-nav.js +58 -0
- package/dist/cjs/client/components/subscription.js +2 -1
- package/dist/cjs/client/components/surfaces.js +54 -0
- package/dist/cjs/client/components/usage-meter.js +3 -2
- package/dist/cjs/client/components/user-menu.js +30 -3
- package/dist/cjs/client/index.js +29 -1
- package/dist/cjs/client/provider.js +54 -2
- package/dist/cjs/client/use-active-path.js +77 -0
- package/dist/cjs/errors.js +1 -1
- package/dist/cjs/next/index.js +96 -15
- package/dist/cjs/server/client.js +10 -2
- package/dist/cjs/server/handler.js +89 -6
- package/dist/cjs/server/index.js +8 -1
- package/dist/cjs/server/resources/analytics.js +66 -0
- package/dist/cjs/server/resources/identity.js +1 -1
- package/dist/cjs/server/resources/integrations.js +66 -0
- package/dist/cjs/server/resources/sessions.js +1 -1
- package/dist/cjs/server/webhooks.js +127 -0
- package/dist/cjs/this-entry-is-server-only.js +31 -0
- package/dist/esm/cli/doctor.js +206 -0
- package/dist/esm/cli/init.js +20 -8
- package/dist/esm/client/components/access-gate.js +158 -0
- package/dist/esm/client/components/account-sessions.js +21 -19
- package/dist/esm/client/components/app-shell.js +154 -0
- package/dist/esm/client/components/apps-grid.js +2 -1
- package/dist/esm/client/components/integrations-modal.js +92 -0
- package/dist/esm/client/components/motion.js +21 -0
- package/dist/esm/client/components/nav.js +89 -0
- package/dist/esm/client/components/plans.js +39 -37
- package/dist/esm/client/components/readiness.js +3 -1
- package/dist/esm/client/components/side-nav.js +53 -0
- package/dist/esm/client/components/subscription.js +2 -1
- package/dist/esm/client/components/surfaces.js +51 -0
- package/dist/esm/client/components/usage-meter.js +3 -2
- package/dist/esm/client/components/user-menu.js +31 -4
- package/dist/esm/client/index.js +15 -1
- package/dist/esm/client/provider.js +53 -2
- package/dist/esm/client/use-active-path.js +74 -0
- package/dist/esm/errors.js +1 -1
- package/dist/esm/next/index.js +95 -15
- package/dist/esm/server/client.js +10 -2
- package/dist/esm/server/handler.js +89 -6
- package/dist/esm/server/index.js +5 -0
- package/dist/esm/server/resources/analytics.js +62 -0
- package/dist/esm/server/resources/identity.js +1 -1
- package/dist/esm/server/resources/integrations.js +62 -0
- package/dist/esm/server/resources/sessions.js +1 -1
- package/dist/esm/server/webhooks.js +123 -0
- package/dist/esm/this-entry-is-server-only.js +30 -0
- package/dist/theme.css +28 -0
- package/dist/types/cli/doctor.d.ts +23 -0
- package/dist/types/cli/init.d.ts +2 -3
- package/dist/types/client/components/access-gate.d.ts +79 -0
- package/dist/types/client/components/app-shell.d.ts +115 -0
- package/dist/types/client/components/integrations-modal.d.ts +21 -0
- package/dist/types/client/components/motion.d.ts +22 -0
- package/dist/types/client/components/nav.d.ts +110 -0
- package/dist/types/client/components/side-nav.d.ts +31 -0
- package/dist/types/client/components/surfaces.d.ts +51 -0
- package/dist/types/client/index.d.ts +12 -1
- package/dist/types/client/provider.d.ts +38 -3
- package/dist/types/client/use-active-path.d.ts +8 -0
- package/dist/types/errors.d.ts +1 -1
- package/dist/types/next/index.d.ts +40 -0
- package/dist/types/server/client.d.ts +8 -2
- package/dist/types/server/index.d.ts +17 -2
- package/dist/types/server/resources/analytics.d.ts +31 -0
- package/dist/types/server/resources/identity.d.ts +12 -2
- package/dist/types/server/resources/integrations.d.ts +40 -0
- package/dist/types/server/webhooks.d.ts +67 -0
- package/dist/types/this-entry-is-server-only.d.ts +1 -0
- package/dist/types/types.d.ts +182 -1
- package/package.json +22 -4
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
/**
|
|
4
|
+
* The module a browser bundle gets if it reaches for `/server` or `/next`.
|
|
5
|
+
*
|
|
6
|
+
* Neither entry may run in a browser: both build a `ConnectClient` around
|
|
7
|
+
* `CONNECT_API_KEY`. Nothing enforced that before - the split was documented
|
|
8
|
+
* and unguarded, so a client component importing `@cosmoops/connect-sdk/server`
|
|
9
|
+
* compiled cleanly and failed later, somewhere else, for reasons that did not
|
|
10
|
+
* mention the import.
|
|
11
|
+
*
|
|
12
|
+
* The key itself does not leak: `CONNECT_API_KEY` has no `NEXT_PUBLIC_` prefix,
|
|
13
|
+
* so Next replaces the read with `undefined` in a client bundle rather than
|
|
14
|
+
* inlining the secret. What ships is the credential-handling code path and a
|
|
15
|
+
* client that authenticates with `undefined` - which 401s against Connect and
|
|
16
|
+
* looks like a server bug. This turns that into a build-time failure naming the
|
|
17
|
+
* entry to import instead.
|
|
18
|
+
*
|
|
19
|
+
* Wired through the `browser` export condition, which Next's client compiler
|
|
20
|
+
* resolves and its server, RSC and SSR passes do not - so the same import stays
|
|
21
|
+
* legal in a Route Handler, a Server Component and a non-Next backend.
|
|
22
|
+
*
|
|
23
|
+
* The filename is the error message. A bundler reaches this module while
|
|
24
|
+
* resolving a *named* import, so it reports "no matching export" and never
|
|
25
|
+
* evaluates the throw below - the path is the only part of that error carrying
|
|
26
|
+
* any meaning, so the path has to say what went wrong. The throw still covers
|
|
27
|
+
* side-effect, default and namespace imports, which do evaluate it.
|
|
28
|
+
*/
|
|
29
|
+
throw new Error('@cosmoops/connect-sdk: "@cosmoops/connect-sdk/server" and "@cosmoops/connect-sdk/next" hold your CONNECT_API_KEY and cannot be imported from browser code.\n' +
|
|
30
|
+
'Import "@cosmoops/connect-sdk/client" instead - its components and hooks call your own origin, and the bridge route reaches Connect for them.\n' +
|
|
31
|
+
'For types only, import from "@cosmoops/connect-sdk" (isomorphic) or use `import type`, which erases at compile time.');
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `npx @cosmoops/connect-sdk doctor` - checks a wired-up project for the
|
|
3
|
+
* mistakes that `init` cannot prevent.
|
|
4
|
+
*
|
|
5
|
+
* `init` writes the two files it owns. Everything else in the setup is a step
|
|
6
|
+
* someone performs by hand in a file this package must not rewrite - the
|
|
7
|
+
* provider goes into a layout somebody else wrote, the theme import goes into
|
|
8
|
+
* their stylesheet in a specific position, and the redirect URI lives in
|
|
9
|
+
* Connect rather than in the repo. Those are where setup actually breaks, and
|
|
10
|
+
* each one fails in a way that does not name its cause: a missing provider
|
|
11
|
+
* throws from a hook, a mis-ordered theme import silently loses to HeroUI's
|
|
12
|
+
* defaults, and an unregistered redirect URI only shows up as an OAuth error
|
|
13
|
+
* after a round trip to Connect.
|
|
14
|
+
*
|
|
15
|
+
* Deliberately offline. Connect exposes no endpoint that lists a client's
|
|
16
|
+
* registered redirect URIs, so there is nothing to check remotely that would
|
|
17
|
+
* justify the cost - and an offline check needs no credentials, which is what
|
|
18
|
+
* lets this run in CI on a pull request.
|
|
19
|
+
*
|
|
20
|
+
* The exit code is the point: `fail` means the app is broken and returns 1,
|
|
21
|
+
* `warn` means this cannot tell from the outside and returns 0.
|
|
22
|
+
*/
|
|
23
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
24
|
+
import { join, relative, resolve } from "node:path";
|
|
25
|
+
/** Directories that are never a project's own source, and are large enough to matter. */
|
|
26
|
+
const SKIP = new Set(["node_modules", ".next", ".git", "dist", "build", ".turbo", "coverage"]);
|
|
27
|
+
function walk(dir, extensions, found = [], depth = 0) {
|
|
28
|
+
if (depth > 8 || !existsSync(dir))
|
|
29
|
+
return found;
|
|
30
|
+
for (const entry of readdirSync(dir)) {
|
|
31
|
+
if (SKIP.has(entry))
|
|
32
|
+
continue;
|
|
33
|
+
const path = join(dir, entry);
|
|
34
|
+
if (statSync(path).isDirectory())
|
|
35
|
+
walk(path, extensions, found, depth + 1);
|
|
36
|
+
else if (extensions.some((extension) => entry.endsWith(extension)))
|
|
37
|
+
found.push(path);
|
|
38
|
+
}
|
|
39
|
+
return found;
|
|
40
|
+
}
|
|
41
|
+
function read(path) {
|
|
42
|
+
try {
|
|
43
|
+
return readFileSync(path, "utf8");
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return "";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function findAppDir(root) {
|
|
50
|
+
for (const candidate of [join(root, "app"), join(root, "src", "app")]) {
|
|
51
|
+
if (existsSync(candidate))
|
|
52
|
+
return candidate;
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The bridge is found by what it exports, not by where it sits.
|
|
58
|
+
*
|
|
59
|
+
* `createConnectHandlers({ basePath })` exists precisely so the route can be
|
|
60
|
+
* mounted somewhere other than `/api/connect`, so checking for that one path
|
|
61
|
+
* would report a false failure on every app that took the option.
|
|
62
|
+
*/
|
|
63
|
+
function checkBridge(appDir, root) {
|
|
64
|
+
const routes = walk(appDir, ["route.ts", "route.tsx", "route.js"]);
|
|
65
|
+
const bridge = routes.find((path) => /@cosmoops\/connect-sdk\/next/.test(read(path)));
|
|
66
|
+
if (!bridge) {
|
|
67
|
+
return {
|
|
68
|
+
status: "fail",
|
|
69
|
+
title: "Bridge route handler",
|
|
70
|
+
detail: 'No route re-exports the bridge. Create app/api/connect/[...connect]/route.ts containing:\n export { GET, POST } from "@cosmoops/connect-sdk/next";\n or run `npx @cosmoops/connect-sdk init`.',
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const source = read(bridge);
|
|
74
|
+
const exportsBoth = /\bGET\b/.test(source) && /\bPOST\b/.test(source);
|
|
75
|
+
if (!exportsBoth) {
|
|
76
|
+
return {
|
|
77
|
+
status: "fail",
|
|
78
|
+
title: "Bridge route handler",
|
|
79
|
+
detail: `${relative(root, bridge)} exports only one verb. GET and POST are the same function - the bridge routes on method itself - and sign-out POSTs, so both must be exported.`,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
return { status: "pass", title: `Bridge route handler (${relative(root, bridge)})` };
|
|
83
|
+
}
|
|
84
|
+
function checkProvider(appDir, root) {
|
|
85
|
+
const layouts = walk(appDir, ["layout.tsx", "layout.jsx"]);
|
|
86
|
+
const hosting = layouts.filter((path) => /<ConnectProvider/.test(read(path)));
|
|
87
|
+
if (hosting.length === 0) {
|
|
88
|
+
return {
|
|
89
|
+
status: "fail",
|
|
90
|
+
title: "ConnectProvider in a layout",
|
|
91
|
+
detail: 'Nothing renders <ConnectProvider>. Every client hook and component below it throws without one. In app/layout.tsx:\n import { ConnectProvider } from "@cosmoops/connect-sdk/client";\n <ConnectProvider>{children}</ConnectProvider>',
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
// A nested provider re-fetches the session and keeps a second cache that the
|
|
95
|
+
// first one's mutations never invalidate, so a plan change updates one half
|
|
96
|
+
// of the page. Worth naming even though both layouts look correct alone.
|
|
97
|
+
if (hosting.length > 1) {
|
|
98
|
+
return {
|
|
99
|
+
status: "warn",
|
|
100
|
+
title: "ConnectProvider in a layout",
|
|
101
|
+
detail: `Found in ${hosting.length} layouts (${hosting.map((path) => relative(root, path)).join(", ")}). Nested providers keep separate caches, so a mutation in one is invisible to the other. Keep the outermost one only.`,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
return { status: "pass", title: `ConnectProvider in a layout (${relative(root, hosting[0])})` };
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Order is the whole check.
|
|
108
|
+
*
|
|
109
|
+
* `theme.css` sets the HeroUI token values Connect's components read. Imported
|
|
110
|
+
* before `@heroui/styles`, HeroUI's own defaults are declared later, win on
|
|
111
|
+
* source order, and the theme silently does nothing - the app looks fine, just
|
|
112
|
+
* not themed. The import also has to live in the app's own stylesheet: from
|
|
113
|
+
* inside node_modules, Tailwind roots its content scan there and never scans
|
|
114
|
+
* the app.
|
|
115
|
+
*/
|
|
116
|
+
function checkTheme(root) {
|
|
117
|
+
const stylesheets = walk(root, [".css"]).filter((path) => !path.includes("node_modules"));
|
|
118
|
+
const importing = stylesheets.filter((path) => read(path).includes("@cosmoops/connect-sdk/theme.css"));
|
|
119
|
+
if (importing.length === 0) {
|
|
120
|
+
return {
|
|
121
|
+
status: "fail",
|
|
122
|
+
title: "Theme stylesheet imported",
|
|
123
|
+
detail: 'No stylesheet imports the Connect theme, so the components render with HeroUI defaults. Add it last of the three, in your own global CSS:\n @import "tailwindcss";\n @import "@heroui/styles";\n @import "@cosmoops/connect-sdk/theme.css";',
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
for (const path of importing) {
|
|
127
|
+
const source = read(path);
|
|
128
|
+
const connect = source.indexOf("@cosmoops/connect-sdk/theme.css");
|
|
129
|
+
const heroui = source.indexOf("@heroui/styles");
|
|
130
|
+
if (heroui !== -1 && heroui > connect) {
|
|
131
|
+
return {
|
|
132
|
+
status: "fail",
|
|
133
|
+
title: "Theme stylesheet imported",
|
|
134
|
+
detail: `${relative(root, path)} imports @heroui/styles *after* the Connect theme, so HeroUI's defaults win on source order and the theme has no effect. Put "@cosmoops/connect-sdk/theme.css" last.`,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return { status: "pass", title: `Theme stylesheet imported (${relative(root, importing[0])})` };
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* `.env.local` is read directly rather than trusting `process.env`, because
|
|
142
|
+
* the interesting case is a developer running this in a shell that never
|
|
143
|
+
* loaded it - exactly the shell `next dev` will inherit.
|
|
144
|
+
*/
|
|
145
|
+
function checkEnv(root) {
|
|
146
|
+
const files = [".env.local", ".env.development.local", ".env"].map((name) => join(root, name));
|
|
147
|
+
const combined = files.filter(existsSync).map(read).join("\n");
|
|
148
|
+
return ["CONNECT_API_KEY", "CONNECT_CLIENT_ID"].map((name) => {
|
|
149
|
+
// Horizontal whitespace only. `\s*` also matches the newline, so a bare
|
|
150
|
+
// `CONNECT_API_KEY=` was satisfied by the *next* line's value and an empty
|
|
151
|
+
// credential reported as set - which is the exact failure this check exists
|
|
152
|
+
// to catch.
|
|
153
|
+
const assigned = new RegExp(`^[ \\t]*${name}[ \\t]*=[ \\t]*\\S`, "m").test(combined);
|
|
154
|
+
if (assigned || process.env[name]) {
|
|
155
|
+
return { status: "pass", title: `${name} set` };
|
|
156
|
+
}
|
|
157
|
+
const declaredEmpty = new RegExp(`^[ \\t]*${name}[ \\t]*=`, "m").test(combined);
|
|
158
|
+
return {
|
|
159
|
+
status: "fail",
|
|
160
|
+
title: `${name} set`,
|
|
161
|
+
detail: declaredEmpty
|
|
162
|
+
? `Declared but empty in .env.local. The value is in your service's Integration tab in Connect.`
|
|
163
|
+
: `Not found in .env.local or the environment. Both values are in your service's Integration tab in Connect.`,
|
|
164
|
+
};
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Nothing here can verify this - Connect has no endpoint listing a client's
|
|
169
|
+
* redirect URIs - but it is the single most common reason a correct setup
|
|
170
|
+
* still fails at sign-in, so it is worth a line that always prints.
|
|
171
|
+
*/
|
|
172
|
+
function checkRedirectUri() {
|
|
173
|
+
return {
|
|
174
|
+
status: "warn",
|
|
175
|
+
title: "Redirect URI registered in Connect",
|
|
176
|
+
detail: "Not checkable from here. Confirm {your origin}/api/connect/callback is listed as a redirect URI in your service's Integration tab - including the deployed origin, not just http://localhost:3000.",
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
const MARKER = { pass: " ok ", warn: " note ", fail: " FAIL " };
|
|
180
|
+
export function runDoctor(argv = []) {
|
|
181
|
+
const root = resolve(argv[0] ?? process.cwd());
|
|
182
|
+
const appDir = findAppDir(root);
|
|
183
|
+
if (!appDir) {
|
|
184
|
+
console.error(`[connect-sdk] No App Router directory found in ${root} - looked for "app/" and "src/app/".\n` +
|
|
185
|
+
"Run this from your Next.js project root, or pass the path: npx @cosmoops/connect-sdk doctor ./my-app");
|
|
186
|
+
return 1;
|
|
187
|
+
}
|
|
188
|
+
console.log(`[connect-sdk] Checking ${relative(process.cwd(), root) || root}\n`);
|
|
189
|
+
const checks = [
|
|
190
|
+
checkBridge(appDir, root),
|
|
191
|
+
checkProvider(appDir, root),
|
|
192
|
+
checkTheme(root),
|
|
193
|
+
...checkEnv(root),
|
|
194
|
+
checkRedirectUri(),
|
|
195
|
+
];
|
|
196
|
+
for (const check of checks) {
|
|
197
|
+
console.log(` ${MARKER[check.status]} ${check.title}`);
|
|
198
|
+
if (check.detail)
|
|
199
|
+
console.log(` ${check.detail.replace(/\n/g, "\n ")}\n`);
|
|
200
|
+
}
|
|
201
|
+
const failed = checks.filter((check) => check.status === "fail").length;
|
|
202
|
+
console.log(failed === 0
|
|
203
|
+
? "\nNo problems found.\n"
|
|
204
|
+
: `\n${failed} problem${failed === 1 ? "" : "s"} to fix. Run \`npx @cosmoops/connect-sdk init\` to scaffold anything missing.\n`);
|
|
205
|
+
return failed === 0 ? 0 : 1;
|
|
206
|
+
}
|
package/dist/esm/cli/init.js
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
*/
|
|
23
23
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
24
24
|
import { dirname, join, relative, resolve } from "node:path";
|
|
25
|
+
import { runDoctor } from "./doctor.js";
|
|
25
26
|
const BRIDGE_ROUTE = `// The Connect bridge - the only place your API key is used.
|
|
26
27
|
//
|
|
27
28
|
// It answers your own origin, so the browser half of the SDK never holds a
|
|
@@ -38,7 +39,7 @@ const PLANS_PAGE = `"use client";
|
|
|
38
39
|
// with the other exports) whenever you want your own copy or layout.
|
|
39
40
|
export { ConnectPlansPage as default } from "@cosmoops/connect-sdk/client";
|
|
40
41
|
`;
|
|
41
|
-
const ENV_TEMPLATE = `# CosmoOps Connect - values come from your service's
|
|
42
|
+
const ENV_TEMPLATE = `# CosmoOps Connect - values come from your service's Integration tab.
|
|
42
43
|
CONNECT_API_KEY=
|
|
43
44
|
CONNECT_CLIENT_ID=
|
|
44
45
|
`;
|
|
@@ -105,7 +106,7 @@ export function runInit(argv = []) {
|
|
|
105
106
|
console.log(` ${marker} ${relative(root, target)} - ${scaffold.description}`);
|
|
106
107
|
}
|
|
107
108
|
const env = ensureEnv(root);
|
|
108
|
-
console.log(` ${env === "skipped" ? "exists " : env === "appended" ? "updated" : "created"} .env.local - fill in the two values from your service's
|
|
109
|
+
console.log(` ${env === "skipped" ? "exists " : env === "appended" ? "updated" : "created"} .env.local - fill in the two values from your service's Integration tab`);
|
|
109
110
|
// The two steps a scaffolder must not do for you: editing an existing layout
|
|
110
111
|
// means parsing and rewriting JSX someone else wrote, and the redirect URI
|
|
111
112
|
// lives in Connect, not in this repo.
|
|
@@ -131,7 +132,7 @@ Three things left, all one-time:
|
|
|
131
132
|
Tailwind roots its content scan inside node_modules and skips your app.
|
|
132
133
|
|
|
133
134
|
3. Register {your origin}/api/connect/callback as a redirect URI in your
|
|
134
|
-
service's
|
|
135
|
+
service's Integration tab in Connect.
|
|
135
136
|
|
|
136
137
|
No next.config.ts changes needed - not even transpilePackages: dist/ is
|
|
137
138
|
already ES2022 with "use client" hoisted, so Turbopack and webpack consume it
|
|
@@ -140,15 +141,17 @@ as-is.
|
|
|
140
141
|
Then <ConnectPlans />, <ConnectSubscriptionGate>, <ConnectFeatureGate> and the
|
|
141
142
|
rest work anywhere below the provider, and getConnectSession() reads the same
|
|
142
143
|
session from any Server Component.
|
|
144
|
+
|
|
145
|
+
Run \`npx @cosmoops/connect-sdk doctor\` when you have done those three - it
|
|
146
|
+
checks all of them and says which are still outstanding.
|
|
143
147
|
`);
|
|
144
148
|
return 0;
|
|
145
149
|
}
|
|
146
150
|
/**
|
|
147
|
-
*
|
|
148
|
-
* `check` later does not change how the existing one is invoked.
|
|
151
|
+
* `init` writes the wiring; `doctor` checks the parts `init` cannot write.
|
|
149
152
|
*
|
|
150
153
|
* A bare path runs `init` against it, so both `connect-sdk init ./my-app` and
|
|
151
|
-
* `connect-sdk ./my-app` work. A first argument that is neither
|
|
154
|
+
* `connect-sdk ./my-app` work. A first argument that is neither a command nor
|
|
152
155
|
* an existing directory is a typo, and saying so beats reporting that
|
|
153
156
|
* `./innit` contains no App Router - which is true, unhelpful, and points at
|
|
154
157
|
* the wrong mistake.
|
|
@@ -156,13 +159,22 @@ session from any Server Component.
|
|
|
156
159
|
export function main(argv) {
|
|
157
160
|
const [first, ...rest] = argv;
|
|
158
161
|
if (first === "--help" || first === "-h") {
|
|
159
|
-
console.log(
|
|
162
|
+
console.log([
|
|
163
|
+
"Usage: connect-sdk <command> [project-dir]",
|
|
164
|
+
"",
|
|
165
|
+
" init scaffold the bridge route, /plans page and .env.local",
|
|
166
|
+
" doctor check an existing setup and report what is missing",
|
|
167
|
+
"",
|
|
168
|
+
"With no command, runs init against the given directory (default: cwd).",
|
|
169
|
+
].join("\n"));
|
|
160
170
|
return 0;
|
|
161
171
|
}
|
|
162
172
|
if (first === "init")
|
|
163
173
|
return runInit(rest);
|
|
174
|
+
if (first === "doctor" || first === "check")
|
|
175
|
+
return runDoctor(rest);
|
|
164
176
|
if (!first || existsSync(first))
|
|
165
177
|
return runInit(argv);
|
|
166
|
-
console.error(`[connect-sdk] Unknown command "${first}". Try: connect-sdk init`);
|
|
178
|
+
console.error(`[connect-sdk] Unknown command "${first}". Try: connect-sdk init, or connect-sdk doctor`);
|
|
167
179
|
return 1;
|
|
168
180
|
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useState } from "react";
|
|
4
|
+
import { Ban, AlertTriangle, Clock, CreditCard, ExternalLink, X } from "lucide-react";
|
|
5
|
+
import { Button, Card, Skeleton } from "@heroui/react";
|
|
6
|
+
import { blockingBlockers } from "../../helpers.js";
|
|
7
|
+
import { useConnect, useConnectEntitlements } from "../provider.js";
|
|
8
|
+
import { ENTER, m, MotionProvider } from "./motion.js";
|
|
9
|
+
import { ConnectReadinessBanner } from "./readiness.js";
|
|
10
|
+
function formatDate(iso) {
|
|
11
|
+
return new Date(iso).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The single composed answer to "can this workspace use my app right now,
|
|
15
|
+
* and if not, which of the four things is it": choose a plan, wait on
|
|
16
|
+
* approval, resolve an overdue payment, or - a suspended workspace - none of
|
|
17
|
+
* the above, because nothing short of a platform admin fixes that one.
|
|
18
|
+
*
|
|
19
|
+
* Reuses the existing single sources of truth rather than re-deriving them:
|
|
20
|
+
* `blockingBlockers()` (`helpers.ts`) for severity, the same readiness read
|
|
21
|
+
* `ConnectReadinessGate`/`ConnectReadinessBanner` already use. `ConnectAccessGate`
|
|
22
|
+
* is a priority ordering over the same data, not a second opinion about it.
|
|
23
|
+
*
|
|
24
|
+
* Priority, first match wins: `suspended` > `no_subscription` >
|
|
25
|
+
* `onboarding_pending` > any other blocking code (`blocked`) >
|
|
26
|
+
* `payment_retry` (advisory - `children` still render) > `clear`.
|
|
27
|
+
*/
|
|
28
|
+
export function useConnectAccessGate() {
|
|
29
|
+
const { session, isLoading: sessionLoading } = useConnect();
|
|
30
|
+
const { data, isLoading: entitlementsLoading } = useConnectEntitlements();
|
|
31
|
+
if (sessionLoading || (session?.user && entitlementsLoading)) {
|
|
32
|
+
return { state: "loading", blocker: null, paymentRetry: null };
|
|
33
|
+
}
|
|
34
|
+
if (!session?.user) {
|
|
35
|
+
return { state: "signed_out", blocker: null, paymentRetry: null };
|
|
36
|
+
}
|
|
37
|
+
if (!data) {
|
|
38
|
+
// Signed in, not loading, yet nothing came back - a failed read (see
|
|
39
|
+
// `error` on `useConnectEntitlements`). Fail open rather than hard-block
|
|
40
|
+
// the whole app on a network hiccup; `ConnectReadinessBanner` makes the
|
|
41
|
+
// same call for its own "no data" branch.
|
|
42
|
+
return { state: "clear", blocker: null, paymentRetry: null };
|
|
43
|
+
}
|
|
44
|
+
const readiness = data.readiness;
|
|
45
|
+
const blocking = blockingBlockers(readiness);
|
|
46
|
+
const suspended = blocking.find((b) => b.code === "organization_suspended");
|
|
47
|
+
if (suspended)
|
|
48
|
+
return { state: "suspended", blocker: suspended, paymentRetry: null };
|
|
49
|
+
const noSubscription = blocking.find((b) => b.code === "subscription_missing");
|
|
50
|
+
if (noSubscription)
|
|
51
|
+
return { state: "no_subscription", blocker: noSubscription, paymentRetry: null };
|
|
52
|
+
const onboardingPending = blocking.find((b) => b.code === "onboarding_approval_pending");
|
|
53
|
+
if (onboardingPending) {
|
|
54
|
+
return { state: "onboarding_pending", blocker: onboardingPending, paymentRetry: null };
|
|
55
|
+
}
|
|
56
|
+
if (blocking.length > 0) {
|
|
57
|
+
return { state: "blocked", blocker: blocking[0] ?? null, paymentRetry: null };
|
|
58
|
+
}
|
|
59
|
+
const paymentRetry = readiness.readiness.blockers.find((b) => b.code === "payment_retry_pending");
|
|
60
|
+
if (paymentRetry)
|
|
61
|
+
return { state: "payment_retry", blocker: null, paymentRetry };
|
|
62
|
+
return { state: "clear", blocker: null, paymentRetry: null };
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Wrap your app's content once - typically in your root layout, alongside
|
|
66
|
+
* (not instead of) your own header/nav - and it renders exactly one of: the
|
|
67
|
+
* hard-block card for a suspended workspace, one with no plan, or one
|
|
68
|
+
* waiting on approval; your `children` plus a dismissible payment-due banner
|
|
69
|
+
* during an automatic dunning retry; or just `children` once everything is
|
|
70
|
+
* clear.
|
|
71
|
+
*
|
|
72
|
+
* **Do not wrap your own plans/pricing page with this.** The `no_subscription`
|
|
73
|
+
* card's button sends someone to Connect's subscribe page directly (see
|
|
74
|
+
* `GateCard`'s doc comment on why - it used to link to your in-app `/plans`
|
|
75
|
+
* instead, which is a dead end once this gate hides that very page too), but
|
|
76
|
+
* a customer can still navigate to your plans page on their own (a nav link,
|
|
77
|
+
* a bookmark) and must actually see it there. Since the gate is mounted once
|
|
78
|
+
* around every route, carving out that exception is your router's job, not
|
|
79
|
+
* a prop on this component: check the current path in your layout/shell and
|
|
80
|
+
* skip wrapping `children` in `<ConnectAccessGate>` for that one route.
|
|
81
|
+
*
|
|
82
|
+
* **Signed-out renders `children`, not a fallback** - deliberately different
|
|
83
|
+
* from `ConnectReadinessGate`/`ConnectSubscriptionGate`, which show nothing
|
|
84
|
+
* until signed in. None of the four states this component composes is a
|
|
85
|
+
* property of a signed-out visitor, and a component mounted around your
|
|
86
|
+
* entire app must not hide a public landing page behind an empty gate. Your
|
|
87
|
+
* own sign-in flow decides what a signed-out visitor sees.
|
|
88
|
+
*
|
|
89
|
+
* **This is a UX gate, not a security boundary** - same caveat as every
|
|
90
|
+
* other gate in this package. The authoritative check is
|
|
91
|
+
* `client.entitlements.getReadiness` on your server, before you do the
|
|
92
|
+
* thing.
|
|
93
|
+
*/
|
|
94
|
+
export function ConnectAccessGate({ children, fallback, loading, className }) {
|
|
95
|
+
const gate = useConnectAccessGate();
|
|
96
|
+
if (gate.state === "loading") {
|
|
97
|
+
return _jsx(_Fragment, { children: loading ?? _jsx(Skeleton, { className: `h-32 rounded-xl ${className ?? ""}` }) });
|
|
98
|
+
}
|
|
99
|
+
if (gate.state === "signed_out" || gate.state === "clear") {
|
|
100
|
+
return _jsx(_Fragment, { children: children });
|
|
101
|
+
}
|
|
102
|
+
if (gate.state === "payment_retry") {
|
|
103
|
+
return (_jsxs(_Fragment, { children: [gate.paymentRetry && _jsx(PaymentRetryBanner, { blocker: gate.paymentRetry, className: className }), children] }));
|
|
104
|
+
}
|
|
105
|
+
return (_jsx(_Fragment, { children: fallback ?? _jsx(AccessGateFallback, { state: gate.state, blocker: gate.blocker, className: className }) }));
|
|
106
|
+
}
|
|
107
|
+
function AccessGateFallback({ state, blocker, className, }) {
|
|
108
|
+
if (state === "no_subscription") {
|
|
109
|
+
return (_jsx(GateCard, { icon: CreditCard, iconClassName: "text-accent", title: "Choose a plan to continue", message: blocker?.message ?? "This workspace isn't subscribed to this service yet.", actionLabel: "See plans", resolveUrl: blocker?.resolveUrl ?? null, className: className }));
|
|
110
|
+
}
|
|
111
|
+
if (state === "suspended") {
|
|
112
|
+
return (_jsx(GateCard, { icon: Ban, iconClassName: "text-danger", title: "Workspace suspended", message: blocker?.message ?? "This workspace has been suspended.", resolveUrl: null, className: className }));
|
|
113
|
+
}
|
|
114
|
+
if (state === "onboarding_pending") {
|
|
115
|
+
return (_jsx(GateCard, { icon: Clock, iconClassName: "text-muted", title: "Waiting on approval", message: blocker?.message ?? "This workspace is waiting on approval before it can use this service.", resolveUrl: null, className: className }));
|
|
116
|
+
}
|
|
117
|
+
// "blocked" - any other blocking code (verification, audience, seats, ...).
|
|
118
|
+
// Full fidelity for a code this component doesn't special-case: the same
|
|
119
|
+
// banner-in-a-card `ConnectReadinessGate` falls back to, rather than
|
|
120
|
+
// `GateCard`'s single-blocker shape - there can be more than one of these
|
|
121
|
+
// at once, and each already carries its own action.
|
|
122
|
+
return (_jsx(Card, { className: className, children: _jsx(Card.Content, { className: "py-6", children: _jsx(ConnectReadinessBanner, {}) }) }));
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* One card shape for every hard-block state: an icon, what's wrong, and -
|
|
126
|
+
* when the server sent a `resolveUrl` - the one button that fixes it,
|
|
127
|
+
* opening Connect directly in a new tab. The same pattern every other
|
|
128
|
+
* resolvable blocker in this package uses (`BlockerRow`, `PaymentRetryBanner`
|
|
129
|
+
* below) - `no_subscription` used to be the one exception, sending someone
|
|
130
|
+
* to the host app's own `/plans` page instead. That was a deliberate choice
|
|
131
|
+
* on `ConnectNoSubscriptionCard` (browsing plans belongs in your product),
|
|
132
|
+
* but inside a gate mounted around your *entire* app it is a dead end: the
|
|
133
|
+
* card replaces whatever page it is rendered on, including your own plans
|
|
134
|
+
* page if you did not carve it out (see `ConnectAccessGate`'s doc comment),
|
|
135
|
+
* so "see plans" landing back on the same blocked screen never gets anyone
|
|
136
|
+
* to a choice they can act on. Sending them to Connect's own subscribe page
|
|
137
|
+
* always resolves.
|
|
138
|
+
*/
|
|
139
|
+
function GateCard({ icon: Icon, iconClassName, title, message, actionLabel, resolveUrl, className, }) {
|
|
140
|
+
return (_jsx(MotionProvider, { children: _jsx(m.div, { initial: { opacity: 0, y: -6 }, animate: { opacity: 1, y: 0 }, transition: ENTER, children: _jsxs(Card, { className: className, children: [_jsxs(Card.Header, { children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Icon, { className: `size-5 shrink-0 ${iconClassName}`, "aria-hidden": "true" }), _jsx(Card.Title, { children: title })] }), _jsx(Card.Description, { children: message })] }), resolveUrl && (_jsx(Card.Footer, { children: _jsxs(Button, { variant: "primary", onPress: () => window.open(resolveUrl, "_blank", "noopener,noreferrer"), children: [actionLabel ?? "Resolve on Connect", _jsx(ExternalLink, { className: "size-3.5" })] }) }))] }) }) }));
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The skippable payment-due warning. Dismissal is scoped to this specific
|
|
144
|
+
* dunning cycle - keyed by `graceEndsAt`, so a dismissed banner reappears on
|
|
145
|
+
* its own if a *new* retry cycle starts (a different `graceEndsAt`) even
|
|
146
|
+
* though an old dismissal is still on record.
|
|
147
|
+
*/
|
|
148
|
+
function PaymentRetryBanner({ blocker, className, }) {
|
|
149
|
+
const dismissKey = blocker.graceEndsAt ? `connect_dismissed_payment_retry_pending_${blocker.graceEndsAt}` : null;
|
|
150
|
+
const [dismissed, setDismissed] = useState(() => dismissKey !== null && typeof window !== "undefined" && window.localStorage.getItem(dismissKey) === "1");
|
|
151
|
+
if (dismissed)
|
|
152
|
+
return null;
|
|
153
|
+
return (_jsx(MotionProvider, { children: _jsxs(m.div, { className: `flex flex-wrap items-center justify-between gap-3 rounded-lg bg-accent-soft px-3 py-2 text-sm text-accent ${className ?? ""}`, role: "status", initial: { opacity: 0, y: -6 }, animate: { opacity: 1, y: 0 }, transition: ENTER, children: [_jsxs("span", { className: "flex items-center gap-2", children: [_jsx(AlertTriangle, { className: "size-4 shrink-0", "aria-hidden": "true" }), blocker.message, blocker.graceEndsAt && ` Resolve by ${formatDate(blocker.graceEndsAt)} to avoid losing access.`] }), _jsxs("div", { className: "flex items-center gap-2", children: [blocker.resolveUrl && (_jsxs(Button, { variant: "secondary", onPress: () => window.open(blocker.resolveUrl, "_blank", "noopener,noreferrer"), children: ["Resolve payment", _jsx(ExternalLink, { className: "size-3.5" })] })), _jsx(Button, { variant: "tertiary", isIconOnly: true, "aria-label": "Dismiss", onPress: () => {
|
|
154
|
+
setDismissed(true);
|
|
155
|
+
if (dismissKey && typeof window !== "undefined")
|
|
156
|
+
window.localStorage.setItem(dismissKey, "1");
|
|
157
|
+
}, children: _jsx(X, { className: "size-4" }) })] })] }) }));
|
|
158
|
+
}
|
|
@@ -4,6 +4,8 @@ import { useState } from "react";
|
|
|
4
4
|
import { AlertDialog, Button, Chip, Skeleton } from "@heroui/react";
|
|
5
5
|
import { LogOut, Monitor, MonitorSmartphone, Smartphone, Tablet } from "lucide-react";
|
|
6
6
|
import { useConnect, useConnectSessions } from "../provider.js";
|
|
7
|
+
import { AnimatePresence, EASE_OUT_QUART, m, MotionProvider } from "./motion.js";
|
|
8
|
+
import { ICON, PANEL_FILL } from "./surfaces.js";
|
|
7
9
|
import { formatRelativeTime } from "../../format-relative-time.js";
|
|
8
10
|
const DEVICE_ICONS = {
|
|
9
11
|
desktop: Monitor,
|
|
@@ -75,13 +77,13 @@ export function ConnectAccountSessions({ className, maxVisible = 4 }) {
|
|
|
75
77
|
const [isRevokingOthers, setIsRevokingOthers] = useState(false);
|
|
76
78
|
const [showAll, setShowAll] = useState(false);
|
|
77
79
|
if (isLoading) {
|
|
78
|
-
return (_jsxs("section", { className: `flex flex-col gap-3 ${className ?? ""}`, children: [_jsx(Skeleton, { className: "h-4 w-28" }), _jsx("div", { className:
|
|
80
|
+
return (_jsxs("section", { className: `flex flex-col gap-3 ${className ?? ""}`, children: [_jsx(Skeleton, { className: "h-4 w-28" }), _jsx("div", { className: `flex flex-col divide-y divide-border overflow-hidden rounded-xl border border-border ${PANEL_FILL}`, children: Array.from({ length: 2 }, (_, index) => (_jsxs("div", { className: "flex items-center gap-3 px-3 py-3", children: [_jsx(Skeleton, { className: "size-9 shrink-0 rounded-xl" }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-1.5", children: [_jsx(Skeleton, { className: "h-3.5 w-32" }), _jsx(Skeleton, { className: "h-3 w-24" })] })] }, index))) })] }));
|
|
79
81
|
}
|
|
80
82
|
// A failed read used to render as *nothing*, which is indistinguishable
|
|
81
83
|
// from "you have no other devices" - the one reading of this list that
|
|
82
84
|
// should never be guessed at.
|
|
83
85
|
if (error) {
|
|
84
|
-
return (_jsxs("section", { className: `flex flex-col gap-2 ${className ?? ""}`, children: [_jsx("p", { className: "text-sm font-medium text-foreground", children: "Active sessions" }), _jsx("p", { className:
|
|
86
|
+
return (_jsxs("section", { className: `flex flex-col gap-2 ${className ?? ""}`, children: [_jsx("p", { className: "text-sm font-medium text-foreground", children: "Active sessions" }), _jsx("p", { className: `rounded-xl border border-border ${PANEL_FILL} px-3 py-4 text-xs text-muted`, children: "Could not load your sessions. Try again in a moment." })] }));
|
|
85
87
|
}
|
|
86
88
|
const sessions = ordered(data?.items ?? []);
|
|
87
89
|
if (sessions.length === 0)
|
|
@@ -89,21 +91,21 @@ export function ConnectAccountSessions({ className, maxVisible = 4 }) {
|
|
|
89
91
|
const hasOtherSessions = sessions.some((session) => !session.isCurrent);
|
|
90
92
|
const isCollapsible = maxVisible > 0 && sessions.length > maxVisible;
|
|
91
93
|
const visible = isCollapsible && !showAll ? sessions.slice(0, maxVisible) : sessions;
|
|
92
|
-
return (_jsxs("section", { className: `flex flex-col gap-3 ${className ?? ""}`, children: [_jsxs("div", { className: "flex items-start justify-between gap-3", children: [_jsxs("div", { className: "min-w-0", children: [_jsxs("p", { className: "flex items-center gap-2 text-sm font-medium text-foreground", children: ["Active sessions", _jsx(Chip, { size: "sm", variant: "soft", children: sessions.length })] }), _jsx("p", { className: "text-xs text-muted", children: "Devices signed in to your Connect account." })] }), hasOtherSessions && (_jsx(Button, { size: "sm", variant: "tertiary", className: "shrink-0 text-xs text-danger", isPending: isRevokingOthers, isDisabled: isRevokingOthers, onPress: () => {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
94
|
+
return (_jsx(MotionProvider, { children: _jsxs("section", { className: `flex flex-col gap-3 ${className ?? ""}`, children: [_jsxs("div", { className: "flex items-start justify-between gap-3", children: [_jsxs("div", { className: "min-w-0", children: [_jsxs("p", { className: "flex items-center gap-2 text-sm font-medium text-foreground", children: ["Active sessions", _jsx(Chip, { size: "sm", variant: "soft", children: sessions.length })] }), _jsx("p", { className: "text-xs text-muted", children: "Devices signed in to your Connect account." })] }), hasOtherSessions && (_jsx(Button, { size: "sm", variant: "tertiary", className: "shrink-0 text-xs text-danger", isPending: isRevokingOthers, isDisabled: isRevokingOthers, onPress: () => {
|
|
95
|
+
setIsRevokingOthers(true);
|
|
96
|
+
void mutateResource("/sessions/revoke-others")
|
|
97
|
+
.then(() => {
|
|
98
|
+
invalidateResource("/sessions");
|
|
99
|
+
refetch();
|
|
100
|
+
})
|
|
101
|
+
.finally(() => setIsRevokingOthers(false));
|
|
102
|
+
}, children: "Sign out others" }))] }), _jsx("div", { className: `flex flex-col divide-y divide-border overflow-hidden rounded-xl border border-border ${PANEL_FILL}`, children: _jsx(AnimatePresence, { initial: false, children: visible.map((session) => {
|
|
103
|
+
const Icon = DEVICE_ICONS[session.device.deviceType];
|
|
104
|
+
return (_jsxs(m.div, { layout: true, exit: { opacity: 0, height: 0, overflow: "hidden" }, transition: { duration: 0.25, ease: EASE_OUT_QUART }, className: "flex items-center gap-3 px-3 py-2.5", children: [_jsx("span", { className: `flex size-9 shrink-0 items-center justify-center rounded-xl ${session.isCurrent ? "bg-accent-soft text-accent-soft-foreground" : "bg-surface text-muted"}`, children: _jsx(Icon, { className: ICON, "aria-hidden": "true" }) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("span", { className: "flex items-center gap-2", children: [_jsx("span", { className: "truncate text-sm font-medium text-foreground", children: deviceLabel(session) }), session.isCurrent && (_jsx(Chip, { size: "sm", variant: "soft", color: "accent", className: "shrink-0", children: "This device" }))] }), _jsx("p", { className: "truncate text-xs text-muted", children: metaLine(session) })] }), !session.isCurrent && (_jsx(RevokeRow, { session: session, onRevoke: () => {
|
|
105
|
+
void mutateResource("/sessions/revoke", { sessionId: session.id }).then(() => {
|
|
106
|
+
invalidateResource("/sessions");
|
|
107
|
+
refetch();
|
|
108
|
+
});
|
|
109
|
+
} }))] }, session.id));
|
|
110
|
+
}) }) }), isCollapsible && (_jsx(Button, { size: "sm", variant: "tertiary", className: "self-start text-xs", onPress: () => setShowAll((open) => !open), children: showAll ? "Show fewer" : `Show all ${sessions.length} devices` }))] }) }));
|
|
109
111
|
}
|