scriptable 0.1.0 → 0.2.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/dist/evaluate.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import binaryOps from "./binary-ops.js";
2
- import logicOps from "./logic-ops.js";
3
2
  // Properties that enable sandbox escape (prototype chain → Function constructor)
4
3
  // or prototype pollution. Blocked in both MemberExpression and deep path access.
5
4
  const BLOCKED_PROPS = new Set([
@@ -16,23 +15,61 @@ function assertSafeProperty(prop) {
16
15
  throw new Error(`Access to property '${prop}' is not allowed`);
17
16
  }
18
17
  }
19
- // Execution step counter — reset via resetStepCounter() before each run.
20
- let _steps = 0;
21
- let _maxSteps = 0;
22
- export function resetStepCounter(maxSteps) {
23
- _steps = 0;
24
- _maxSteps = maxSteps;
18
+ // Sentinel thrown by ReturnStatement and caught at the nearest function
19
+ // boundary (makeFunc). Without this, a `return` nested inside an `if` (or
20
+ // any non-ReturnStatement node) would be evaluated but the enclosing
21
+ // BlockStatement would keep iterating the remaining statements — so
22
+ // `function f(n) { if (n==0) return 1; f(0); return n; }` would fall
23
+ // through to `f(0)` after the guarded return and recurse forever.
24
+ class ReturnValue {
25
+ constructor(value) {
26
+ this.value = value;
27
+ }
25
28
  }
26
29
  function loc(exp) {
27
30
  return exp.loc.start;
28
31
  }
32
+ // Resolve an LHS or callee expression to an array of path segments. Used by
33
+ // AssignmentExpression target and CallExpression callee. Unlike full
34
+ // evaluation, this walks Identifier → name and stitches member accesses into
35
+ // a segment list; but it *does* evaluate the key of a computed member
36
+ // (`a[k]`) in the runtime env so the path reflects the actual property being
37
+ // addressed. Returning segments (not a dotted string) keeps dot-containing
38
+ // keys like `a["x.y"]` as a single segment — a dotted string would be
39
+ // re-split on the way through deepSet and write to `a.x.y` instead.
40
+ function evalAsPath(exp, env, functions) {
41
+ if (exp.type === "Identifier")
42
+ return [exp.name];
43
+ if (exp.type === "Literal")
44
+ return [String(exp.value)];
45
+ if (exp.type === "MemberExpression") {
46
+ const objParts = evalAsPath(exp.object, env, functions);
47
+ const propStr = exp.computed
48
+ ? String(evaluate(exp.property, env, functions))
49
+ : String(exp.property.name);
50
+ assertSafeProperty(propStr);
51
+ return [...objParts, propStr];
52
+ }
53
+ throw new Error("Cannot evaluate " + exp.type + " as assignment target");
54
+ }
29
55
  function makeFunc(params, body, env, functions) {
30
- const scope = env.extend();
56
+ // Fresh scope per invocation — a scope hoisted to closure creation time was
57
+ // shared across every call, so recursion overwrote the caller's params and
58
+ // any let/const it had set on the function scope. `env` is the closure's
59
+ // captured lexical parent; extend it anew on every call.
31
60
  return (...args) => {
61
+ const scope = env.extend();
32
62
  params.forEach((param, idx) => {
33
- scope.def(param, idx < args.length ? args[idx] : false);
63
+ scope.def([param], idx < args.length ? args[idx] : false);
34
64
  });
35
- return evaluate(body, scope, functions);
65
+ try {
66
+ return evaluate(body, scope, functions);
67
+ }
68
+ catch (err) {
69
+ if (err instanceof ReturnValue)
70
+ return err.value;
71
+ throw err;
72
+ }
36
73
  };
37
74
  }
38
75
  const evals = {
@@ -45,7 +82,13 @@ const evals = {
45
82
  for (const el of exp.elements) {
46
83
  if (el && el.type === "SpreadElement") {
47
84
  const spread = evaluate(el.argument, env, functions);
48
- result.push(...spread);
85
+ // Check projected length before growing. push(...spread) hits V8's
86
+ // argument-stack limit (~65K) well below maxAllocSize, so enforce here
87
+ // and grow via a loop instead.
88
+ const addLen = spread && typeof spread.length === "number" ? spread.length : 0;
89
+ env.runtime.checkLength(result.length + addLen);
90
+ for (const item of spread)
91
+ result.push(item);
49
92
  }
50
93
  else if (el) {
51
94
  result.push(evaluate(el, env, functions));
@@ -54,8 +97,31 @@ const evals = {
54
97
  return result;
55
98
  },
56
99
  AssignmentExpression(exp, env, functions) {
57
- const target = evaluate(exp.left);
58
- return env.set(target, evaluate(exp.right, env, functions), loc(exp));
100
+ // Previously the operator was ignored, so `a += 1` silently behaved as
101
+ // `a = 1`. Compound ops now read the current value, combine with the rhs
102
+ // via the matching binary op, and write back. Logical compounds
103
+ // (`||=`, `&&=`, `??=`) short-circuit: rhs is only evaluated and written
104
+ // when the gate condition holds.
105
+ const target = evalAsPath(exp.left, env, functions);
106
+ if (exp.operator === "=") {
107
+ return env.set(target, evaluate(exp.right, env, functions), loc(exp));
108
+ }
109
+ const current = env.get(target, loc(exp));
110
+ if (exp.operator === "||=") {
111
+ return current || env.set(target, evaluate(exp.right, env, functions), loc(exp));
112
+ }
113
+ if (exp.operator === "&&=") {
114
+ return current && env.set(target, evaluate(exp.right, env, functions), loc(exp));
115
+ }
116
+ if (exp.operator === "??=") {
117
+ return current ?? env.set(target, evaluate(exp.right, env, functions), loc(exp));
118
+ }
119
+ const op = exp.operator.slice(0, -1);
120
+ if (!binaryOps[op]) {
121
+ throw new Error(`Unsupported assignment operator: ${exp.operator}`);
122
+ }
123
+ const rhs = evaluate(exp.right, env, functions);
124
+ return env.set(target, binaryOps[op](current, rhs), loc(exp));
59
125
  },
60
126
  BinaryExpression(exp, env, functions) {
61
127
  const left = evaluate(exp.left, env, functions);
@@ -67,36 +133,59 @@ const evals = {
67
133
  let result;
68
134
  for (const part of exp.body) {
69
135
  result = evaluate(part, scope, functions);
70
- if (part.type === "ReturnStatement") {
71
- break;
72
- }
73
136
  }
74
137
  return result;
75
138
  },
76
139
  CallExpression(exp, env, functions) {
77
- const func = evaluate(exp.callee);
78
- // Collect args, handling spread
140
+ // Path-based resolution for static callees (Identifier / MemberExpression)
141
+ // lets us look up builtins in the `functions` map and dotted-path names in
142
+ // env. For dynamic callees (e.g. `f()()`, `(() => 1)()`), evaluate the
143
+ // callee as a value and call it directly if it's a function.
144
+ let fn;
145
+ let name;
146
+ if (exp.callee.type === "Identifier" ||
147
+ exp.callee.type === "MemberExpression") {
148
+ const path = evalAsPath(exp.callee, env, functions);
149
+ name = path.join(".");
150
+ // hasOwn, not `functions[name]`: a plain-object `functions` map inherits
151
+ // from Object.prototype, so `functions["constructor"]` would resolve to
152
+ // `Object`, `functions["toString"]` to `Object.prototype.toString`, etc.
153
+ // Not directly exploitable today (returned wrappers can't reach blocked
154
+ // props) but a foot-gun the moment a builtin shares a name with an
155
+ // Object.prototype member.
156
+ if (Object.prototype.hasOwnProperty.call(functions, name)) {
157
+ fn = functions[name];
158
+ }
159
+ else if (env.defined(path)) {
160
+ const value = env.get(path, loc(exp));
161
+ if (typeof value === "function")
162
+ fn = value;
163
+ }
164
+ }
165
+ else {
166
+ const value = evaluate(exp.callee, env, functions);
167
+ if (typeof value === "function")
168
+ fn = value;
169
+ }
170
+ // Collect args, handling spread. Same V8 argument-stack consideration
171
+ // as ArrayExpression — cap projected length and grow via a loop.
79
172
  const args = [];
80
173
  for (const arg of exp.arguments) {
81
174
  if (arg.type === "SpreadElement") {
82
175
  const spread = evaluate(arg.argument, env, functions);
83
- args.push(...spread);
176
+ const addLen = spread && typeof spread.length === "number" ? spread.length : 0;
177
+ env.runtime.checkLength(args.length + addLen);
178
+ for (const item of spread)
179
+ args.push(item);
84
180
  }
85
181
  else {
86
182
  args.push(evaluate(arg, env, functions));
87
183
  }
88
184
  }
89
- if (functions[func]) {
90
- return functions[func](...args);
91
- }
92
- if (env.defined(func)) {
93
- const customFunc = env.get(func, loc(exp));
94
- if (typeof customFunc === "function") {
95
- return customFunc(...args);
96
- }
97
- }
185
+ if (fn)
186
+ return fn(...args);
98
187
  const l = loc(exp);
99
- throw new Error(`${func} is not a function (${l.line}:${l.column})`);
188
+ throw new Error(`${name ?? exp.callee.type} is not a function (${l.line}:${l.column})`);
100
189
  },
101
190
  ConditionalExpression(exp, env, functions) {
102
191
  const test = evaluate(exp.test, env, functions);
@@ -110,11 +199,11 @@ const evals = {
110
199
  FunctionDeclaration(exp, env, functions) {
111
200
  const name = evaluate(exp.id);
112
201
  const params = exp.params.map((param) => evaluate(param));
113
- env.set(name, makeFunc(params, exp.body, env, functions), loc(exp));
202
+ env.set([name], makeFunc(params, exp.body, env, functions), loc(exp));
114
203
  },
115
204
  Identifier(exp, env) {
116
205
  if (env) {
117
- return env.get(exp.name, loc(exp));
206
+ return env.get([exp.name], loc(exp));
118
207
  }
119
208
  return exp.name;
120
209
  },
@@ -131,17 +220,22 @@ const evals = {
131
220
  return exp.value;
132
221
  },
133
222
  LogicalExpression(exp, env, functions) {
223
+ // Short-circuit: `a || b` must not evaluate `b` when `a` is truthy, and
224
+ // `a && b` must not evaluate `b` when `a` is falsy. Previously both sides
225
+ // were evaluated eagerly, which broke the common `guard && action` idiom.
134
226
  const left = evaluate(exp.left, env, functions);
135
- const right = evaluate(exp.right, env, functions);
136
- return logicOps[exp.operator](left, right);
227
+ switch (exp.operator) {
228
+ case "||":
229
+ return left || evaluate(exp.right, env, functions);
230
+ case "&&":
231
+ return left && evaluate(exp.right, env, functions);
232
+ case "??":
233
+ return left ?? evaluate(exp.right, env, functions);
234
+ default:
235
+ throw new Error(`Unsupported logical operator: ${exp.operator}`);
236
+ }
137
237
  },
138
238
  MemberExpression(exp, env, functions) {
139
- if (!env) {
140
- const obj = evaluate(exp.object);
141
- const prop = evaluate(exp.property);
142
- assertSafeProperty(prop);
143
- return `${obj}.${prop}`;
144
- }
145
239
  const obj = evaluate(exp.object, env, functions);
146
240
  if (exp.computed) {
147
241
  const prop = evaluate(exp.property, env, functions);
@@ -154,14 +248,56 @@ const evals = {
154
248
  },
155
249
  ObjectExpression(exp, env, functions) {
156
250
  const result = {};
251
+ // Track own-key count so we can bound via checkLength without an O(N)
252
+ // Object.keys(result).length call on every iteration.
253
+ let ownCount = 0;
157
254
  for (const prop of exp.properties) {
158
255
  if (prop.type === "SpreadElement") {
159
256
  const spread = evaluate(prop.argument, env, functions);
160
- Object.assign(result, spread);
257
+ // Object.assign invokes setters, which includes Object.prototype's
258
+ // __proto__ setter when source has own __proto__. Copy own enumerable
259
+ // keys manually and drop blocked keys so a spread can't set the
260
+ // prototype of result or plant a booby-trapped own "constructor".
261
+ if (spread != null && typeof spread === "object") {
262
+ const keys = Object.keys(spread);
263
+ // Project before writing: `reduce(arr, (a,k) => ({...a,[k]:k}), {})`
264
+ // grows the accumulator by one key per step and would otherwise run
265
+ // until maxSteps exhausts, leaving a maxSteps-sized object behind.
266
+ env.runtime.checkLength(ownCount + keys.length);
267
+ for (const key of keys) {
268
+ if (!BLOCKED_PROPS.has(key)) {
269
+ if (!Object.prototype.hasOwnProperty.call(result, key)) {
270
+ ownCount++;
271
+ }
272
+ result[key] = spread[key];
273
+ }
274
+ }
275
+ }
161
276
  }
162
277
  else {
163
- // Property — key can be Identifier or Literal
164
- const key = prop.key.type === "Identifier" ? prop.key.name : prop.key.value;
278
+ // Property — non-computed keys are Identifier (shorthand/name) or
279
+ // Literal; computed keys (`{[expr]: v}`) require evaluating the
280
+ // expression. The previous code ignored `computed`, so `{[k]: v}`
281
+ // silently used the identifier NAME "k" instead of its value.
282
+ let key;
283
+ if (prop.computed) {
284
+ key = String(evaluate(prop.key, env, functions));
285
+ }
286
+ else if (prop.key.type === "Identifier") {
287
+ key = prop.key.name;
288
+ }
289
+ else {
290
+ key = String(prop.key.value);
291
+ }
292
+ // Block "__proto__", "constructor", etc. as keys so user code can't
293
+ // set the prototype of a fresh object via literal syntax, and so an
294
+ // object leaving the sandbox can't carry a booby-trapped "constructor"
295
+ // into the caller's scope.
296
+ assertSafeProperty(key);
297
+ if (!Object.prototype.hasOwnProperty.call(result, key)) {
298
+ env.runtime.checkLength(ownCount + 1);
299
+ ownCount++;
300
+ }
165
301
  result[key] = evaluate(prop.value, env, functions);
166
302
  }
167
303
  }
@@ -175,7 +311,9 @@ const evals = {
175
311
  return result;
176
312
  },
177
313
  ReturnStatement(exp, env, functions) {
178
- return evaluate(exp.argument, env, functions);
314
+ // Throw a sentinel so control unwinds to the nearest function boundary
315
+ // regardless of which nested construct (if/block/etc.) contains the return.
316
+ throw new ReturnValue(exp.argument ? evaluate(exp.argument, env, functions) : undefined);
179
317
  },
180
318
  TemplateLiteral(exp, env, functions) {
181
319
  let result = "";
@@ -217,15 +355,23 @@ const evals = {
217
355
  VariableDeclarator(exp, env, functions) {
218
356
  const name = evaluate(exp.id);
219
357
  const value = exp.init ? evaluate(exp.init, env, functions) : undefined;
220
- return env.def(name, value);
358
+ return env.def([name], value);
221
359
  },
222
360
  };
223
361
  function evaluate(exp, env, functions) {
224
- if (_maxSteps > 0 && ++_steps > _maxSteps) {
225
- throw new Error("Execution limit exceeded");
226
- }
362
+ // env is absent when we're resolving a static path (AssignmentExpression
363
+ // target, CallExpression callee, function/variable names, params). Those
364
+ // branches don't execute user code, so the counter only needs to run here.
365
+ if (env)
366
+ env.runtime.step();
227
367
  if (evals[exp.type]) {
228
- return evals[exp.type](exp, env, functions);
368
+ const result = evals[exp.type](exp, env, functions);
369
+ // checkSize inspects strings and arrays; other return types are no-ops.
370
+ // Covers both interpreter-built values (BinaryExpression +, TemplateLiteral,
371
+ // ArrayExpression) and builtin results (CallExpression).
372
+ if (env)
373
+ env.runtime.checkSize(result);
374
+ return result;
229
375
  }
230
376
  throw new Error("Cannot evaluate " + exp.type);
231
377
  }
package/dist/index.d.ts CHANGED
@@ -1,13 +1,38 @@
1
1
  import type { FunctionMap } from "./builtin-functions.js";
2
- import Environment from "./environment.js";
2
+ import Environment, { Runtime } from "./environment.js";
3
3
  export interface RunnerOptions {
4
4
  functions?: FunctionMap;
5
5
  maxSteps?: number;
6
+ /**
7
+ * Maximum length (in UTF-16 code units) of the source string. The step
8
+ * counter only bounds execution; parsing a multi-megabyte string still
9
+ * consumes proportional CPU and memory inside acorn before the interpreter
10
+ * runs. Set to 0 to disable. Defaults to 64 KiB.
11
+ */
12
+ maxCodeSize?: number;
13
+ /**
14
+ * Maximum length of any string or array value produced during a run, and
15
+ * maximum key count of any object literal. String concatenation, array
16
+ * spread, and object spread-accumulation can grow exponentially in a handful
17
+ * of steps, well within the step budget. Set to 0 to disable. Defaults to
18
+ * 1,000,000 (strings ≤ 1M UTF-16 units ≈ 2 MB; arrays ≤ 1M elements;
19
+ * objects ≤ 1M keys).
20
+ */
21
+ maxAllocSize?: number;
22
+ /**
23
+ * Maximum wall-clock duration of a single run, in milliseconds. Checked
24
+ * between interpreter steps — a single long native builtin call (e.g.
25
+ * `sort` on a large array) can overshoot the deadline by up to its own
26
+ * duration, but subsequent interpreter work is rejected. Set to 0 to
27
+ * disable. Defaults to 0 (disabled); set to a positive value for hostile
28
+ * multi-tenant workloads.
29
+ */
30
+ maxDurationMs?: number;
6
31
  }
7
32
  export interface RunResult {
8
33
  result: any;
9
34
  env: Record<string, any>;
10
35
  }
11
- export default function runner({ functions, maxSteps }?: RunnerOptions): (code: string, env?: Record<string, any>, debug?: boolean) => RunResult;
12
- export { Environment };
36
+ export default function runner({ functions, maxSteps, maxCodeSize, maxAllocSize, maxDurationMs, }?: RunnerOptions): (code: string, env?: Record<string, any>, debug?: boolean) => RunResult;
37
+ export { Environment, Runtime };
13
38
  export type { FunctionMap };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as acorn from "acorn";
2
- import evaluate, { resetStepCounter } from "./evaluate.js";
2
+ import evaluate from "./evaluate.js";
3
3
  import builtinFuncs from "./builtin-functions.js";
4
- import Environment from "./environment.js";
4
+ import Environment, { Runtime } from "./environment.js";
5
5
  function parse(code) {
6
6
  return acorn.parse(code, {
7
7
  ecmaVersion: "latest",
@@ -10,17 +10,22 @@ function parse(code) {
10
10
  });
11
11
  }
12
12
  const DEFAULT_MAX_STEPS = 100000;
13
- export default function runner({ functions = builtinFuncs, maxSteps = DEFAULT_MAX_STEPS } = {}) {
13
+ const DEFAULT_MAX_CODE_SIZE = 64 * 1024;
14
+ const DEFAULT_MAX_ALLOC_SIZE = 1000000;
15
+ const DEFAULT_MAX_DURATION_MS = 0;
16
+ export default function runner({ functions = builtinFuncs, maxSteps = DEFAULT_MAX_STEPS, maxCodeSize = DEFAULT_MAX_CODE_SIZE, maxAllocSize = DEFAULT_MAX_ALLOC_SIZE, maxDurationMs = DEFAULT_MAX_DURATION_MS, } = {}) {
14
17
  return (code, env = {}, debug) => {
18
+ if (maxCodeSize > 0 && code.length > maxCodeSize) {
19
+ throw new Error(`Source exceeds maxCodeSize (${code.length} > ${maxCodeSize})`);
20
+ }
15
21
  const ast = parse(code);
16
22
  debug && console.log(JSON.stringify(ast.body, null, 2));
17
- resetStepCounter(maxSteps);
18
- const globalEnv = new Environment();
23
+ const globalEnv = new Environment(undefined, new Runtime(maxSteps, maxAllocSize, maxDurationMs));
19
24
  Object.keys(env).forEach((key) => {
20
- globalEnv.def(key, env[key]);
25
+ globalEnv.def([key], env[key]);
21
26
  });
22
27
  const result = evaluate(ast, globalEnv, functions);
23
28
  return { result, env: globalEnv.vars };
24
29
  };
25
30
  }
26
- export { Environment };
31
+ export { Environment, Runtime };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scriptable",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -16,16 +16,19 @@
16
16
  "type": "git",
17
17
  "url": "https://github.com/lecstor/scriptable.git"
18
18
  },
19
- "scripts": {
20
- "build": "tsc",
21
- "test": "vitest run",
22
- "test:watch": "vitest"
23
- },
24
19
  "dependencies": {
25
20
  "acorn": "^8.14.1"
26
21
  },
27
22
  "devDependencies": {
23
+ "@changesets/cli": "^2.30.0",
28
24
  "typescript": "^5.7.0",
29
- "vitest": "^3.1.0"
25
+ "vitest": "^4.1.4"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc",
29
+ "test": "vitest run",
30
+ "test:watch": "vitest",
31
+ "changeset": "changeset",
32
+ "release": "node scripts/release.js"
30
33
  }
31
- }
34
+ }
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Release a new version end-to-end.
4
+ *
5
+ * Guards:
6
+ * 1. Refuses to run on a dirty tree.
7
+ * 2. Refuses to run off main.
8
+ * 3. Refuses to run if local main is behind origin/main (fetches first).
9
+ * 4. Refuses to run with no pending changesets.
10
+ *
11
+ * Steps:
12
+ * 5. Runs tests + build as a safety gate.
13
+ * 6. Consumes changesets to bump package.json + CHANGELOG.md.
14
+ * 7. Commits the result as "Version X.Y.Z".
15
+ * 8. Shows the commit and prompts for confirmation.
16
+ * 9. On confirm: pushes main, creates the vX.Y.Z annotated tag,
17
+ * pushes the tag. The tag push triggers .github/workflows/release.yml,
18
+ * which publishes to npm via OIDC (with provenance).
19
+ * 10. On abort: prints instructions to undo the version commit and exits 1.
20
+ *
21
+ * There is deliberately only one user-facing pnpm script (`pnpm release`) —
22
+ * the interactive prompt at step 8 is the abort window. Everything before
23
+ * the prompt is local-only and reversible with `git reset --hard HEAD^`.
24
+ */
25
+ import { execSync } from "node:child_process";
26
+ import { readFileSync, readdirSync } from "node:fs";
27
+ import { createInterface } from "node:readline/promises";
28
+ import { stdin, stdout } from "node:process";
29
+
30
+ function run(cmd) {
31
+ execSync(cmd, { stdio: "inherit" });
32
+ }
33
+
34
+ function capture(cmd) {
35
+ return execSync(cmd, { encoding: "utf-8" }).trim();
36
+ }
37
+
38
+ function fail(msg) {
39
+ console.error(`release: ${msg}`);
40
+ process.exit(1);
41
+ }
42
+
43
+ async function prompt(question) {
44
+ const rl = createInterface({ input: stdin, output: stdout });
45
+ try {
46
+ return (await rl.question(question)).trim().toLowerCase();
47
+ } finally {
48
+ rl.close();
49
+ }
50
+ }
51
+
52
+ // 1. Clean tree check.
53
+ if (capture("git status --porcelain")) {
54
+ fail("working tree is not clean — commit or stash first.");
55
+ }
56
+
57
+ // 2. On main?
58
+ const branch = capture("git rev-parse --abbrev-ref HEAD");
59
+ if (branch !== "main") {
60
+ fail(`not on main branch (currently on ${branch}).`);
61
+ }
62
+
63
+ // 3. Up-to-date check.
64
+ run("git fetch origin main");
65
+ const localMain = capture("git rev-parse main");
66
+ const remoteMain = capture("git rev-parse origin/main");
67
+ if (localMain !== remoteMain) {
68
+ const behind = capture(`git rev-list --count ${localMain}..${remoteMain}`);
69
+ if (behind !== "0") {
70
+ fail(`local main is ${behind} commit(s) behind origin/main — pull first.`);
71
+ }
72
+ }
73
+
74
+ // 4. Pending changeset check.
75
+ const pending = readdirSync(".changeset").filter(
76
+ (f) => f.endsWith(".md") && f.toLowerCase() !== "readme.md",
77
+ );
78
+ if (pending.length === 0) {
79
+ fail("no pending changesets — run `pnpm changeset` first.");
80
+ }
81
+ console.log(
82
+ `Found ${pending.length} pending changeset(s): ${pending.join(", ")}\n`,
83
+ );
84
+
85
+ // 5. Safety gate.
86
+ run("pnpm test");
87
+ run("pnpm build");
88
+
89
+ // 6. Consume changesets → bump package.json + CHANGELOG.md.
90
+ run("pnpm exec changeset version");
91
+
92
+ // 7. Commit. Stage only the files changeset version touches.
93
+ const { version } = JSON.parse(readFileSync("./package.json", "utf-8"));
94
+ run("git add package.json CHANGELOG.md .changeset");
95
+ run(`git commit -m "Version ${version}"`);
96
+
97
+ // 8. Show the commit and prompt.
98
+ console.log("");
99
+ run("git --no-pager show HEAD --stat");
100
+ console.log("");
101
+ console.log("-".repeat(60));
102
+ console.log(` About to release scriptable v${version}`);
103
+ console.log("-".repeat(60));
104
+ console.log(` Next: push main, create tag v${version}, push tag`);
105
+ console.log(" -> tag push triggers .github/workflows/release.yml");
106
+ console.log(" -> CI publishes to npm via OIDC (with provenance)");
107
+ console.log("");
108
+ console.log(" This is your last chance to abort. Once the tag is pushed,");
109
+ console.log(" publishing happens automatically.");
110
+ console.log("");
111
+ const answer = await prompt("Proceed? [y/N] ");
112
+
113
+ if (answer !== "y" && answer !== "yes") {
114
+ console.log("\nAborted. To undo the version commit locally:");
115
+ console.log(" git reset --hard HEAD^");
116
+ console.log(" # your .changeset files will come back from the reset");
117
+ process.exit(1);
118
+ }
119
+
120
+ // 9. Push main, tag, push tag.
121
+ run("git push origin main");
122
+ run("pnpm exec changeset tag");
123
+ run("git push --follow-tags");
124
+
125
+ console.log(`\nv${version} tag pushed.`);
126
+ console.log(` https://github.com/lecstor/scriptable/actions`);
127
+ console.log(` The release workflow will publish to npm shortly.`);