@deepraxis/cli 0.2.2-dev.1b23ee0 → 0.2.2-dev.214765b

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 +1393 -34
  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
 
@@ -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);
@@ -46200,18 +46224,23 @@ function packageManifestOf(text) {
46200
46224
  return null;
46201
46225
  const name = parsed.name;
46202
46226
  const dependencies = new Set;
46203
- for (const field of ["dependencies", "devDependencies"]) {
46227
+ const devOnly = new Set;
46228
+ for (const field of ["dependencies", "peerDependencies", "optionalDependencies", "devDependencies"]) {
46204
46229
  const block = parsed[field];
46205
46230
  if (block === null || typeof block !== "object" || Array.isArray(block))
46206
46231
  continue;
46207
46232
  for (const [dependency, version] of Object.entries(block)) {
46208
- if (typeof version === "string" && version.startsWith("workspace:"))
46209
- dependencies.add(dependency);
46233
+ if (typeof version !== "string" || !version.startsWith("workspace:") || dependencies.has(dependency))
46234
+ continue;
46235
+ dependencies.add(dependency);
46236
+ if (field === "devDependencies")
46237
+ devOnly.add(dependency);
46210
46238
  }
46211
46239
  }
46212
46240
  return {
46213
46241
  ...typeof name === "string" && name !== "" ? { name } : {},
46214
- workspaceDependencies: [...dependencies].sort()
46242
+ workspaceDependencies: [...dependencies].sort(),
46243
+ devOnlyWorkspaceDependencies: [...devOnly].sort()
46215
46244
  };
46216
46245
  }
46217
46246
  function lifecycleOf(text) {
@@ -46405,7 +46434,8 @@ async function readWorkspacesOnce(facts, options) {
46405
46434
  config,
46406
46435
  ...workerNameOf(config) === undefined ? {} : { workerName: workerNameOf(config) },
46407
46436
  lifecycle: lifecycleOf(manifestText),
46408
- workspaceDependencies: pkg?.workspaceDependencies ?? []
46437
+ workspaceDependencies: pkg?.workspaceDependencies ?? [],
46438
+ devOnlyWorkspaceDependencies: pkg?.devOnlyWorkspaceDependencies ?? []
46409
46439
  };
46410
46440
  });
46411
46441
  }
@@ -46447,7 +46477,9 @@ function workspaceCloudflareProvider(options = {}) {
46447
46477
  name: workspace.packageName ?? (workspace.dir === "." ? "app" : workspace.dir.split("/").at(-1)),
46448
46478
  destination: "cloudflare",
46449
46479
  ...workspace.workerName === undefined ? {} : { workerName: workspace.workerName },
46450
- ...environments === undefined ? {} : { environments }
46480
+ ...environments === undefined ? {} : { environments },
46481
+ production: productionBlockOf(workspace.config) !== undefined,
46482
+ onTrain: lifecycle?.train !== false
46451
46483
  });
46452
46484
  }
46453
46485
  return { targets: [...partial.targets, ...targets] };
@@ -46496,19 +46528,50 @@ function closePlan(drafts, workspaces) {
46496
46528
  const configOf = new Map(workspaces.map((workspace) => [workspace.dir, workspace.config]));
46497
46529
  const edges = wranglerEdges(drafts.map((draft) => ({ id: draft.path, config: configOf.get(draft.path) ?? null })));
46498
46530
  const byName = directoriesOfPackageNames(workspaces);
46499
- const dependenciesOf = (dir) => workspaces.find((workspace) => workspace.dir === dir)?.workspaceDependencies ?? [];
46531
+ const dependenciesOf = (dir) => {
46532
+ const workspace = workspaces.find((entry) => entry.dir === dir);
46533
+ if (workspace === undefined)
46534
+ return [];
46535
+ const devOnly = new Set(workspace.devOnlyWorkspaceDependencies ?? []);
46536
+ return workspace.workspaceDependencies.filter((name) => {
46537
+ if (!devOnly.has(name))
46538
+ return true;
46539
+ const path = byName.get(name);
46540
+ return path === undefined || !isDeployToolDependency(name, path);
46541
+ });
46542
+ };
46500
46543
  return drafts.map((draft) => ({
46501
46544
  path: draft.path,
46502
46545
  name: draft.name,
46503
46546
  destination: draft.destination,
46504
46547
  dependsOn: edges.get(draft.path) ?? [],
46505
46548
  ...draft.environments === undefined ? {} : { environments: draft.environments },
46549
+ production: draft.production === true,
46550
+ onTrain: draft.onTrain !== false,
46506
46551
  workspaceDeps: workspaceClosureOf(draft.path, byName, dependenciesOf)
46507
46552
  })).sort((a, b) => a.path.localeCompare(b.path));
46508
46553
  }
46554
+ function isDeployToolDependency(name, path) {
46555
+ const directory = path.replace(/^(\.\/)+/, "").replace(/^\/+/, "").replace(/\/+$/, "");
46556
+ if (directory === "packages/mise" || directory.startsWith("packages/mise/"))
46557
+ return true;
46558
+ if (directory === "packages/testing" || directory.startsWith("packages/testing/"))
46559
+ return true;
46560
+ return name.startsWith("@mise/");
46561
+ }
46509
46562
  function targetsFor(plan, environment2) {
46510
46563
  return plan.targets.filter((target) => target.environments === undefined || target.environments.includes(environment2));
46511
46564
  }
46565
+ var TARGET_EXTERNAL_INPUTS = {
46566
+ "apps/docs": [
46567
+ "apps/api/openapi/openapi.yaml",
46568
+ "packages/praxis/rpc-kit/src/errors.ts",
46569
+ "services/agent/src/domain/error-codes.ts",
46570
+ ...["application", "database", "knowledge"].map((s) => `services/${s}/src/api/error-exit.ts`),
46571
+ ...["router", "vault", "browser", "search"].map((s) => `services/${s}/src/api/rpc-contract.ts`),
46572
+ ...["media", "automation", "sandbox", "file", "billing", "config", "eventbus", "lakehouse", "identity", "notification", "ops", "registry"].map((s) => `services/${s}/src/api/contract.ts`)
46573
+ ]
46574
+ };
46512
46575
  function diffTargets(plan, changedPaths) {
46513
46576
  const changed = new Set(changedPaths);
46514
46577
  const touches = (dir) => {
@@ -46520,7 +46583,8 @@ function diffTargets(plan, changedPaths) {
46520
46583
  return true;
46521
46584
  return false;
46522
46585
  };
46523
- return plan.targets.filter((target) => touches(target.path) || target.workspaceDeps.some(touches)).map((target) => target.path);
46586
+ const readsChangedInput = (dir) => (TARGET_EXTERNAL_INPUTS[dir] ?? []).some((file) => changed.has(file));
46587
+ return plan.targets.filter((target) => touches(target.path) || target.workspaceDeps.some(touches) || readsChangedInput(target.path) || target.workspaceDeps.some(readsChangedInput)).map((target) => target.path);
46524
46588
  }
46525
46589
  function layersOf(plan) {
46526
46590
  const paths = plan.targets.map((target) => target.path);
@@ -46690,6 +46754,1231 @@ async function devopsDeployPlan(args, ports) {
46690
46754
  ports.human(renderDeployPlan(view));
46691
46755
  }
46692
46756
 
46757
+ // src/commands/canvas-import.ts
46758
+ import { basename as basename2, dirname as dirname2, join as join5, resolve as resolve3 } from "node:path";
46759
+
46760
+ // ../../packages/canvas/document/src/types.ts
46761
+ class OpRejectedError extends Error {
46762
+ rejection;
46763
+ constructor(rejection) {
46764
+ super(`${rejection.code}: ${JSON.stringify(rejection)}`);
46765
+ this.rejection = rejection;
46766
+ }
46767
+ }
46768
+ var CONTAINER_TYPES = new Set(["frame", "group"]);
46769
+ // ../../packages/canvas/document/src/legacy-props.ts
46770
+ function ownIconProps(node2) {
46771
+ const out = { ...node2 };
46772
+ if ((node2.type === "icon" || node2.type === undefined) && "iconName" in node2) {
46773
+ if (!("icon" in node2))
46774
+ out.icon = node2.iconName;
46775
+ delete out.iconName;
46776
+ }
46777
+ return out;
46778
+ }
46779
+ function migrateLegacyIconProps(node2) {
46780
+ const out = ownIconProps(node2);
46781
+ if (node2.descendants && typeof node2.descendants === "object" && !Array.isArray(node2.descendants))
46782
+ out.descendants = Object.fromEntries(Object.entries(node2.descendants).map(([key, value]) => [
46783
+ key,
46784
+ value && typeof value === "object" && !Array.isArray(value) ? migrateLegacyIconProps(value) : value
46785
+ ]));
46786
+ if (Array.isArray(node2.children))
46787
+ out.children = node2.children.map((child) => migrateLegacyIconProps(child));
46788
+ return out;
46789
+ }
46790
+ function migrateLegacyProps(node2) {
46791
+ const out = ownIconProps(node2);
46792
+ const stroke = node2.stroke;
46793
+ if (stroke && typeof stroke === "object" && !Array.isArray(stroke) && "fill" in stroke) {
46794
+ const old = stroke;
46795
+ out.stroke = old.fill;
46796
+ if (!("strokeWidth" in node2) && "thickness" in old)
46797
+ out.strokeWidth = old.thickness;
46798
+ if (!("strokeAlignment" in node2) && "align" in old) {
46799
+ out.strokeAlignment = old.align === "inside" ? "inner" : old.align === "outside" ? "outer" : old.align;
46800
+ }
46801
+ }
46802
+ if (Array.isArray(node2.children))
46803
+ out.children = node2.children.map((child) => migrateLegacyProps(child));
46804
+ if (node2.descendants && typeof node2.descendants === "object" && !Array.isArray(node2.descendants))
46805
+ out.descendants = Object.fromEntries(Object.entries(node2.descendants).map(([key, value]) => [
46806
+ key,
46807
+ value && typeof value === "object" && !Array.isArray(value) ? migrateLegacyProps(value) : value
46808
+ ]));
46809
+ return out;
46810
+ }
46811
+
46812
+ // ../../packages/canvas/document/src/store.ts
46813
+ var DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
46814
+ var BASE = DIGITS.length;
46815
+ function midpoint(a, b) {
46816
+ if (b !== null) {
46817
+ let n = 0;
46818
+ while ((a[n] ?? "0") === b[n])
46819
+ n++;
46820
+ if (n > 0)
46821
+ return b.slice(0, n) + midpoint(a.slice(n), b.slice(n));
46822
+ }
46823
+ const da = a ? DIGITS.indexOf(a[0]) : 0;
46824
+ const db = b !== null ? DIGITS.indexOf(b[0]) : BASE;
46825
+ if (db - da > 1)
46826
+ return DIGITS[Math.floor((da + db) / 2)];
46827
+ if (b !== null && b.length > 1)
46828
+ return b.slice(0, 1);
46829
+ return DIGITS[da] + midpoint(a.slice(1), null);
46830
+ }
46831
+ function between(a, b) {
46832
+ return midpoint(a ?? "", b);
46833
+ }
46834
+ function spacedKeys(n) {
46835
+ let width = 1;
46836
+ while (BASE ** width < n + 2)
46837
+ width++;
46838
+ const keys = [];
46839
+ for (let i = 1;i <= n; i++) {
46840
+ let v = i;
46841
+ let s = "";
46842
+ for (let d = 0;d < width; d++) {
46843
+ s = DIGITS[v % BASE] + s;
46844
+ v = Math.floor(v / BASE);
46845
+ }
46846
+ keys.push(s + "V");
46847
+ }
46848
+ return keys;
46849
+ }
46850
+
46851
+ class MapNodeStore {
46852
+ nodes = new Map;
46853
+ kids = new Map;
46854
+ vars = {};
46855
+ themeAxes = {};
46856
+ rev = 0;
46857
+ get(id) {
46858
+ return this.nodes.get(id);
46859
+ }
46860
+ children(id) {
46861
+ return this.kids.get(id) ?? [];
46862
+ }
46863
+ variables() {
46864
+ return this.vars;
46865
+ }
46866
+ themes() {
46867
+ return this.themeAxes;
46868
+ }
46869
+ revision() {
46870
+ return this.rev;
46871
+ }
46872
+ unlink(n) {
46873
+ const list = this.kids.get(n.parent);
46874
+ if (!list)
46875
+ return;
46876
+ const i = list.indexOf(n.id);
46877
+ if (i >= 0)
46878
+ list.splice(i, 1);
46879
+ }
46880
+ link(n) {
46881
+ let list = this.kids.get(n.parent);
46882
+ if (!list)
46883
+ this.kids.set(n.parent, list = []);
46884
+ let lo = 0;
46885
+ let hi = list.length;
46886
+ if (hi && this.nodes.get(list[hi - 1]).ord < n.ord)
46887
+ lo = hi;
46888
+ while (lo < hi) {
46889
+ const mid = lo + hi >> 1;
46890
+ const o = this.nodes.get(list[mid]).ord;
46891
+ if (o < n.ord || o === n.ord && list[mid] < n.id)
46892
+ lo = mid + 1;
46893
+ else
46894
+ hi = mid;
46895
+ }
46896
+ list.splice(lo, 0, n.id);
46897
+ }
46898
+ put(node2) {
46899
+ const prev = this.nodes.get(node2.id);
46900
+ if (prev && (prev.parent !== node2.parent || prev.ord !== node2.ord))
46901
+ this.unlink(prev);
46902
+ this.nodes.set(node2.id, node2);
46903
+ if (!prev || prev.parent !== node2.parent || prev.ord !== node2.ord)
46904
+ this.link(node2);
46905
+ }
46906
+ remove(id) {
46907
+ const prev = this.nodes.get(id);
46908
+ if (!prev)
46909
+ return;
46910
+ this.unlink(prev);
46911
+ this.kids.delete(id);
46912
+ this.nodes.delete(id);
46913
+ }
46914
+ setVariables(vars, themes) {
46915
+ this.vars = vars;
46916
+ this.themeAxes = themes;
46917
+ }
46918
+ setRevision(rev) {
46919
+ this.rev = rev;
46920
+ }
46921
+ size() {
46922
+ return this.nodes.size;
46923
+ }
46924
+ reindex() {}
46925
+ }
46926
+ function ownProps(node2) {
46927
+ const { children: _c, ...rest } = node2;
46928
+ return rest;
46929
+ }
46930
+ function flatten(nodes, parent, top, rev, out = []) {
46931
+ const keys = spacedKeys(nodes.length);
46932
+ nodes.forEach((n, i) => {
46933
+ const t = top ?? n.id;
46934
+ const props = ownProps(n);
46935
+ const ord = typeof props.__ord === "string" ? props.__ord : keys[i];
46936
+ delete props.__ord;
46937
+ out.push({ id: n.id, parent, ord, top: t, props, rev });
46938
+ if (Array.isArray(n.children) && n.children.length)
46939
+ flatten(n.children, n.id, t, rev, out);
46940
+ });
46941
+ return out;
46942
+ }
46943
+ function subtree(store, id, depth = Infinity, withOrd = false) {
46944
+ const row = store.get(id);
46945
+ if (!row)
46946
+ throw new Error(`node ${id} not found`);
46947
+ const node2 = migrateLegacyIconProps(row.props);
46948
+ if (withOrd)
46949
+ node2.__ord = row.ord;
46950
+ const kids = store.children(id);
46951
+ if (kids.length) {
46952
+ if (depth <= 0)
46953
+ node2.children = "...";
46954
+ else
46955
+ node2.children = kids.map((k) => subtree(store, k, depth - 1, withOrd));
46956
+ }
46957
+ return node2;
46958
+ }
46959
+ // ../../packages/canvas/document/src/apply.ts
46960
+ function applyOp(store, op, rev) {
46961
+ switch (op.op) {
46962
+ case "insert": {
46963
+ const top = op.parent === null ? null : store.get(op.parent).top;
46964
+ const rows = flatten([op.node], op.parent, top, rev);
46965
+ rows[0] = { ...rows[0], ord: op.ord };
46966
+ for (const r of rows)
46967
+ store.put(r);
46968
+ return [rows[0].top];
46969
+ }
46970
+ case "update": {
46971
+ const row = store.get(op.id);
46972
+ const props = { ...row.props };
46973
+ for (const [k, v] of Object.entries(op.patch)) {
46974
+ if (v === undefined || v === null)
46975
+ delete props[k];
46976
+ else
46977
+ props[k] = v;
46978
+ }
46979
+ store.put({ ...row, props, rev });
46980
+ return [row.top];
46981
+ }
46982
+ case "delete": {
46983
+ const row = store.get(op.id);
46984
+ removeSubtree(store, op.id);
46985
+ return [row.top];
46986
+ }
46987
+ case "move": {
46988
+ const row = store.get(op.id);
46989
+ const oldTop = row.top;
46990
+ const newTop = op.parent === null ? op.id : store.get(op.parent).top;
46991
+ store.put({ ...row, parent: op.parent, ord: op.ord, top: newTop, rev });
46992
+ if (newTop !== oldTop)
46993
+ retop(store, op.id, newTop, rev);
46994
+ return oldTop === newTop ? [newTop] : [oldTop, newTop];
46995
+ }
46996
+ case "setVariables": {
46997
+ const vars = op.replace ? op.variables : { ...store.variables(), ...op.variables };
46998
+ const themes = { ...store.themes() };
46999
+ for (const [axis, values] of Object.entries(op.themes)) {
47000
+ const cur = themes[axis] ?? [];
47001
+ themes[axis] = [...cur, ...values.filter((v) => !cur.includes(v))];
47002
+ }
47003
+ store.setVariables(vars, themes);
47004
+ return [];
47005
+ }
47006
+ }
47007
+ }
47008
+ function removeSubtree(store, id) {
47009
+ for (const c of store.children(id))
47010
+ removeSubtree(store, c);
47011
+ store.remove(id);
47012
+ }
47013
+ function retop(store, id, top, rev) {
47014
+ for (const c of store.children(id)) {
47015
+ const row = store.get(c);
47016
+ store.put({ ...row, top, rev });
47017
+ retop(store, c, top, rev);
47018
+ }
47019
+ }
47020
+ // ../../packages/canvas/document/src/expand.ts
47021
+ function defaultTheme(themes) {
47022
+ const t = {};
47023
+ for (const [axis, values] of Object.entries(themes))
47024
+ if (values.length)
47025
+ t[axis] = values[0];
47026
+ return t;
47027
+ }
47028
+ function resolveVariable(name, vars, theme, depth = 0) {
47029
+ const def = vars[name];
47030
+ if (!def || depth > 8)
47031
+ return;
47032
+ let v;
47033
+ if (Array.isArray(def.value)) {
47034
+ let best;
47035
+ for (const e of def.value) {
47036
+ const keys = Object.keys(e.theme ?? {});
47037
+ if (keys.every((k) => theme[k] === e.theme[k]) && (!best || keys.length > best.score))
47038
+ best = { value: e.value, score: keys.length };
47039
+ }
47040
+ v = best?.value ?? def.value[0]?.value;
47041
+ } else
47042
+ v = def.value;
47043
+ if (typeof v === "string" && v.startsWith("$") && vars[v.slice(1)])
47044
+ return resolveVariable(v.slice(1), vars, theme, depth + 1);
47045
+ return v;
47046
+ }
47047
+ function resolveDeep(value, vars, theme) {
47048
+ if (typeof value === "string") {
47049
+ if (value.startsWith("$") && vars[value.slice(1)] !== undefined)
47050
+ return resolveVariable(value.slice(1), vars, theme);
47051
+ return value;
47052
+ }
47053
+ if (Array.isArray(value))
47054
+ return value.map((v) => resolveDeep(v, vars, theme));
47055
+ if (value && typeof value === "object") {
47056
+ const out = {};
47057
+ for (const [k, v] of Object.entries(value))
47058
+ out[k] = resolveDeep(v, vars, theme);
47059
+ return out;
47060
+ }
47061
+ return value;
47062
+ }
47063
+ var SKIP_RESOLVE = new Set(["id", "type", "ref", "descendants", "name", "content", "children"]);
47064
+ function resolveProps(props, vars, theme) {
47065
+ const out = {};
47066
+ for (const [k, v] of Object.entries(props))
47067
+ out[k] = SKIP_RESOLVE.has(k) ? v : resolveDeep(v, vars, theme);
47068
+ if (typeof props.content === "string" && props.content.startsWith("$") && vars[props.content.slice(1)] !== undefined)
47069
+ out.content = String(resolveVariable(props.content.slice(1), vars, theme));
47070
+ return out;
47071
+ }
47072
+ function propsOf(store, src) {
47073
+ if (src.kind === "store")
47074
+ return store.get(src.id)?.props;
47075
+ const { children: _c, ...rest } = src.node;
47076
+ return rest;
47077
+ }
47078
+ function childrenOf(store, src) {
47079
+ if (src.kind === "store")
47080
+ return store.children(src.id).map((id) => ({ kind: "store", id }));
47081
+ return (src.node.children ?? []).map((node2) => ({ kind: "inline", node: node2 }));
47082
+ }
47083
+ function expandNode(store, id, parentTheme) {
47084
+ return expandSrc({ store, vars: store.variables(), stack: [] }, { kind: "store", id }, parentTheme, null, {});
47085
+ }
47086
+ function expandSrc(ctx, src, parentTheme, pathPrefix, overrides) {
47087
+ let props = propsOf(ctx.store, src);
47088
+ if (!props)
47089
+ return null;
47090
+ const ownId = props.id;
47091
+ const path = pathPrefix ? `${pathPrefix}/${ownId}` : ownId;
47092
+ const ov = pathPrefix ? overrides[ownId] : undefined;
47093
+ if (ov && typeof ov.type === "string") {
47094
+ const repl = ov;
47095
+ const replId = typeof repl.id === "string" ? repl.id : ownId;
47096
+ const e = expandSrc(ctx, { kind: "inline", node: { ...repl, id: replId } }, parentTheme, null, {});
47097
+ return e ? { ...e, role: "instance-child" } : null;
47098
+ }
47099
+ if (ov)
47100
+ props = { ...props, ...ov };
47101
+ const theme = props.theme && typeof props.theme === "object" ? { ...parentTheme, ...props.theme } : parentTheme;
47102
+ if (props.type === "ref")
47103
+ return expandRef(ctx, props, path, theme, pathPrefix ? childOverrides(overrides, ownId) : {});
47104
+ const resolved = resolveProps(props, ctx.vars, theme);
47105
+ const children = [];
47106
+ for (const c of childrenOf(ctx.store, src)) {
47107
+ const e = expandSrc(ctx, c, theme, pathPrefix, overrides);
47108
+ if (e)
47109
+ children.push(e);
47110
+ }
47111
+ return {
47112
+ path,
47113
+ type: props.type,
47114
+ props: resolved,
47115
+ children,
47116
+ theme,
47117
+ role: pathPrefix ? "instance-child" : props.reusable ? "component" : "plain"
47118
+ };
47119
+ }
47120
+ function childOverrides(overrides, id) {
47121
+ const out = {};
47122
+ const prefix = id + "/";
47123
+ for (const [k, v] of Object.entries(overrides))
47124
+ if (k.startsWith(prefix))
47125
+ out[k.slice(prefix.length)] = v;
47126
+ return out;
47127
+ }
47128
+ function expandRef(ctx, ref, path, theme, inherited) {
47129
+ const target = ref.ref;
47130
+ const comp = ctx.store.get(target);
47131
+ if (!comp || ctx.stack.includes(target))
47132
+ return null;
47133
+ const descendants = { ...ref.descendants ?? {} };
47134
+ for (const [id, override] of Object.entries(inherited)) {
47135
+ descendants[id] = typeof override.type === "string" ? override : { ...descendants[id], ...override };
47136
+ }
47137
+ const { id: _i, type: _t, ref: _r, descendants: _d, reusable: _re, ...refOwn } = ref;
47138
+ const root = { ...comp.props, ...refOwn, id: ref.id };
47139
+ delete root.reusable;
47140
+ ctx.stack.push(target);
47141
+ const rootTheme = root.theme && typeof root.theme === "object" ? { ...theme, ...root.theme } : theme;
47142
+ const children = [];
47143
+ for (const c of ctx.store.children(target)) {
47144
+ const e = expandSrc(ctx, { kind: "store", id: c }, rootTheme, path, descendants);
47145
+ if (e)
47146
+ children.push(e);
47147
+ }
47148
+ ctx.stack.pop();
47149
+ return { path, type: root.type, props: resolveProps(root, ctx.vars, rootTheme), children, theme: rootTheme, role: "instance" };
47150
+ }
47151
+ // ../../packages/canvas/document/src/known-props.ts
47152
+ var ENTITY = "id type name context reusable theme enabled opacity flipX flipY layoutPosition metadata rotation x y children";
47153
+ var SIZE = "width height";
47154
+ var STROKE = "stroke strokeWidth strokeLinecap strokeLinejoin strokeAlignment";
47155
+ var EFFECTS = "effect";
47156
+ var GRAPHICS = `${EFFECTS} ${STROKE} fill`;
47157
+ var TEXT = "fontFamily fontSize fontWeight letterSpacing fontStyle underline lineHeight textAlign textAlignVertical strikethrough href";
47158
+ var LAYOUT = "layout gap layoutIncludeStroke padding justifyContent alignItems";
47159
+ var RECTANGLE = `${SIZE} ${GRAPHICS} cornerRadius`;
47160
+ var keys = (extra) => new Set(`${ENTITY} ${extra}`.split(/\s+/));
47161
+ var KNOWN_PROPS = {
47162
+ rectangle: keys(RECTANGLE),
47163
+ ellipse: keys(`${SIZE} ${GRAPHICS} innerRadius startAngle sweepAngle`),
47164
+ polygon: keys(`${SIZE} ${GRAPHICS} polygonCount cornerRadius`),
47165
+ path: keys(`${SIZE} ${GRAPHICS} fillRule geometry viewBox`),
47166
+ text: keys(`${SIZE} ${GRAPHICS} ${TEXT} content textGrowth`),
47167
+ frame: keys(`${RECTANGLE} ${LAYOUT} clip placeholder slot`),
47168
+ group: keys(EFFECTS),
47169
+ note: keys(`${SIZE} ${TEXT} content`),
47170
+ prompt: keys(`${SIZE} ${TEXT} content model`),
47171
+ context: keys(`${SIZE} ${TEXT} content`),
47172
+ icon: keys(`${SIZE} ${EFFECTS} library icon weight fill`),
47173
+ script: keys(`${SIZE} clip scriptUri inputs`),
47174
+ browser: keys(`${SIZE} ${EFFECTS} ${STROKE} url deviceId zoom scrollX scrollY cornerRadius`),
47175
+ ref: keys("ref descendants")
47176
+ };
47177
+ function unknownProperties(node2, type) {
47178
+ if (type === "ref")
47179
+ return [];
47180
+ const allowed = Object.hasOwn(KNOWN_PROPS, type) ? KNOWN_PROPS[type] : keys("");
47181
+ return Object.keys(node2).filter((key) => !key.startsWith("__") && !allowed.has(key));
47182
+ }
47183
+ function iconNameOf(node2) {
47184
+ for (const key of ["icon", "iconName"]) {
47185
+ const value = node2[key];
47186
+ if (typeof value === "string" && value.trim() !== "")
47187
+ return value;
47188
+ }
47189
+ return "";
47190
+ }
47191
+ function hasUnsupportedImageUrl(node2) {
47192
+ const invalid = (paint) => {
47193
+ if (Array.isArray(paint))
47194
+ return paint.some(invalid);
47195
+ if (!paint || typeof paint !== "object")
47196
+ return false;
47197
+ const fill = paint;
47198
+ return fill.type === "image" && (typeof fill.url !== "string" || !/^file-[0-9A-Za-z]{24}$/.test(fill.url));
47199
+ };
47200
+ return invalid(node2.fill) || invalid(node2.stroke);
47201
+ }
47202
+
47203
+ // ../../packages/canvas/document/src/execute-api.ts
47204
+ var LIMITS = { ops: 5000, printBytes: 64 * 1024, screenshots: 4 };
47205
+ var ID_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
47206
+ class ExecuteApi {
47207
+ store;
47208
+ rec;
47209
+ bounds;
47210
+ rev;
47211
+ random;
47212
+ document = "document";
47213
+ layoutCache = new Map;
47214
+ constructor(store, rec, bounds, rev, random = Math.random) {
47215
+ this.store = store;
47216
+ this.rec = rec;
47217
+ this.bounds = bounds;
47218
+ this.rev = rev;
47219
+ this.random = random;
47220
+ }
47221
+ mint() {
47222
+ for (;; ) {
47223
+ let id = "";
47224
+ for (let i = 0;i < 5; i++)
47225
+ id += ID_CHARS[Math.floor(this.random() * ID_CHARS.length)];
47226
+ if (!this.store.get(id))
47227
+ return id;
47228
+ }
47229
+ }
47230
+ commit(op) {
47231
+ if (this.rec.ops.length >= LIMITS.ops)
47232
+ throw new Error(`SCRIPT_LIMIT: more than ${LIMITS.ops} operations in one execute`);
47233
+ const touched = applyOp(this.store, op, this.rev);
47234
+ this.mutations++;
47235
+ this.rec.ops.push(op);
47236
+ if (op.op === "setVariables")
47237
+ this.rec.allTouched = true;
47238
+ for (const t of touched) {
47239
+ this.rec.touchedTop.add(t);
47240
+ this.layoutCache.delete(t);
47241
+ }
47242
+ if (op.op === "setVariables")
47243
+ this.layoutCache.clear();
47244
+ }
47245
+ parentId(parent) {
47246
+ if (parent === "document" || parent === "" || parent == null)
47247
+ return null;
47248
+ if (parent.includes("/"))
47249
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "parent", reason: "cannot insert inside a component instance; use Replace on the instance child" });
47250
+ const row = this.store.get(parent);
47251
+ if (!row)
47252
+ throw new OpRejectedError({ code: "PARENT_NOT_FOUND", path: parent });
47253
+ if (!CONTAINER_TYPES.has(row.props.type))
47254
+ throw new OpRejectedError({ code: "CANNOT_HAVE_CHILDREN", parent, type: row.props.type });
47255
+ return parent;
47256
+ }
47257
+ lastOrd(parent) {
47258
+ const kids = this.store.children(parent);
47259
+ return kids.length ? this.store.get(kids[kids.length - 1]).ord : null;
47260
+ }
47261
+ withIds(node2) {
47262
+ if (typeof node2 !== "object" || node2 === null || typeof node2.type !== "string")
47263
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "type", reason: "node needs a type" });
47264
+ if (node2.type === "ref") {
47265
+ const target = node2.ref;
47266
+ if (!this.store.get(target))
47267
+ throw new OpRejectedError({ code: "UNKNOWN_REF", ref: target });
47268
+ }
47269
+ for (const k of ["width", "height"]) {
47270
+ const v = node2[k];
47271
+ if (typeof v === "number" && v < 0)
47272
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: k, reason: "negative size" });
47273
+ if (typeof v === "string" && /%|vh|vw|calc/.test(v))
47274
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: k, reason: "percentage and viewport sizes are not supported" });
47275
+ }
47276
+ const id = this.mint();
47277
+ const out = { ...node2, id };
47278
+ if (typeof node2.name === "string")
47279
+ this.rec.created[node2.name] = id;
47280
+ if (Array.isArray(node2.children)) {
47281
+ if (!CONTAINER_TYPES.has(node2.type))
47282
+ throw new OpRejectedError({ code: "CANNOT_HAVE_CHILDREN", parent: id, type: node2.type });
47283
+ out.children = node2.children.map((c) => this.withIds(c));
47284
+ }
47285
+ return out;
47286
+ }
47287
+ warnProps(data, type, nodeId) {
47288
+ if (hasUnsupportedImageUrl(data) && this.rec.warnings.length < 20 && !this.rec.warnings.some((w) => w.code === "UNSUPPORTED_IMAGE_URL" && w.nodeId === nodeId))
47289
+ this.rec.warnings.push({ code: "UNSUPPORTED_IMAGE_URL", nodeId, message: "image fill url must be a file id (file-…)" });
47290
+ if (data.type === "icon" && !iconNameOf(data) && this.rec.warnings.length < 20 && !this.rec.warnings.some((w) => w.code === "ICON_NAME_MISSING" && w.nodeId === nodeId))
47291
+ 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)" });
47292
+ for (const prop of unknownProperties(data, type)) {
47293
+ const message = `${prop} is not a .pen property`;
47294
+ if (this.rec.warnings.length >= 20)
47295
+ break;
47296
+ if (!this.rec.warnings.some((w) => w.code === "UNKNOWN_PROPERTY" && w.nodeId === nodeId && w.message === message))
47297
+ this.rec.warnings.push({ code: "UNKNOWN_PROPERTY", nodeId, message });
47298
+ }
47299
+ for (const child of Array.isArray(data.children) ? data.children : [])
47300
+ this.warnProps(child, child.type, child.id ?? nodeId);
47301
+ if (data.descendants && typeof data.descendants === "object") {
47302
+ const descendants = typeof data.ref === "string" ? this.resolveDescendantKeys(data.ref, data.descendants) : data.descendants;
47303
+ for (const [key, value] of Object.entries(descendants)) {
47304
+ if (!value || typeof value !== "object")
47305
+ continue;
47306
+ const patch = value;
47307
+ const target = this.store.get(key)?.props.type ?? (typeof data.ref === "string" ? this.expandedAt(`${data.ref}/${key}`, {})?.node.type : undefined);
47308
+ this.warnProps(patch, typeof patch.type === "string" ? patch.type : target ?? "ref", `${nodeId}/${key}`);
47309
+ }
47310
+ }
47311
+ }
47312
+ splitInstancePath(path) {
47313
+ const i = path.indexOf("/");
47314
+ if (i < 0)
47315
+ return null;
47316
+ return { owner: path.slice(0, i), rest: path.slice(i + 1) };
47317
+ }
47318
+ resolveDescendantKeys(rootId, desc) {
47319
+ const byName = new Map;
47320
+ const walk = (id) => {
47321
+ for (const c of this.store.children(id)) {
47322
+ const n = this.store.get(c).props;
47323
+ if (n.name)
47324
+ byName.set(n.name, [...byName.get(n.name) ?? [], c]);
47325
+ walk(c);
47326
+ }
47327
+ };
47328
+ walk(rootId);
47329
+ const out = {};
47330
+ for (const [k, v] of Object.entries(desc)) {
47331
+ let key = k;
47332
+ if (!k.includes("/") && !this.store.get(k)) {
47333
+ const hits = byName.get(k);
47334
+ if (hits?.length === 1)
47335
+ key = hits[0];
47336
+ }
47337
+ out[key] = v;
47338
+ }
47339
+ return out;
47340
+ }
47341
+ Insert(parent, nodeData) {
47342
+ const p = this.parentId(parent);
47343
+ let node2 = this.withIds(migrateLegacyProps(nodeData));
47344
+ if (node2.type === "ref" && node2.descendants && typeof node2.descendants === "object")
47345
+ node2 = { ...node2, descendants: this.resolveDescendantKeys(node2.ref, node2.descendants) };
47346
+ this.warnProps(node2, node2.type, node2.id);
47347
+ this.commit({ op: "insert", parent: p, ord: between(this.lastOrd(p), null), node: node2 });
47348
+ return node2.id;
47349
+ }
47350
+ Copy(path, parent, copyNodeData = {}) {
47351
+ if (path.includes("/"))
47352
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "path", reason: "copying an instance child is not supported in this spike" });
47353
+ const src = this.store.get(path);
47354
+ if (!src)
47355
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47356
+ const p = this.parentId(parent);
47357
+ const { descendants, ...over } = migrateLegacyProps(copyNodeData);
47358
+ let node2;
47359
+ if (src.props.reusable) {
47360
+ node2 = { type: "ref", ref: src.id, ...over };
47361
+ if (descendants)
47362
+ node2.descendants = this.resolveDescendantKeys(src.id, descendants);
47363
+ node2 = this.withIds(node2);
47364
+ } else {
47365
+ const tree = subtree(this.store, src.id);
47366
+ const descMap = descendants ? this.resolveDescendantKeys(src.id, descendants) : {};
47367
+ const apply = (n) => {
47368
+ const d = descMap[n.id];
47369
+ let out = d && typeof d.type === "string" ? { ...d } : { ...n, ...d ?? {} };
47370
+ if (Array.isArray(n.children) && !(d && typeof d.type === "string"))
47371
+ out = { ...out, children: n.children.map(apply) };
47372
+ return out;
47373
+ };
47374
+ node2 = this.withIds({ ...apply(tree), ...over });
47375
+ }
47376
+ this.warnProps(node2, node2.type, node2.id);
47377
+ this.commit({ op: "insert", parent: p, ord: between(this.lastOrd(p), null), node: node2 });
47378
+ return node2.id;
47379
+ }
47380
+ Update(path, updateData) {
47381
+ updateData = migrateLegacyProps(updateData);
47382
+ const inst = this.splitInstancePath(path);
47383
+ if (inst) {
47384
+ const owner = this.store.get(inst.owner);
47385
+ if (!owner || owner.props.type !== "ref")
47386
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47387
+ const desc = { ...owner.props.descendants ?? {} };
47388
+ this.warnProps(updateData, this.expandedAt(path, {})?.node.type ?? "ref", path);
47389
+ desc[inst.rest] = { ...desc[inst.rest] ?? {}, ...updateData };
47390
+ this.commit({ op: "update", id: owner.id, patch: { descendants: desc } });
47391
+ return;
47392
+ }
47393
+ const row = this.store.get(path);
47394
+ if (!row)
47395
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47396
+ for (const f of ["id", "type", "ref"])
47397
+ if (f in updateData && updateData[f] !== row.props[f])
47398
+ throw new OpRejectedError({ code: "IMMUTABLE_FIELD", field: f });
47399
+ if ("children" in updateData)
47400
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "children", reason: "use Replace to change children" });
47401
+ const { id: _i, type: _t, ref: _r, ...patch } = updateData;
47402
+ if (patch.descendants && row.props.type === "ref")
47403
+ patch.descendants = { ...row.props.descendants ?? {}, ...this.resolveDescendantKeys(row.props.ref, patch.descendants) };
47404
+ this.warnProps({ ...patch, ...row.props.type === "ref" ? { ref: row.props.ref } : {} }, row.props.type, row.id);
47405
+ this.commit({ op: "update", id: row.id, patch });
47406
+ }
47407
+ Replace(path, nodeData) {
47408
+ const inst = this.splitInstancePath(path);
47409
+ if (inst) {
47410
+ const owner = this.store.get(inst.owner);
47411
+ if (!owner || owner.props.type !== "ref")
47412
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47413
+ const node3 = this.withIds(migrateLegacyProps(nodeData));
47414
+ this.warnProps(node3, node3.type, node3.id);
47415
+ const desc = { ...owner.props.descendants ?? {}, [inst.rest]: node3 };
47416
+ this.commit({ op: "update", id: owner.id, patch: { descendants: desc } });
47417
+ return node3.id;
47418
+ }
47419
+ const row = this.store.get(path);
47420
+ if (!row)
47421
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47422
+ const node2 = this.withIds(migrateLegacyProps(nodeData));
47423
+ this.warnProps(node2, node2.type, node2.id);
47424
+ this.commit({ op: "delete", id: row.id });
47425
+ this.commit({ op: "insert", parent: row.parent, ord: row.ord, node: node2 });
47426
+ return node2.id;
47427
+ }
47428
+ Move(path, parent, index) {
47429
+ if (path.includes("/"))
47430
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "path", reason: "instance children cannot be moved; edit the component" });
47431
+ const row = this.store.get(path);
47432
+ if (!row)
47433
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47434
+ const p = parent === undefined ? row.parent : this.parentId(parent);
47435
+ for (let cur = p;cur !== null; cur = this.store.get(cur)?.parent ?? null)
47436
+ if (cur === row.id)
47437
+ throw new OpRejectedError({ code: "CYCLE", id: row.id, parent: p });
47438
+ const siblings = this.store.children(p).filter((s) => s !== row.id);
47439
+ const i = index === undefined ? siblings.length : Math.max(0, Math.min(index, siblings.length));
47440
+ const before = i > 0 ? this.store.get(siblings[i - 1]).ord : null;
47441
+ const after = i < siblings.length ? this.store.get(siblings[i]).ord : null;
47442
+ this.commit({ op: "move", id: row.id, parent: p, ord: between(before, after) });
47443
+ }
47444
+ Delete(path) {
47445
+ if (path === "document")
47446
+ throw new OpRejectedError({ code: "ROOT_PROTECTED" });
47447
+ if (path.includes("/"))
47448
+ throw new OpRejectedError({ code: "INSTANCE_CHILD_DELETE", path });
47449
+ if (!this.store.get(path))
47450
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47451
+ this.commit({ op: "delete", id: path });
47452
+ }
47453
+ SetVariables(variables, replace = false) {
47454
+ const themes = {};
47455
+ for (const [name, def] of Object.entries(variables ?? {})) {
47456
+ if (name.startsWith("$"))
47457
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: name, reason: "variable names must not start with $" });
47458
+ if (!def || typeof def !== "object" || !("type" in def) || !("value" in def))
47459
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: name, reason: "expected { type, value }" });
47460
+ if (Array.isArray(def.value))
47461
+ for (const e of def.value)
47462
+ for (const [axis, v] of Object.entries(e.theme ?? {}))
47463
+ themes[axis] = [...new Set([...themes[axis] ?? [], v])];
47464
+ }
47465
+ this.commit({ op: "setVariables", variables, themes, replace });
47466
+ }
47467
+ GetVariables() {
47468
+ return { variables: this.store.variables(), themes: this.store.themes() };
47469
+ }
47470
+ Get(a, b, c) {
47471
+ let path = null;
47472
+ let visit2 = null;
47473
+ let opts = {};
47474
+ for (const arg of [a, b, c]) {
47475
+ if (typeof arg === "string")
47476
+ path = arg;
47477
+ else if (typeof arg === "function")
47478
+ visit2 = arg;
47479
+ else if (arg && typeof arg === "object")
47480
+ opts = arg;
47481
+ }
47482
+ if (!path && !visit2)
47483
+ throw new Error("Reading the whole document without a visitor would return everything! Pass a visitor or target a specific node.");
47484
+ if (!visit2)
47485
+ return this.readNode(path, opts);
47486
+ const out = [];
47487
+ const roots = path && path !== "document" ? [path] : this.store.children(null);
47488
+ for (const r of roots)
47489
+ this.visitFrom(r, visit2, opts, out);
47490
+ return out;
47491
+ }
47492
+ readNode(path, opts) {
47493
+ if (opts.resolveInstances || opts.resolveVariables || path.includes("/")) {
47494
+ const e = this.expandedAt(path, opts);
47495
+ if (!e)
47496
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47497
+ return toPen(e.node, opts.depth ?? Infinity, !!opts.resolveVariables, opts.resolveInstances !== false || path.includes("/"));
47498
+ }
47499
+ if (!this.store.get(path))
47500
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47501
+ return subtree(this.store, path, opts.depth ?? Infinity);
47502
+ }
47503
+ expandedCache = new Map;
47504
+ mutations = 0;
47505
+ expandedAt(path, _opts) {
47506
+ const first = path.split("/")[0];
47507
+ const row = this.store.get(first);
47508
+ if (!row)
47509
+ return null;
47510
+ let hit = this.expandedCache.get(row.top);
47511
+ if (!hit || hit.rev !== this.mutations) {
47512
+ const tree = expandNode(this.store, row.top, defaultTheme(this.store.themes()));
47513
+ if (!tree)
47514
+ return null;
47515
+ const index = new Map;
47516
+ const walk = (n) => {
47517
+ index.set(n.path, n);
47518
+ n.children.forEach(walk);
47519
+ };
47520
+ walk(tree);
47521
+ hit = { rev: this.mutations, index };
47522
+ this.expandedCache.set(row.top, hit);
47523
+ if (this.expandedCache.size > 8)
47524
+ this.expandedCache.delete(this.expandedCache.keys().next().value);
47525
+ }
47526
+ const node2 = hit.index.get(path);
47527
+ return node2 ? { node: node2, top: row.top } : null;
47528
+ }
47529
+ layoutOf(top) {
47530
+ let l = this.layoutCache.get(top);
47531
+ if (!l) {
47532
+ l = this.bounds.layout(top);
47533
+ this.layoutCache.set(top, l);
47534
+ if (this.layoutCache.size > 8)
47535
+ this.layoutCache.delete(this.layoutCache.keys().next().value);
47536
+ }
47537
+ return l;
47538
+ }
47539
+ visitFrom(startPath, visit2, opts, out) {
47540
+ const at = this.expandedAt(startPath, opts);
47541
+ if (!at)
47542
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: startPath });
47543
+ const self = this;
47544
+ const withInstances = !!opts.resolveInstances;
47545
+ const walk = (e, parentCtx, depth, index) => {
47546
+ if (opts.depth !== undefined && depth > opts.depth)
47547
+ return;
47548
+ let skip = false;
47549
+ const node2 = toPen(e, 0, !!opts.resolveVariables, withInstances, true);
47550
+ const ctx = {
47551
+ node: node2,
47552
+ parentCtx,
47553
+ depth,
47554
+ index,
47555
+ get bounds() {
47556
+ const b = self.layoutOf(at.top).boxes.get(e.path);
47557
+ return b ? { x: b.x, y: b.y, width: b.width, height: b.height } : { x: 0, y: 0, width: 0, height: 0 };
47558
+ },
47559
+ get problems() {
47560
+ const p = self.layoutOf(at.top).problems.find((q) => q.path === e.path && (q.code === "PARTIALLY_CLIPPED" || q.code === "FULLY_CLIPPED"));
47561
+ return p ? p.code === "FULLY_CLIPPED" ? "fully clipped" : "partially clipped" : undefined;
47562
+ },
47563
+ skipChildren() {
47564
+ skip = true;
47565
+ }
47566
+ };
47567
+ const r = visit2(node2, ctx);
47568
+ if (r !== undefined)
47569
+ out.push(r);
47570
+ if (skip)
47571
+ return;
47572
+ if (e.role === "instance" && !withInstances)
47573
+ return;
47574
+ e.children.forEach((c, i) => walk(c, ctx, depth + 1, i));
47575
+ };
47576
+ walk(at.node, undefined, 0, 0);
47577
+ }
47578
+ level(root, parent, opts) {
47579
+ const withInstances = !!opts.resolveInstances;
47580
+ const conv = (e) => ({
47581
+ node: toPen(e, 0, !!opts.resolveVariables, withInstances, true),
47582
+ path: e.path,
47583
+ more: e.children.length > 0 && !(e.role === "instance" && !withInstances)
47584
+ });
47585
+ if (parent === null) {
47586
+ const roots = root && root !== "document" ? [root] : this.store.children(null);
47587
+ return roots.map((r) => {
47588
+ const at2 = this.expandedAt(r, opts);
47589
+ if (!at2)
47590
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: r });
47591
+ return conv(at2.node);
47592
+ });
47593
+ }
47594
+ const at = this.expandedAt(parent, opts);
47595
+ return at ? at.node.children.map(conv) : [];
47596
+ }
47597
+ tree(path, opts) {
47598
+ const withInstances = !!opts.resolveInstances;
47599
+ const roots = path && path !== "document" ? [path] : this.store.children(null);
47600
+ const out = [];
47601
+ for (const r of roots) {
47602
+ const at = this.expandedAt(r, opts);
47603
+ if (!at)
47604
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: r });
47605
+ const conv = (e, depth) => ({
47606
+ node: toPen(e, 0, !!opts.resolveVariables, withInstances, true),
47607
+ path: e.path,
47608
+ children: e.role === "instance" && !withInstances || opts.depth !== undefined && depth >= opts.depth ? [] : e.children.map((c) => conv(c, depth + 1))
47609
+ });
47610
+ out.push(conv(at.node, 0));
47611
+ }
47612
+ return out;
47613
+ }
47614
+ boundsOf(path) {
47615
+ const first = path.split("/")[0];
47616
+ const row = this.store.get(first);
47617
+ if (!row)
47618
+ return { bounds: { x: 0, y: 0, width: 0, height: 0 } };
47619
+ const l = this.layoutOf(row.top);
47620
+ const b = l.boxes.get(path);
47621
+ const p = l.problems.find((q) => q.path === path && (q.code === "PARTIALLY_CLIPPED" || q.code === "FULLY_CLIPPED"));
47622
+ return {
47623
+ bounds: b ? { x: b.x, y: b.y, width: b.width, height: b.height } : { x: 0, y: 0, width: 0, height: 0 },
47624
+ problems: p ? p.code === "FULLY_CLIPPED" ? "fully clipped" : "partially clipped" : undefined
47625
+ };
47626
+ }
47627
+ FindEmptySpace(input) {
47628
+ const dir = input.direction ?? "right";
47629
+ const pad = input.padding ?? 0;
47630
+ const rects = [];
47631
+ const tops = input.nodeId ? [input.nodeId] : this.store.children(null);
47632
+ for (const t of tops) {
47633
+ const row = this.store.get(t);
47634
+ if (!row)
47635
+ continue;
47636
+ const b = this.layoutOf(row.top).boxes.get(t);
47637
+ if (b)
47638
+ rects.push({ x: b.wx, y: b.wy, width: b.width, height: b.height });
47639
+ }
47640
+ if (!rects.length)
47641
+ return { x: 0, y: 0 };
47642
+ const minX = Math.min(...rects.map((r) => r.x));
47643
+ const minY = Math.min(...rects.map((r) => r.y));
47644
+ const maxX = Math.max(...rects.map((r) => r.x + r.width));
47645
+ const maxY = Math.max(...rects.map((r) => r.y + r.height));
47646
+ if (dir === "right")
47647
+ return { x: maxX + pad, y: minY };
47648
+ if (dir === "left")
47649
+ return { x: minX - pad - input.width, y: minY };
47650
+ if (dir === "bottom")
47651
+ return { x: minX, y: maxY + pad };
47652
+ return { x: minX, y: minY - pad - input.height };
47653
+ }
47654
+ Print(...values) {
47655
+ const line = values.map((v) => typeof v === "string" ? v : JSON.stringify(v)).join(" ");
47656
+ this.rec.printBytes += line.length;
47657
+ if (this.rec.printBytes > LIMITS.printBytes)
47658
+ throw new Error(`SCRIPT_LIMIT: Print output over ${LIMITS.printBytes} bytes`);
47659
+ this.rec.prints.push(line);
47660
+ }
47661
+ TakeScreenshot(nodeIds) {
47662
+ for (const id of nodeIds)
47663
+ if (this.rec.screenshots.length < LIMITS.screenshots)
47664
+ this.rec.screenshots.push(id);
47665
+ }
47666
+ }
47667
+ function toPen(e, depth, _resolved, _instances, shallow = false) {
47668
+ const node2 = { ...e.props, id: e.path, type: e.type };
47669
+ if (!shallow && e.children.length) {
47670
+ if (depth <= 0)
47671
+ node2.children = "...";
47672
+ else
47673
+ node2.children = e.children.map((c) => toPen(c, depth - 1, _resolved, _instances));
47674
+ }
47675
+ return node2;
47676
+ }
47677
+ // ../../packages/canvas/document/src/pen-import.ts
47678
+ var FILE_ID = /^file-/;
47679
+ var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
47680
+ var isImage = (node2) => node2.type === "image" && typeof node2.url === "string";
47681
+ var isRef = (node2) => node2.type === "ref" && typeof node2.ref === "string";
47682
+ function visit2(value, nodeId, fn) {
47683
+ if (Array.isArray(value)) {
47684
+ for (const item of value)
47685
+ visit2(item, nodeId, fn);
47686
+ return;
47687
+ }
47688
+ const node2 = asRecord(value);
47689
+ if (!node2)
47690
+ return;
47691
+ const id = typeof node2.id === "string" ? node2.id : nodeId;
47692
+ fn(node2, id);
47693
+ for (const key of Object.keys(node2))
47694
+ visit2(node2[key], id, fn);
47695
+ }
47696
+ function indexTops(tops) {
47697
+ const owner = new Map;
47698
+ for (const top of tops) {
47699
+ visit2(top, top.id, (node2) => {
47700
+ if (typeof node2.id === "string")
47701
+ owner.set(node2.id, top.id);
47702
+ });
47703
+ }
47704
+ return owner;
47705
+ }
47706
+ var clone = (value) => JSON.parse(JSON.stringify(value));
47707
+ function penImageUrls(nodes) {
47708
+ const urls = [];
47709
+ const seen = new Set;
47710
+ for (const node2 of nodes) {
47711
+ visit2(node2, node2.id, (value) => {
47712
+ if (!isImage(value))
47713
+ return;
47714
+ const url = value.url;
47715
+ if (FILE_ID.test(url) || seen.has(url))
47716
+ return;
47717
+ seen.add(url);
47718
+ urls.push(url);
47719
+ });
47720
+ }
47721
+ return urls;
47722
+ }
47723
+ function planPenImport(doc, opts = {}) {
47724
+ const tops = Array.isArray(doc.children) ? doc.children : [];
47725
+ const warnings = [];
47726
+ const selected = new Set;
47727
+ const added = [];
47728
+ if (opts.frames === undefined) {
47729
+ for (const top of tops)
47730
+ selected.add(top.id);
47731
+ } else {
47732
+ const frames = new Set(opts.frames);
47733
+ for (const id of frames) {
47734
+ if (!tops.some((top) => top.id === id))
47735
+ warnings.push({ code: "FRAME_NOT_FOUND", id });
47736
+ else
47737
+ selected.add(id);
47738
+ }
47739
+ const owner = indexTops(tops);
47740
+ const byId = new Map(tops.map((top) => [top.id, top]));
47741
+ const dangling = new Set;
47742
+ for (let queue = [...selected];queue.length > 0; ) {
47743
+ const top = byId.get(queue.shift());
47744
+ if (!top)
47745
+ continue;
47746
+ visit2(top, top.id, (node2, nodeId) => {
47747
+ if (!isRef(node2))
47748
+ return;
47749
+ const ref = node2.ref;
47750
+ const target = owner.get(ref);
47751
+ if (target === undefined) {
47752
+ const key = `${ref}\x00${nodeId}`;
47753
+ if (dangling.has(key))
47754
+ return;
47755
+ dangling.add(key);
47756
+ warnings.push({ code: "REF_DANGLING", ref, nodeId });
47757
+ return;
47758
+ }
47759
+ if (selected.has(target))
47760
+ return;
47761
+ selected.add(target);
47762
+ queue.push(target);
47763
+ });
47764
+ }
47765
+ for (const top of tops)
47766
+ if (selected.has(top.id) && !frames.has(top.id))
47767
+ added.push(top.id);
47768
+ }
47769
+ const images = opts.images ?? {};
47770
+ const unmapped = new Map;
47771
+ const children = tops.filter((top) => selected.has(top.id)).map((top) => clone(top));
47772
+ for (const node2 of children) {
47773
+ visit2(node2, node2.id, (value, nodeId) => {
47774
+ if (!isImage(value))
47775
+ return;
47776
+ const url = value.url;
47777
+ if (FILE_ID.test(url))
47778
+ return;
47779
+ const fileId = Object.hasOwn(images, url) ? images[url] : undefined;
47780
+ if (typeof fileId === "string") {
47781
+ value.url = fileId;
47782
+ return;
47783
+ }
47784
+ const nodeIds = unmapped.get(url);
47785
+ if (nodeIds) {
47786
+ if (!nodeIds.includes(nodeId))
47787
+ nodeIds.push(nodeId);
47788
+ } else
47789
+ unmapped.set(url, [nodeId]);
47790
+ });
47791
+ }
47792
+ for (const [url, nodeIds] of unmapped)
47793
+ warnings.push({ code: "IMAGE_UNMAPPED", url, nodeIds });
47794
+ return {
47795
+ children,
47796
+ ...doc.variables ? { variables: clone(doc.variables) } : {},
47797
+ ...doc.themes ? { themes: clone(doc.themes) } : {},
47798
+ added,
47799
+ warnings
47800
+ };
47801
+ }
47802
+ // src/commands/canvas-import.ts
47803
+ var CHUNK_CHARS = 1500000;
47804
+ function countNodes(nodes) {
47805
+ let total = 0;
47806
+ const walk = (list) => {
47807
+ for (const node2 of list) {
47808
+ total++;
47809
+ if (Array.isArray(node2.children))
47810
+ walk(node2.children);
47811
+ }
47812
+ };
47813
+ walk(nodes);
47814
+ return total;
47815
+ }
47816
+ function chunkTopNodes(nodes, limit = CHUNK_CHARS) {
47817
+ const chunks = [];
47818
+ let current = [];
47819
+ let size = 0;
47820
+ for (const node2 of nodes) {
47821
+ const length = JSON.stringify(node2).length;
47822
+ if (current.length && size + length > limit) {
47823
+ chunks.push(current);
47824
+ current = [];
47825
+ size = 0;
47826
+ }
47827
+ current.push(node2);
47828
+ size += length;
47829
+ }
47830
+ if (current.length)
47831
+ chunks.push(current);
47832
+ return chunks;
47833
+ }
47834
+ var CONTENT_TYPES = {
47835
+ png: "image/png",
47836
+ jpg: "image/jpeg",
47837
+ jpeg: "image/jpeg",
47838
+ webp: "image/webp",
47839
+ gif: "image/gif",
47840
+ svg: "image/svg+xml",
47841
+ avif: "image/avif"
47842
+ };
47843
+ var contentTypeOf = (url) => CONTENT_TYPES[url.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
47844
+ var viewerUrlFor = (canvasId, env) => `https://console${env === "develop" ? "-develop" : ""}.deepraxis.com/canvases/${canvasId}`;
47845
+ function imageCandidates(url, penFile, roots) {
47846
+ const name = basename2(url);
47847
+ return [...new Set([
47848
+ join5(dirname2(penFile), url),
47849
+ ...roots.map((root) => join5(root, url)),
47850
+ ...roots.map((root) => join5(root, name))
47851
+ ])];
47852
+ }
47853
+ var isMissing = (error) => error?.code === "ENOENT";
47854
+ var reason = (error) => error instanceof Error ? error.message : String(error);
47855
+ async function findImage(url, candidates, ports) {
47856
+ for (const path of candidates) {
47857
+ try {
47858
+ return await ports.readBytes(path);
47859
+ } catch (error) {
47860
+ if (!isMissing(error))
47861
+ throw new UsageError(`cannot read ${path}, needed for image ${url}`, reason(error));
47862
+ }
47863
+ }
47864
+ return;
47865
+ }
47866
+ var warningKey = (warning) => `${warning.code}\x00${"url" in warning ? warning.url : ("id" in warning) ? warning.id : warning.ref}\x00${"nodeId" in warning ? warning.nodeId : ""}`;
47867
+ var warningLine = (warning) => {
47868
+ switch (warning.code) {
47869
+ case "IMAGE_UNMAPPED":
47870
+ return `${warning.code}: ${warning.url} (${warning.nodeIds.length} node(s))`;
47871
+ case "REF_DANGLING":
47872
+ return `${warning.code}: ${warning.ref} at ${warning.nodeId}`;
47873
+ case "FRAME_NOT_FOUND":
47874
+ return `${warning.code}: ${warning.id}`;
47875
+ default:
47876
+ return `${warning.code}: ${warning.url}`;
47877
+ }
47878
+ };
47879
+ async function canvasImport(args, ports) {
47880
+ if (args.canvas !== undefined && !args.yes) {
47881
+ 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.");
47882
+ }
47883
+ const file = resolve3(ports.cwd, args.file);
47884
+ let text;
47885
+ try {
47886
+ text = await ports.readFile(file);
47887
+ } catch (error) {
47888
+ throw new UsageError(`cannot read ${args.file}`, isMissing(error) ? "Check the path: `praxis canvas import <file.pen>`." : reason(error));
47889
+ }
47890
+ let doc;
47891
+ try {
47892
+ doc = JSON.parse(text);
47893
+ } catch (error) {
47894
+ throw new UsageError(`${args.file} is not valid JSON`, reason(error));
47895
+ }
47896
+ if (!Array.isArray(doc.children))
47897
+ throw new UsageError(`${args.file} has no children array`, "A .pen document is an object with a children array of top-level nodes.");
47898
+ const frames = args.frames?.filter((frame) => frame !== "");
47899
+ const roots = (args.imageRoots ?? []).map((root) => resolve3(ports.cwd, root));
47900
+ const selection = planPenImport(doc, frames ? { frames } : {});
47901
+ const urls = penImageUrls(selection.children);
47902
+ const found = new Map;
47903
+ const missing = [];
47904
+ for (const url of urls) {
47905
+ const bytes = await findImage(url, imageCandidates(url, file, roots), ports);
47906
+ if (bytes === undefined)
47907
+ missing.push(url);
47908
+ else
47909
+ found.set(url, { bytes, digest: await ports.hash(bytes) });
47910
+ }
47911
+ const images = {};
47912
+ let uploaded = 0;
47913
+ let reused = 0;
47914
+ if (!args.dryRun) {
47915
+ const byDigest = new Map;
47916
+ for (const [url, { bytes, digest }] of found) {
47917
+ const existing = byDigest.get(digest);
47918
+ if (existing !== undefined) {
47919
+ images[url] = existing;
47920
+ reused++;
47921
+ continue;
47922
+ }
47923
+ const id = await ports.upload({ filename: basename2(url), bytes, contentType: contentTypeOf(url) });
47924
+ byDigest.set(digest, id);
47925
+ images[url] = id;
47926
+ uploaded++;
47927
+ }
47928
+ }
47929
+ const plan = planPenImport(doc, { ...frames ? { frames } : {}, images });
47930
+ const chunks = chunkTopNodes(plan.children);
47931
+ const nodes = countNodes(plan.children);
47932
+ const warnings = plan.warnings.filter((warning) => !(args.dryRun && warning.code === "IMAGE_UNMAPPED" && !missing.includes(warning.url)));
47933
+ let canvasId = null;
47934
+ let revision = null;
47935
+ if (!args.dryRun) {
47936
+ canvasId = args.canvas ?? (await ports.rpc("canvas.canvases.create", { name: args.name ?? basename2(file).replace(/\.pen$/, "") })).id;
47937
+ for (let index = 0;index < chunks.length; index++) {
47938
+ const result2 = await ports.rpc("canvas.canvases.import", {
47939
+ canvasId,
47940
+ reset: index === 0,
47941
+ ...index === 0 && plan.variables ? { variables: plan.variables } : {},
47942
+ ...index === 0 && plan.themes ? { themes: plan.themes } : {},
47943
+ children: chunks[index]
47944
+ });
47945
+ revision = result2.revision;
47946
+ const seen = new Set(warnings.map(warningKey));
47947
+ for (const warning of result2.warnings ?? []) {
47948
+ if (seen.has(warningKey(warning)))
47949
+ continue;
47950
+ seen.add(warningKey(warning));
47951
+ warnings.push(warning);
47952
+ }
47953
+ }
47954
+ }
47955
+ const result = {
47956
+ canvas_id: canvasId,
47957
+ viewer_url: canvasId === null ? null : viewerUrlFor(canvasId, ports.env),
47958
+ revision,
47959
+ frames: plan.children.map((node2) => node2.id),
47960
+ added: plan.added,
47961
+ nodes,
47962
+ images: { uploaded, reused, missing },
47963
+ chunks: chunks.length,
47964
+ warnings,
47965
+ dry_run: args.dryRun
47966
+ };
47967
+ ports.emit({ kind: "object", data: result });
47968
+ const name = args.name ?? basename2(file).replace(/\.pen$/, "");
47969
+ const headline = `${plan.children.length} top-level nodes (${plan.added.length} added as component dependencies), ${nodes} nodes, ${chunks.length} chunk(s)`;
47970
+ ports.human([
47971
+ args.dryRun ? `${file}: ${headline}` : `${canvasId} ${name} — ${headline}, ${uploaded} image(s) uploaded${reused ? `, ${reused} reused` : ""}`,
47972
+ ...result.viewer_url ? [result.viewer_url] : [],
47973
+ ...plan.added.length ? [`added as dependencies: ${plan.added.join(", ")}`] : [],
47974
+ `${urls.length - missing.length}/${urls.length} image(s) found locally`,
47975
+ ...missing.length ? [`not found (they will not render): ${missing.join(", ")}`] : [],
47976
+ ...warnings.map(warningLine)
47977
+ ].join(`
47978
+ `));
47979
+ return 0;
47980
+ }
47981
+
46693
47982
  // src/main.ts
46694
47983
  import { spawnSync } from "node:child_process";
46695
47984
 
@@ -46749,13 +48038,13 @@ var groups = [["id"], ["name", "title", "display_name"], ["status", "state"], ["
46749
48038
  var isExtraColumn = (key) => !groups.some((group) => group.includes(key));
46750
48039
  function columnsFor(items) {
46751
48040
  const rows = items.map(record);
46752
- const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))];
48041
+ const keys2 = [...new Set(rows.flatMap((row) => Object.keys(row)))];
46753
48042
  const chosen = groups.flatMap((group) => {
46754
- const key = group.find((k) => keys.includes(k));
48043
+ const key = group.find((k) => keys2.includes(k));
46755
48044
  return key ? [key] : [];
46756
48045
  });
46757
48046
  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) => {
48047
+ const extra = keys2.filter((key) => !standard.has(key) && rows.some((row) => row[key] !== null && row[key] !== undefined) && rows.every((row) => {
46759
48048
  const v = row[key];
46760
48049
  return v === null || v === undefined || typeof v === "boolean" || typeof v === "number" || typeof v === "string" && [...v].length <= 24;
46761
48050
  })).slice(0, 2);
@@ -46810,9 +48099,9 @@ class ModelStream {
46810
48099
  const data = streamData(event), message = record(data.message), response = record(data.response);
46811
48100
  this.chunks.push(streamText(event));
46812
48101
  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;
48102
+ 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;
48103
+ if (typeof reason2 === "string" && reason2)
48104
+ this.finishReason = reason2;
46816
48105
  else if (["response.completed", "response.incomplete", "response.failed"].includes(String(data.type)))
46817
48106
  this.finishReason = String(data.type).slice("response.".length);
46818
48107
  for (const usage of [message.usage, data.usage, response.usage]) {
@@ -47323,7 +48612,7 @@ function startProgress(ctx, write = (text) => writeOutput({ stderr: text })) {
47323
48612
  }
47324
48613
 
47325
48614
  // src/main.ts
47326
- var version = "0.2.2-dev.1b23ee0";
48615
+ var version = "0.2.2-dev.214765b";
47327
48616
  var commands = commandTree(operations);
47328
48617
  var manual = [...workflows.map((w) => w.words), [API_WORD]];
47329
48618
  function route(argv) {
@@ -47360,19 +48649,21 @@ var defaults = {
47360
48649
  stderrIsTTY: Boolean(process.stderr.isTTY),
47361
48650
  columns: process.stdout.columns ?? 100,
47362
48651
  readFile: (path) => readFile3(path, "utf8"),
48652
+ readBytes: (path) => readFile3(path),
48653
+ sha256: async (bytes) => createHash3("sha256").update(bytes).digest("hex"),
47363
48654
  async readStdin() {
47364
48655
  const chunks = [];
47365
48656
  for await (const chunk of process.stdin)
47366
48657
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
47367
48658
  return Buffer.concat(chunks).toString("utf8");
47368
48659
  },
47369
- ask: () => new Promise((resolve3) => {
48660
+ ask: () => new Promise((resolve4) => {
47370
48661
  const input = createInterface({ input: process.stdin, terminal: false });
47371
48662
  input.once("line", (line) => {
47372
- resolve3(/^(y|yes)$/i.test(line.trim()));
48663
+ resolve4(/^(y|yes)$/i.test(line.trim()));
47373
48664
  input.close();
47374
48665
  });
47375
- input.once("close", () => resolve3(false));
48666
+ input.once("close", () => resolve4(false));
47376
48667
  }),
47377
48668
  async openBrowser(url) {
47378
48669
  try {
@@ -47380,27 +48671,27 @@ var defaults = {
47380
48671
  if (!["https:", "http:"].includes(parsed.protocol))
47381
48672
  return;
47382
48673
  const cmd = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler", url] : ["xdg-open", url];
47383
- await new Promise((resolve3, reject) => {
48674
+ await new Promise((resolve4, reject) => {
47384
48675
  const child = spawn2(cmd[0], cmd.slice(1), { stdio: "ignore" });
47385
48676
  child.once("error", reject);
47386
- child.once("close", () => resolve3());
48677
+ child.once("close", () => resolve4());
47387
48678
  });
47388
48679
  } catch {}
47389
48680
  },
47390
- wait: (ms) => new Promise((resolve3) => setTimeout(resolve3, ms)),
48681
+ wait: (ms) => new Promise((resolve4) => setTimeout(resolve4, ms)),
47391
48682
  render,
47392
- spawn: (cmd, args, options) => new Promise((resolve3, reject) => {
48683
+ spawn: (cmd, args, options) => new Promise((resolve4, reject) => {
47393
48684
  const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
47394
48685
  child.once("error", reject);
47395
- child.once("close", (code) => resolve3(code ?? 1));
48686
+ child.once("close", (code) => resolve4(code ?? 1));
47396
48687
  }),
47397
- spawnCapture: (cmd, args, options) => new Promise((resolve3, reject) => {
48688
+ spawnCapture: (cmd, args, options) => new Promise((resolve4, reject) => {
47398
48689
  const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
47399
48690
  const chunks = [];
47400
48691
  child.stdout.on("data", (c) => chunks.push(c));
47401
48692
  child.stderr.on("data", (c) => chunks.push(c));
47402
48693
  child.once("error", reject);
47403
- child.once("close", (code) => resolve3({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
48694
+ child.once("close", (code) => resolve4({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
47404
48695
  }),
47405
48696
  has: (bin) => spawnSync(process.platform === "win32" ? "where" : "which", [bin], { stdio: "ignore" }).status === 0,
47406
48697
  cwd: process.cwd()
@@ -47419,6 +48710,13 @@ var appOptions = {
47419
48710
  { name: "no-wait", type: "boolean", description: "Return as soon as the run exists instead of waiting for a verdict." },
47420
48711
  { name: "repeat", type: "string", description: "How many times each selected case runs (default: 1)." },
47421
48712
  { 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>." }
48713
+ ],
48714
+ "canvas import": [
48715
+ { name: "name", type: "string", description: "Name for the new canvas (default: the file name without .pen)." },
48716
+ { 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." },
48717
+ { name: "frames", type: "string", description: "Comma-separated top-level node ids to import. The components they reference come along automatically." },
48718
+ { 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." },
48719
+ { name: "dry-run", type: "boolean", description: "Read the local file and print the plan. No login and no request." }
47422
48720
  ]
47423
48721
  };
47424
48722
  async function main(argv, injected = {}) {
@@ -47516,7 +48814,7 @@ Examples:
47516
48814
  return 0;
47517
48815
  }
47518
48816
  const path = ports.tokenPath ?? tokenPath(config.env);
47519
- const store = createTokenStore(config.env, path, selectSecretStore(ports.env, ports.secretStore));
48817
+ const store2 = createTokenStore(config.env, path, selectSecretStore(ports.env, ports.secretStore));
47520
48818
  const wireFetch = async (input, init) => {
47521
48819
  const request = new Request(input, init);
47522
48820
  request.headers.set("User-Agent", `praxis-cli/${version}${ctx.mode === "agent" ? ` agent/${ctx.agentName ?? "unknown"}` : ""}`);
@@ -47526,7 +48824,7 @@ Examples:
47526
48824
  }
47527
48825
  return ports.fetch(request);
47528
48826
  };
47529
- const auth = credentials(config, ports.env, { fetch: wireFetch, now: ports.now, path, store, remember: (s) => {
48827
+ const auth = credentials(config, ports.env, { fetch: wireFetch, now: ports.now, path, store: store2, remember: (s) => {
47530
48828
  secrets.push(s);
47531
48829
  } });
47532
48830
  ctx.credentialSource = auth.source;
@@ -47602,7 +48900,7 @@ Examples:
47602
48900
  return 0;
47603
48901
  }
47604
48902
  const name = selected.words.join(" ");
47605
- const arity = name === "api" ? 2 : name === "org switch" || name === "app create" ? 1 : 0;
48903
+ const arity = name === "api" ? 2 : name === "org switch" || name === "app create" || name === "canvas import" ? 1 : 0;
47606
48904
  if (parsed.positional.length !== arity)
47607
48905
  throw new UsageError(`${name} expects ${arity} positional argument(s)`);
47608
48906
  if (name === "devops deploy plan") {
@@ -47637,10 +48935,10 @@ Examples:
47637
48935
  if (flags["no-input"] || quiet)
47638
48936
  throw new UsageError("login requires displaying a device code", "Remove --no-input / --quiet or set PRAXIS_API_KEY for scripts.");
47639
48937
  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) });
48938
+ await login(config, path, { ...ports, source: auth.source, json: ctx.mode === "json", store: store2, fetch: wireFetch, emit, remember: (s) => secrets.push(s) });
47641
48939
  break;
47642
48940
  case "logout":
47643
- emit({ kind: "message", text: await store.delete() ? "Logged out." : "Not logged in." });
48941
+ emit({ kind: "message", text: await store2.delete() ? "Logged out." : "Not logged in." });
47644
48942
  break;
47645
48943
  case "whoami":
47646
48944
  emit({ kind: "object", data: await whoami(auth, config.env, org) });
@@ -47699,6 +48997,67 @@ Examples:
47699
48997
  cwd: ports.cwd
47700
48998
  });
47701
48999
  }
49000
+ case "canvas import": {
49001
+ const authorize = async () => {
49002
+ const credential = await auth.get(org);
49003
+ return { Authorization: `Bearer ${credential.token}`, ...credential.source === "api-key" ? { "X-API-Key": credential.token } : {} };
49004
+ };
49005
+ const rpc = async (method, params) => {
49006
+ const response = await wireFetch(`${config.apiUrl}/canvas/v1/rpc`, {
49007
+ method: "POST",
49008
+ headers: { ...await authorize(), "content-type": "application/json" },
49009
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
49010
+ signal: AbortSignal.timeout(120000),
49011
+ redirect: "error"
49012
+ });
49013
+ const reply = await response.json();
49014
+ if (!response.ok || reply.error)
49015
+ throw new PraxisError({ code: "CANVAS_RPC_ERROR", message: `${method}: ${reply.error?.message ?? `HTTP ${response.status}`}` });
49016
+ if (!Object.hasOwn(reply, "result"))
49017
+ throw new PraxisError({ code: "INVALID_RESPONSE", message: `${method} answered no result` });
49018
+ return reply.result;
49019
+ };
49020
+ const upload = async ({ filename, bytes, contentType }) => {
49021
+ const signed = await wireFetch(`${config.apiUrl}/file/v1/uploads/signed`, {
49022
+ method: "POST",
49023
+ headers: { ...await authorize(), "content-type": "application/json" },
49024
+ body: JSON.stringify({ filename, bytes: bytes.length, content_type: contentType, purpose: "user_data" }),
49025
+ signal: AbortSignal.timeout(60000),
49026
+ redirect: "error"
49027
+ });
49028
+ const session = await signed.json();
49029
+ if (!signed.ok || typeof session.url !== "string")
49030
+ throw new PraxisError({ code: "UPLOAD_REJECTED", message: `signed upload for ${filename} failed (HTTP ${signed.status})` });
49031
+ 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" });
49032
+ const file = await sent.json();
49033
+ if (!sent.ok || typeof file.id !== "string")
49034
+ throw new PraxisError({ code: "UPLOAD_FAILED", message: `uploading ${filename} failed (HTTP ${sent.status})` });
49035
+ return file.id;
49036
+ };
49037
+ return await canvasImport({
49038
+ file: parsed.positional[0],
49039
+ name: parsed.flags.name?.[0],
49040
+ canvas: parsed.flags.canvas?.[0],
49041
+ frames: typeof parsed.flags.frames?.[0] === "string" ? parsed.flags.frames[0].split(",").map((frame) => frame.trim()).filter(Boolean) : undefined,
49042
+ imageRoots: parsed.flags["image-root"],
49043
+ dryRun: Boolean(parsed.flags["dry-run"]?.[0]),
49044
+ yes: Boolean(flags.yes)
49045
+ }, {
49046
+ readFile: ports.readFile,
49047
+ readBytes: ports.readBytes,
49048
+ hash: ports.sha256,
49049
+ env: config.env,
49050
+ mode: ctx.mode,
49051
+ emit,
49052
+ cwd: ports.cwd,
49053
+ rpc,
49054
+ upload,
49055
+ human: (text) => {
49056
+ if (ctx.mode === "human")
49057
+ emit({ kind: "message", channel: "stdout", text });
49058
+ }
49059
+ });
49060
+ }
47702
49061
  case "api": {
47703
49062
  const method = parsed.positional[0];
47704
49063
  if (!HTTP_METHOD.test(method))