@palettelab/cli 0.3.71 → 0.3.72
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 +21 -7
- package/lib/agent-client.js +0 -9
- package/lib/bundler.js +32 -1
- package/lib/commands/agent.js +1 -102
- package/lib/commands/build.js +27 -12
- package/lib/commands/check.js +1 -1
- package/lib/css-scope.js +90 -18
- package/lib/migration_lint.py +128 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -980,11 +980,6 @@ pltt agent archive bas_123 [--undo]
|
|
|
980
980
|
pltt agent move bas_123 --app 43
|
|
981
981
|
pltt agent delete bas_123
|
|
982
982
|
|
|
983
|
-
# A terminal in the session's build sandbox (Ctrl-] closes it; Node 22 or later)
|
|
984
|
-
pltt agent terminal bas_123
|
|
985
|
-
pltt agent terminal bas_123 --attach term_456
|
|
986
|
-
pltt agent terminals bas_123 [--read] [--lines 50]
|
|
987
|
-
|
|
988
983
|
# What the agent made, and what it can use
|
|
989
984
|
pltt agent artifacts bas_123
|
|
990
985
|
pltt agent artifact bas_123 art_1 -o ./mockup
|
|
@@ -1003,8 +998,6 @@ pltt agent edit --app 42 "add a CSV export"
|
|
|
1003
998
|
pltt agent init
|
|
1004
999
|
```
|
|
1005
1000
|
|
|
1006
|
-
`terminal` opens an interactive shell in the session's build sandbox: the project's files and `pltt`, no network. Keys go to it as you type and its output is drawn by your terminal; resizing the window resizes it, and Ctrl-] closes it. A terminal opened while the agent works opens at its next step; on an idle session it starts an edit build that holds it. It closes after 10 minutes without typing. Files the app may not change are put back when it closes, and the agent is told what the terminal showed. `--attach` reconnects to one that is still open; `terminals --read` prints the newest one's last lines.
|
|
1007
|
-
|
|
1008
1001
|
`run` sends the change (it steers the agent when it is already working on the app), follows the session that carries it out until the session is idle again, and exits 0 when the agent finished (`done`), 2 when it stopped short (`blocked`, `declined`, `stalled`, `gate_rounds`, `steps`, `timeout`, `tokens`, `output_limit`, or still running at `--timeout`, default 1800 s), and 1 on errors. With `--format json` (or `--json`) it writes the edit response, then one event per line, then the final state. `run` is unattended: the agent's permission asks are denied by the platform. `edit --follow` does the same as `run`.
|
|
1009
1002
|
|
|
1010
1003
|
`attach` is the interactive follower: it streams the log, keeps the owner present (the agent's permission asks and questions wait for you instead of being decided unattended), prompts `Allow <action> on <resource>? [o]nce/[a]lways/[r]eject:` for each ask (a reject may carry a message after the letter), lists each question's options to answer by number or in your own words, sends any other line you type as a steering message, and leaves on `/exit`.
|
|
@@ -1308,6 +1301,27 @@ Subcommands:
|
|
|
1308
1301
|
`pltt test` verifies every agent capability has a stable `capability_id` and a
|
|
1309
1302
|
matching `@capability(...)` / `service(..., agent_exposable=True)` handler.
|
|
1310
1303
|
|
|
1304
|
+
## App CSS Isolation
|
|
1305
|
+
|
|
1306
|
+
The bundler scopes every stylesheet your frontend imports to your app's root
|
|
1307
|
+
element, `[data-palette-plugin-root="<id>"]`, so app CSS never restyles Palette
|
|
1308
|
+
or another app.
|
|
1309
|
+
|
|
1310
|
+
- `:root`, `html` and `body` all mean that one root element. Chains such as
|
|
1311
|
+
`html body .x` or `:root[data-theme=dark] body` collapse onto it, so
|
|
1312
|
+
`:root[data-theme=dark] { --bg: #000 }` needs `data-theme` on the root
|
|
1313
|
+
element itself (`el.closest("[data-palette-plugin-root]")`), not on
|
|
1314
|
+
`document.documentElement`. For an in-app theme, font-size, contrast or
|
|
1315
|
+
motion toggle you can also put the attribute on your own top-level wrapper
|
|
1316
|
+
and write `.app[data-theme=dark] …`.
|
|
1317
|
+
- Nested CSS is supported: it is flattened before scoping, with the same
|
|
1318
|
+
matching as in a normal page.
|
|
1319
|
+
- Palette's dark mode is a `dark` class on `<html>`. `.dark .your-root { … }`
|
|
1320
|
+
and `.dark { … }` follow it; a `.dark` class your app sets on its own
|
|
1321
|
+
elements does not.
|
|
1322
|
+
- An unclosed `{`, `(` or `[`, a stray `}`, or a `//` comment fails the build
|
|
1323
|
+
with its file and line. The browser would silently drop the rules after it.
|
|
1324
|
+
|
|
1311
1325
|
## Global Flags
|
|
1312
1326
|
|
|
1313
1327
|
- `--json` emits machine-readable output for `package`, `publish`, `status`, `logs`, `test`, `update`, `version`, `login`, `dev --sandbox`, `platform list`, `services list`, and `capabilities`.
|
package/lib/agent-client.js
CHANGED
|
@@ -107,15 +107,6 @@ class AgentClient {
|
|
|
107
107
|
models(query = "") { return this.request("GET", `/models${query ? `?q=${q(query)}` : ""}`) }
|
|
108
108
|
config() { return this.request("GET", "/config") }
|
|
109
109
|
plugins() { return this.request("GET", "/plugins") }
|
|
110
|
-
terminals(id) { return this.request("GET", `/${q(id)}/terminals`) }
|
|
111
|
-
openTerminal(id, { cols, rows, title } = {}) { return this.request("POST", `/${q(id)}/terminals`, { cols, rows, title }) }
|
|
112
|
-
readTerminal(id, lines = 100) { return this.request("GET", `/${q(id)}/terminals/read?lines=${lines}`) }
|
|
113
|
-
closeTerminal(id, terminal) { return this.request("DELETE", `/${q(id)}/terminals/${q(terminal)}`) }
|
|
114
|
-
terminalTicket(id, terminal) { return this.request("POST", `/${q(id)}/terminals/${q(terminal)}/ticket`) }
|
|
115
|
-
// The terminal's WebSocket, authorised by a one-use ticket (a WebSocket cannot carry the token header).
|
|
116
|
-
terminalUrl(id, terminal, ticket, after = "0") {
|
|
117
|
-
return `${this.base.replace(/^http/, "ws")}/${q(id)}/terminals/${q(terminal)}/connect?ticket=${q(ticket)}&after=${q(after)}`
|
|
118
|
-
}
|
|
119
110
|
// A raw call under /build-sessions, for scripting what has no subcommand.
|
|
120
111
|
raw(method, route, body) { return this.request(method.toUpperCase(), route.startsWith("/") || route.startsWith("?") ? route : `/${route}`, body) }
|
|
121
112
|
answer(id, question, answer) { return this.request("POST", `/${q(id)}/questions/${q(question)}`, { answer }) }
|
package/lib/bundler.js
CHANGED
|
@@ -369,12 +369,43 @@ export function Link({ href, replace, onClick, children, ...props }) {
|
|
|
369
369
|
}
|
|
370
370
|
}
|
|
371
371
|
|
|
372
|
+
// esbuild "repairs" broken CSS: an unclosed "{" or "(" swallows every later rule, and a
|
|
373
|
+
// stray "}" or a "//" comment eats the next selector. The browser then drops those rules
|
|
374
|
+
// with no error, so fail the build on these and print the remaining CSS warnings.
|
|
375
|
+
function isBrokenCss(warning) {
|
|
376
|
+
return (
|
|
377
|
+
warning.id === "js-comment-in-css" ||
|
|
378
|
+
(warning.id === "css-syntax-error" && /^(Expected "[)\]}]" to go with "[([{]"|Unexpected "}")$/.test(warning.text))
|
|
379
|
+
)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const cssGuardPlugin = {
|
|
383
|
+
name: "palette-css-guard",
|
|
384
|
+
setup(build) {
|
|
385
|
+
build.onEnd((result) => {
|
|
386
|
+
const css = result.warnings.filter((w) => /\.css$/i.test(w.location?.file || ""))
|
|
387
|
+
for (const w of css) {
|
|
388
|
+
if (!isBrokenCss(w)) console.warn(`[pltt] CSS warning: ${w.location.file}:${w.location.line}: ${w.text}`)
|
|
389
|
+
}
|
|
390
|
+
const broken = css.filter(isBrokenCss)
|
|
391
|
+
if (!broken.length) return undefined
|
|
392
|
+
return {
|
|
393
|
+
errors: broken.map((w) => ({
|
|
394
|
+
text: `${w.text}${w.notes?.[0]?.location ? ` (opened on line ${w.notes[0].location.line})` : ""}. The browser would silently drop the rules this breaks; fix the CSS.`,
|
|
395
|
+
location: w.location,
|
|
396
|
+
notes: w.notes,
|
|
397
|
+
})),
|
|
398
|
+
}
|
|
399
|
+
})
|
|
400
|
+
},
|
|
401
|
+
}
|
|
402
|
+
|
|
372
403
|
function frontendBuildConfig(pluginDir, frontend = {}) {
|
|
373
404
|
const framework = frontendFramework(frontend)
|
|
374
405
|
const define = {
|
|
375
406
|
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || "production"),
|
|
376
407
|
}
|
|
377
|
-
const plugins = []
|
|
408
|
+
const plugins = [cssGuardPlugin]
|
|
378
409
|
const tsconfigPaths = framework === "next" || framework === "palette-app" ? makeTsconfigPathsPlugin(pluginDir, frontend) : null
|
|
379
410
|
if (tsconfigPaths) plugins.push(tsconfigPaths)
|
|
380
411
|
if (framework === "palette-app") plugins.push(makePaletteAppNextCompatPlugin(pluginDir))
|
package/lib/commands/agent.js
CHANGED
|
@@ -22,11 +22,6 @@ const USAGE = `usage:
|
|
|
22
22
|
pltt agent edit --app <id> "<change>" [--follow] start a change (steers the agent when it is working)
|
|
23
23
|
pltt agent attach <session> follow live, answer permission asks and questions,
|
|
24
24
|
type to steer, /exit to leave
|
|
25
|
-
pltt agent terminal <session> [--attach <terminal>]
|
|
26
|
-
an interactive shell in the session's build sandbox
|
|
27
|
-
(Ctrl-] closes it; needs Node 22 or later)
|
|
28
|
-
pltt agent terminals <session> [--read] [--lines <n>]
|
|
29
|
-
its terminals, or the newest one's last lines
|
|
30
25
|
pltt agent acp --app <id> Agent Client Protocol server on stdio (Zed and other editors)
|
|
31
26
|
pltt agent sessions --app <id> [--archived] [--limit <n>]
|
|
32
27
|
list an app's build sessions
|
|
@@ -184,8 +179,6 @@ function describe(event) {
|
|
|
184
179
|
return `moved to app ${d.to}`
|
|
185
180
|
case "skill.activated":
|
|
186
181
|
return `skill ${d.name}${d.by === "owner" ? " (you asked)" : ""}`
|
|
187
|
-
case "shell.ended":
|
|
188
|
-
return `you ran: ${String(d.command || "").slice(0, 120)}${d.failed ? " (failed)" : ""}`
|
|
189
182
|
case "cache.warmed":
|
|
190
183
|
return null
|
|
191
184
|
default:
|
|
@@ -343,79 +336,6 @@ async function attach(client, sessionId, { log }) {
|
|
|
343
336
|
}
|
|
344
337
|
}
|
|
345
338
|
|
|
346
|
-
// `terminal`: an interactive shell in the session's build sandbox. Keys go to it raw and its output is written as it
|
|
347
|
-
// comes, so the local terminal draws it; a resize follows the window. Ctrl-] closes it. A dropped connection (a proxy's
|
|
348
|
-
// connection limit, a network blip) reconnects and resumes after the last frame it showed, so nothing is drawn twice.
|
|
349
|
-
// Resolves with the shell's exit code (1 when it did not exit by itself).
|
|
350
|
-
async function terminal(client, sessionId, { attachTo, stdin, stdout, log, WS = globalThis.WebSocket, retries = 5, backoffMs = 500 }) {
|
|
351
|
-
if (typeof WS !== "function") throw new Error("pltt agent terminal needs Node 22 or later (its built-in WebSocket)")
|
|
352
|
-
const size = () => ({ cols: stdout.columns || 100, rows: stdout.rows || 30 })
|
|
353
|
-
let entry = { id: attachTo }
|
|
354
|
-
if (!attachTo) {
|
|
355
|
-
entry = await client.openTerminal(sessionId, size())
|
|
356
|
-
log(entry.start === "queued" ? "[pltt] the terminal opens when the app's running build ends"
|
|
357
|
-
: entry.start === "opening" ? "[pltt] the terminal opens at the agent's next step"
|
|
358
|
-
: "[pltt] starting the terminal (Ctrl-] closes it)")
|
|
359
|
-
}
|
|
360
|
-
let socket = null
|
|
361
|
-
let last = "0" // the stream id of the last frame shown: a reconnect resumes after it
|
|
362
|
-
let ended = null
|
|
363
|
-
const held = [] // keys typed while reconnecting: sent once the new connection opens, never dropped
|
|
364
|
-
const send = (frame) => {
|
|
365
|
-
if (socket && socket.readyState === 1) socket.send(JSON.stringify(frame))
|
|
366
|
-
else held.push(frame)
|
|
367
|
-
}
|
|
368
|
-
const onKey = (chunk) => {
|
|
369
|
-
const keys = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
|
|
370
|
-
if (keys.length === 1 && keys[0] === 0x1d) return send({ t: "close" }) // Ctrl-]
|
|
371
|
-
send({ t: "in", d: keys.toString("utf8") })
|
|
372
|
-
}
|
|
373
|
-
const onResize = () => send({ t: "resize", ...size() })
|
|
374
|
-
if (stdin.isTTY) stdin.setRawMode(true)
|
|
375
|
-
stdin.on("data", onKey)
|
|
376
|
-
stdin.resume()
|
|
377
|
-
stdout.on("resize", onResize)
|
|
378
|
-
try {
|
|
379
|
-
for (let tries = 0; ;) {
|
|
380
|
-
const { ticket } = await client.terminalTicket(sessionId, entry.id)
|
|
381
|
-
const code = await new Promise((resolve) => {
|
|
382
|
-
socket = new WS(client.terminalUrl(sessionId, entry.id, ticket, last))
|
|
383
|
-
socket.onopen = () => {
|
|
384
|
-
tries = 0
|
|
385
|
-
onResize()
|
|
386
|
-
for (const frame of held.splice(0)) send(frame)
|
|
387
|
-
}
|
|
388
|
-
socket.onmessage = (message) => {
|
|
389
|
-
const frame = JSON.parse(typeof message.data === "string" ? message.data : Buffer.from(message.data).toString())
|
|
390
|
-
if (frame.i) last = frame.i
|
|
391
|
-
if (frame.t === "out") stdout.write(frame.d)
|
|
392
|
-
if (frame.t === "exit") {
|
|
393
|
-
ended = frame
|
|
394
|
-
socket.close()
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
socket.onerror = () => {} // onclose follows with the reason
|
|
398
|
-
socket.onclose = (event) => resolve(event.code)
|
|
399
|
-
})
|
|
400
|
-
if (ended) break
|
|
401
|
-
if (code === 4401) throw new Error("the terminal refused the connection: sign in again (pltt login)")
|
|
402
|
-
if (code === 4404) throw new Error(`no terminal ${entry.id} in session ${sessionId}`)
|
|
403
|
-
if (tries >= retries) break
|
|
404
|
-
tries += 1
|
|
405
|
-
await sleep(Math.min(8000, backoffMs * 2 ** tries))
|
|
406
|
-
}
|
|
407
|
-
} finally {
|
|
408
|
-
stdin.off("data", onKey)
|
|
409
|
-
stdout.off("resize", onResize)
|
|
410
|
-
if (stdin.isTTY) stdin.setRawMode(false)
|
|
411
|
-
stdin.pause()
|
|
412
|
-
}
|
|
413
|
-
const how = ended ? `ended (${ended.reason}${ended.code != null ? `, exit ${ended.code}` : ""})${ended.message ? `: ${ended.message}` : ""}`
|
|
414
|
-
: `connection lost (it may still be open: pltt agent terminal ${sessionId} --attach ${entry.id})`
|
|
415
|
-
log(`\r\n[pltt] terminal ${entry.id} ${how}`)
|
|
416
|
-
return ended && Number.isInteger(ended.code) && ended.reason === "exited" ? ended.code : 1
|
|
417
|
-
}
|
|
418
|
-
|
|
419
339
|
// `acp`: JSON-RPC on stdio. stdout carries protocol messages only; everything else goes to stderr.
|
|
420
340
|
async function serveAcp(client, app) {
|
|
421
341
|
let closed = false
|
|
@@ -451,7 +371,7 @@ function diffStat(data, log) {
|
|
|
451
371
|
log(` ${files.length} file${files.length === 1 ? "" : "s"} changed, +${data.additions} -${data.deletions}`)
|
|
452
372
|
}
|
|
453
373
|
|
|
454
|
-
async function run(argv, { cwd = process.cwd(), log = console.log
|
|
374
|
+
async function run(argv, { cwd = process.cwd(), log = console.log } = {}) {
|
|
455
375
|
const [sub, ...args] = argv
|
|
456
376
|
const { flags, rest } = parseFlags(args)
|
|
457
377
|
const json = flags.json
|
|
@@ -539,27 +459,6 @@ async function run(argv, { cwd = process.cwd(), log = console.log, stdin = proce
|
|
|
539
459
|
case "attach":
|
|
540
460
|
need(id)
|
|
541
461
|
return attach(client, id, { log })
|
|
542
|
-
case "terminal": {
|
|
543
|
-
const attachTo = option(rest, "--attach")
|
|
544
|
-
need(rest[0])
|
|
545
|
-
process.exitCode = await terminal(client, rest[0], { attachTo, stdin, stdout, log })
|
|
546
|
-
return
|
|
547
|
-
}
|
|
548
|
-
case "terminals": {
|
|
549
|
-
const read = flag(rest, "--read")
|
|
550
|
-
const lines = option(rest, "--lines")
|
|
551
|
-
need(rest[0])
|
|
552
|
-
if (read) {
|
|
553
|
-
const { data } = await client.readTerminal(rest[0], lines ? positiveInt(lines, "--lines") : 100)
|
|
554
|
-
if (json) return log(JSON.stringify(data))
|
|
555
|
-
return log(data ? data.text || "(nothing shown yet)" : "no terminal in this session")
|
|
556
|
-
}
|
|
557
|
-
const { terminals } = await client.terminals(rest[0])
|
|
558
|
-
if (json) return log(JSON.stringify(terminals))
|
|
559
|
-
if (!terminals.length) return log("no terminals")
|
|
560
|
-
for (const t of terminals) log(`${t.id} ${t.status}${t.reason ? ` (${t.reason})` : ""} ${t.cols}x${t.rows}${t.title ? ` ${t.title}` : ""}`)
|
|
561
|
-
return
|
|
562
|
-
}
|
|
563
462
|
case "acp": {
|
|
564
463
|
const app = option(rest, "--app")
|
|
565
464
|
need(app)
|
package/lib/commands/build.js
CHANGED
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
const fs = require("fs")
|
|
4
4
|
const path = require("path")
|
|
5
|
+
const { spawnSync } = require("child_process")
|
|
5
6
|
const { loadManifest, validateManifest } = require("../manifest")
|
|
6
7
|
|
|
7
|
-
//
|
|
8
|
-
//
|
|
8
|
+
// What a migration may not run is decided by the platform's own lint, lib/migration_lint.py (a byte-identical
|
|
9
|
+
// copy of the server's), run with python3 so `pltt check` and publish agree — GRANT counts only as a SQL
|
|
10
|
+
// statement, never as a word. Without a usable python3 these word patterns stand in: stricter, never laxer.
|
|
11
|
+
const LINT_PY = path.join(__dirname, "..", "migration_lint.py")
|
|
9
12
|
const BANNED_PATTERNS = [
|
|
10
13
|
{ re: /DROP\s+POLICY/i, reason: "DROP POLICY weakens RLS" },
|
|
11
14
|
{ re: /DISABLE\s+ROW\s+LEVEL\s+SECURITY/i, reason: "DISABLE ROW LEVEL SECURITY removes tenant isolation" },
|
|
@@ -59,17 +62,31 @@ function crossPluginSchemaRefs(src, allowedSchema) {
|
|
|
59
62
|
return [...refs].sort()
|
|
60
63
|
}
|
|
61
64
|
|
|
62
|
-
|
|
65
|
+
// { absPath: [[line, reason], ...] } from the platform lint, or null when python3 cannot run it.
|
|
66
|
+
function bannedOperations(files) {
|
|
67
|
+
if (!files.length) return {}
|
|
68
|
+
const res = spawnSync(process.env.PALETTE_PYTHON || "python3", ["-I", LINT_PY, ...files], { encoding: "utf8" })
|
|
69
|
+
try {
|
|
70
|
+
return res.status === 0 ? JSON.parse(res.stdout) : null
|
|
71
|
+
} catch {
|
|
72
|
+
return null
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function lintMigrationFile(absPath, pluginId, sharedTables = [], banned = bannedOperations([absPath])) {
|
|
63
77
|
const issues = []
|
|
64
78
|
const src = fs.readFileSync(absPath, "utf8")
|
|
65
79
|
const requiredPrefix = pluginId ? pluginTablePrefix(pluginId) : null
|
|
66
80
|
const allowedSchema = pluginId ? pluginSchema(pluginId) : null
|
|
67
81
|
const sharedTableNames = new Set(sharedTables || [])
|
|
68
82
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
83
|
+
const hits = banned?.[absPath] || BANNED_PATTERNS.flatMap(({ re, reason }) => {
|
|
84
|
+
const match = re.exec(src)
|
|
85
|
+
return match ? [[src.slice(0, match.index).split("\n").length, reason]] : []
|
|
86
|
+
})
|
|
87
|
+
for (const [line, reason] of hits) {
|
|
88
|
+
const file = path.basename(absPath)
|
|
89
|
+
issues.push(makeIssue(`${file} line ${line}: ${reason}`, null, { code: "banned_operation", file, line }))
|
|
73
90
|
}
|
|
74
91
|
|
|
75
92
|
for (const schema of crossPluginSchemaRefs(src, allowedSchema)) {
|
|
@@ -138,11 +155,9 @@ function lintMigrationsDir(migrationsDir, pluginId, sharedTables = []) {
|
|
|
138
155
|
errors.push(`migrations directory has no versions/ subfolder: ${migrationsDir}`)
|
|
139
156
|
return errors
|
|
140
157
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
errors.push(...lintMigrationFile(abs, pluginId, sharedTables))
|
|
145
|
-
}
|
|
158
|
+
const files = fs.readdirSync(versionsDir).filter((entry) => entry.endsWith(".py")).map((entry) => path.join(versionsDir, entry))
|
|
159
|
+
const banned = bannedOperations(files)
|
|
160
|
+
for (const abs of files) errors.push(...lintMigrationFile(abs, pluginId, sharedTables, banned))
|
|
146
161
|
return errors
|
|
147
162
|
}
|
|
148
163
|
|
package/lib/commands/check.js
CHANGED
|
@@ -62,7 +62,7 @@ function diagnosticsFor(result, cwd) {
|
|
|
62
62
|
}
|
|
63
63
|
if (result.file) {
|
|
64
64
|
const file = String(result.file).includes("/") || !result.code ? String(result.file) : `backend/migrations/versions/${result.file}`
|
|
65
|
-
return [{ ...base, file }]
|
|
65
|
+
return [{ ...base, file, ...(result.line ? { line: Number(result.line) } : {}) }]
|
|
66
66
|
}
|
|
67
67
|
return [base]
|
|
68
68
|
}
|
package/lib/css-scope.js
CHANGED
|
@@ -31,28 +31,80 @@ function isRootLike(node) {
|
|
|
31
31
|
)
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
// Selector lists that match when any branch matches (`:where(html)`, `:is(html, body)`).
|
|
35
|
+
const MATCHES_ANY = /^:(is|where|matches|-webkit-any|-moz-any)$/i
|
|
36
|
+
|
|
37
|
+
// Only this plugin's own root counts: a hand-written `[data-palette-plugin-root]` may be
|
|
38
|
+
// another app's root and keeps its prefix.
|
|
39
|
+
function isPluginRoot(node, root) {
|
|
40
|
+
return node.type === "attribute" && node.attribute === root.attribute && node.value === root.value
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isChildStep(node) {
|
|
44
|
+
return node?.type === "combinator" && (node.value === " " || node.value === ">")
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function splitCompounds(selector) {
|
|
48
|
+
const compounds = [[]]
|
|
49
|
+
const combinators = []
|
|
50
|
+
for (const node of selector.nodes) {
|
|
51
|
+
if (node.type === "combinator") {
|
|
52
|
+
combinators.push(node)
|
|
53
|
+
compounds.push([])
|
|
54
|
+
} else {
|
|
55
|
+
compounds[compounds.length - 1].push(node)
|
|
56
|
+
}
|
|
37
57
|
}
|
|
58
|
+
return { compounds, combinators }
|
|
38
59
|
}
|
|
39
60
|
|
|
40
|
-
function
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
61
|
+
function isRootCompound(nodes, root) {
|
|
62
|
+
return nodes.some(
|
|
63
|
+
(node) =>
|
|
64
|
+
isPluginRoot(node, root) ||
|
|
65
|
+
(node.type === "pseudo" &&
|
|
66
|
+
MATCHES_ANY.test(node.value) &&
|
|
67
|
+
node.nodes.length > 0 &&
|
|
68
|
+
node.nodes.every((branch) => isInsideRoot(branch, root))),
|
|
69
|
+
)
|
|
48
70
|
}
|
|
49
71
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
72
|
+
// True when the subject can only be the plugin root or a descendant of it: walking left
|
|
73
|
+
// over descendant/child steps reaches a root compound. A root that only appears inside
|
|
74
|
+
// `:not(body)` or before `~`/`+` confines nothing, so such selectors still get prefixed.
|
|
75
|
+
function isInsideRoot(selector, root) {
|
|
76
|
+
const { compounds, combinators } = splitCompounds(selector)
|
|
77
|
+
for (let i = compounds.length - 1; i >= 0; i--) {
|
|
78
|
+
if (isRootCompound(compounds[i], root)) return true
|
|
79
|
+
if (!isChildStep(combinators[i - 1])) return false
|
|
80
|
+
}
|
|
81
|
+
return false
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// html, body and :root all become the one plugin root element, so `html body` or
|
|
85
|
+
// `:root[data-theme=x] > body` must merge into a single compound: a plugin root nested
|
|
86
|
+
// inside itself never matches.
|
|
87
|
+
function collapseRootChains(selector, root) {
|
|
88
|
+
const { compounds, combinators } = splitCompounds(selector)
|
|
89
|
+
for (let i = combinators.length - 1; i >= 0; i--) {
|
|
90
|
+
if (!isChildStep(combinators[i]) || !isRootCompound(compounds[i], root) || !isRootCompound(compounds[i + 1], root)) continue
|
|
91
|
+
combinators[i].remove()
|
|
92
|
+
for (const node of compounds[i + 1]) if (isPluginRoot(node, root)) node.remove()
|
|
55
93
|
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function confineSelector(selector, rootNode) {
|
|
97
|
+
if (!selector.nodes.length) return
|
|
98
|
+
collapseRootChains(selector, rootNode)
|
|
99
|
+
if (isInsideRoot(selector, rootNode)) return
|
|
100
|
+
// `body, .x { .card {} }` flattens to `:is(body, .x) .card`: scope each branch, since
|
|
101
|
+
// one outer prefix would need the root inside itself for the `body` branch.
|
|
102
|
+
const lists = splitCompounds(selector).compounds[0].filter(
|
|
103
|
+
(node) =>
|
|
104
|
+
node.type === "pseudo" && MATCHES_ANY.test(node.value) && node.nodes.some((branch) => isInsideRoot(branch, rootNode)),
|
|
105
|
+
)
|
|
106
|
+
for (const list of lists) list.each((branch) => confineSelector(branch, rootNode))
|
|
107
|
+
if (lists.length && isInsideRoot(selector, rootNode)) return
|
|
56
108
|
selector.prepend(selectorParser.combinator({ value: " " }))
|
|
57
109
|
selector.prepend(rootNode.clone())
|
|
58
110
|
}
|
|
@@ -66,10 +118,30 @@ function scopeSelectors(selector, pluginId) {
|
|
|
66
118
|
})
|
|
67
119
|
|
|
68
120
|
return selectorParser((selectors) => {
|
|
69
|
-
selectors.
|
|
121
|
+
selectors.walk((node) => {
|
|
122
|
+
if (isRootLike(node)) node.replaceWith(rootNode.clone())
|
|
123
|
+
})
|
|
124
|
+
selectors.each((sel) => confineSelector(sel, rootNode))
|
|
70
125
|
}).processSync(selector)
|
|
71
126
|
}
|
|
72
127
|
|
|
128
|
+
// A nested rule is matched relative to its parent, so scoping every level would ask for
|
|
129
|
+
// a plugin root inside the plugin root (`[root] .a { [root] .b {} }` never matches).
|
|
130
|
+
// Flatten nesting first with esbuild, which already bundles this CSS.
|
|
131
|
+
function flattenNesting(css, root) {
|
|
132
|
+
let nested = false
|
|
133
|
+
root.walk((node) => {
|
|
134
|
+
if (node.parent?.type === "rule" && (node.type === "rule" || node.type === "atrule")) nested = true
|
|
135
|
+
})
|
|
136
|
+
if (!nested) return root
|
|
137
|
+
const flat = require("esbuild").transformSync(css, {
|
|
138
|
+
loader: "css",
|
|
139
|
+
minifyWhitespace: true,
|
|
140
|
+
supported: { nesting: false },
|
|
141
|
+
})
|
|
142
|
+
return postcss.parse(flat.code)
|
|
143
|
+
}
|
|
144
|
+
|
|
73
145
|
function renameKeyframes(root, pluginId) {
|
|
74
146
|
const prefix = `palette-${cssIdentifier(pluginId)}-`
|
|
75
147
|
const names = new Map()
|
|
@@ -97,7 +169,7 @@ function renameKeyframes(root, pluginId) {
|
|
|
97
169
|
|
|
98
170
|
function scopePluginCss(css, pluginId) {
|
|
99
171
|
if (!css || !String(css).trim()) return ""
|
|
100
|
-
const root = postcss.parse(css)
|
|
172
|
+
const root = flattenNesting(String(css), postcss.parse(css))
|
|
101
173
|
|
|
102
174
|
renameKeyframes(root, pluginId)
|
|
103
175
|
root.walkRules((rule) => {
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""What an app migration may not do.
|
|
2
|
+
|
|
3
|
+
One file, two copies kept byte-identical: the platform's
|
|
4
|
+
(backend/app/plugins/migration_lint.py — install-time lint, App Store review,
|
|
5
|
+
App Builder guard) and the CLI's (sdk/cli-npm/lib/migration_lint.py, run with
|
|
6
|
+
the developer's python3), so `pltt check` and publish agree. Standard library
|
|
7
|
+
only; run as a script it prints {path: [[line, reason], ...]} as JSON.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import ast
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
GRANT_REASON = "GRANT is reserved for the platform"
|
|
18
|
+
|
|
19
|
+
BANNED_MIGRATION_PATTERNS = [
|
|
20
|
+
(re.compile(r"\bpublic\.", re.I), "plugin migrations must not reference public schema"),
|
|
21
|
+
(re.compile(r"\bDROP\s+POLICY\b", re.I), "DROP POLICY weakens RLS"),
|
|
22
|
+
(
|
|
23
|
+
re.compile(r"\bDISABLE\s+ROW\s+LEVEL\s+SECURITY\b", re.I),
|
|
24
|
+
"DISABLE ROW LEVEL SECURITY removes tenant isolation",
|
|
25
|
+
),
|
|
26
|
+
(
|
|
27
|
+
re.compile(r"\bNO\s+FORCE\s+ROW\s+LEVEL\s+SECURITY\b", re.I),
|
|
28
|
+
"NO FORCE ROW LEVEL SECURITY lets table owners bypass RLS",
|
|
29
|
+
),
|
|
30
|
+
(re.compile(r"\bSET\s+ROLE\b", re.I), "SET ROLE is reserved for the platform"),
|
|
31
|
+
(re.compile(r"\bALTER\s+ROLE\b", re.I), "ALTER ROLE is reserved for the platform"),
|
|
32
|
+
(re.compile(r"\bCREATE\s+EXTENSION\b", re.I), "CREATE EXTENSION is reserved for the platform"),
|
|
33
|
+
(re.compile(r"\bALTER\s+DATABASE\b", re.I), "ALTER DATABASE is not allowed"),
|
|
34
|
+
(re.compile(r"\bDROP\s+SCHEMA\b", re.I), "DROP SCHEMA is not allowed"),
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
# "grant" is everyday vocabulary — a leave grant, MONTHS_AFTER_GRANT, def
|
|
38
|
+
# grant(), "Grant of Copyright License" — so GRANT counts only as a SQL
|
|
39
|
+
# statement: in a Python string (docstrings skipped), after the string's SQL
|
|
40
|
+
# comments and quoted literals are blanked (RAISE messages, enum values; the
|
|
41
|
+
# dynamic SQL an EXECUTE runs stays code), at the start of a statement, and
|
|
42
|
+
# shaped like one: privileges ON objects TO roles, or roles TO roles, ending
|
|
43
|
+
# the statement.
|
|
44
|
+
_START = r"(?:^|;|\$\w*\$|\b(?:BEGIN|THEN|ELSE|LOOP|EXECUTE)\b(?:\s+format\s*\()?)\s*"
|
|
45
|
+
_ROLE = r'(?:"[^"]*"|[\w$%{}.]+)'
|
|
46
|
+
_ROLES = rf"{_ROLE}(?:\s*,\s*{_ROLE})*"
|
|
47
|
+
_PRIVILEGES = (
|
|
48
|
+
r"(?:ALL|SELECT|INSERT|UPDATE|DELETE|TRUNCATE|REFERENCES|TRIGGER|USAGE|CREATE|CONNECT"
|
|
49
|
+
r"|TEMP(?:ORARY)?|EXECUTE|SET|ALTER\s+SYSTEM|MAINTAIN)\b[^;]*?\bON\b[^;]*?"
|
|
50
|
+
)
|
|
51
|
+
GRANT_STATEMENT = re.compile(
|
|
52
|
+
rf"{_START}(GRANT\s+(?:{_PRIVILEGES}|{_ROLES})\s+TO\s+{_ROLES}"
|
|
53
|
+
rf"\s*(?:WITH\s+[\w\s,]+?)?(?:GRANTED\s+BY\s+{_ROLE}\s*)?(?:;|\)|$))"
|
|
54
|
+
r"|(\bALTER\s+DEFAULT\s+PRIVILEGES\b)",
|
|
55
|
+
re.I,
|
|
56
|
+
)
|
|
57
|
+
_DYNAMIC_SQL = re.compile(r"\bEXECUTE\b(?:'(?:[^']|'')*'|[^;'])*", re.I)
|
|
58
|
+
_SQL_PROSE = re.compile(r"--[^\n]*|/\*.*?\*/|'(?:[^']|'')*'", re.S)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _python_strings(tree: ast.AST):
|
|
62
|
+
"""(line, text) of each string expression, docstrings skipped; f-string and
|
|
63
|
+
`+` parts are joined, with x standing in for each expression."""
|
|
64
|
+
seen = {
|
|
65
|
+
id(node.body[0].value)
|
|
66
|
+
for node in ast.walk(tree)
|
|
67
|
+
if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))
|
|
68
|
+
and node.body
|
|
69
|
+
and isinstance(node.body[0], ast.Expr)
|
|
70
|
+
and isinstance(node.body[0].value, ast.Constant)
|
|
71
|
+
and isinstance(node.body[0].value.value, str)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
def text(node: ast.AST) -> str:
|
|
75
|
+
seen.add(id(node))
|
|
76
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
77
|
+
return node.value
|
|
78
|
+
if isinstance(node, ast.JoinedStr):
|
|
79
|
+
return "".join(text(part) for part in node.values)
|
|
80
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
|
81
|
+
return text(node.left) + text(node.right)
|
|
82
|
+
return " x "
|
|
83
|
+
|
|
84
|
+
for node in ast.walk(tree):
|
|
85
|
+
if id(node) not in seen and (
|
|
86
|
+
isinstance(node, ast.JoinedStr)
|
|
87
|
+
or (isinstance(node, ast.Constant) and isinstance(node.value, str))
|
|
88
|
+
or (isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add))
|
|
89
|
+
):
|
|
90
|
+
yield node.lineno, text(node)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _blank(match: re.Match) -> str:
|
|
94
|
+
return re.sub(r"[^\n]+", " ", match.group())
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _grant_line(source: str) -> int | None:
|
|
98
|
+
try:
|
|
99
|
+
strings = list(_python_strings(ast.parse(source)))
|
|
100
|
+
except (SyntaxError, ValueError): # unreadable as Python: every GRANT word counts
|
|
101
|
+
match = re.search(r"\bGRANT\b", source, re.I)
|
|
102
|
+
return source.count("\n", 0, match.start()) + 1 if match else None
|
|
103
|
+
for line, value in strings:
|
|
104
|
+
sql = _SQL_PROSE.sub(_blank, _DYNAMIC_SQL.sub(lambda m: m.group().replace("'", " "), value))
|
|
105
|
+
if match := GRANT_STATEMENT.search(sql):
|
|
106
|
+
# An escaped "\n" in a one-line string is a newline here, not in the file.
|
|
107
|
+
return min(line + sql.count("\n", 0, match.start(match.lastindex)), source.count("\n") + 1)
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def migration_lint_hits(source: str) -> list[tuple[int, str]]:
|
|
112
|
+
"""(line, reason) for each operation one migration file must not run."""
|
|
113
|
+
hits = [
|
|
114
|
+
(source.count("\n", 0, match.start()) + 1, reason)
|
|
115
|
+
for pattern, reason in BANNED_MIGRATION_PATTERNS
|
|
116
|
+
if (match := pattern.search(source))
|
|
117
|
+
]
|
|
118
|
+
if (line := _grant_line(source)) is not None:
|
|
119
|
+
hits.append((line, GRANT_REASON))
|
|
120
|
+
return sorted(hits)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
if __name__ == "__main__":
|
|
124
|
+
report = {}
|
|
125
|
+
for path in sys.argv[1:]:
|
|
126
|
+
with open(path, encoding="utf-8", errors="ignore") as handle:
|
|
127
|
+
report[path] = migration_lint_hits(handle.read())
|
|
128
|
+
print(json.dumps(report))
|