@palettelab/cli 0.3.17 → 0.3.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/README.md CHANGED
@@ -8,7 +8,8 @@ The installed executable is `pltt`.
8
8
 
9
9
  - Node.js 18+
10
10
  - Python 3.12+ for local backend simulation
11
- - Docker Desktop only for `pltt dev --platform`
11
+ - No Docker is required for normal app development, testing, or publishing.
12
+ - Docker Desktop is only for internal `pltt dev --platform` parity checks.
12
13
 
13
14
  ## Install
14
15
 
@@ -48,8 +49,10 @@ Run a no-Docker local SDK simulator with your plugin mounted live. Run this from
48
49
 
49
50
  ```bash
50
51
  pltt dev
51
- pltt dev --platform
52
+ pltt sandbox --env staging
53
+ pltt dev --sandbox --env staging
52
54
  pltt dev --cloud --env staging
55
+ pltt dev --platform
53
56
  ```
54
57
 
55
58
  By default this starts:
@@ -57,18 +60,27 @@ By default this starts:
57
60
  - A small local app shell on the first available port starting at http://localhost:3000
58
61
  - A local FastAPI backend runner on the first available port starting at http://localhost:8000
59
62
  - A mock Palette platform context for `usePlatform()`, toasts, org/user data, and authenticated API calls
63
+ - A plugin-local SQLite database under `.palette/dev/` when `capabilities.database` or `database` is enabled
60
64
 
61
65
  Your frontend entry is bundled and watched. Your backend entry is loaded under
62
66
  `/api/v1/plugins/<your-id>/*` with a dev `PluginContext`, so normal SDK calls
63
67
  work without Docker or platform source.
64
68
 
69
+ For Python apps with database tables, `ctx.db` is an async SQLAlchemy session in
70
+ local dev. The simulator imports `backend/api/models.py` when present and creates
71
+ tables from `palette_sdk.db.PluginBase.metadata`. Production installs still use
72
+ the declared Alembic migrations and platform-managed Postgres/RLS.
73
+
65
74
  `3000` and `8000` are preferred defaults, not hard requirements. If either port is already in use, `pltt dev` automatically picks the next free port and prints the actual URLs.
66
75
 
67
- `pltt dev --platform` runs the full Docker `platform-dev` image for deeper
68
- integration/parity testing. It pulls `ghcr.io/palette-lab/platform-dev:latest`
69
- and mounts your plugin at `/plugins/<your-id>`.
76
+ `pltt dev --sandbox` skips Docker and publishes a reviewable preview to a configured Palette sandbox. This is the payment-gateway-style flow: your app uses local SDKs, while real platform services such as login, Data Room, storage, database policies, logs, review, and publish lifecycle run in the hosted sandbox. It defaults to `--env staging` unless `--env` or `PALETTE_ENV` is set, adds a 24-hour preview TTL by default, and prints the preview/status/log commands returned by the platform.
77
+
78
+ `pltt dev --cloud` is kept as an alias for `--sandbox`.
70
79
 
71
- `pltt dev --cloud` skips Docker and publishes a reviewable preview to a configured cloud sandbox. It defaults to `--env staging` unless `--env` or `PALETTE_ENV` is set, adds a 24-hour preview TTL by default, and prints the preview/status/log commands returned by the platform.
80
+ `pltt sandbox --env staging` is the same hosted preview flow as
81
+ `pltt dev --sandbox --env staging`.
82
+
83
+ `pltt dev --platform` runs the full Docker `platform-dev` image for internal platform parity testing. App developers should not need it. It pulls `ghcr.io/palette-lab/platform-dev:latest` and mounts your plugin at `/plugins/<your-id>`.
72
84
 
73
85
  Environment variables:
74
86
 
@@ -77,6 +89,16 @@ Environment variables:
77
89
  | `PALETTE_DEV_IMAGE` | `ghcr.io/palette-lab/platform-dev:latest` | Override the platform image for `--platform` |
78
90
  | `PALETTE_FRONTEND_PORT` | `3000` | Preferred starting host port for the frontend |
79
91
  | `PALETTE_BACKEND_PORT` | `8000` | Preferred starting host port for the backend |
92
+ | `PALETTE_DEV_DATABASE_URL` | `.palette/dev/<plugin-id>.sqlite3` | Override the local dev database URL |
93
+
94
+ ### `pltt login`
95
+
96
+ Save a Palette sandbox or production environment URL plus token in `~/.palette/config.json` with file mode `0600`. Environment variables still override the stored token when present.
97
+
98
+ ```bash
99
+ pltt login --env staging --url https://sandbox.pltt.ai --token <publish-token>
100
+ pltt dev --sandbox --env staging
101
+ ```
80
102
 
81
103
  ### `pltt doctor`
82
104
 
@@ -86,7 +108,15 @@ Check local tooling and common setup problems.
86
108
  pltt doctor
87
109
  ```
88
110
 
89
- Checks include Node version, Docker availability, platform image availability, port availability, manifest validity, entry files, and frontend bundling.
111
+ Checks include Node version, port availability, manifest validity, entry files, and frontend bundling.
112
+
113
+ Docker is intentionally skipped by default:
114
+
115
+ ```bash
116
+ pltt doctor --platform
117
+ ```
118
+
119
+ Use `--platform` only when validating the internal Docker parity harness.
90
120
 
91
121
  ### `pltt build`
92
122
 
@@ -135,7 +165,7 @@ pltt publish --env staging --ttl-hours 24
135
165
 
136
166
  Publishing first runs the same contract checks as `pltt test`. If preflight passes, it bundles frontend/backend artifacts, uploads them, creates a `pending_review` publish record, and prints review/preview URLs when the platform returns them.
137
167
 
138
- `--ttl-hours` sets an expiration on the preview URL. It is mainly used by `pltt dev --cloud`, which defaults previews to 24 hours.
168
+ `--ttl-hours` sets an expiration on the preview URL. It is mainly used by `pltt dev --sandbox`, which defaults previews to 24 hours.
139
169
 
140
170
  Environment config is read from `./palette.config.json`, `~/.palette/config.json`, or `PALETTE_<ENV>_URL` plus `PALETTE_<ENV>_TOKEN` / `PALETTE_PUBLISH_TOKEN`.
141
171
 
@@ -176,7 +206,7 @@ If no plugin ID is provided, the CLI uses the current `palette-plugin.json` or `
176
206
  - `bin/pltt.js` — entry point
177
207
  - `backend-sdk/` — backend SDK files used by local contract tests and simulator
178
208
  - `lib/` — pure-Node command implementations (no runtime dependencies)
179
- - `platform-dev/docker-compose.yml` — compose file for `pltt dev --platform`
209
+ - `platform-dev/docker-compose.yml` — compose file for internal `pltt dev --platform` parity checks
180
210
  - `template-fallback/` — offline fallback for `pltt init` if git is unavailable
181
211
 
182
212
  ## See also
package/lib/cli.js CHANGED
@@ -6,6 +6,7 @@ const doctor = require("./commands/doctor")
6
6
  const build = require("./commands/build")
7
7
  const test = require("./commands/test")
8
8
  const publish = require("./commands/publish")
9
+ const login = require("./commands/login")
9
10
  const pkg = require("./commands/package")
10
11
  const status = require("./commands/status")
11
12
  const logs = require("./commands/logs")
@@ -14,11 +15,16 @@ const COMMANDS = {
14
15
  init: { run: init, help: "Scaffold a new plugin directory from the template" },
15
16
  dev: {
16
17
  run: dev,
17
- help: "Run the local SDK simulator; use --platform for Docker platform parity",
18
+ help: "Run the no-Docker SDK simulator; use --sandbox for hosted preview",
18
19
  },
20
+ sandbox: {
21
+ run: (args, ctx) => dev([...args, "--sandbox"], ctx),
22
+ help: "Publish a no-Docker hosted sandbox preview",
23
+ },
24
+ login: { run: login, help: "Save a Palette sandbox environment for publish/dev preview" },
19
25
  doctor: {
20
26
  run: doctor,
21
- help: "Check local tooling, ports, manifest, Docker, and frontend bundling",
27
+ help: "Check local tooling, ports, manifest, and frontend bundling",
22
28
  },
23
29
  build: { run: build, help: "Validate palette-plugin.json and check entry points exist" },
24
30
  test: { run: test, help: "Run local plugin contract checks before publishing" },
@@ -50,8 +56,13 @@ function printHelp() {
50
56
  console.log(" --env <name> Target environment from ~/.palette/config.json (default: local)")
51
57
  console.log(" -y, --yes Skip interactive confirmation for production pushes")
52
58
  console.log("\nDev flags:")
53
- console.log(" --platform Run the full Docker platform-dev container")
54
- console.log(" --cloud Publish a reviewable preview to a configured cloud sandbox")
59
+ console.log(" --sandbox Publish a reviewable preview to a configured Palette sandbox (no Docker)")
60
+ console.log(" --cloud Alias for --sandbox")
61
+ console.log(" --platform Internal only: run the Docker platform-dev parity container")
62
+ console.log("\nLogin flags:")
63
+ console.log(" --url <url> Palette platform URL for pltt login")
64
+ console.log(" --token <token> Publish token for pltt login")
65
+ console.log(" --no-default Do not make this environment the default")
55
66
  console.log("\nInit flags:")
56
67
  console.log(" --template <name> One of: dashboard, agent-tool, external-service, database, frontend-only")
57
68
  console.log("\nLogs flags:")
@@ -59,7 +70,10 @@ function printHelp() {
59
70
  console.log(" -f, --follow Stream events (poll every 3s)")
60
71
  console.log("\nExamples:")
61
72
  console.log(" pltt init my-app --template database")
73
+ console.log(" pltt login --env staging --url https://sandbox.pltt.ai --token <token>")
62
74
  console.log(" cd my-app && pltt dev")
75
+ console.log(" pltt sandbox --env staging")
76
+ console.log(" pltt dev --sandbox --env staging")
63
77
  console.log(" pltt package")
64
78
  console.log(" pltt publish --env staging")
65
79
  console.log(" pltt status")
@@ -76,7 +76,7 @@ function imagePullHelp(image, output) {
76
76
 
77
77
  async function run(args, { cwd }) {
78
78
  const { flags, rest } = parseFlags(args)
79
- const cloud = rest.includes("--cloud")
79
+ const cloud = rest.includes("--cloud") || rest.includes("--sandbox")
80
80
  const platform = rest.includes("--platform")
81
81
  if (cloud) {
82
82
  const json = args.includes("--json")
@@ -92,7 +92,7 @@ async function run(args, { cwd }) {
92
92
  if (!flags.env && !process.env.PALETTE_ENV) publishArgs.push("--env", "staging")
93
93
  if (!json) {
94
94
  console.log(
95
- "[pltt] cloud dev publishes a reviewable preview to the configured cloud sandbox.",
95
+ "[pltt] sandbox dev publishes a reviewable preview to the configured Palette sandbox.",
96
96
  )
97
97
  }
98
98
  const record = await publish(publishArgs, { cwd })
@@ -146,6 +146,7 @@ async function run(args, { cwd }) {
146
146
  }
147
147
 
148
148
  console.log(`[pltt] starting ${DEFAULT_IMAGE} via docker compose`)
149
+ console.log("[pltt] --platform is for internal parity testing; app developers should use `pltt dev` or `pltt dev --sandbox`.")
149
150
  console.log(`[pltt] mounting ${cwd} → /plugins/${pluginId}`)
150
151
  if (ports.frontend !== ports.preferredFrontend) {
151
152
  console.log(`[pltt] frontend port ${ports.preferredFrontend} is busy; using ${ports.frontend}`)
@@ -51,27 +51,39 @@ function checkEntry(cwd, label, rel) {
51
51
 
52
52
  async function run(args, { cwd }) {
53
53
  let failures = 0
54
+ const platform = args.includes("--platform")
54
55
 
55
56
  if (nodeMajor() >= 18) ok(`Node ${process.versions.node}`)
56
57
  else failures += fail("Node 18+ is required", "Install Node.js 18 or newer.")
57
58
 
58
- if (dockerRunning()) ok("Docker is running")
59
- else failures += fail(
60
- "Docker is not running",
61
- "Start Docker Desktop, then rerun pltt doctor.",
62
- )
59
+ if (platform) {
60
+ if (dockerRunning()) ok("Docker is running")
61
+ else failures += fail(
62
+ "Docker is not running",
63
+ "Start Docker Desktop, then rerun pltt doctor --platform.",
64
+ )
63
65
 
64
- if (imageExistsLocally(DEFAULT_IMAGE)) {
65
- ok(`platform image is available locally: ${DEFAULT_IMAGE}`)
66
+ if (imageExistsLocally(DEFAULT_IMAGE)) {
67
+ ok(`platform image is available locally: ${DEFAULT_IMAGE}`)
68
+ } else {
69
+ warn(
70
+ `platform image is not present locally: ${DEFAULT_IMAGE}`,
71
+ "pltt dev --platform will try to pull it. If that fails, run docker login ghcr.io or set PALETTE_DEV_IMAGE.",
72
+ )
73
+ }
66
74
  } else {
67
75
  warn(
68
- `platform image is not present locally: ${DEFAULT_IMAGE}`,
69
- "pltt dev will try to pull it. If that fails, run docker login ghcr.io or set PALETTE_DEV_IMAGE.",
76
+ "Docker check skipped",
77
+ "Normal app development uses no Docker. Run `pltt doctor --platform` only for internal platform parity testing.",
70
78
  )
71
79
  }
72
80
 
73
81
  try {
74
- const ports = await resolveDevPorts({ frontend: FRONTEND_PORT, backend: BACKEND_PORT })
82
+ const ports = await resolveDevPorts({
83
+ frontend: FRONTEND_PORT,
84
+ backend: BACKEND_PORT,
85
+ host: platform ? "0.0.0.0" : "127.0.0.1",
86
+ })
75
87
  if (ports.frontend === FRONTEND_PORT) ok(`frontend port ${FRONTEND_PORT} is available`)
76
88
  else warn(`frontend port ${FRONTEND_PORT} is already in use`, `pltt dev will use ${ports.frontend}`)
77
89
  if (ports.backend === BACKEND_PORT) ok(`backend port ${BACKEND_PORT} is available`)
@@ -84,6 +84,9 @@ function rewriteScaffold(destDir, slug, displayName) {
84
84
  const rewrittenManifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"))
85
85
  rewrittenManifest.id = slug
86
86
  rewrittenManifest.name = displayName
87
+ if (rewrittenManifest.database?.schema) {
88
+ rewrittenManifest.database.schema = `app_${slug.replace(/-/g, "_")}`
89
+ }
87
90
  fs.writeFileSync(manifestPath, JSON.stringify(rewrittenManifest, null, 2) + "\n")
88
91
  }
89
92
 
@@ -0,0 +1,51 @@
1
+ "use strict"
2
+
3
+ const { parseFlags, writeUserEnvironment } = require("../environments")
4
+
5
+ function tokenEnvFor(name) {
6
+ if (name === "production") return "PALETTE_PROD_TOKEN"
7
+ return `PALETTE_${name.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_TOKEN`
8
+ }
9
+
10
+ async function run(argv) {
11
+ const { flags } = parseFlags(argv)
12
+ const name = flags.env || process.env.PALETTE_ENV || "staging"
13
+ const url = flags.url || process.env.PALETTE_PLATFORM_URL || process.env[`PALETTE_${name.toUpperCase()}_URL`]
14
+ const token = flags.token || process.env.PALETTE_PUBLISH_TOKEN || process.env[tokenEnvFor(name)]
15
+
16
+ if (!url) {
17
+ console.error(
18
+ `[pltt] missing platform URL for "${name}".\n` +
19
+ ` Usage: pltt login --env ${name} --url https://palette.example.com --token <publish-token>`,
20
+ )
21
+ process.exit(1)
22
+ }
23
+ if (!token) {
24
+ console.error(
25
+ `[pltt] missing publish token for "${name}".\n` +
26
+ ` Pass --token <token> or set $PALETTE_PUBLISH_TOKEN.`,
27
+ )
28
+ process.exit(1)
29
+ }
30
+
31
+ const tokenEnv = tokenEnvFor(name)
32
+ const configPath = writeUserEnvironment({
33
+ name,
34
+ url,
35
+ token,
36
+ tokenEnv,
37
+ defaultEnvironment: flags.default,
38
+ })
39
+
40
+ if (flags.json) {
41
+ console.log(JSON.stringify({ ok: true, env: name, url: url.replace(/\/+$/, ""), token_env: tokenEnv, config: configPath }, null, 2))
42
+ return
43
+ }
44
+
45
+ console.log(`[pltt] saved ${name} → ${url.replace(/\/+$/, "")}`)
46
+ console.log(`[pltt] config: ${configPath}`)
47
+ console.log(`[pltt] token stored in user config with file mode 0600`)
48
+ console.log(`[pltt] env override: ${tokenEnv}`)
49
+ }
50
+
51
+ module.exports = run
@@ -44,12 +44,17 @@ function pyprojectDependencies(cwd) {
44
44
  return extractPyprojectDependencies(fs.readFileSync(pyprojectPath, "utf8"))
45
45
  }
46
46
 
47
- function ensurePythonEnv(cwd, devDir) {
47
+ function needsDatabase(manifest) {
48
+ return Boolean(manifest.database || manifest.capabilities?.database)
49
+ }
50
+
51
+ function ensurePythonEnv(cwd, devDir, manifest) {
48
52
  const hostPython = process.env.PALETTE_PYTHON || "python3"
49
53
  const venvDir = path.join(devDir, "backend-venv")
50
54
  const venvPython = path.join(venvDir, "bin", "python")
51
55
  const lockPath = path.join(venvDir, ".palette-dev-deps-lock")
52
- const deps = Array.from(new Set([...pyprojectDependencies(cwd), "uvicorn>=0.30.0"]))
56
+ const dbDeps = needsDatabase(manifest) ? ["aiosqlite>=0.20.0", "greenlet>=3.0.0"] : []
57
+ const deps = Array.from(new Set([...pyprojectDependencies(cwd), ...dbDeps, "uvicorn>=0.30.0"]))
53
58
  const lock = JSON.stringify(deps)
54
59
 
55
60
  if (!fs.existsSync(venvPython)) {
@@ -88,10 +93,13 @@ function ensurePythonEnv(cwd, devDir) {
88
93
  function writeBackendRunner(cwd, devDir, manifest, backendEntry) {
89
94
  const runner = path.join(devDir, "backend_runner.py")
90
95
  const sdkPath = localBackendSdkPath()
96
+ const databasePath = path.join(devDir, `${manifest.id}.sqlite3`)
91
97
  const content = `from __future__ import annotations
92
98
 
99
+ import importlib
93
100
  import importlib.util
94
101
  import json
102
+ import os
95
103
  import pathlib
96
104
  import sys
97
105
  from types import SimpleNamespace
@@ -104,6 +112,8 @@ ROOT = pathlib.Path(${JSON.stringify(cwd)}).resolve()
104
112
  ENTRY = pathlib.Path(${JSON.stringify(path.resolve(cwd, backendEntry))}).resolve()
105
113
  MANIFEST = json.loads(${JSON.stringify(JSON.stringify(manifest))})
106
114
  SDK_PATH = ${JSON.stringify(sdkPath || "")}
115
+ DATABASE_ENABLED = bool(MANIFEST.get("database") or MANIFEST.get("capabilities", {}).get("database"))
116
+ DATABASE_URL = os.environ.get("PALETTE_DEV_DATABASE_URL", "sqlite+aiosqlite:///${databasePath.replace(/\\/g, "/")}")
107
117
 
108
118
  if SDK_PATH:
109
119
  sys.path.insert(0, SDK_PATH)
@@ -118,9 +128,21 @@ router = getattr(module, "router", None)
118
128
  if router is None:
119
129
  raise RuntimeError(f"backend entry has no router export: {ENTRY}")
120
130
 
131
+ engine = None
132
+ SessionLocal = None
133
+ if DATABASE_ENABLED:
134
+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
135
+ from palette_sdk.db import PluginBase
136
+
137
+ models_file = ENTRY.parent / "models.py"
138
+ if models_file.exists():
139
+ importlib.import_module("models")
140
+
141
+ engine = create_async_engine(DATABASE_URL)
142
+ SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
143
+
121
144
  class DevPluginContextMiddleware(BaseHTTPMiddleware):
122
145
  async def dispatch(self, request: Request, call_next):
123
- request.state.db = None
124
146
  request.state.user = SimpleNamespace(
125
147
  id="dev-user",
126
148
  email="developer@palette.local",
@@ -132,7 +154,17 @@ class DevPluginContextMiddleware(BaseHTTPMiddleware):
132
154
  request.state.plugin_permissions = MANIFEST.get("permissions", [])
133
155
  request.state.plugin_config = {}
134
156
  request.state.storage = None
135
- return await call_next(request)
157
+ if SessionLocal is None:
158
+ request.state.db = None
159
+ return await call_next(request)
160
+
161
+ async with SessionLocal() as session:
162
+ request.state.db = session
163
+ try:
164
+ return await call_next(request)
165
+ except Exception:
166
+ await session.rollback()
167
+ raise
136
168
 
137
169
  app = FastAPI(title=f"{MANIFEST.get('name', 'Palette Plugin')} Local Backend")
138
170
  app.add_middleware(
@@ -144,6 +176,13 @@ app.add_middleware(
144
176
  )
145
177
  app.add_middleware(DevPluginContextMiddleware)
146
178
  app.include_router(router, prefix=f"/api/v1/plugins/{MANIFEST['id']}")
179
+
180
+ @app.on_event("startup")
181
+ async def create_local_database_tables():
182
+ if engine is None:
183
+ return
184
+ async with engine.begin() as conn:
185
+ await conn.run_sync(PluginBase.metadata.create_all)
147
186
  `
148
187
  fs.writeFileSync(runner, content)
149
188
  return runner
@@ -155,7 +194,7 @@ function startBackend(cwd, devDir, manifest, backendPort) {
155
194
  const absEntry = path.resolve(cwd, backendEntry)
156
195
  if (!fs.existsSync(absEntry)) throw new Error(`backend entry not found: ${backendEntry}`)
157
196
 
158
- const python = ensurePythonEnv(cwd, devDir)
197
+ const python = ensurePythonEnv(cwd, devDir, manifest)
159
198
  const runner = writeBackendRunner(cwd, devDir, manifest, backendEntry)
160
199
  const sdkPath = localBackendSdkPath()
161
200
  const env = { ...process.env }
@@ -65,6 +65,40 @@ function loadConfig(cwd) {
65
65
  return DEFAULTS
66
66
  }
67
67
 
68
+ function mergeConfig(cfg) {
69
+ return {
70
+ ...DEFAULTS,
71
+ ...cfg,
72
+ environments: {
73
+ ...DEFAULTS.environments,
74
+ ...(cfg.environments || {}),
75
+ },
76
+ }
77
+ }
78
+
79
+ function userConfigPath() {
80
+ return path.join(os.homedir(), ".palette", "config.json")
81
+ }
82
+
83
+ function writeUserEnvironment({ name, url, token, tokenEnv, defaultEnvironment = true }) {
84
+ const target = userConfigPath()
85
+ const existing = readJsonIfExists(target) || {}
86
+ const cfg = mergeConfig(existing)
87
+ cfg.environments[name] = {
88
+ ...(cfg.environments[name] || {}),
89
+ url: url.replace(/\/+$/, ""),
90
+ token,
91
+ token_env: tokenEnv,
92
+ production: Boolean(cfg.environments[name]?.production),
93
+ }
94
+ if (defaultEnvironment) cfg.default_environment = name
95
+
96
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 })
97
+ fs.writeFileSync(target, `${JSON.stringify(cfg, null, 2)}\n`, { mode: 0o600 })
98
+ fs.chmodSync(target, 0o600)
99
+ return target
100
+ }
101
+
68
102
  /**
69
103
  * Resolve the effective environment.
70
104
  *
@@ -106,7 +140,7 @@ function resolveEnvironment({ cwd, flags }) {
106
140
 
107
141
  const token = useLegacy
108
142
  ? process.env.PALETTE_PUBLISH_TOKEN || ""
109
- : process.env[envCfg.token_env] || process.env.PALETTE_PUBLISH_TOKEN || ""
143
+ : process.env[envCfg.token_env] || process.env.PALETTE_PUBLISH_TOKEN || envCfg.token || ""
110
144
 
111
145
  if (!url) {
112
146
  throw new Error(
@@ -130,7 +164,16 @@ function resolveEnvironment({ cwd, flags }) {
130
164
  * Leaves positional args in `rest`.
131
165
  */
132
166
  function parseFlags(argv) {
133
- const flags = { env: undefined, yes: false, ttlHours: undefined, wait: false }
167
+ const flags = {
168
+ env: undefined,
169
+ yes: false,
170
+ ttlHours: undefined,
171
+ wait: false,
172
+ json: false,
173
+ url: undefined,
174
+ token: undefined,
175
+ default: true,
176
+ }
134
177
  const rest = []
135
178
  for (let i = 0; i < argv.length; i++) {
136
179
  const a = argv[i]
@@ -146,6 +189,18 @@ function parseFlags(argv) {
146
189
  flags.ttlHours = Number.parseInt(a.slice("--ttl-hours=".length), 10)
147
190
  } else if (a === "--wait") {
148
191
  flags.wait = true
192
+ } else if (a === "--json") {
193
+ flags.json = true
194
+ } else if (a === "--url") {
195
+ flags.url = argv[++i]
196
+ } else if (a.startsWith("--url=")) {
197
+ flags.url = a.slice("--url=".length)
198
+ } else if (a === "--token") {
199
+ flags.token = argv[++i]
200
+ } else if (a.startsWith("--token=")) {
201
+ flags.token = a.slice("--token=".length)
202
+ } else if (a === "--no-default") {
203
+ flags.default = false
149
204
  } else {
150
205
  rest.push(a)
151
206
  }
@@ -168,4 +223,10 @@ async function confirmProduction(env) {
168
223
  })
169
224
  }
170
225
 
171
- module.exports = { resolveEnvironment, parseFlags, confirmProduction, loadConfig }
226
+ module.exports = {
227
+ resolveEnvironment,
228
+ parseFlags,
229
+ confirmProduction,
230
+ loadConfig,
231
+ writeUserEnvironment,
232
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@palettelab/cli",
3
- "version": "0.3.17",
3
+ "version": "0.3.19",
4
4
  "description": "Developer CLI for building Palette platform plugins — no platform source access required.",
5
5
  "bin": {
6
6
  "pltt": "bin/pltt.js"
@@ -18,7 +18,7 @@ class NoteIn(BaseModel):
18
18
  async def list_notes(ctx: PluginContext = Depends(get_plugin_context)) -> list[dict]:
19
19
  rows = (
20
20
  await ctx.db.execute(
21
- select(Note).where(Note.organization_id == ctx.organization_id).order_by(Note.id.desc())
21
+ select(Note).order_by(Note.id.desc())
22
22
  )
23
23
  ).scalars().all()
24
24
  return [{"id": r.id, "body": r.body} for r in rows]
@@ -0,0 +1,37 @@
1
+ """Alembic environment for the plugin database template."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from alembic import context
6
+ from sqlalchemy import engine_from_config, pool
7
+
8
+ from models import Note # noqa: F401 - registers model metadata
9
+ from palette_sdk.db import PluginBase
10
+
11
+ config = context.config
12
+ target_metadata = PluginBase.metadata
13
+
14
+
15
+ def run_migrations_offline() -> None:
16
+ url = config.get_main_option("sqlalchemy.url")
17
+ context.configure(url=url, target_metadata=target_metadata, literal_binds=True)
18
+ with context.begin_transaction():
19
+ context.run_migrations()
20
+
21
+
22
+ def run_migrations_online() -> None:
23
+ connectable = engine_from_config(
24
+ config.get_section(config.config_ini_section, {}),
25
+ prefix="sqlalchemy.",
26
+ poolclass=pool.NullPool,
27
+ )
28
+ with connectable.connect() as connection:
29
+ context.configure(connection=connection, target_metadata=target_metadata)
30
+ with context.begin_transaction():
31
+ context.run_migrations()
32
+
33
+
34
+ if context.is_offline_mode():
35
+ run_migrations_offline()
36
+ else:
37
+ run_migrations_online()
@@ -1,8 +1,7 @@
1
- """Initial migration creates notes table with org RLS."""
1
+ """Initial migration - creates notes table with org RLS."""
2
2
 
3
3
  from alembic import op
4
4
  import sqlalchemy as sa
5
- from sqlalchemy.dialects import postgresql
6
5
 
7
6
  from palette_sdk.db import ensure_org_rls
8
7
 
@@ -14,13 +13,13 @@ def upgrade() -> None:
14
13
  op.create_table(
15
14
  "notes",
16
15
  sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
17
- sa.Column("organization_id", postgresql.UUID(as_uuid=True), nullable=False),
16
+ sa.Column("organization_id", sa.BigInteger(), nullable=False),
18
17
  sa.Column("body", sa.Text(), nullable=False),
19
18
  )
20
- op.create_index("ix_notes_organization_id", "notes", ["organization_id"])
21
- ensure_org_rls("notes")
19
+ op.create_index("ix_notes_org", "notes", ["organization_id"])
20
+ ensure_org_rls(op, "notes")
22
21
 
23
22
 
24
23
  def downgrade() -> None:
25
- op.drop_index("ix_notes_organization_id", table_name="notes")
24
+ op.drop_index("ix_notes_org", table_name="notes")
26
25
  op.drop_table("notes")
@@ -6,52 +6,178 @@ import type { PluginComponentProps } from "@palettelab/sdk"
6
6
 
7
7
  type Note = { id: number; body: string }
8
8
 
9
+ const styles = `
10
+ .notes-app {
11
+ min-height: 100vh;
12
+ background: #f6f3ee;
13
+ color: #111827;
14
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
15
+ }
16
+ .notes-shell {
17
+ width: min(100%, 880px);
18
+ margin: 0 auto;
19
+ padding: 32px 20px;
20
+ }
21
+ .notes-kicker {
22
+ margin: 0 0 8px;
23
+ color: #7c3aed;
24
+ font-size: 12px;
25
+ font-weight: 800;
26
+ letter-spacing: .14em;
27
+ text-transform: uppercase;
28
+ }
29
+ .notes-title {
30
+ margin: 0;
31
+ font-size: clamp(32px, 4vw, 48px);
32
+ line-height: 1;
33
+ }
34
+ .notes-copy {
35
+ max-width: 640px;
36
+ margin: 14px 0 24px;
37
+ color: #667085;
38
+ line-height: 1.65;
39
+ }
40
+ .notes-form {
41
+ display: grid;
42
+ grid-template-columns: minmax(0, 1fr) auto;
43
+ gap: 10px;
44
+ }
45
+ .notes-input {
46
+ min-height: 48px;
47
+ border: 1px solid #c9c3ba;
48
+ background: #fff;
49
+ padding: 0 14px;
50
+ font: inherit;
51
+ outline: none;
52
+ }
53
+ .notes-input:focus {
54
+ border-color: #7c3aed;
55
+ box-shadow: 0 0 0 3px rgba(124, 58, 237, .14);
56
+ }
57
+ .notes-button {
58
+ min-height: 48px;
59
+ border: 0;
60
+ background: #7c3aed;
61
+ color: #fff;
62
+ padding: 0 22px;
63
+ font: inherit;
64
+ font-weight: 800;
65
+ cursor: pointer;
66
+ }
67
+ .notes-button:disabled {
68
+ background: #a7b1c2;
69
+ cursor: not-allowed;
70
+ }
71
+ .notes-list {
72
+ margin-top: 16px;
73
+ border: 1px solid #ded8cf;
74
+ background: #fff;
75
+ box-shadow: 0 18px 40px rgba(31, 41, 51, .08);
76
+ }
77
+ .notes-empty,
78
+ .notes-item {
79
+ margin: 0;
80
+ padding: 16px 18px;
81
+ border-top: 1px solid #ece7df;
82
+ }
83
+ .notes-empty,
84
+ .notes-item:first-child {
85
+ border-top: 0;
86
+ }
87
+ .notes-empty {
88
+ color: #667085;
89
+ }
90
+ @media (max-width: 680px) {
91
+ .notes-form {
92
+ grid-template-columns: 1fr;
93
+ }
94
+ }
95
+ `
96
+
9
97
  export default function NotesApp(_props: PluginComponentProps) {
10
- const { apiFetch, showToast } = usePlatform()
98
+ const { apiFetch, showToast, user } = usePlatform()
11
99
  const [notes, setNotes] = useState<Note[]>([])
12
100
  const [body, setBody] = useState("")
101
+ const [loading, setLoading] = useState(true)
102
+ const [saving, setSaving] = useState(false)
13
103
 
14
104
  async function load() {
15
- const r = await apiFetch("/api/v1/plugins/my-db-plugin/notes")
16
- setNotes(await r.json())
105
+ setLoading(true)
106
+ try {
107
+ const response = await apiFetch("/api/v1/plugins/my-db-plugin/notes")
108
+ if (!response.ok) throw new Error("Could not load notes")
109
+ setNotes(await response.json())
110
+ } finally {
111
+ setLoading(false)
112
+ }
17
113
  }
114
+
18
115
  useEffect(() => {
19
116
  load()
20
- }, [])
117
+ }, [apiFetch])
21
118
 
22
119
  async function add() {
23
- if (!body.trim()) return
24
- const r = await apiFetch("/api/v1/plugins/my-db-plugin/notes", {
25
- method: "POST",
26
- headers: { "Content-Type": "application/json" },
27
- body: JSON.stringify({ body }),
28
- })
29
- if (r.ok) {
120
+ const cleaned = body.trim()
121
+ if (!cleaned) return
122
+ setSaving(true)
123
+ try {
124
+ const response = await apiFetch("/api/v1/plugins/my-db-plugin/notes", {
125
+ method: "POST",
126
+ headers: { "Content-Type": "application/json" },
127
+ body: JSON.stringify({ body: cleaned }),
128
+ })
129
+ if (!response.ok) throw new Error("Could not save note")
30
130
  setBody("")
31
131
  showToast("Note saved", "success")
32
- load()
132
+ await load()
133
+ } finally {
134
+ setSaving(false)
33
135
  }
34
136
  }
35
137
 
36
138
  return (
37
- <div className="p-6 space-y-3">
38
- <h1 className="text-2xl font-bold">Notes</h1>
39
- <div className="flex gap-2">
40
- <input
41
- className="border rounded px-2 py-1 text-sm flex-1"
42
- value={body}
43
- onChange={(e) => setBody(e.target.value)}
44
- placeholder="New note…"
45
- />
46
- <button onClick={add} className="px-3 py-1 rounded bg-primary text-primary-foreground text-sm">
47
- Add
48
- </button>
49
- </div>
50
- <ul className="space-y-1 text-sm">
51
- {notes.map((n) => (
52
- <li key={n.id} className="border rounded px-2 py-1">{n.body}</li>
53
- ))}
54
- </ul>
139
+ <div className="notes-app">
140
+ <style>{styles}</style>
141
+ <main className="notes-shell">
142
+ <p className="notes-kicker">Palette DB App</p>
143
+ <h1 className="notes-title">Org Notes</h1>
144
+ <p className="notes-copy">
145
+ Built for {user.name}. This app uses a Python backend and the Palette
146
+ SDK database session exposed as <code>ctx.db</code>.
147
+ </p>
148
+ <section className="notes-form">
149
+ <input
150
+ className="notes-input"
151
+ value={body}
152
+ onChange={(event) => setBody(event.target.value)}
153
+ onKeyDown={(event) => {
154
+ if (event.key === "Enter") void add()
155
+ }}
156
+ placeholder="New note..."
157
+ />
158
+ <button
159
+ type="button"
160
+ onClick={() => void add()}
161
+ disabled={saving || body.trim().length === 0}
162
+ className="notes-button"
163
+ >
164
+ {saving ? "Saving" : "Add Note"}
165
+ </button>
166
+ </section>
167
+ <section className="notes-list">
168
+ {loading ? (
169
+ <p className="notes-empty">Loading notes...</p>
170
+ ) : notes.length === 0 ? (
171
+ <p className="notes-empty">No notes yet.</p>
172
+ ) : (
173
+ notes.map((note) => (
174
+ <p key={note.id} className="notes-item">
175
+ {note.body}
176
+ </p>
177
+ ))
178
+ )}
179
+ </section>
180
+ </main>
55
181
  </div>
56
182
  )
57
183
  }
@@ -20,6 +20,10 @@
20
20
  "file_uploads": false,
21
21
  "external_network": []
22
22
  },
23
+ "database": {
24
+ "schema": "app_my_db_plugin",
25
+ "migrations": "./backend/migrations"
26
+ },
23
27
  "frontend": { "entry": "./frontend/src/index.tsx", "sandbox": true },
24
28
  "backend": { "entry": "./backend/api/main.py" },
25
29
  "permissions": ["resources:read", "resources:write"]
@@ -6,5 +6,7 @@ dependencies = [
6
6
  "fastapi>=0.129.0",
7
7
  "sqlalchemy>=2.0.47",
8
8
  "alembic>=1.17.0",
9
+ "aiosqlite>=0.20.0",
10
+ "greenlet>=3.0.0",
9
11
  # `pltt test` ships the backend SDK on PYTHONPATH.
10
12
  ]