@deepraxis/cli 0.2.2-dev.b4438f4 → 0.2.2-dev.bac4728

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.
Files changed (3) hide show
  1. package/COMMANDS.md +1 -1
  2. package/dist/praxis.js +1364 -30
  3. package/package.json +1 -1
package/dist/praxis.js CHANGED
@@ -6946,6 +6946,7 @@ var require_public_api = __commonJS((exports) => {
6946
6946
 
6947
6947
  // src/main.ts
6948
6948
  import { readFile as readFile3 } from "node:fs/promises";
6949
+ import { createHash as createHash3 } from "node:crypto";
6949
6950
  import { spawn as spawn2 } from "node:child_process";
6950
6951
  import { createInterface } from "node:readline";
6951
6952
 
@@ -17166,7 +17167,7 @@ Execution errors include error.details.prints containing output printed before f
17166
17167
  name: "folder",
17167
17168
  type: "string",
17168
17169
  required: false,
17169
- description: "Optional destination path within the bound media library; omitted uses its default folder."
17170
+ description: "Optional destination path within the bound media library; omitted uses its default folder. Naming a binding or a folder also imports the finished video into that media library as an asset. Omit both and the export is a file only: read file.url to download it."
17170
17171
  },
17171
17172
  {
17172
17173
  name: "name",
@@ -17184,7 +17185,7 @@ Execution errors include error.details.prints containing output printed before f
17184
17185
  name: "binding",
17185
17186
  type: "string",
17186
17187
  required: false,
17187
- description: "Writable binding name used as the export destination; omission uses default_upload."
17188
+ description: "Writable binding name used as the export destination; omission uses default_upload. Naming a binding or a folder also imports the finished video into that media library as an asset. Omit both and the export is a file only; read file.url to download it."
17188
17189
  },
17189
17190
  {
17190
17191
  name: "revision",
@@ -24652,7 +24653,7 @@ for more details.`
24652
24653
  resource: "ontology.nodes",
24653
24654
  method: "create",
24654
24655
  summary: "Create node",
24655
- description: "Record one entity in the graph, for a system mirroring a record it owns. type must already be registered and ref, when given, must match that type's ref_prefix. Send an Idempotency-Key header; repeating the same key with the same content returns the first result instead of creating a second node. This writes structure only — to give an agent something to remember, use POST /agent/v1/agents/{agent_id}/consolidations.",
24656
+ description: "Record one entity in the graph, for a system mirroring a record it owns. type must already be registered and ref, when given, must match that type's ref_prefix. Send an Idempotency-Key header; repeating the same key with the same content returns the first result instead of creating a second node. This writes structure only; it does not give any agent a memory.",
24656
24657
  http: "POST",
24657
24658
  path: "/ontology/v1/nodes",
24658
24659
  streaming: "no",
@@ -24926,7 +24927,7 @@ for more details.`
24926
24927
  resource: "ontology.relations",
24927
24928
  method: "create",
24928
24929
  summary: "Create relation",
24929
- description: "Record one fact between two existing nodes, for a system mirroring a relationship it owns. type must be registered and must admit these endpoints; fact states the relationship in one sentence. Send an Idempotency-Key header; repeating the same key returns the first result instead of writing a second relation. This writes structure only — to give an agent something to remember, use POST /agent/v1/agents/{agent_id}/consolidations.",
24930
+ description: "Record one fact between two existing nodes, for a system mirroring a relationship it owns. type must be registered and must admit these endpoints; fact states the relationship in one sentence. Send an Idempotency-Key header; repeating the same key returns the first result instead of writing a second relation. This writes structure only; it does not give any agent a memory.",
24930
24931
  http: "POST",
24931
24932
  path: "/ontology/v1/relations",
24932
24933
  streaming: "no",
@@ -25038,7 +25039,7 @@ for more details.`
25038
25039
  resource: "ontology.search",
25039
25040
  method: "create",
25040
25041
  summary: "Search nodes",
25041
- description: "Resolve text to the nodes it most likely names, when a mirror holds a name and needs the node id it corresponds to. Results are ranked candidates, not an answer, each reporting whether the match came from the node's name, an alias, its description or a relation's fact. Narrow with types, and cap the result count with limit (1–50, default 20). This reads structure; it is not an agent recall — agents recall through POST /agent/v1/agents/{agent_id}/consolidations.",
25042
+ description: "Resolve text to the nodes it most likely names, when a mirror holds a name and needs the node id it corresponds to. Results are ranked candidates, not an answer, each reporting whether the match came from the node's name, an alias, its description or a relation's fact. Narrow with types, and cap the result count with limit (1–50, default 20). This reads structure; it is not an agent's recall, which reads the graph from that agent's own viewpoint inside its sessions.",
25042
25043
  http: "POST",
25043
25044
  path: "/ontology/v1/search",
25044
25045
  streaming: "no",
@@ -44735,6 +44736,7 @@ var workflows = [
44735
44736
  { words: ["app", "rollback"], usage: "app rollback [--dir <path>] [--to <version_id>]", summary: "Deploy the previous version again (or --to a given version) and wait until it is active.", example: "praxis app rollback --to <version_id>" },
44736
44737
  { words: ["devops", "deploy", "plan"], usage: "devops deploy plan [--env <name>] [--since <commit>]", summary: "Plan this repository's deploy: the targets by dependency layer, and with --since the ones a change touches. Local facts only — no login, no request.", example: "praxis devops deploy plan --env develop --since HEAD~1" },
44737
44738
  { words: ["devops", "test", "run"], usage: "devops test run --remote [--project <dvp_…>] [--no-wait] [--repeat <n>] [--select <kind:value>]", summary: "Run the DevOps test selection for the pushed HEAD on the Praxis cloud, wait for the verdict and list the failed cases.", example: "praxis devops test run --remote --select smoke" },
44739
+ { words: ["canvas", "import"], usage: "canvas import <file.pen> [--name <name>] [--canvas <cvs_…> --yes] [--frames <id,id>] [--image-root <dir>] [--dry-run]", summary: "Import a Pencil .pen file as a canvas, uploading the images it references first.", example: 'praxis canvas import design.pen --name "Landing page"' },
44738
44740
  { words: ["skill"], usage: "skill [--install <dir>]", summary: "Print the AI skill, or write <dir>/praxis-cli/SKILL.md." }
44739
44741
  ];
44740
44742
  var workflowNouns = [...new Set(workflows.filter((w) => w.words.length > 1).map((w) => w.words[0]))];
@@ -45305,7 +45307,22 @@ function skillDocument(commands) {
45305
45307
  "- `--select` narrows the run: `tag:<tag>` (a bare word reads as a tag), `package:<path>`, `suite:<path>`, `file:<path>`. `--repeat N` runs each selected case N times (a flake then shows up as flaky, not as a failure).",
45306
45308
  "- The run waits by default and polls every 5s; `--no-wait` returns as soon as the run exists, with `result` still `pending`.",
45307
45309
  "- Exit code 0 means the verdict passed (or is still pending); 1 means failed, errored, cancelled or timed out — the failed cases are listed, up to 20, with the run URL for the rest; 2 is a usage error.",
45308
- "- The run URL is on the Console of the environment the CLI talks to; the run id is also on stdout with `--json`."
45310
+ "- The run URL is on the Console of the environment the CLI talks to; the run id is also on stdout with `--json`.",
45311
+ "",
45312
+ "## canvas import (workflow)",
45313
+ "",
45314
+ "Import a Pencil `.pen` file as a canvas, uploading the images it references first:",
45315
+ "",
45316
+ "- Use it for a `.pen` file on this machine. The canvas API itself only takes nodes that already point at platform file ids, and a codemode program runs in the cloud where it cannot read your files — this command is the local half.",
45317
+ "- Node ids, component references, variables and themes are preserved as written: the file imports as it is, not as a redraw.",
45318
+ "- `--name <name>` names a new canvas (default: the file name without `.pen`). `--canvas <cvs_…>` imports into an existing canvas instead, which **clears every node already on it** — that is why it also requires `--yes`.",
45319
+ "- `--frames <id,id>` imports only these top-level nodes, in document order. The top-level nodes their `ref`s need come along automatically and are listed as `added`.",
45320
+ "- Images: an image fill must name a platform file id (`file-…`). Each non-`file-` url is looked up beside the `.pen` file, then under each `--image-root <dir>` (repeatable), then by file name under each root, and uploaded with a signed URL. Identical content uploads once.",
45321
+ "- An image that is not found locally is **not** a failure: it is listed under `images.missing` and `warnings` and the import continues. The canvas then shows a placeholder there — fix the path and re-import rather than leaving it.",
45322
+ "- `--dry-run` reads the local file and prints the plan (top-level nodes, added dependencies, node count, images found/missing, chunk count) without logging in or sending any request. Use it to check a document before it reaches a canvas.",
45323
+ "- Large documents go up in chunks of at most 1.5 M JSON characters; the first chunk resets the canvas and carries the variables and themes. The command is not atomic across chunks: a failure part-way leaves what already arrived, so re-run it (`--canvas … --yes` replaces the whole canvas).",
45324
+ "- Exit code 0 means the import completed, warnings included; 2 is a usage error (missing `--yes` with `--canvas`, an unreadable or non-`.pen` file).",
45325
+ "- `--format json` prints `{ canvas_id, viewer_url, revision, frames, added, nodes, images: { uploaded, reused, missing }, chunks, warnings, dry_run }`. Warnings are `FRAME_NOT_FOUND`, `REF_DANGLING`, `IMAGE_UNMAPPED` (planned) and `UNSUPPORTED_IMAGE_URL` (the service could not resolve one)."
45309
45326
  ];
45310
45327
  let domain;
45311
45328
  for (const command of commands) {
@@ -46121,6 +46138,13 @@ function workerNameOf(config) {
46121
46138
  const name = config?.name;
46122
46139
  return typeof name === "string" && name !== "" ? name : undefined;
46123
46140
  }
46141
+ function productionBlockOf(config) {
46142
+ const env = config?.env;
46143
+ if (env === null || typeof env !== "object")
46144
+ return;
46145
+ const block = env.production;
46146
+ return block !== null && typeof block === "object" ? block : undefined;
46147
+ }
46124
46148
  function bindingReferences(config) {
46125
46149
  const references = [];
46126
46150
  const own = workerNameOf(config);
@@ -46447,7 +46471,9 @@ function workspaceCloudflareProvider(options = {}) {
46447
46471
  name: workspace.packageName ?? (workspace.dir === "." ? "app" : workspace.dir.split("/").at(-1)),
46448
46472
  destination: "cloudflare",
46449
46473
  ...workspace.workerName === undefined ? {} : { workerName: workspace.workerName },
46450
- ...environments === undefined ? {} : { environments }
46474
+ ...environments === undefined ? {} : { environments },
46475
+ production: productionBlockOf(workspace.config) !== undefined,
46476
+ onTrain: lifecycle?.train !== false
46451
46477
  });
46452
46478
  }
46453
46479
  return { targets: [...partial.targets, ...targets] };
@@ -46503,12 +46529,24 @@ function closePlan(drafts, workspaces) {
46503
46529
  destination: draft.destination,
46504
46530
  dependsOn: edges.get(draft.path) ?? [],
46505
46531
  ...draft.environments === undefined ? {} : { environments: draft.environments },
46532
+ production: draft.production === true,
46533
+ onTrain: draft.onTrain !== false,
46506
46534
  workspaceDeps: workspaceClosureOf(draft.path, byName, dependenciesOf)
46507
46535
  })).sort((a, b) => a.path.localeCompare(b.path));
46508
46536
  }
46509
46537
  function targetsFor(plan, environment2) {
46510
46538
  return plan.targets.filter((target) => target.environments === undefined || target.environments.includes(environment2));
46511
46539
  }
46540
+ var TARGET_EXTERNAL_INPUTS = {
46541
+ "apps/docs": [
46542
+ "apps/api/openapi/openapi.yaml",
46543
+ "packages/praxis/rpc-kit/src/errors.ts",
46544
+ "services/agent/src/domain/error-codes.ts",
46545
+ ...["application", "database", "knowledge"].map((s) => `services/${s}/src/api/error-exit.ts`),
46546
+ ...["router", "vault", "browser", "search"].map((s) => `services/${s}/src/api/rpc-contract.ts`),
46547
+ ...["media", "automation", "sandbox", "file", "billing", "config", "eventbus", "lakehouse", "identity", "notification", "ops", "registry"].map((s) => `services/${s}/src/api/contract.ts`)
46548
+ ]
46549
+ };
46512
46550
  function diffTargets(plan, changedPaths) {
46513
46551
  const changed = new Set(changedPaths);
46514
46552
  const touches = (dir) => {
@@ -46520,7 +46558,8 @@ function diffTargets(plan, changedPaths) {
46520
46558
  return true;
46521
46559
  return false;
46522
46560
  };
46523
- return plan.targets.filter((target) => touches(target.path) || target.workspaceDeps.some(touches)).map((target) => target.path);
46561
+ const readsChangedInput = (dir) => (TARGET_EXTERNAL_INPUTS[dir] ?? []).some((file) => changed.has(file));
46562
+ return plan.targets.filter((target) => touches(target.path) || target.workspaceDeps.some(touches) || readsChangedInput(target.path) || target.workspaceDeps.some(readsChangedInput)).map((target) => target.path);
46524
46563
  }
46525
46564
  function layersOf(plan) {
46526
46565
  const paths = plan.targets.map((target) => target.path);
@@ -46690,6 +46729,1231 @@ async function devopsDeployPlan(args, ports) {
46690
46729
  ports.human(renderDeployPlan(view));
46691
46730
  }
46692
46731
 
46732
+ // src/commands/canvas-import.ts
46733
+ import { basename as basename2, dirname as dirname2, join as join5, resolve as resolve3 } from "node:path";
46734
+
46735
+ // ../../packages/canvas/document/src/types.ts
46736
+ class OpRejectedError extends Error {
46737
+ rejection;
46738
+ constructor(rejection) {
46739
+ super(`${rejection.code}: ${JSON.stringify(rejection)}`);
46740
+ this.rejection = rejection;
46741
+ }
46742
+ }
46743
+ var CONTAINER_TYPES = new Set(["frame", "group"]);
46744
+ // ../../packages/canvas/document/src/legacy-props.ts
46745
+ function ownIconProps(node2) {
46746
+ const out = { ...node2 };
46747
+ if ((node2.type === "icon" || node2.type === undefined) && "iconName" in node2) {
46748
+ if (!("icon" in node2))
46749
+ out.icon = node2.iconName;
46750
+ delete out.iconName;
46751
+ }
46752
+ return out;
46753
+ }
46754
+ function migrateLegacyIconProps(node2) {
46755
+ const out = ownIconProps(node2);
46756
+ if (node2.descendants && typeof node2.descendants === "object" && !Array.isArray(node2.descendants))
46757
+ out.descendants = Object.fromEntries(Object.entries(node2.descendants).map(([key, value]) => [
46758
+ key,
46759
+ value && typeof value === "object" && !Array.isArray(value) ? migrateLegacyIconProps(value) : value
46760
+ ]));
46761
+ if (Array.isArray(node2.children))
46762
+ out.children = node2.children.map((child) => migrateLegacyIconProps(child));
46763
+ return out;
46764
+ }
46765
+ function migrateLegacyProps(node2) {
46766
+ const out = ownIconProps(node2);
46767
+ const stroke = node2.stroke;
46768
+ if (stroke && typeof stroke === "object" && !Array.isArray(stroke) && "fill" in stroke) {
46769
+ const old = stroke;
46770
+ out.stroke = old.fill;
46771
+ if (!("strokeWidth" in node2) && "thickness" in old)
46772
+ out.strokeWidth = old.thickness;
46773
+ if (!("strokeAlignment" in node2) && "align" in old) {
46774
+ out.strokeAlignment = old.align === "inside" ? "inner" : old.align === "outside" ? "outer" : old.align;
46775
+ }
46776
+ }
46777
+ if (Array.isArray(node2.children))
46778
+ out.children = node2.children.map((child) => migrateLegacyProps(child));
46779
+ if (node2.descendants && typeof node2.descendants === "object" && !Array.isArray(node2.descendants))
46780
+ out.descendants = Object.fromEntries(Object.entries(node2.descendants).map(([key, value]) => [
46781
+ key,
46782
+ value && typeof value === "object" && !Array.isArray(value) ? migrateLegacyProps(value) : value
46783
+ ]));
46784
+ return out;
46785
+ }
46786
+
46787
+ // ../../packages/canvas/document/src/store.ts
46788
+ var DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
46789
+ var BASE = DIGITS.length;
46790
+ function midpoint(a, b) {
46791
+ if (b !== null) {
46792
+ let n = 0;
46793
+ while ((a[n] ?? "0") === b[n])
46794
+ n++;
46795
+ if (n > 0)
46796
+ return b.slice(0, n) + midpoint(a.slice(n), b.slice(n));
46797
+ }
46798
+ const da = a ? DIGITS.indexOf(a[0]) : 0;
46799
+ const db = b !== null ? DIGITS.indexOf(b[0]) : BASE;
46800
+ if (db - da > 1)
46801
+ return DIGITS[Math.floor((da + db) / 2)];
46802
+ if (b !== null && b.length > 1)
46803
+ return b.slice(0, 1);
46804
+ return DIGITS[da] + midpoint(a.slice(1), null);
46805
+ }
46806
+ function between(a, b) {
46807
+ return midpoint(a ?? "", b);
46808
+ }
46809
+ function spacedKeys(n) {
46810
+ let width = 1;
46811
+ while (BASE ** width < n + 2)
46812
+ width++;
46813
+ const keys = [];
46814
+ for (let i = 1;i <= n; i++) {
46815
+ let v = i;
46816
+ let s = "";
46817
+ for (let d = 0;d < width; d++) {
46818
+ s = DIGITS[v % BASE] + s;
46819
+ v = Math.floor(v / BASE);
46820
+ }
46821
+ keys.push(s + "V");
46822
+ }
46823
+ return keys;
46824
+ }
46825
+
46826
+ class MapNodeStore {
46827
+ nodes = new Map;
46828
+ kids = new Map;
46829
+ vars = {};
46830
+ themeAxes = {};
46831
+ rev = 0;
46832
+ get(id) {
46833
+ return this.nodes.get(id);
46834
+ }
46835
+ children(id) {
46836
+ return this.kids.get(id) ?? [];
46837
+ }
46838
+ variables() {
46839
+ return this.vars;
46840
+ }
46841
+ themes() {
46842
+ return this.themeAxes;
46843
+ }
46844
+ revision() {
46845
+ return this.rev;
46846
+ }
46847
+ unlink(n) {
46848
+ const list = this.kids.get(n.parent);
46849
+ if (!list)
46850
+ return;
46851
+ const i = list.indexOf(n.id);
46852
+ if (i >= 0)
46853
+ list.splice(i, 1);
46854
+ }
46855
+ link(n) {
46856
+ let list = this.kids.get(n.parent);
46857
+ if (!list)
46858
+ this.kids.set(n.parent, list = []);
46859
+ let lo = 0;
46860
+ let hi = list.length;
46861
+ if (hi && this.nodes.get(list[hi - 1]).ord < n.ord)
46862
+ lo = hi;
46863
+ while (lo < hi) {
46864
+ const mid = lo + hi >> 1;
46865
+ const o = this.nodes.get(list[mid]).ord;
46866
+ if (o < n.ord || o === n.ord && list[mid] < n.id)
46867
+ lo = mid + 1;
46868
+ else
46869
+ hi = mid;
46870
+ }
46871
+ list.splice(lo, 0, n.id);
46872
+ }
46873
+ put(node2) {
46874
+ const prev = this.nodes.get(node2.id);
46875
+ if (prev && (prev.parent !== node2.parent || prev.ord !== node2.ord))
46876
+ this.unlink(prev);
46877
+ this.nodes.set(node2.id, node2);
46878
+ if (!prev || prev.parent !== node2.parent || prev.ord !== node2.ord)
46879
+ this.link(node2);
46880
+ }
46881
+ remove(id) {
46882
+ const prev = this.nodes.get(id);
46883
+ if (!prev)
46884
+ return;
46885
+ this.unlink(prev);
46886
+ this.kids.delete(id);
46887
+ this.nodes.delete(id);
46888
+ }
46889
+ setVariables(vars, themes) {
46890
+ this.vars = vars;
46891
+ this.themeAxes = themes;
46892
+ }
46893
+ setRevision(rev) {
46894
+ this.rev = rev;
46895
+ }
46896
+ size() {
46897
+ return this.nodes.size;
46898
+ }
46899
+ reindex() {}
46900
+ }
46901
+ function ownProps(node2) {
46902
+ const { children: _c, ...rest } = node2;
46903
+ return rest;
46904
+ }
46905
+ function flatten(nodes, parent, top, rev, out = []) {
46906
+ const keys = spacedKeys(nodes.length);
46907
+ nodes.forEach((n, i) => {
46908
+ const t = top ?? n.id;
46909
+ const props = ownProps(n);
46910
+ const ord = typeof props.__ord === "string" ? props.__ord : keys[i];
46911
+ delete props.__ord;
46912
+ out.push({ id: n.id, parent, ord, top: t, props, rev });
46913
+ if (Array.isArray(n.children) && n.children.length)
46914
+ flatten(n.children, n.id, t, rev, out);
46915
+ });
46916
+ return out;
46917
+ }
46918
+ function subtree(store, id, depth = Infinity, withOrd = false) {
46919
+ const row = store.get(id);
46920
+ if (!row)
46921
+ throw new Error(`node ${id} not found`);
46922
+ const node2 = migrateLegacyIconProps(row.props);
46923
+ if (withOrd)
46924
+ node2.__ord = row.ord;
46925
+ const kids = store.children(id);
46926
+ if (kids.length) {
46927
+ if (depth <= 0)
46928
+ node2.children = "...";
46929
+ else
46930
+ node2.children = kids.map((k) => subtree(store, k, depth - 1, withOrd));
46931
+ }
46932
+ return node2;
46933
+ }
46934
+ // ../../packages/canvas/document/src/apply.ts
46935
+ function applyOp(store, op, rev) {
46936
+ switch (op.op) {
46937
+ case "insert": {
46938
+ const top = op.parent === null ? null : store.get(op.parent).top;
46939
+ const rows = flatten([op.node], op.parent, top, rev);
46940
+ rows[0] = { ...rows[0], ord: op.ord };
46941
+ for (const r of rows)
46942
+ store.put(r);
46943
+ return [rows[0].top];
46944
+ }
46945
+ case "update": {
46946
+ const row = store.get(op.id);
46947
+ const props = { ...row.props };
46948
+ for (const [k, v] of Object.entries(op.patch)) {
46949
+ if (v === undefined || v === null)
46950
+ delete props[k];
46951
+ else
46952
+ props[k] = v;
46953
+ }
46954
+ store.put({ ...row, props, rev });
46955
+ return [row.top];
46956
+ }
46957
+ case "delete": {
46958
+ const row = store.get(op.id);
46959
+ removeSubtree(store, op.id);
46960
+ return [row.top];
46961
+ }
46962
+ case "move": {
46963
+ const row = store.get(op.id);
46964
+ const oldTop = row.top;
46965
+ const newTop = op.parent === null ? op.id : store.get(op.parent).top;
46966
+ store.put({ ...row, parent: op.parent, ord: op.ord, top: newTop, rev });
46967
+ if (newTop !== oldTop)
46968
+ retop(store, op.id, newTop, rev);
46969
+ return oldTop === newTop ? [newTop] : [oldTop, newTop];
46970
+ }
46971
+ case "setVariables": {
46972
+ const vars = op.replace ? op.variables : { ...store.variables(), ...op.variables };
46973
+ const themes = { ...store.themes() };
46974
+ for (const [axis, values] of Object.entries(op.themes)) {
46975
+ const cur = themes[axis] ?? [];
46976
+ themes[axis] = [...cur, ...values.filter((v) => !cur.includes(v))];
46977
+ }
46978
+ store.setVariables(vars, themes);
46979
+ return [];
46980
+ }
46981
+ }
46982
+ }
46983
+ function removeSubtree(store, id) {
46984
+ for (const c of store.children(id))
46985
+ removeSubtree(store, c);
46986
+ store.remove(id);
46987
+ }
46988
+ function retop(store, id, top, rev) {
46989
+ for (const c of store.children(id)) {
46990
+ const row = store.get(c);
46991
+ store.put({ ...row, top, rev });
46992
+ retop(store, c, top, rev);
46993
+ }
46994
+ }
46995
+ // ../../packages/canvas/document/src/expand.ts
46996
+ function defaultTheme(themes) {
46997
+ const t = {};
46998
+ for (const [axis, values] of Object.entries(themes))
46999
+ if (values.length)
47000
+ t[axis] = values[0];
47001
+ return t;
47002
+ }
47003
+ function resolveVariable(name, vars, theme, depth = 0) {
47004
+ const def = vars[name];
47005
+ if (!def || depth > 8)
47006
+ return;
47007
+ let v;
47008
+ if (Array.isArray(def.value)) {
47009
+ let best;
47010
+ for (const e of def.value) {
47011
+ const keys = Object.keys(e.theme ?? {});
47012
+ if (keys.every((k) => theme[k] === e.theme[k]) && (!best || keys.length > best.score))
47013
+ best = { value: e.value, score: keys.length };
47014
+ }
47015
+ v = best?.value ?? def.value[0]?.value;
47016
+ } else
47017
+ v = def.value;
47018
+ if (typeof v === "string" && v.startsWith("$") && vars[v.slice(1)])
47019
+ return resolveVariable(v.slice(1), vars, theme, depth + 1);
47020
+ return v;
47021
+ }
47022
+ function resolveDeep(value, vars, theme) {
47023
+ if (typeof value === "string") {
47024
+ if (value.startsWith("$") && vars[value.slice(1)] !== undefined)
47025
+ return resolveVariable(value.slice(1), vars, theme);
47026
+ return value;
47027
+ }
47028
+ if (Array.isArray(value))
47029
+ return value.map((v) => resolveDeep(v, vars, theme));
47030
+ if (value && typeof value === "object") {
47031
+ const out = {};
47032
+ for (const [k, v] of Object.entries(value))
47033
+ out[k] = resolveDeep(v, vars, theme);
47034
+ return out;
47035
+ }
47036
+ return value;
47037
+ }
47038
+ var SKIP_RESOLVE = new Set(["id", "type", "ref", "descendants", "name", "content", "children"]);
47039
+ function resolveProps(props, vars, theme) {
47040
+ const out = {};
47041
+ for (const [k, v] of Object.entries(props))
47042
+ out[k] = SKIP_RESOLVE.has(k) ? v : resolveDeep(v, vars, theme);
47043
+ if (typeof props.content === "string" && props.content.startsWith("$") && vars[props.content.slice(1)] !== undefined)
47044
+ out.content = String(resolveVariable(props.content.slice(1), vars, theme));
47045
+ return out;
47046
+ }
47047
+ function propsOf(store, src) {
47048
+ if (src.kind === "store")
47049
+ return store.get(src.id)?.props;
47050
+ const { children: _c, ...rest } = src.node;
47051
+ return rest;
47052
+ }
47053
+ function childrenOf(store, src) {
47054
+ if (src.kind === "store")
47055
+ return store.children(src.id).map((id) => ({ kind: "store", id }));
47056
+ return (src.node.children ?? []).map((node2) => ({ kind: "inline", node: node2 }));
47057
+ }
47058
+ function expandNode(store, id, parentTheme) {
47059
+ return expandSrc({ store, vars: store.variables(), stack: [] }, { kind: "store", id }, parentTheme, null, {});
47060
+ }
47061
+ function expandSrc(ctx, src, parentTheme, pathPrefix, overrides) {
47062
+ let props = propsOf(ctx.store, src);
47063
+ if (!props)
47064
+ return null;
47065
+ const ownId = props.id;
47066
+ const path = pathPrefix ? `${pathPrefix}/${ownId}` : ownId;
47067
+ const ov = pathPrefix ? overrides[ownId] : undefined;
47068
+ if (ov && typeof ov.type === "string") {
47069
+ const repl = ov;
47070
+ const replId = typeof repl.id === "string" ? repl.id : ownId;
47071
+ const e = expandSrc(ctx, { kind: "inline", node: { ...repl, id: replId } }, parentTheme, null, {});
47072
+ return e ? { ...e, role: "instance-child" } : null;
47073
+ }
47074
+ if (ov)
47075
+ props = { ...props, ...ov };
47076
+ const theme = props.theme && typeof props.theme === "object" ? { ...parentTheme, ...props.theme } : parentTheme;
47077
+ if (props.type === "ref")
47078
+ return expandRef(ctx, props, path, theme, pathPrefix ? childOverrides(overrides, ownId) : {});
47079
+ const resolved = resolveProps(props, ctx.vars, theme);
47080
+ const children = [];
47081
+ for (const c of childrenOf(ctx.store, src)) {
47082
+ const e = expandSrc(ctx, c, theme, pathPrefix, overrides);
47083
+ if (e)
47084
+ children.push(e);
47085
+ }
47086
+ return {
47087
+ path,
47088
+ type: props.type,
47089
+ props: resolved,
47090
+ children,
47091
+ theme,
47092
+ role: pathPrefix ? "instance-child" : props.reusable ? "component" : "plain"
47093
+ };
47094
+ }
47095
+ function childOverrides(overrides, id) {
47096
+ const out = {};
47097
+ const prefix = id + "/";
47098
+ for (const [k, v] of Object.entries(overrides))
47099
+ if (k.startsWith(prefix))
47100
+ out[k.slice(prefix.length)] = v;
47101
+ return out;
47102
+ }
47103
+ function expandRef(ctx, ref, path, theme, inherited) {
47104
+ const target = ref.ref;
47105
+ const comp = ctx.store.get(target);
47106
+ if (!comp || ctx.stack.includes(target))
47107
+ return null;
47108
+ const descendants = { ...ref.descendants ?? {} };
47109
+ for (const [id, override] of Object.entries(inherited)) {
47110
+ descendants[id] = typeof override.type === "string" ? override : { ...descendants[id], ...override };
47111
+ }
47112
+ const { id: _i, type: _t, ref: _r, descendants: _d, reusable: _re, ...refOwn } = ref;
47113
+ const root = { ...comp.props, ...refOwn, id: ref.id };
47114
+ delete root.reusable;
47115
+ ctx.stack.push(target);
47116
+ const rootTheme = root.theme && typeof root.theme === "object" ? { ...theme, ...root.theme } : theme;
47117
+ const children = [];
47118
+ for (const c of ctx.store.children(target)) {
47119
+ const e = expandSrc(ctx, { kind: "store", id: c }, rootTheme, path, descendants);
47120
+ if (e)
47121
+ children.push(e);
47122
+ }
47123
+ ctx.stack.pop();
47124
+ return { path, type: root.type, props: resolveProps(root, ctx.vars, rootTheme), children, theme: rootTheme, role: "instance" };
47125
+ }
47126
+ // ../../packages/canvas/document/src/known-props.ts
47127
+ var ENTITY = "id type name context reusable theme enabled opacity flipX flipY layoutPosition metadata rotation x y children";
47128
+ var SIZE = "width height";
47129
+ var STROKE = "stroke strokeWidth strokeLinecap strokeLinejoin strokeAlignment";
47130
+ var EFFECTS = "effect";
47131
+ var GRAPHICS = `${EFFECTS} ${STROKE} fill`;
47132
+ var TEXT = "fontFamily fontSize fontWeight letterSpacing fontStyle underline lineHeight textAlign textAlignVertical strikethrough href";
47133
+ var LAYOUT = "layout gap layoutIncludeStroke padding justifyContent alignItems";
47134
+ var RECTANGLE = `${SIZE} ${GRAPHICS} cornerRadius`;
47135
+ var keys = (extra) => new Set(`${ENTITY} ${extra}`.split(/\s+/));
47136
+ var KNOWN_PROPS = {
47137
+ rectangle: keys(RECTANGLE),
47138
+ ellipse: keys(`${SIZE} ${GRAPHICS} innerRadius startAngle sweepAngle`),
47139
+ polygon: keys(`${SIZE} ${GRAPHICS} polygonCount cornerRadius`),
47140
+ path: keys(`${SIZE} ${GRAPHICS} fillRule geometry viewBox`),
47141
+ text: keys(`${SIZE} ${GRAPHICS} ${TEXT} content textGrowth`),
47142
+ frame: keys(`${RECTANGLE} ${LAYOUT} clip placeholder slot`),
47143
+ group: keys(EFFECTS),
47144
+ note: keys(`${SIZE} ${TEXT} content`),
47145
+ prompt: keys(`${SIZE} ${TEXT} content model`),
47146
+ context: keys(`${SIZE} ${TEXT} content`),
47147
+ icon: keys(`${SIZE} ${EFFECTS} library icon weight fill`),
47148
+ script: keys(`${SIZE} clip scriptUri inputs`),
47149
+ browser: keys(`${SIZE} ${EFFECTS} ${STROKE} url deviceId zoom scrollX scrollY cornerRadius`),
47150
+ ref: keys("ref descendants")
47151
+ };
47152
+ function unknownProperties(node2, type) {
47153
+ if (type === "ref")
47154
+ return [];
47155
+ const allowed = Object.hasOwn(KNOWN_PROPS, type) ? KNOWN_PROPS[type] : keys("");
47156
+ return Object.keys(node2).filter((key) => !key.startsWith("__") && !allowed.has(key));
47157
+ }
47158
+ function iconNameOf(node2) {
47159
+ for (const key of ["icon", "iconName"]) {
47160
+ const value = node2[key];
47161
+ if (typeof value === "string" && value.trim() !== "")
47162
+ return value;
47163
+ }
47164
+ return "";
47165
+ }
47166
+ function hasUnsupportedImageUrl(node2) {
47167
+ const invalid = (paint) => {
47168
+ if (Array.isArray(paint))
47169
+ return paint.some(invalid);
47170
+ if (!paint || typeof paint !== "object")
47171
+ return false;
47172
+ const fill = paint;
47173
+ return fill.type === "image" && (typeof fill.url !== "string" || !/^file-[0-9A-Za-z]{24}$/.test(fill.url));
47174
+ };
47175
+ return invalid(node2.fill) || invalid(node2.stroke);
47176
+ }
47177
+
47178
+ // ../../packages/canvas/document/src/execute-api.ts
47179
+ var LIMITS = { ops: 5000, printBytes: 64 * 1024, screenshots: 4 };
47180
+ var ID_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
47181
+ class ExecuteApi {
47182
+ store;
47183
+ rec;
47184
+ bounds;
47185
+ rev;
47186
+ random;
47187
+ document = "document";
47188
+ layoutCache = new Map;
47189
+ constructor(store, rec, bounds, rev, random = Math.random) {
47190
+ this.store = store;
47191
+ this.rec = rec;
47192
+ this.bounds = bounds;
47193
+ this.rev = rev;
47194
+ this.random = random;
47195
+ }
47196
+ mint() {
47197
+ for (;; ) {
47198
+ let id = "";
47199
+ for (let i = 0;i < 5; i++)
47200
+ id += ID_CHARS[Math.floor(this.random() * ID_CHARS.length)];
47201
+ if (!this.store.get(id))
47202
+ return id;
47203
+ }
47204
+ }
47205
+ commit(op) {
47206
+ if (this.rec.ops.length >= LIMITS.ops)
47207
+ throw new Error(`SCRIPT_LIMIT: more than ${LIMITS.ops} operations in one execute`);
47208
+ const touched = applyOp(this.store, op, this.rev);
47209
+ this.mutations++;
47210
+ this.rec.ops.push(op);
47211
+ if (op.op === "setVariables")
47212
+ this.rec.allTouched = true;
47213
+ for (const t of touched) {
47214
+ this.rec.touchedTop.add(t);
47215
+ this.layoutCache.delete(t);
47216
+ }
47217
+ if (op.op === "setVariables")
47218
+ this.layoutCache.clear();
47219
+ }
47220
+ parentId(parent) {
47221
+ if (parent === "document" || parent === "" || parent == null)
47222
+ return null;
47223
+ if (parent.includes("/"))
47224
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "parent", reason: "cannot insert inside a component instance; use Replace on the instance child" });
47225
+ const row = this.store.get(parent);
47226
+ if (!row)
47227
+ throw new OpRejectedError({ code: "PARENT_NOT_FOUND", path: parent });
47228
+ if (!CONTAINER_TYPES.has(row.props.type))
47229
+ throw new OpRejectedError({ code: "CANNOT_HAVE_CHILDREN", parent, type: row.props.type });
47230
+ return parent;
47231
+ }
47232
+ lastOrd(parent) {
47233
+ const kids = this.store.children(parent);
47234
+ return kids.length ? this.store.get(kids[kids.length - 1]).ord : null;
47235
+ }
47236
+ withIds(node2) {
47237
+ if (typeof node2 !== "object" || node2 === null || typeof node2.type !== "string")
47238
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "type", reason: "node needs a type" });
47239
+ if (node2.type === "ref") {
47240
+ const target = node2.ref;
47241
+ if (!this.store.get(target))
47242
+ throw new OpRejectedError({ code: "UNKNOWN_REF", ref: target });
47243
+ }
47244
+ for (const k of ["width", "height"]) {
47245
+ const v = node2[k];
47246
+ if (typeof v === "number" && v < 0)
47247
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: k, reason: "negative size" });
47248
+ if (typeof v === "string" && /%|vh|vw|calc/.test(v))
47249
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: k, reason: "percentage and viewport sizes are not supported" });
47250
+ }
47251
+ const id = this.mint();
47252
+ const out = { ...node2, id };
47253
+ if (typeof node2.name === "string")
47254
+ this.rec.created[node2.name] = id;
47255
+ if (Array.isArray(node2.children)) {
47256
+ if (!CONTAINER_TYPES.has(node2.type))
47257
+ throw new OpRejectedError({ code: "CANNOT_HAVE_CHILDREN", parent: id, type: node2.type });
47258
+ out.children = node2.children.map((c) => this.withIds(c));
47259
+ }
47260
+ return out;
47261
+ }
47262
+ warnProps(data, type, nodeId) {
47263
+ if (hasUnsupportedImageUrl(data) && this.rec.warnings.length < 20 && !this.rec.warnings.some((w) => w.code === "UNSUPPORTED_IMAGE_URL" && w.nodeId === nodeId))
47264
+ this.rec.warnings.push({ code: "UNSUPPORTED_IMAGE_URL", nodeId, message: "image fill url must be a file id (file-…)" });
47265
+ if (data.type === "icon" && !iconNameOf(data) && this.rec.warnings.length < 20 && !this.rec.warnings.some((w) => w.code === "ICON_NAME_MISSING" && w.nodeId === nodeId))
47266
+ this.rec.warnings.push({ code: "ICON_NAME_MISSING", nodeId, message: "icon node has no icon: set icon to a lucide name (name is the node's name, not the icon)" });
47267
+ for (const prop of unknownProperties(data, type)) {
47268
+ const message = `${prop} is not a .pen property`;
47269
+ if (this.rec.warnings.length >= 20)
47270
+ break;
47271
+ if (!this.rec.warnings.some((w) => w.code === "UNKNOWN_PROPERTY" && w.nodeId === nodeId && w.message === message))
47272
+ this.rec.warnings.push({ code: "UNKNOWN_PROPERTY", nodeId, message });
47273
+ }
47274
+ for (const child of Array.isArray(data.children) ? data.children : [])
47275
+ this.warnProps(child, child.type, child.id ?? nodeId);
47276
+ if (data.descendants && typeof data.descendants === "object") {
47277
+ const descendants = typeof data.ref === "string" ? this.resolveDescendantKeys(data.ref, data.descendants) : data.descendants;
47278
+ for (const [key, value] of Object.entries(descendants)) {
47279
+ if (!value || typeof value !== "object")
47280
+ continue;
47281
+ const patch = value;
47282
+ const target = this.store.get(key)?.props.type ?? (typeof data.ref === "string" ? this.expandedAt(`${data.ref}/${key}`, {})?.node.type : undefined);
47283
+ this.warnProps(patch, typeof patch.type === "string" ? patch.type : target ?? "ref", `${nodeId}/${key}`);
47284
+ }
47285
+ }
47286
+ }
47287
+ splitInstancePath(path) {
47288
+ const i = path.indexOf("/");
47289
+ if (i < 0)
47290
+ return null;
47291
+ return { owner: path.slice(0, i), rest: path.slice(i + 1) };
47292
+ }
47293
+ resolveDescendantKeys(rootId, desc) {
47294
+ const byName = new Map;
47295
+ const walk = (id) => {
47296
+ for (const c of this.store.children(id)) {
47297
+ const n = this.store.get(c).props;
47298
+ if (n.name)
47299
+ byName.set(n.name, [...byName.get(n.name) ?? [], c]);
47300
+ walk(c);
47301
+ }
47302
+ };
47303
+ walk(rootId);
47304
+ const out = {};
47305
+ for (const [k, v] of Object.entries(desc)) {
47306
+ let key = k;
47307
+ if (!k.includes("/") && !this.store.get(k)) {
47308
+ const hits = byName.get(k);
47309
+ if (hits?.length === 1)
47310
+ key = hits[0];
47311
+ }
47312
+ out[key] = v;
47313
+ }
47314
+ return out;
47315
+ }
47316
+ Insert(parent, nodeData) {
47317
+ const p = this.parentId(parent);
47318
+ let node2 = this.withIds(migrateLegacyProps(nodeData));
47319
+ if (node2.type === "ref" && node2.descendants && typeof node2.descendants === "object")
47320
+ node2 = { ...node2, descendants: this.resolveDescendantKeys(node2.ref, node2.descendants) };
47321
+ this.warnProps(node2, node2.type, node2.id);
47322
+ this.commit({ op: "insert", parent: p, ord: between(this.lastOrd(p), null), node: node2 });
47323
+ return node2.id;
47324
+ }
47325
+ Copy(path, parent, copyNodeData = {}) {
47326
+ if (path.includes("/"))
47327
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "path", reason: "copying an instance child is not supported in this spike" });
47328
+ const src = this.store.get(path);
47329
+ if (!src)
47330
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47331
+ const p = this.parentId(parent);
47332
+ const { descendants, ...over } = migrateLegacyProps(copyNodeData);
47333
+ let node2;
47334
+ if (src.props.reusable) {
47335
+ node2 = { type: "ref", ref: src.id, ...over };
47336
+ if (descendants)
47337
+ node2.descendants = this.resolveDescendantKeys(src.id, descendants);
47338
+ node2 = this.withIds(node2);
47339
+ } else {
47340
+ const tree = subtree(this.store, src.id);
47341
+ const descMap = descendants ? this.resolveDescendantKeys(src.id, descendants) : {};
47342
+ const apply = (n) => {
47343
+ const d = descMap[n.id];
47344
+ let out = d && typeof d.type === "string" ? { ...d } : { ...n, ...d ?? {} };
47345
+ if (Array.isArray(n.children) && !(d && typeof d.type === "string"))
47346
+ out = { ...out, children: n.children.map(apply) };
47347
+ return out;
47348
+ };
47349
+ node2 = this.withIds({ ...apply(tree), ...over });
47350
+ }
47351
+ this.warnProps(node2, node2.type, node2.id);
47352
+ this.commit({ op: "insert", parent: p, ord: between(this.lastOrd(p), null), node: node2 });
47353
+ return node2.id;
47354
+ }
47355
+ Update(path, updateData) {
47356
+ updateData = migrateLegacyProps(updateData);
47357
+ const inst = this.splitInstancePath(path);
47358
+ if (inst) {
47359
+ const owner = this.store.get(inst.owner);
47360
+ if (!owner || owner.props.type !== "ref")
47361
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47362
+ const desc = { ...owner.props.descendants ?? {} };
47363
+ this.warnProps(updateData, this.expandedAt(path, {})?.node.type ?? "ref", path);
47364
+ desc[inst.rest] = { ...desc[inst.rest] ?? {}, ...updateData };
47365
+ this.commit({ op: "update", id: owner.id, patch: { descendants: desc } });
47366
+ return;
47367
+ }
47368
+ const row = this.store.get(path);
47369
+ if (!row)
47370
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47371
+ for (const f of ["id", "type", "ref"])
47372
+ if (f in updateData && updateData[f] !== row.props[f])
47373
+ throw new OpRejectedError({ code: "IMMUTABLE_FIELD", field: f });
47374
+ if ("children" in updateData)
47375
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "children", reason: "use Replace to change children" });
47376
+ const { id: _i, type: _t, ref: _r, ...patch } = updateData;
47377
+ if (patch.descendants && row.props.type === "ref")
47378
+ patch.descendants = { ...row.props.descendants ?? {}, ...this.resolveDescendantKeys(row.props.ref, patch.descendants) };
47379
+ this.warnProps({ ...patch, ...row.props.type === "ref" ? { ref: row.props.ref } : {} }, row.props.type, row.id);
47380
+ this.commit({ op: "update", id: row.id, patch });
47381
+ }
47382
+ Replace(path, nodeData) {
47383
+ const inst = this.splitInstancePath(path);
47384
+ if (inst) {
47385
+ const owner = this.store.get(inst.owner);
47386
+ if (!owner || owner.props.type !== "ref")
47387
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47388
+ const node3 = this.withIds(migrateLegacyProps(nodeData));
47389
+ this.warnProps(node3, node3.type, node3.id);
47390
+ const desc = { ...owner.props.descendants ?? {}, [inst.rest]: node3 };
47391
+ this.commit({ op: "update", id: owner.id, patch: { descendants: desc } });
47392
+ return node3.id;
47393
+ }
47394
+ const row = this.store.get(path);
47395
+ if (!row)
47396
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47397
+ const node2 = this.withIds(migrateLegacyProps(nodeData));
47398
+ this.warnProps(node2, node2.type, node2.id);
47399
+ this.commit({ op: "delete", id: row.id });
47400
+ this.commit({ op: "insert", parent: row.parent, ord: row.ord, node: node2 });
47401
+ return node2.id;
47402
+ }
47403
+ Move(path, parent, index) {
47404
+ if (path.includes("/"))
47405
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "path", reason: "instance children cannot be moved; edit the component" });
47406
+ const row = this.store.get(path);
47407
+ if (!row)
47408
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47409
+ const p = parent === undefined ? row.parent : this.parentId(parent);
47410
+ for (let cur = p;cur !== null; cur = this.store.get(cur)?.parent ?? null)
47411
+ if (cur === row.id)
47412
+ throw new OpRejectedError({ code: "CYCLE", id: row.id, parent: p });
47413
+ const siblings = this.store.children(p).filter((s) => s !== row.id);
47414
+ const i = index === undefined ? siblings.length : Math.max(0, Math.min(index, siblings.length));
47415
+ const before = i > 0 ? this.store.get(siblings[i - 1]).ord : null;
47416
+ const after = i < siblings.length ? this.store.get(siblings[i]).ord : null;
47417
+ this.commit({ op: "move", id: row.id, parent: p, ord: between(before, after) });
47418
+ }
47419
+ Delete(path) {
47420
+ if (path === "document")
47421
+ throw new OpRejectedError({ code: "ROOT_PROTECTED" });
47422
+ if (path.includes("/"))
47423
+ throw new OpRejectedError({ code: "INSTANCE_CHILD_DELETE", path });
47424
+ if (!this.store.get(path))
47425
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47426
+ this.commit({ op: "delete", id: path });
47427
+ }
47428
+ SetVariables(variables, replace = false) {
47429
+ const themes = {};
47430
+ for (const [name, def] of Object.entries(variables ?? {})) {
47431
+ if (name.startsWith("$"))
47432
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: name, reason: "variable names must not start with $" });
47433
+ if (!def || typeof def !== "object" || !("type" in def) || !("value" in def))
47434
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: name, reason: "expected { type, value }" });
47435
+ if (Array.isArray(def.value))
47436
+ for (const e of def.value)
47437
+ for (const [axis, v] of Object.entries(e.theme ?? {}))
47438
+ themes[axis] = [...new Set([...themes[axis] ?? [], v])];
47439
+ }
47440
+ this.commit({ op: "setVariables", variables, themes, replace });
47441
+ }
47442
+ GetVariables() {
47443
+ return { variables: this.store.variables(), themes: this.store.themes() };
47444
+ }
47445
+ Get(a, b, c) {
47446
+ let path = null;
47447
+ let visit2 = null;
47448
+ let opts = {};
47449
+ for (const arg of [a, b, c]) {
47450
+ if (typeof arg === "string")
47451
+ path = arg;
47452
+ else if (typeof arg === "function")
47453
+ visit2 = arg;
47454
+ else if (arg && typeof arg === "object")
47455
+ opts = arg;
47456
+ }
47457
+ if (!path && !visit2)
47458
+ throw new Error("Reading the whole document without a visitor would return everything! Pass a visitor or target a specific node.");
47459
+ if (!visit2)
47460
+ return this.readNode(path, opts);
47461
+ const out = [];
47462
+ const roots = path && path !== "document" ? [path] : this.store.children(null);
47463
+ for (const r of roots)
47464
+ this.visitFrom(r, visit2, opts, out);
47465
+ return out;
47466
+ }
47467
+ readNode(path, opts) {
47468
+ if (opts.resolveInstances || opts.resolveVariables || path.includes("/")) {
47469
+ const e = this.expandedAt(path, opts);
47470
+ if (!e)
47471
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47472
+ return toPen(e.node, opts.depth ?? Infinity, !!opts.resolveVariables, opts.resolveInstances !== false || path.includes("/"));
47473
+ }
47474
+ if (!this.store.get(path))
47475
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47476
+ return subtree(this.store, path, opts.depth ?? Infinity);
47477
+ }
47478
+ expandedCache = new Map;
47479
+ mutations = 0;
47480
+ expandedAt(path, _opts) {
47481
+ const first = path.split("/")[0];
47482
+ const row = this.store.get(first);
47483
+ if (!row)
47484
+ return null;
47485
+ let hit = this.expandedCache.get(row.top);
47486
+ if (!hit || hit.rev !== this.mutations) {
47487
+ const tree = expandNode(this.store, row.top, defaultTheme(this.store.themes()));
47488
+ if (!tree)
47489
+ return null;
47490
+ const index = new Map;
47491
+ const walk = (n) => {
47492
+ index.set(n.path, n);
47493
+ n.children.forEach(walk);
47494
+ };
47495
+ walk(tree);
47496
+ hit = { rev: this.mutations, index };
47497
+ this.expandedCache.set(row.top, hit);
47498
+ if (this.expandedCache.size > 8)
47499
+ this.expandedCache.delete(this.expandedCache.keys().next().value);
47500
+ }
47501
+ const node2 = hit.index.get(path);
47502
+ return node2 ? { node: node2, top: row.top } : null;
47503
+ }
47504
+ layoutOf(top) {
47505
+ let l = this.layoutCache.get(top);
47506
+ if (!l) {
47507
+ l = this.bounds.layout(top);
47508
+ this.layoutCache.set(top, l);
47509
+ if (this.layoutCache.size > 8)
47510
+ this.layoutCache.delete(this.layoutCache.keys().next().value);
47511
+ }
47512
+ return l;
47513
+ }
47514
+ visitFrom(startPath, visit2, opts, out) {
47515
+ const at = this.expandedAt(startPath, opts);
47516
+ if (!at)
47517
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: startPath });
47518
+ const self = this;
47519
+ const withInstances = !!opts.resolveInstances;
47520
+ const walk = (e, parentCtx, depth, index) => {
47521
+ if (opts.depth !== undefined && depth > opts.depth)
47522
+ return;
47523
+ let skip = false;
47524
+ const node2 = toPen(e, 0, !!opts.resolveVariables, withInstances, true);
47525
+ const ctx = {
47526
+ node: node2,
47527
+ parentCtx,
47528
+ depth,
47529
+ index,
47530
+ get bounds() {
47531
+ const b = self.layoutOf(at.top).boxes.get(e.path);
47532
+ return b ? { x: b.x, y: b.y, width: b.width, height: b.height } : { x: 0, y: 0, width: 0, height: 0 };
47533
+ },
47534
+ get problems() {
47535
+ const p = self.layoutOf(at.top).problems.find((q) => q.path === e.path && (q.code === "PARTIALLY_CLIPPED" || q.code === "FULLY_CLIPPED"));
47536
+ return p ? p.code === "FULLY_CLIPPED" ? "fully clipped" : "partially clipped" : undefined;
47537
+ },
47538
+ skipChildren() {
47539
+ skip = true;
47540
+ }
47541
+ };
47542
+ const r = visit2(node2, ctx);
47543
+ if (r !== undefined)
47544
+ out.push(r);
47545
+ if (skip)
47546
+ return;
47547
+ if (e.role === "instance" && !withInstances)
47548
+ return;
47549
+ e.children.forEach((c, i) => walk(c, ctx, depth + 1, i));
47550
+ };
47551
+ walk(at.node, undefined, 0, 0);
47552
+ }
47553
+ level(root, parent, opts) {
47554
+ const withInstances = !!opts.resolveInstances;
47555
+ const conv = (e) => ({
47556
+ node: toPen(e, 0, !!opts.resolveVariables, withInstances, true),
47557
+ path: e.path,
47558
+ more: e.children.length > 0 && !(e.role === "instance" && !withInstances)
47559
+ });
47560
+ if (parent === null) {
47561
+ const roots = root && root !== "document" ? [root] : this.store.children(null);
47562
+ return roots.map((r) => {
47563
+ const at2 = this.expandedAt(r, opts);
47564
+ if (!at2)
47565
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: r });
47566
+ return conv(at2.node);
47567
+ });
47568
+ }
47569
+ const at = this.expandedAt(parent, opts);
47570
+ return at ? at.node.children.map(conv) : [];
47571
+ }
47572
+ tree(path, opts) {
47573
+ const withInstances = !!opts.resolveInstances;
47574
+ const roots = path && path !== "document" ? [path] : this.store.children(null);
47575
+ const out = [];
47576
+ for (const r of roots) {
47577
+ const at = this.expandedAt(r, opts);
47578
+ if (!at)
47579
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: r });
47580
+ const conv = (e, depth) => ({
47581
+ node: toPen(e, 0, !!opts.resolveVariables, withInstances, true),
47582
+ path: e.path,
47583
+ children: e.role === "instance" && !withInstances || opts.depth !== undefined && depth >= opts.depth ? [] : e.children.map((c) => conv(c, depth + 1))
47584
+ });
47585
+ out.push(conv(at.node, 0));
47586
+ }
47587
+ return out;
47588
+ }
47589
+ boundsOf(path) {
47590
+ const first = path.split("/")[0];
47591
+ const row = this.store.get(first);
47592
+ if (!row)
47593
+ return { bounds: { x: 0, y: 0, width: 0, height: 0 } };
47594
+ const l = this.layoutOf(row.top);
47595
+ const b = l.boxes.get(path);
47596
+ const p = l.problems.find((q) => q.path === path && (q.code === "PARTIALLY_CLIPPED" || q.code === "FULLY_CLIPPED"));
47597
+ return {
47598
+ bounds: b ? { x: b.x, y: b.y, width: b.width, height: b.height } : { x: 0, y: 0, width: 0, height: 0 },
47599
+ problems: p ? p.code === "FULLY_CLIPPED" ? "fully clipped" : "partially clipped" : undefined
47600
+ };
47601
+ }
47602
+ FindEmptySpace(input) {
47603
+ const dir = input.direction ?? "right";
47604
+ const pad = input.padding ?? 0;
47605
+ const rects = [];
47606
+ const tops = input.nodeId ? [input.nodeId] : this.store.children(null);
47607
+ for (const t of tops) {
47608
+ const row = this.store.get(t);
47609
+ if (!row)
47610
+ continue;
47611
+ const b = this.layoutOf(row.top).boxes.get(t);
47612
+ if (b)
47613
+ rects.push({ x: b.wx, y: b.wy, width: b.width, height: b.height });
47614
+ }
47615
+ if (!rects.length)
47616
+ return { x: 0, y: 0 };
47617
+ const minX = Math.min(...rects.map((r) => r.x));
47618
+ const minY = Math.min(...rects.map((r) => r.y));
47619
+ const maxX = Math.max(...rects.map((r) => r.x + r.width));
47620
+ const maxY = Math.max(...rects.map((r) => r.y + r.height));
47621
+ if (dir === "right")
47622
+ return { x: maxX + pad, y: minY };
47623
+ if (dir === "left")
47624
+ return { x: minX - pad - input.width, y: minY };
47625
+ if (dir === "bottom")
47626
+ return { x: minX, y: maxY + pad };
47627
+ return { x: minX, y: minY - pad - input.height };
47628
+ }
47629
+ Print(...values) {
47630
+ const line = values.map((v) => typeof v === "string" ? v : JSON.stringify(v)).join(" ");
47631
+ this.rec.printBytes += line.length;
47632
+ if (this.rec.printBytes > LIMITS.printBytes)
47633
+ throw new Error(`SCRIPT_LIMIT: Print output over ${LIMITS.printBytes} bytes`);
47634
+ this.rec.prints.push(line);
47635
+ }
47636
+ TakeScreenshot(nodeIds) {
47637
+ for (const id of nodeIds)
47638
+ if (this.rec.screenshots.length < LIMITS.screenshots)
47639
+ this.rec.screenshots.push(id);
47640
+ }
47641
+ }
47642
+ function toPen(e, depth, _resolved, _instances, shallow = false) {
47643
+ const node2 = { ...e.props, id: e.path, type: e.type };
47644
+ if (!shallow && e.children.length) {
47645
+ if (depth <= 0)
47646
+ node2.children = "...";
47647
+ else
47648
+ node2.children = e.children.map((c) => toPen(c, depth - 1, _resolved, _instances));
47649
+ }
47650
+ return node2;
47651
+ }
47652
+ // ../../packages/canvas/document/src/pen-import.ts
47653
+ var FILE_ID = /^file-/;
47654
+ var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
47655
+ var isImage = (node2) => node2.type === "image" && typeof node2.url === "string";
47656
+ var isRef = (node2) => node2.type === "ref" && typeof node2.ref === "string";
47657
+ function visit2(value, nodeId, fn) {
47658
+ if (Array.isArray(value)) {
47659
+ for (const item of value)
47660
+ visit2(item, nodeId, fn);
47661
+ return;
47662
+ }
47663
+ const node2 = asRecord(value);
47664
+ if (!node2)
47665
+ return;
47666
+ const id = typeof node2.id === "string" ? node2.id : nodeId;
47667
+ fn(node2, id);
47668
+ for (const key of Object.keys(node2))
47669
+ visit2(node2[key], id, fn);
47670
+ }
47671
+ function indexTops(tops) {
47672
+ const owner = new Map;
47673
+ for (const top of tops) {
47674
+ visit2(top, top.id, (node2) => {
47675
+ if (typeof node2.id === "string")
47676
+ owner.set(node2.id, top.id);
47677
+ });
47678
+ }
47679
+ return owner;
47680
+ }
47681
+ var clone = (value) => JSON.parse(JSON.stringify(value));
47682
+ function penImageUrls(nodes) {
47683
+ const urls = [];
47684
+ const seen = new Set;
47685
+ for (const node2 of nodes) {
47686
+ visit2(node2, node2.id, (value) => {
47687
+ if (!isImage(value))
47688
+ return;
47689
+ const url = value.url;
47690
+ if (FILE_ID.test(url) || seen.has(url))
47691
+ return;
47692
+ seen.add(url);
47693
+ urls.push(url);
47694
+ });
47695
+ }
47696
+ return urls;
47697
+ }
47698
+ function planPenImport(doc, opts = {}) {
47699
+ const tops = Array.isArray(doc.children) ? doc.children : [];
47700
+ const warnings = [];
47701
+ const selected = new Set;
47702
+ const added = [];
47703
+ if (opts.frames === undefined) {
47704
+ for (const top of tops)
47705
+ selected.add(top.id);
47706
+ } else {
47707
+ const frames = new Set(opts.frames);
47708
+ for (const id of frames) {
47709
+ if (!tops.some((top) => top.id === id))
47710
+ warnings.push({ code: "FRAME_NOT_FOUND", id });
47711
+ else
47712
+ selected.add(id);
47713
+ }
47714
+ const owner = indexTops(tops);
47715
+ const byId = new Map(tops.map((top) => [top.id, top]));
47716
+ const dangling = new Set;
47717
+ for (let queue = [...selected];queue.length > 0; ) {
47718
+ const top = byId.get(queue.shift());
47719
+ if (!top)
47720
+ continue;
47721
+ visit2(top, top.id, (node2, nodeId) => {
47722
+ if (!isRef(node2))
47723
+ return;
47724
+ const ref = node2.ref;
47725
+ const target = owner.get(ref);
47726
+ if (target === undefined) {
47727
+ const key = `${ref}\x00${nodeId}`;
47728
+ if (dangling.has(key))
47729
+ return;
47730
+ dangling.add(key);
47731
+ warnings.push({ code: "REF_DANGLING", ref, nodeId });
47732
+ return;
47733
+ }
47734
+ if (selected.has(target))
47735
+ return;
47736
+ selected.add(target);
47737
+ queue.push(target);
47738
+ });
47739
+ }
47740
+ for (const top of tops)
47741
+ if (selected.has(top.id) && !frames.has(top.id))
47742
+ added.push(top.id);
47743
+ }
47744
+ const images = opts.images ?? {};
47745
+ const unmapped = new Map;
47746
+ const children = tops.filter((top) => selected.has(top.id)).map((top) => clone(top));
47747
+ for (const node2 of children) {
47748
+ visit2(node2, node2.id, (value, nodeId) => {
47749
+ if (!isImage(value))
47750
+ return;
47751
+ const url = value.url;
47752
+ if (FILE_ID.test(url))
47753
+ return;
47754
+ const fileId = Object.hasOwn(images, url) ? images[url] : undefined;
47755
+ if (typeof fileId === "string") {
47756
+ value.url = fileId;
47757
+ return;
47758
+ }
47759
+ const nodeIds = unmapped.get(url);
47760
+ if (nodeIds) {
47761
+ if (!nodeIds.includes(nodeId))
47762
+ nodeIds.push(nodeId);
47763
+ } else
47764
+ unmapped.set(url, [nodeId]);
47765
+ });
47766
+ }
47767
+ for (const [url, nodeIds] of unmapped)
47768
+ warnings.push({ code: "IMAGE_UNMAPPED", url, nodeIds });
47769
+ return {
47770
+ children,
47771
+ ...doc.variables ? { variables: clone(doc.variables) } : {},
47772
+ ...doc.themes ? { themes: clone(doc.themes) } : {},
47773
+ added,
47774
+ warnings
47775
+ };
47776
+ }
47777
+ // src/commands/canvas-import.ts
47778
+ var CHUNK_CHARS = 1500000;
47779
+ function countNodes(nodes) {
47780
+ let total = 0;
47781
+ const walk = (list) => {
47782
+ for (const node2 of list) {
47783
+ total++;
47784
+ if (Array.isArray(node2.children))
47785
+ walk(node2.children);
47786
+ }
47787
+ };
47788
+ walk(nodes);
47789
+ return total;
47790
+ }
47791
+ function chunkTopNodes(nodes, limit = CHUNK_CHARS) {
47792
+ const chunks = [];
47793
+ let current = [];
47794
+ let size = 0;
47795
+ for (const node2 of nodes) {
47796
+ const length = JSON.stringify(node2).length;
47797
+ if (current.length && size + length > limit) {
47798
+ chunks.push(current);
47799
+ current = [];
47800
+ size = 0;
47801
+ }
47802
+ current.push(node2);
47803
+ size += length;
47804
+ }
47805
+ if (current.length)
47806
+ chunks.push(current);
47807
+ return chunks;
47808
+ }
47809
+ var CONTENT_TYPES = {
47810
+ png: "image/png",
47811
+ jpg: "image/jpeg",
47812
+ jpeg: "image/jpeg",
47813
+ webp: "image/webp",
47814
+ gif: "image/gif",
47815
+ svg: "image/svg+xml",
47816
+ avif: "image/avif"
47817
+ };
47818
+ var contentTypeOf = (url) => CONTENT_TYPES[url.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
47819
+ var viewerUrlFor = (canvasId, env) => `https://console${env === "develop" ? "-develop" : ""}.deepraxis.com/canvases/${canvasId}`;
47820
+ function imageCandidates(url, penFile, roots) {
47821
+ const name = basename2(url);
47822
+ return [...new Set([
47823
+ join5(dirname2(penFile), url),
47824
+ ...roots.map((root) => join5(root, url)),
47825
+ ...roots.map((root) => join5(root, name))
47826
+ ])];
47827
+ }
47828
+ var isMissing = (error) => error?.code === "ENOENT";
47829
+ var reason = (error) => error instanceof Error ? error.message : String(error);
47830
+ async function findImage(url, candidates, ports) {
47831
+ for (const path of candidates) {
47832
+ try {
47833
+ return await ports.readBytes(path);
47834
+ } catch (error) {
47835
+ if (!isMissing(error))
47836
+ throw new UsageError(`cannot read ${path}, needed for image ${url}`, reason(error));
47837
+ }
47838
+ }
47839
+ return;
47840
+ }
47841
+ var warningKey = (warning) => `${warning.code}\x00${"url" in warning ? warning.url : ("id" in warning) ? warning.id : warning.ref}\x00${"nodeId" in warning ? warning.nodeId : ""}`;
47842
+ var warningLine = (warning) => {
47843
+ switch (warning.code) {
47844
+ case "IMAGE_UNMAPPED":
47845
+ return `${warning.code}: ${warning.url} (${warning.nodeIds.length} node(s))`;
47846
+ case "REF_DANGLING":
47847
+ return `${warning.code}: ${warning.ref} at ${warning.nodeId}`;
47848
+ case "FRAME_NOT_FOUND":
47849
+ return `${warning.code}: ${warning.id}`;
47850
+ default:
47851
+ return `${warning.code}: ${warning.url}`;
47852
+ }
47853
+ };
47854
+ async function canvasImport(args, ports) {
47855
+ if (args.canvas !== undefined && !args.yes) {
47856
+ throw new UsageError(`--canvas ${args.canvas} clears every node already on that canvas`, "It is a whole-canvas replacement, not a merge. Re-run with --yes, or omit --canvas to import into a new canvas.");
47857
+ }
47858
+ const file = resolve3(ports.cwd, args.file);
47859
+ let text;
47860
+ try {
47861
+ text = await ports.readFile(file);
47862
+ } catch (error) {
47863
+ throw new UsageError(`cannot read ${args.file}`, isMissing(error) ? "Check the path: `praxis canvas import <file.pen>`." : reason(error));
47864
+ }
47865
+ let doc;
47866
+ try {
47867
+ doc = JSON.parse(text);
47868
+ } catch (error) {
47869
+ throw new UsageError(`${args.file} is not valid JSON`, reason(error));
47870
+ }
47871
+ if (!Array.isArray(doc.children))
47872
+ throw new UsageError(`${args.file} has no children array`, "A .pen document is an object with a children array of top-level nodes.");
47873
+ const frames = args.frames?.filter((frame) => frame !== "");
47874
+ const roots = (args.imageRoots ?? []).map((root) => resolve3(ports.cwd, root));
47875
+ const selection = planPenImport(doc, frames ? { frames } : {});
47876
+ const urls = penImageUrls(selection.children);
47877
+ const found = new Map;
47878
+ const missing = [];
47879
+ for (const url of urls) {
47880
+ const bytes = await findImage(url, imageCandidates(url, file, roots), ports);
47881
+ if (bytes === undefined)
47882
+ missing.push(url);
47883
+ else
47884
+ found.set(url, { bytes, digest: await ports.hash(bytes) });
47885
+ }
47886
+ const images = {};
47887
+ let uploaded = 0;
47888
+ let reused = 0;
47889
+ if (!args.dryRun) {
47890
+ const byDigest = new Map;
47891
+ for (const [url, { bytes, digest }] of found) {
47892
+ const existing = byDigest.get(digest);
47893
+ if (existing !== undefined) {
47894
+ images[url] = existing;
47895
+ reused++;
47896
+ continue;
47897
+ }
47898
+ const id = await ports.upload({ filename: basename2(url), bytes, contentType: contentTypeOf(url) });
47899
+ byDigest.set(digest, id);
47900
+ images[url] = id;
47901
+ uploaded++;
47902
+ }
47903
+ }
47904
+ const plan = planPenImport(doc, { ...frames ? { frames } : {}, images });
47905
+ const chunks = chunkTopNodes(plan.children);
47906
+ const nodes = countNodes(plan.children);
47907
+ const warnings = plan.warnings.filter((warning) => !(args.dryRun && warning.code === "IMAGE_UNMAPPED" && !missing.includes(warning.url)));
47908
+ let canvasId = null;
47909
+ let revision = null;
47910
+ if (!args.dryRun) {
47911
+ canvasId = args.canvas ?? (await ports.rpc("canvas.canvases.create", { name: args.name ?? basename2(file).replace(/\.pen$/, "") })).id;
47912
+ for (let index = 0;index < chunks.length; index++) {
47913
+ const result2 = await ports.rpc("canvas.canvases.import", {
47914
+ canvasId,
47915
+ reset: index === 0,
47916
+ ...index === 0 && plan.variables ? { variables: plan.variables } : {},
47917
+ ...index === 0 && plan.themes ? { themes: plan.themes } : {},
47918
+ children: chunks[index]
47919
+ });
47920
+ revision = result2.revision;
47921
+ const seen = new Set(warnings.map(warningKey));
47922
+ for (const warning of result2.warnings ?? []) {
47923
+ if (seen.has(warningKey(warning)))
47924
+ continue;
47925
+ seen.add(warningKey(warning));
47926
+ warnings.push(warning);
47927
+ }
47928
+ }
47929
+ }
47930
+ const result = {
47931
+ canvas_id: canvasId,
47932
+ viewer_url: canvasId === null ? null : viewerUrlFor(canvasId, ports.env),
47933
+ revision,
47934
+ frames: plan.children.map((node2) => node2.id),
47935
+ added: plan.added,
47936
+ nodes,
47937
+ images: { uploaded, reused, missing },
47938
+ chunks: chunks.length,
47939
+ warnings,
47940
+ dry_run: args.dryRun
47941
+ };
47942
+ ports.emit({ kind: "object", data: result });
47943
+ const name = args.name ?? basename2(file).replace(/\.pen$/, "");
47944
+ const headline = `${plan.children.length} top-level nodes (${plan.added.length} added as component dependencies), ${nodes} nodes, ${chunks.length} chunk(s)`;
47945
+ ports.human([
47946
+ args.dryRun ? `${file}: ${headline}` : `${canvasId} ${name} — ${headline}, ${uploaded} image(s) uploaded${reused ? `, ${reused} reused` : ""}`,
47947
+ ...result.viewer_url ? [result.viewer_url] : [],
47948
+ ...plan.added.length ? [`added as dependencies: ${plan.added.join(", ")}`] : [],
47949
+ `${urls.length - missing.length}/${urls.length} image(s) found locally`,
47950
+ ...missing.length ? [`not found (they will not render): ${missing.join(", ")}`] : [],
47951
+ ...warnings.map(warningLine)
47952
+ ].join(`
47953
+ `));
47954
+ return 0;
47955
+ }
47956
+
46693
47957
  // src/main.ts
46694
47958
  import { spawnSync } from "node:child_process";
46695
47959
 
@@ -46749,13 +48013,13 @@ var groups = [["id"], ["name", "title", "display_name"], ["status", "state"], ["
46749
48013
  var isExtraColumn = (key) => !groups.some((group) => group.includes(key));
46750
48014
  function columnsFor(items) {
46751
48015
  const rows = items.map(record);
46752
- const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))];
48016
+ const keys2 = [...new Set(rows.flatMap((row) => Object.keys(row)))];
46753
48017
  const chosen = groups.flatMap((group) => {
46754
- const key = group.find((k) => keys.includes(k));
48018
+ const key = group.find((k) => keys2.includes(k));
46755
48019
  return key ? [key] : [];
46756
48020
  });
46757
48021
  const standard = new Set([...groups.flat(), "object"]);
46758
- const extra = keys.filter((key) => !standard.has(key) && rows.some((row) => row[key] !== null && row[key] !== undefined) && rows.every((row) => {
48022
+ const extra = keys2.filter((key) => !standard.has(key) && rows.some((row) => row[key] !== null && row[key] !== undefined) && rows.every((row) => {
46759
48023
  const v = row[key];
46760
48024
  return v === null || v === undefined || typeof v === "boolean" || typeof v === "number" || typeof v === "string" && [...v].length <= 24;
46761
48025
  })).slice(0, 2);
@@ -46810,9 +48074,9 @@ class ModelStream {
46810
48074
  const data = streamData(event), message = record(data.message), response = record(data.response);
46811
48075
  this.chunks.push(streamText(event));
46812
48076
  const choices = Array.isArray(data.choices) ? data.choices : [];
46813
- const reason = choices.map((c) => record(c).finish_reason).find((r) => typeof r === "string" && r) ?? record(data.delta).stop_reason ?? message.stop_reason ?? data.stop_reason ?? record(response.incomplete_details).reason ?? response.status;
46814
- if (typeof reason === "string" && reason)
46815
- this.finishReason = reason;
48077
+ const reason2 = choices.map((c) => record(c).finish_reason).find((r) => typeof r === "string" && r) ?? record(data.delta).stop_reason ?? message.stop_reason ?? data.stop_reason ?? record(response.incomplete_details).reason ?? response.status;
48078
+ if (typeof reason2 === "string" && reason2)
48079
+ this.finishReason = reason2;
46816
48080
  else if (["response.completed", "response.incomplete", "response.failed"].includes(String(data.type)))
46817
48081
  this.finishReason = String(data.type).slice("response.".length);
46818
48082
  for (const usage of [message.usage, data.usage, response.usage]) {
@@ -47323,7 +48587,7 @@ function startProgress(ctx, write = (text) => writeOutput({ stderr: text })) {
47323
48587
  }
47324
48588
 
47325
48589
  // src/main.ts
47326
- var version = "0.2.2-dev.b4438f4";
48590
+ var version = "0.2.2-dev.bac4728";
47327
48591
  var commands = commandTree(operations);
47328
48592
  var manual = [...workflows.map((w) => w.words), [API_WORD]];
47329
48593
  function route(argv) {
@@ -47360,19 +48624,21 @@ var defaults = {
47360
48624
  stderrIsTTY: Boolean(process.stderr.isTTY),
47361
48625
  columns: process.stdout.columns ?? 100,
47362
48626
  readFile: (path) => readFile3(path, "utf8"),
48627
+ readBytes: (path) => readFile3(path),
48628
+ sha256: async (bytes) => createHash3("sha256").update(bytes).digest("hex"),
47363
48629
  async readStdin() {
47364
48630
  const chunks = [];
47365
48631
  for await (const chunk of process.stdin)
47366
48632
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
47367
48633
  return Buffer.concat(chunks).toString("utf8");
47368
48634
  },
47369
- ask: () => new Promise((resolve3) => {
48635
+ ask: () => new Promise((resolve4) => {
47370
48636
  const input = createInterface({ input: process.stdin, terminal: false });
47371
48637
  input.once("line", (line) => {
47372
- resolve3(/^(y|yes)$/i.test(line.trim()));
48638
+ resolve4(/^(y|yes)$/i.test(line.trim()));
47373
48639
  input.close();
47374
48640
  });
47375
- input.once("close", () => resolve3(false));
48641
+ input.once("close", () => resolve4(false));
47376
48642
  }),
47377
48643
  async openBrowser(url) {
47378
48644
  try {
@@ -47380,27 +48646,27 @@ var defaults = {
47380
48646
  if (!["https:", "http:"].includes(parsed.protocol))
47381
48647
  return;
47382
48648
  const cmd = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler", url] : ["xdg-open", url];
47383
- await new Promise((resolve3, reject) => {
48649
+ await new Promise((resolve4, reject) => {
47384
48650
  const child = spawn2(cmd[0], cmd.slice(1), { stdio: "ignore" });
47385
48651
  child.once("error", reject);
47386
- child.once("close", () => resolve3());
48652
+ child.once("close", () => resolve4());
47387
48653
  });
47388
48654
  } catch {}
47389
48655
  },
47390
- wait: (ms) => new Promise((resolve3) => setTimeout(resolve3, ms)),
48656
+ wait: (ms) => new Promise((resolve4) => setTimeout(resolve4, ms)),
47391
48657
  render,
47392
- spawn: (cmd, args, options) => new Promise((resolve3, reject) => {
48658
+ spawn: (cmd, args, options) => new Promise((resolve4, reject) => {
47393
48659
  const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
47394
48660
  child.once("error", reject);
47395
- child.once("close", (code) => resolve3(code ?? 1));
48661
+ child.once("close", (code) => resolve4(code ?? 1));
47396
48662
  }),
47397
- spawnCapture: (cmd, args, options) => new Promise((resolve3, reject) => {
48663
+ spawnCapture: (cmd, args, options) => new Promise((resolve4, reject) => {
47398
48664
  const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
47399
48665
  const chunks = [];
47400
48666
  child.stdout.on("data", (c) => chunks.push(c));
47401
48667
  child.stderr.on("data", (c) => chunks.push(c));
47402
48668
  child.once("error", reject);
47403
- child.once("close", (code) => resolve3({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
48669
+ child.once("close", (code) => resolve4({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
47404
48670
  }),
47405
48671
  has: (bin) => spawnSync(process.platform === "win32" ? "where" : "which", [bin], { stdio: "ignore" }).status === 0,
47406
48672
  cwd: process.cwd()
@@ -47419,6 +48685,13 @@ var appOptions = {
47419
48685
  { name: "no-wait", type: "boolean", description: "Return as soon as the run exists instead of waiting for a verdict." },
47420
48686
  { name: "repeat", type: "string", description: "How many times each selected case runs (default: 1)." },
47421
48687
  { name: "select", type: "string", repeated: true, description: "Narrow the selection; repeatable. tag:<tag> (a bare word reads as a tag), package:<path>, suite:<path> or file:<path>." }
48688
+ ],
48689
+ "canvas import": [
48690
+ { name: "name", type: "string", description: "Name for the new canvas (default: the file name without .pen)." },
48691
+ { name: "canvas", type: "string", description: "Import into this existing canvas instead of a new one. Whole-canvas replacement: it clears what is already there and requires --yes." },
48692
+ { name: "frames", type: "string", description: "Comma-separated top-level node ids to import. The components they reference come along automatically." },
48693
+ { name: "image-root", type: "string", repeated: true, description: "Directory to resolve image paths against; repeatable. Tried after the .pen file's own directory, then by file name." },
48694
+ { name: "dry-run", type: "boolean", description: "Read the local file and print the plan. No login and no request." }
47422
48695
  ]
47423
48696
  };
47424
48697
  async function main(argv, injected = {}) {
@@ -47516,7 +48789,7 @@ Examples:
47516
48789
  return 0;
47517
48790
  }
47518
48791
  const path = ports.tokenPath ?? tokenPath(config.env);
47519
- const store = createTokenStore(config.env, path, selectSecretStore(ports.env, ports.secretStore));
48792
+ const store2 = createTokenStore(config.env, path, selectSecretStore(ports.env, ports.secretStore));
47520
48793
  const wireFetch = async (input, init) => {
47521
48794
  const request = new Request(input, init);
47522
48795
  request.headers.set("User-Agent", `praxis-cli/${version}${ctx.mode === "agent" ? ` agent/${ctx.agentName ?? "unknown"}` : ""}`);
@@ -47526,7 +48799,7 @@ Examples:
47526
48799
  }
47527
48800
  return ports.fetch(request);
47528
48801
  };
47529
- const auth = credentials(config, ports.env, { fetch: wireFetch, now: ports.now, path, store, remember: (s) => {
48802
+ const auth = credentials(config, ports.env, { fetch: wireFetch, now: ports.now, path, store: store2, remember: (s) => {
47530
48803
  secrets.push(s);
47531
48804
  } });
47532
48805
  ctx.credentialSource = auth.source;
@@ -47602,7 +48875,7 @@ Examples:
47602
48875
  return 0;
47603
48876
  }
47604
48877
  const name = selected.words.join(" ");
47605
- const arity = name === "api" ? 2 : name === "org switch" || name === "app create" ? 1 : 0;
48878
+ const arity = name === "api" ? 2 : name === "org switch" || name === "app create" || name === "canvas import" ? 1 : 0;
47606
48879
  if (parsed.positional.length !== arity)
47607
48880
  throw new UsageError(`${name} expects ${arity} positional argument(s)`);
47608
48881
  if (name === "devops deploy plan") {
@@ -47637,10 +48910,10 @@ Examples:
47637
48910
  if (flags["no-input"] || quiet)
47638
48911
  throw new UsageError("login requires displaying a device code", "Remove --no-input / --quiet or set PRAXIS_API_KEY for scripts.");
47639
48912
  ctx.credentialSource = "login";
47640
- await login(config, path, { ...ports, source: auth.source, json: ctx.mode === "json", store, fetch: wireFetch, emit, remember: (s) => secrets.push(s) });
48913
+ await login(config, path, { ...ports, source: auth.source, json: ctx.mode === "json", store: store2, fetch: wireFetch, emit, remember: (s) => secrets.push(s) });
47641
48914
  break;
47642
48915
  case "logout":
47643
- emit({ kind: "message", text: await store.delete() ? "Logged out." : "Not logged in." });
48916
+ emit({ kind: "message", text: await store2.delete() ? "Logged out." : "Not logged in." });
47644
48917
  break;
47645
48918
  case "whoami":
47646
48919
  emit({ kind: "object", data: await whoami(auth, config.env, org) });
@@ -47699,6 +48972,67 @@ Examples:
47699
48972
  cwd: ports.cwd
47700
48973
  });
47701
48974
  }
48975
+ case "canvas import": {
48976
+ const authorize = async () => {
48977
+ const credential = await auth.get(org);
48978
+ return { Authorization: `Bearer ${credential.token}`, ...credential.source === "api-key" ? { "X-API-Key": credential.token } : {} };
48979
+ };
48980
+ const rpc = async (method, params) => {
48981
+ const response = await wireFetch(`${config.apiUrl}/canvas/v1/rpc`, {
48982
+ method: "POST",
48983
+ headers: { ...await authorize(), "content-type": "application/json" },
48984
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
48985
+ signal: AbortSignal.timeout(120000),
48986
+ redirect: "error"
48987
+ });
48988
+ const reply = await response.json();
48989
+ if (!response.ok || reply.error)
48990
+ throw new PraxisError({ code: "CANVAS_RPC_ERROR", message: `${method}: ${reply.error?.message ?? `HTTP ${response.status}`}` });
48991
+ if (!Object.hasOwn(reply, "result"))
48992
+ throw new PraxisError({ code: "INVALID_RESPONSE", message: `${method} answered no result` });
48993
+ return reply.result;
48994
+ };
48995
+ const upload = async ({ filename, bytes, contentType }) => {
48996
+ const signed = await wireFetch(`${config.apiUrl}/file/v1/uploads/signed`, {
48997
+ method: "POST",
48998
+ headers: { ...await authorize(), "content-type": "application/json" },
48999
+ body: JSON.stringify({ filename, bytes: bytes.length, content_type: contentType, purpose: "user_data" }),
49000
+ signal: AbortSignal.timeout(60000),
49001
+ redirect: "error"
49002
+ });
49003
+ const session = await signed.json();
49004
+ if (!signed.ok || typeof session.url !== "string")
49005
+ throw new PraxisError({ code: "UPLOAD_REJECTED", message: `signed upload for ${filename} failed (HTTP ${signed.status})` });
49006
+ const sent = await wireFetch(session.url, { method: "PUT", headers: { "content-type": contentType, "content-length": String(bytes.length) }, body: bytes, signal: AbortSignal.timeout(120000), redirect: "error" });
49007
+ const file = await sent.json();
49008
+ if (!sent.ok || typeof file.id !== "string")
49009
+ throw new PraxisError({ code: "UPLOAD_FAILED", message: `uploading ${filename} failed (HTTP ${sent.status})` });
49010
+ return file.id;
49011
+ };
49012
+ return await canvasImport({
49013
+ file: parsed.positional[0],
49014
+ name: parsed.flags.name?.[0],
49015
+ canvas: parsed.flags.canvas?.[0],
49016
+ frames: typeof parsed.flags.frames?.[0] === "string" ? parsed.flags.frames[0].split(",").map((frame) => frame.trim()).filter(Boolean) : undefined,
49017
+ imageRoots: parsed.flags["image-root"],
49018
+ dryRun: Boolean(parsed.flags["dry-run"]?.[0]),
49019
+ yes: Boolean(flags.yes)
49020
+ }, {
49021
+ readFile: ports.readFile,
49022
+ readBytes: ports.readBytes,
49023
+ hash: ports.sha256,
49024
+ env: config.env,
49025
+ mode: ctx.mode,
49026
+ emit,
49027
+ cwd: ports.cwd,
49028
+ rpc,
49029
+ upload,
49030
+ human: (text) => {
49031
+ if (ctx.mode === "human")
49032
+ emit({ kind: "message", channel: "stdout", text });
49033
+ }
49034
+ });
49035
+ }
47702
49036
  case "api": {
47703
49037
  const method = parsed.positional[0];
47704
49038
  if (!HTTP_METHOD.test(method))