@deepraxis/cli 0.2.2-dev.1b23ee0 → 0.2.2-dev.29dd643

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 +10 -2
  2. package/dist/praxis.js +1783 -35
  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",
@@ -29171,6 +29172,64 @@ for more details.`
29171
29172
  ],
29172
29173
  query: []
29173
29174
  },
29175
+ {
29176
+ resource: "studio.works.drafts.renditions",
29177
+ method: "create",
29178
+ summary: "Create a rendition of a draft for a platform",
29179
+ description: "Create a rendition: the form of one draft that a platform receives, such as a Xiaohongshu card set, a DOCX file or a Markdown file. Read the platform first with the platform call and pass its versioned key; pass a theme only to override the platform's default layout. Pass render true to render in the same call and read render_state and issues in the answer; without it the rendition starts as pending and the render call produces it. Rendering a Xiaohongshu card set is billed by Browser Rendering time (meter browser_ms, product studio-render); DOCX and Markdown renditions are not billed. A draft with no body renders as invalid with a draft_empty issue, and an unavailable render service leaves render_state failed with a render_unavailable issue, so repeat the render call later. Send a request_id to make a repeated call return the first rendition instead of creating another. Next, publish the rendition to export it.",
29180
+ http: "POST",
29181
+ path: "/studio/v1/works/{work}/drafts/{draft}/renditions",
29182
+ streaming: "no",
29183
+ pagination: false,
29184
+ pathParams: [
29185
+ {
29186
+ name: "work",
29187
+ sdkName: "work",
29188
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29189
+ },
29190
+ {
29191
+ name: "draft",
29192
+ sdkName: "draft",
29193
+ description: "Draft being addressed, either its in-work key such as novel or its drf_ identifier; a key renamed earlier still resolves through its previous value."
29194
+ }
29195
+ ],
29196
+ query: [],
29197
+ body: {
29198
+ required: true,
29199
+ fields: [
29200
+ {
29201
+ name: "platform",
29202
+ type: "string",
29203
+ required: true,
29204
+ description: "Versioned platform key from the platform list. Export platforms today are markdown@1, docx@1 and xiaohongshu@1; a platform that only publishes to an account answers PLATFORM_NOT_AVAILABLE."
29205
+ },
29206
+ {
29207
+ name: "theme",
29208
+ type: "string",
29209
+ required: false,
29210
+ description: "Theme to render with, a thm_ identifier or a built-in key from the theme list; omit it to use the platform default."
29211
+ },
29212
+ {
29213
+ name: "settings",
29214
+ type: "object",
29215
+ required: false,
29216
+ description: "Per-rendition settings; each platform reads only the settings that apply to it and ignores the rest."
29217
+ },
29218
+ {
29219
+ name: "render",
29220
+ type: "boolean",
29221
+ required: false,
29222
+ description: "Whether to render in the same call. True returns a rendition that is already rendered, invalid or failed; false or omitted returns it pending, to be rendered by the render operation."
29223
+ },
29224
+ {
29225
+ name: "request_id",
29226
+ type: "string",
29227
+ required: false,
29228
+ description: "Caller-chosen key that makes a repeated create return the first rendition instead of making another; use a new value for each distinct rendition."
29229
+ }
29230
+ ]
29231
+ }
29232
+ },
29174
29233
  {
29175
29234
  resource: "studio.works.drafts",
29176
29235
  method: "retrieveReview",
@@ -29424,6 +29483,212 @@ for more details.`
29424
29483
  ]
29425
29484
  }
29426
29485
  },
29486
+ {
29487
+ resource: "studio.works.renditions",
29488
+ method: "list",
29489
+ summary: "List the renditions of a work",
29490
+ description: "List the renditions of one work, each with its platform, render state, stale flag and publish state. Pass draft to see only the renditions of one draft. Use it to find the rendition to publish or to render again, and read stale before exporting: a stale rendition was built from an older draft and cannot be exported until the render call has rebuilt it. The answer is one page; keep following next_page_token while it is present.",
29491
+ http: "GET",
29492
+ path: "/studio/v1/works/{work}/renditions",
29493
+ streaming: "no",
29494
+ pagination: false,
29495
+ pathParams: [
29496
+ {
29497
+ name: "work",
29498
+ sdkName: "work",
29499
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29500
+ }
29501
+ ],
29502
+ query: [
29503
+ {
29504
+ name: "draft",
29505
+ type: "string",
29506
+ required: false,
29507
+ description: "Draft key such as novel or its drf_ identifier; when given, only the renditions of that draft are returned. Omit it to list the renditions of every draft in the work."
29508
+ },
29509
+ {
29510
+ name: "page_size",
29511
+ type: "integer",
29512
+ required: false,
29513
+ description: "How many items this page returns, 1 to 100; omitted uses the service default. Treat the answer as one page, not the whole set, and keep following next_page_token while it is present."
29514
+ },
29515
+ {
29516
+ name: "page_token",
29517
+ type: "string",
29518
+ required: false,
29519
+ description: "Cursor from the previous answer's next_page_token; it is opaque, so pass it back unchanged and never build one from an id or an offset."
29520
+ }
29521
+ ]
29522
+ },
29523
+ {
29524
+ resource: "studio.works.renditions",
29525
+ method: "delete",
29526
+ summary: "Delete a rendition",
29527
+ description: "Delete a rendition and stop listing it. The draft it was built from is untouched, and a new rendition can be created from it at any time. Files already downloaded from an earlier export are not affected. Use it to clear a failed or abandoned rendition; to refresh one, call the render operation instead.",
29528
+ http: "DELETE",
29529
+ path: "/studio/v1/works/{work}/renditions/{rendition}",
29530
+ streaming: "no",
29531
+ pagination: false,
29532
+ pathParams: [
29533
+ {
29534
+ name: "work",
29535
+ sdkName: "work",
29536
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29537
+ },
29538
+ {
29539
+ name: "rendition",
29540
+ sdkName: "rendition",
29541
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29542
+ }
29543
+ ],
29544
+ query: []
29545
+ },
29546
+ {
29547
+ resource: "studio.works.renditions",
29548
+ method: "retrieve",
29549
+ summary: "Read one rendition",
29550
+ description: "Read one rendition in full: its render state, the validation issues the render found, the parts (one per card page or thread post), the files it produced and its publish state. Call it after create, render or publish to see the outcome, because a render that finished invalid or failed is reported here and not as an HTTP error. stale is true when the draft has changed since source_revision; call the render operation before exporting a stale rendition.",
29551
+ http: "GET",
29552
+ path: "/studio/v1/works/{work}/renditions/{rendition}",
29553
+ streaming: "no",
29554
+ pagination: false,
29555
+ pathParams: [
29556
+ {
29557
+ name: "work",
29558
+ sdkName: "work",
29559
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29560
+ },
29561
+ {
29562
+ name: "rendition",
29563
+ sdkName: "rendition",
29564
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29565
+ }
29566
+ ],
29567
+ query: []
29568
+ },
29569
+ {
29570
+ resource: "studio.works.renditions",
29571
+ method: "update",
29572
+ summary: "Change the theme or settings of a rendition",
29573
+ description: "Change a rendition's theme or settings. Send update_mask naming exactly the fields you change, such as theme or settings; a field left out keeps its value. The produced files are not rebuilt by this call, so call the render operation afterwards to apply the change. A rendition whose export or publish has started is locked and answers RENDITION_PUBLISH_LOCKED; create a new rendition for new content.",
29574
+ http: "PATCH",
29575
+ path: "/studio/v1/works/{work}/renditions/{rendition}",
29576
+ streaming: "no",
29577
+ pagination: false,
29578
+ pathParams: [
29579
+ {
29580
+ name: "work",
29581
+ sdkName: "work",
29582
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29583
+ },
29584
+ {
29585
+ name: "rendition",
29586
+ sdkName: "rendition",
29587
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29588
+ }
29589
+ ],
29590
+ query: [],
29591
+ body: {
29592
+ required: true,
29593
+ fields: [
29594
+ {
29595
+ name: "update_mask",
29596
+ type: "array",
29597
+ itemType: "string",
29598
+ required: true,
29599
+ description: "Field paths this call changes: theme, settings or both; a field left out keeps its value."
29600
+ },
29601
+ {
29602
+ name: "theme",
29603
+ type: "string",
29604
+ required: false,
29605
+ description: "New theme, a thm_ identifier or a built-in key, used when theme is named in the update mask; render again to apply it."
29606
+ },
29607
+ {
29608
+ name: "settings",
29609
+ type: "object",
29610
+ required: false,
29611
+ description: "Per-rendition settings; each platform reads only the settings that apply to it and ignores the rest."
29612
+ }
29613
+ ]
29614
+ }
29615
+ },
29616
+ {
29617
+ resource: "studio.works.renditions",
29618
+ method: "retrieveContent",
29619
+ summary: "Get a download URL for a rendition file",
29620
+ description: "Get a signed, short-lived URL to download what a rendition produced. Without part it points to the rendition's own first file: the ZIP of pages for a card rendition, the DOCX for docx@1. With part it points to that part's first file, such as one card PNG; a part that has no file, or a rendition not rendered yet, answers RENDITION_NOT_RENDERED, and an index no part has answers INVALID_PARAMS. Call it after a successful render or export, download the url before expire_time, and call again for a fresh one when it has expired. The URL is a credential: do not store or share it.",
29621
+ http: "GET",
29622
+ path: "/studio/v1/works/{work}/renditions/{rendition}/content",
29623
+ streaming: "no",
29624
+ pagination: false,
29625
+ pathParams: [
29626
+ {
29627
+ name: "work",
29628
+ sdkName: "work",
29629
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29630
+ },
29631
+ {
29632
+ name: "rendition",
29633
+ sdkName: "rendition",
29634
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29635
+ }
29636
+ ],
29637
+ query: [
29638
+ {
29639
+ name: "part",
29640
+ type: "integer",
29641
+ required: false,
29642
+ description: "Index of the part to download, the index value of an entry in the rendition's parts list; omit it to get the rendition's own first file."
29643
+ }
29644
+ ]
29645
+ },
29646
+ {
29647
+ resource: "studio.works.renditions",
29648
+ method: "publish",
29649
+ summary: "Export a rendition",
29650
+ description: "Export a rendition for the platforms that deliver a file: markdown@1, docx@1 and xiaohongshu@1 end with publish.state exported, and a card rendition gains one ZIP of its pages in files. Publishing to a platform account such as X or WeChat is not available yet and answers PLATFORM_NOT_AVAILABLE; export instead. The rendition must be rendered, not stale and without error-level issues: RENDITION_NOT_RENDERED means call the render operation first, RENDITION_STALE means the draft changed so render again, RENDITION_INVALID means fix the draft problems listed in issues and render again. Exporting the same rendition twice at once answers REVISION_CONFLICT; retry shortly. Next, call the content operation to download the file.",
29651
+ http: "POST",
29652
+ path: "/studio/v1/works/{work}/renditions/{rendition}:publish",
29653
+ streaming: "no",
29654
+ pagination: false,
29655
+ pathParams: [
29656
+ {
29657
+ name: "work",
29658
+ sdkName: "work",
29659
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29660
+ },
29661
+ {
29662
+ name: "rendition",
29663
+ sdkName: "rendition",
29664
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29665
+ }
29666
+ ],
29667
+ query: []
29668
+ },
29669
+ {
29670
+ resource: "studio.works.renditions",
29671
+ method: "render",
29672
+ summary: "Render a rendition again from the current draft",
29673
+ description: "Render the rendition from the draft as it is now, replacing its parts and files and clearing stale. Call it after the draft changed, after a theme or settings change, or after a failed render. The answer carries render_state: rendered, invalid when the draft has an error-level issue (for example draft_empty on a draft with no body), or failed when the render service was unavailable (issue render_unavailable; repeat later). A render does not fail the HTTP call for those outcomes, so read render_state and issues. Rendering a Xiaohongshu card set is billed by Browser Rendering time (meter browser_ms, product studio-render); DOCX and Markdown are not billed. Rendering the same rendition twice at once answers REVISION_CONFLICT; retry shortly. Next, publish the rendition to export it.",
29674
+ http: "POST",
29675
+ path: "/studio/v1/works/{work}/renditions/{rendition}:render",
29676
+ streaming: "no",
29677
+ pagination: false,
29678
+ pathParams: [
29679
+ {
29680
+ name: "work",
29681
+ sdkName: "work",
29682
+ description: "The work being addressed, either its organization-unique slug or its wk_ identifier; a slug case is what a person would say, and a renamed slug still resolves through its old value."
29683
+ },
29684
+ {
29685
+ name: "rendition",
29686
+ sdkName: "rendition",
29687
+ description: "Rendition being addressed, by its rnd_ identifier from the rendition list or from the create answer."
29688
+ }
29689
+ ],
29690
+ query: []
29691
+ },
29427
29692
  {
29428
29693
  resource: "studio.works.units",
29429
29694
  method: "retrieve",
@@ -40791,6 +41056,118 @@ var studioThemesUpdate = (options) => (options.client ?? client).patch({
40791
41056
  ...options.headers
40792
41057
  }
40793
41058
  });
41059
+ var studioRenditionsCreate = (options) => (options.client ?? client).post({
41060
+ security: [{
41061
+ key: "BearerAuth",
41062
+ scheme: "bearer",
41063
+ type: "http"
41064
+ }, {
41065
+ key: "ApiKeyAuth",
41066
+ name: "X-API-Key",
41067
+ type: "apiKey"
41068
+ }],
41069
+ url: "/studio/v1/works/{work}/drafts/{draft}/renditions",
41070
+ ...options,
41071
+ headers: {
41072
+ "Content-Type": "application/json",
41073
+ ...options.headers
41074
+ }
41075
+ });
41076
+ var studioRenditionsList = (options) => (options.client ?? client).get({
41077
+ security: [{
41078
+ key: "BearerAuth",
41079
+ scheme: "bearer",
41080
+ type: "http"
41081
+ }, {
41082
+ key: "ApiKeyAuth",
41083
+ name: "X-API-Key",
41084
+ type: "apiKey"
41085
+ }],
41086
+ url: "/studio/v1/works/{work}/renditions",
41087
+ ...options
41088
+ });
41089
+ var studioRenditionsDelete = (options) => (options.client ?? client).delete({
41090
+ security: [{
41091
+ key: "BearerAuth",
41092
+ scheme: "bearer",
41093
+ type: "http"
41094
+ }, {
41095
+ key: "ApiKeyAuth",
41096
+ name: "X-API-Key",
41097
+ type: "apiKey"
41098
+ }],
41099
+ url: "/studio/v1/works/{work}/renditions/{rendition}",
41100
+ ...options
41101
+ });
41102
+ var studioRenditionsGet = (options) => (options.client ?? client).get({
41103
+ security: [{
41104
+ key: "BearerAuth",
41105
+ scheme: "bearer",
41106
+ type: "http"
41107
+ }, {
41108
+ key: "ApiKeyAuth",
41109
+ name: "X-API-Key",
41110
+ type: "apiKey"
41111
+ }],
41112
+ url: "/studio/v1/works/{work}/renditions/{rendition}",
41113
+ ...options
41114
+ });
41115
+ var studioRenditionsUpdate = (options) => (options.client ?? client).patch({
41116
+ security: [{
41117
+ key: "BearerAuth",
41118
+ scheme: "bearer",
41119
+ type: "http"
41120
+ }, {
41121
+ key: "ApiKeyAuth",
41122
+ name: "X-API-Key",
41123
+ type: "apiKey"
41124
+ }],
41125
+ url: "/studio/v1/works/{work}/renditions/{rendition}",
41126
+ ...options,
41127
+ headers: {
41128
+ "Content-Type": "application/json",
41129
+ ...options.headers
41130
+ }
41131
+ });
41132
+ var studioRenditionsRender = (options) => (options.client ?? client).post({
41133
+ security: [{
41134
+ key: "BearerAuth",
41135
+ scheme: "bearer",
41136
+ type: "http"
41137
+ }, {
41138
+ key: "ApiKeyAuth",
41139
+ name: "X-API-Key",
41140
+ type: "apiKey"
41141
+ }],
41142
+ url: "/studio/v1/works/{work}/renditions/{rendition}:render",
41143
+ ...options
41144
+ });
41145
+ var studioRenditionsPublish = (options) => (options.client ?? client).post({
41146
+ security: [{
41147
+ key: "BearerAuth",
41148
+ scheme: "bearer",
41149
+ type: "http"
41150
+ }, {
41151
+ key: "ApiKeyAuth",
41152
+ name: "X-API-Key",
41153
+ type: "apiKey"
41154
+ }],
41155
+ url: "/studio/v1/works/{work}/renditions/{rendition}:publish",
41156
+ ...options
41157
+ });
41158
+ var studioRenditionsContentUrl = (options) => (options.client ?? client).get({
41159
+ security: [{
41160
+ key: "BearerAuth",
41161
+ scheme: "bearer",
41162
+ type: "http"
41163
+ }, {
41164
+ key: "ApiKeyAuth",
41165
+ name: "X-API-Key",
41166
+ type: "apiKey"
41167
+ }],
41168
+ url: "/studio/v1/works/{work}/renditions/{rendition}/content",
41169
+ ...options
41170
+ });
40794
41171
  var vaultListVaults = (options) => (options?.client ?? client).get({
40795
41172
  security: [{
40796
41173
  key: "vault-bearerAuth",
@@ -42746,6 +43123,9 @@ function createStudio(transport) {
42746
43123
  create: bind(transport, studioDraftsCreate),
42747
43124
  list: bind(transport, studioDraftsList),
42748
43125
  rebase: bind(transport, studioDraftsRebase),
43126
+ renditions: {
43127
+ create: bind(transport, studioRenditionsCreate)
43128
+ },
42749
43129
  retrieve: bind(transport, studioDraftsGet),
42750
43130
  retrieveExport: bind(transport, studioDraftsExport),
42751
43131
  retrieveOutline: bind(transport, studioDraftsOutline),
@@ -42761,6 +43141,15 @@ function createStudio(transport) {
42761
43141
  update: bind(transport, studioDraftsUpdate)
42762
43142
  },
42763
43143
  list: bind(transport, studioWorksList),
43144
+ renditions: {
43145
+ delete: bind(transport, studioRenditionsDelete),
43146
+ list: bind(transport, studioRenditionsList),
43147
+ publish: bind(transport, studioRenditionsPublish),
43148
+ render: bind(transport, studioRenditionsRender),
43149
+ retrieve: bind(transport, studioRenditionsGet),
43150
+ retrieveContent: bind(transport, studioRenditionsContentUrl),
43151
+ update: bind(transport, studioRenditionsUpdate)
43152
+ },
42764
43153
  resolve: bind(transport, studioWorksResolve),
42765
43154
  retrieve: bind(transport, studioWorksGet),
42766
43155
  units: {
@@ -44735,6 +45124,7 @@ var workflows = [
44735
45124
  { 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
45125
  { 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
45126
  { 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" },
45127
+ { 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
45128
  { words: ["skill"], usage: "skill [--install <dir>]", summary: "Print the AI skill, or write <dir>/praxis-cli/SKILL.md." }
44739
45129
  ];
44740
45130
  var workflowNouns = [...new Set(workflows.filter((w) => w.words.length > 1).map((w) => w.words[0]))];
@@ -45305,7 +45695,22 @@ function skillDocument(commands) {
45305
45695
  "- `--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
45696
  "- The run waits by default and polls every 5s; `--no-wait` returns as soon as the run exists, with `result` still `pending`.",
45307
45697
  "- 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`."
45698
+ "- The run URL is on the Console of the environment the CLI talks to; the run id is also on stdout with `--json`.",
45699
+ "",
45700
+ "## canvas import (workflow)",
45701
+ "",
45702
+ "Import a Pencil `.pen` file as a canvas, uploading the images it references first:",
45703
+ "",
45704
+ "- 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.",
45705
+ "- Node ids, component references, variables and themes are preserved as written: the file imports as it is, not as a redraw.",
45706
+ "- `--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`.",
45707
+ "- `--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`.",
45708
+ "- 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.",
45709
+ "- 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.",
45710
+ "- `--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.",
45711
+ "- 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).",
45712
+ "- Exit code 0 means the import completed, warnings included; 2 is a usage error (missing `--yes` with `--canvas`, an unreadable or non-`.pen` file).",
45713
+ "- `--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
45714
  ];
45310
45715
  let domain;
45311
45716
  for (const command of commands) {
@@ -46121,6 +46526,13 @@ function workerNameOf(config) {
46121
46526
  const name = config?.name;
46122
46527
  return typeof name === "string" && name !== "" ? name : undefined;
46123
46528
  }
46529
+ function productionBlockOf(config) {
46530
+ const env = config?.env;
46531
+ if (env === null || typeof env !== "object")
46532
+ return;
46533
+ const block = env.production;
46534
+ return block !== null && typeof block === "object" ? block : undefined;
46535
+ }
46124
46536
  function bindingReferences(config) {
46125
46537
  const references = [];
46126
46538
  const own = workerNameOf(config);
@@ -46200,18 +46612,23 @@ function packageManifestOf(text) {
46200
46612
  return null;
46201
46613
  const name = parsed.name;
46202
46614
  const dependencies = new Set;
46203
- for (const field of ["dependencies", "devDependencies"]) {
46615
+ const devOnly = new Set;
46616
+ for (const field of ["dependencies", "peerDependencies", "optionalDependencies", "devDependencies"]) {
46204
46617
  const block = parsed[field];
46205
46618
  if (block === null || typeof block !== "object" || Array.isArray(block))
46206
46619
  continue;
46207
46620
  for (const [dependency, version] of Object.entries(block)) {
46208
- if (typeof version === "string" && version.startsWith("workspace:"))
46209
- dependencies.add(dependency);
46621
+ if (typeof version !== "string" || !version.startsWith("workspace:") || dependencies.has(dependency))
46622
+ continue;
46623
+ dependencies.add(dependency);
46624
+ if (field === "devDependencies")
46625
+ devOnly.add(dependency);
46210
46626
  }
46211
46627
  }
46212
46628
  return {
46213
46629
  ...typeof name === "string" && name !== "" ? { name } : {},
46214
- workspaceDependencies: [...dependencies].sort()
46630
+ workspaceDependencies: [...dependencies].sort(),
46631
+ devOnlyWorkspaceDependencies: [...devOnly].sort()
46215
46632
  };
46216
46633
  }
46217
46634
  function lifecycleOf(text) {
@@ -46390,7 +46807,8 @@ var WORKSPACE_PASSES = Symbol("deploy-core.workspace-passes");
46390
46807
  async function readWorkspacesOnce(facts, options) {
46391
46808
  const tree = new Set(facts.tree);
46392
46809
  const index = await workspaceIndexOf(facts, options);
46393
- return await mapBounded(index.packages, READ_CONCURRENCY, async (entry) => {
46810
+ const limit = options.readConcurrency !== undefined && options.readConcurrency >= 1 ? Math.floor(options.readConcurrency) : READ_CONCURRENCY;
46811
+ return await mapBounded(index.packages, limit, async (entry) => {
46394
46812
  const manifest = manifestPathIn(entry.dir, tree);
46395
46813
  const [manifestText, configText] = await Promise.all([
46396
46814
  facts.read(entry.packageJson),
@@ -46405,7 +46823,8 @@ async function readWorkspacesOnce(facts, options) {
46405
46823
  config,
46406
46824
  ...workerNameOf(config) === undefined ? {} : { workerName: workerNameOf(config) },
46407
46825
  lifecycle: lifecycleOf(manifestText),
46408
- workspaceDependencies: pkg?.workspaceDependencies ?? []
46826
+ workspaceDependencies: pkg?.workspaceDependencies ?? [],
46827
+ devOnlyWorkspaceDependencies: pkg?.devOnlyWorkspaceDependencies ?? []
46409
46828
  };
46410
46829
  });
46411
46830
  }
@@ -46447,7 +46866,9 @@ function workspaceCloudflareProvider(options = {}) {
46447
46866
  name: workspace.packageName ?? (workspace.dir === "." ? "app" : workspace.dir.split("/").at(-1)),
46448
46867
  destination: "cloudflare",
46449
46868
  ...workspace.workerName === undefined ? {} : { workerName: workspace.workerName },
46450
- ...environments === undefined ? {} : { environments }
46869
+ ...environments === undefined ? {} : { environments },
46870
+ production: productionBlockOf(workspace.config) !== undefined,
46871
+ onTrain: lifecycle?.train !== false
46451
46872
  });
46452
46873
  }
46453
46874
  return { targets: [...partial.targets, ...targets] };
@@ -46496,19 +46917,50 @@ function closePlan(drafts, workspaces) {
46496
46917
  const configOf = new Map(workspaces.map((workspace) => [workspace.dir, workspace.config]));
46497
46918
  const edges = wranglerEdges(drafts.map((draft) => ({ id: draft.path, config: configOf.get(draft.path) ?? null })));
46498
46919
  const byName = directoriesOfPackageNames(workspaces);
46499
- const dependenciesOf = (dir) => workspaces.find((workspace) => workspace.dir === dir)?.workspaceDependencies ?? [];
46920
+ const dependenciesOf = (dir) => {
46921
+ const workspace = workspaces.find((entry) => entry.dir === dir);
46922
+ if (workspace === undefined)
46923
+ return [];
46924
+ const devOnly = new Set(workspace.devOnlyWorkspaceDependencies ?? []);
46925
+ return workspace.workspaceDependencies.filter((name) => {
46926
+ if (!devOnly.has(name))
46927
+ return true;
46928
+ const path = byName.get(name);
46929
+ return path === undefined || !isDeployToolDependency(name, path);
46930
+ });
46931
+ };
46500
46932
  return drafts.map((draft) => ({
46501
46933
  path: draft.path,
46502
46934
  name: draft.name,
46503
46935
  destination: draft.destination,
46504
46936
  dependsOn: edges.get(draft.path) ?? [],
46505
46937
  ...draft.environments === undefined ? {} : { environments: draft.environments },
46938
+ production: draft.production === true,
46939
+ onTrain: draft.onTrain !== false,
46506
46940
  workspaceDeps: workspaceClosureOf(draft.path, byName, dependenciesOf)
46507
46941
  })).sort((a, b) => a.path.localeCompare(b.path));
46508
46942
  }
46943
+ function isDeployToolDependency(name, path) {
46944
+ const directory = path.replace(/^(\.\/)+/, "").replace(/^\/+/, "").replace(/\/+$/, "");
46945
+ if (directory === "packages/mise" || directory.startsWith("packages/mise/"))
46946
+ return true;
46947
+ if (directory === "packages/testing" || directory.startsWith("packages/testing/"))
46948
+ return true;
46949
+ return name.startsWith("@mise/");
46950
+ }
46509
46951
  function targetsFor(plan, environment2) {
46510
46952
  return plan.targets.filter((target) => target.environments === undefined || target.environments.includes(environment2));
46511
46953
  }
46954
+ var TARGET_EXTERNAL_INPUTS = {
46955
+ "apps/docs": [
46956
+ "apps/api/openapi/openapi.yaml",
46957
+ "packages/praxis/rpc-kit/src/errors.ts",
46958
+ "services/agent/src/domain/error-codes.ts",
46959
+ ...["application", "database", "knowledge"].map((s) => `services/${s}/src/api/error-exit.ts`),
46960
+ ...["router", "vault", "browser", "search"].map((s) => `services/${s}/src/api/rpc-contract.ts`),
46961
+ ...["media", "automation", "sandbox", "file", "billing", "config", "eventbus", "lakehouse", "identity", "notification", "ops", "registry"].map((s) => `services/${s}/src/api/contract.ts`)
46962
+ ]
46963
+ };
46512
46964
  function diffTargets(plan, changedPaths) {
46513
46965
  const changed = new Set(changedPaths);
46514
46966
  const touches = (dir) => {
@@ -46520,7 +46972,8 @@ function diffTargets(plan, changedPaths) {
46520
46972
  return true;
46521
46973
  return false;
46522
46974
  };
46523
- return plan.targets.filter((target) => touches(target.path) || target.workspaceDeps.some(touches)).map((target) => target.path);
46975
+ const readsChangedInput = (dir) => (TARGET_EXTERNAL_INPUTS[dir] ?? []).some((file) => changed.has(file));
46976
+ return plan.targets.filter((target) => touches(target.path) || target.workspaceDeps.some(touches) || readsChangedInput(target.path) || target.workspaceDeps.some(readsChangedInput)).map((target) => target.path);
46524
46977
  }
46525
46978
  function layersOf(plan) {
46526
46979
  const paths = plan.targets.map((target) => target.path);
@@ -46690,6 +47143,1231 @@ async function devopsDeployPlan(args, ports) {
46690
47143
  ports.human(renderDeployPlan(view));
46691
47144
  }
46692
47145
 
47146
+ // src/commands/canvas-import.ts
47147
+ import { basename as basename2, dirname as dirname2, join as join5, resolve as resolve3 } from "node:path";
47148
+
47149
+ // ../../packages/canvas/document/src/types.ts
47150
+ class OpRejectedError extends Error {
47151
+ rejection;
47152
+ constructor(rejection) {
47153
+ super(`${rejection.code}: ${JSON.stringify(rejection)}`);
47154
+ this.rejection = rejection;
47155
+ }
47156
+ }
47157
+ var CONTAINER_TYPES = new Set(["frame", "group"]);
47158
+ // ../../packages/canvas/document/src/legacy-props.ts
47159
+ function ownIconProps(node2) {
47160
+ const out = { ...node2 };
47161
+ if ((node2.type === "icon" || node2.type === undefined) && "iconName" in node2) {
47162
+ if (!("icon" in node2))
47163
+ out.icon = node2.iconName;
47164
+ delete out.iconName;
47165
+ }
47166
+ return out;
47167
+ }
47168
+ function migrateLegacyIconProps(node2) {
47169
+ const out = ownIconProps(node2);
47170
+ if (node2.descendants && typeof node2.descendants === "object" && !Array.isArray(node2.descendants))
47171
+ out.descendants = Object.fromEntries(Object.entries(node2.descendants).map(([key, value]) => [
47172
+ key,
47173
+ value && typeof value === "object" && !Array.isArray(value) ? migrateLegacyIconProps(value) : value
47174
+ ]));
47175
+ if (Array.isArray(node2.children))
47176
+ out.children = node2.children.map((child) => migrateLegacyIconProps(child));
47177
+ return out;
47178
+ }
47179
+ function migrateLegacyProps(node2) {
47180
+ const out = ownIconProps(node2);
47181
+ const stroke = node2.stroke;
47182
+ if (stroke && typeof stroke === "object" && !Array.isArray(stroke) && "fill" in stroke) {
47183
+ const old = stroke;
47184
+ out.stroke = old.fill;
47185
+ if (!("strokeWidth" in node2) && "thickness" in old)
47186
+ out.strokeWidth = old.thickness;
47187
+ if (!("strokeAlignment" in node2) && "align" in old) {
47188
+ out.strokeAlignment = old.align === "inside" ? "inner" : old.align === "outside" ? "outer" : old.align;
47189
+ }
47190
+ }
47191
+ if (Array.isArray(node2.children))
47192
+ out.children = node2.children.map((child) => migrateLegacyProps(child));
47193
+ if (node2.descendants && typeof node2.descendants === "object" && !Array.isArray(node2.descendants))
47194
+ out.descendants = Object.fromEntries(Object.entries(node2.descendants).map(([key, value]) => [
47195
+ key,
47196
+ value && typeof value === "object" && !Array.isArray(value) ? migrateLegacyProps(value) : value
47197
+ ]));
47198
+ return out;
47199
+ }
47200
+
47201
+ // ../../packages/canvas/document/src/store.ts
47202
+ var DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
47203
+ var BASE = DIGITS.length;
47204
+ function midpoint(a, b) {
47205
+ if (b !== null) {
47206
+ let n = 0;
47207
+ while ((a[n] ?? "0") === b[n])
47208
+ n++;
47209
+ if (n > 0)
47210
+ return b.slice(0, n) + midpoint(a.slice(n), b.slice(n));
47211
+ }
47212
+ const da = a ? DIGITS.indexOf(a[0]) : 0;
47213
+ const db = b !== null ? DIGITS.indexOf(b[0]) : BASE;
47214
+ if (db - da > 1)
47215
+ return DIGITS[Math.floor((da + db) / 2)];
47216
+ if (b !== null && b.length > 1)
47217
+ return b.slice(0, 1);
47218
+ return DIGITS[da] + midpoint(a.slice(1), null);
47219
+ }
47220
+ function between(a, b) {
47221
+ return midpoint(a ?? "", b);
47222
+ }
47223
+ function spacedKeys(n) {
47224
+ let width = 1;
47225
+ while (BASE ** width < n + 2)
47226
+ width++;
47227
+ const keys = [];
47228
+ for (let i = 1;i <= n; i++) {
47229
+ let v = i;
47230
+ let s = "";
47231
+ for (let d = 0;d < width; d++) {
47232
+ s = DIGITS[v % BASE] + s;
47233
+ v = Math.floor(v / BASE);
47234
+ }
47235
+ keys.push(s + "V");
47236
+ }
47237
+ return keys;
47238
+ }
47239
+
47240
+ class MapNodeStore {
47241
+ nodes = new Map;
47242
+ kids = new Map;
47243
+ vars = {};
47244
+ themeAxes = {};
47245
+ rev = 0;
47246
+ get(id) {
47247
+ return this.nodes.get(id);
47248
+ }
47249
+ children(id) {
47250
+ return this.kids.get(id) ?? [];
47251
+ }
47252
+ variables() {
47253
+ return this.vars;
47254
+ }
47255
+ themes() {
47256
+ return this.themeAxes;
47257
+ }
47258
+ revision() {
47259
+ return this.rev;
47260
+ }
47261
+ unlink(n) {
47262
+ const list = this.kids.get(n.parent);
47263
+ if (!list)
47264
+ return;
47265
+ const i = list.indexOf(n.id);
47266
+ if (i >= 0)
47267
+ list.splice(i, 1);
47268
+ }
47269
+ link(n) {
47270
+ let list = this.kids.get(n.parent);
47271
+ if (!list)
47272
+ this.kids.set(n.parent, list = []);
47273
+ let lo = 0;
47274
+ let hi = list.length;
47275
+ if (hi && this.nodes.get(list[hi - 1]).ord < n.ord)
47276
+ lo = hi;
47277
+ while (lo < hi) {
47278
+ const mid = lo + hi >> 1;
47279
+ const o = this.nodes.get(list[mid]).ord;
47280
+ if (o < n.ord || o === n.ord && list[mid] < n.id)
47281
+ lo = mid + 1;
47282
+ else
47283
+ hi = mid;
47284
+ }
47285
+ list.splice(lo, 0, n.id);
47286
+ }
47287
+ put(node2) {
47288
+ const prev = this.nodes.get(node2.id);
47289
+ if (prev && (prev.parent !== node2.parent || prev.ord !== node2.ord))
47290
+ this.unlink(prev);
47291
+ this.nodes.set(node2.id, node2);
47292
+ if (!prev || prev.parent !== node2.parent || prev.ord !== node2.ord)
47293
+ this.link(node2);
47294
+ }
47295
+ remove(id) {
47296
+ const prev = this.nodes.get(id);
47297
+ if (!prev)
47298
+ return;
47299
+ this.unlink(prev);
47300
+ this.kids.delete(id);
47301
+ this.nodes.delete(id);
47302
+ }
47303
+ setVariables(vars, themes) {
47304
+ this.vars = vars;
47305
+ this.themeAxes = themes;
47306
+ }
47307
+ setRevision(rev) {
47308
+ this.rev = rev;
47309
+ }
47310
+ size() {
47311
+ return this.nodes.size;
47312
+ }
47313
+ reindex() {}
47314
+ }
47315
+ function ownProps(node2) {
47316
+ const { children: _c, ...rest } = node2;
47317
+ return rest;
47318
+ }
47319
+ function flatten(nodes, parent, top, rev, out = []) {
47320
+ const keys = spacedKeys(nodes.length);
47321
+ nodes.forEach((n, i) => {
47322
+ const t = top ?? n.id;
47323
+ const props = ownProps(n);
47324
+ const ord = typeof props.__ord === "string" ? props.__ord : keys[i];
47325
+ delete props.__ord;
47326
+ out.push({ id: n.id, parent, ord, top: t, props, rev });
47327
+ if (Array.isArray(n.children) && n.children.length)
47328
+ flatten(n.children, n.id, t, rev, out);
47329
+ });
47330
+ return out;
47331
+ }
47332
+ function subtree(store, id, depth = Infinity, withOrd = false) {
47333
+ const row = store.get(id);
47334
+ if (!row)
47335
+ throw new Error(`node ${id} not found`);
47336
+ const node2 = migrateLegacyIconProps(row.props);
47337
+ if (withOrd)
47338
+ node2.__ord = row.ord;
47339
+ const kids = store.children(id);
47340
+ if (kids.length) {
47341
+ if (depth <= 0)
47342
+ node2.children = "...";
47343
+ else
47344
+ node2.children = kids.map((k) => subtree(store, k, depth - 1, withOrd));
47345
+ }
47346
+ return node2;
47347
+ }
47348
+ // ../../packages/canvas/document/src/apply.ts
47349
+ function applyOp(store, op, rev) {
47350
+ switch (op.op) {
47351
+ case "insert": {
47352
+ const top = op.parent === null ? null : store.get(op.parent).top;
47353
+ const rows = flatten([op.node], op.parent, top, rev);
47354
+ rows[0] = { ...rows[0], ord: op.ord };
47355
+ for (const r of rows)
47356
+ store.put(r);
47357
+ return [rows[0].top];
47358
+ }
47359
+ case "update": {
47360
+ const row = store.get(op.id);
47361
+ const props = { ...row.props };
47362
+ for (const [k, v] of Object.entries(op.patch)) {
47363
+ if (v === undefined || v === null)
47364
+ delete props[k];
47365
+ else
47366
+ props[k] = v;
47367
+ }
47368
+ store.put({ ...row, props, rev });
47369
+ return [row.top];
47370
+ }
47371
+ case "delete": {
47372
+ const row = store.get(op.id);
47373
+ removeSubtree(store, op.id);
47374
+ return [row.top];
47375
+ }
47376
+ case "move": {
47377
+ const row = store.get(op.id);
47378
+ const oldTop = row.top;
47379
+ const newTop = op.parent === null ? op.id : store.get(op.parent).top;
47380
+ store.put({ ...row, parent: op.parent, ord: op.ord, top: newTop, rev });
47381
+ if (newTop !== oldTop)
47382
+ retop(store, op.id, newTop, rev);
47383
+ return oldTop === newTop ? [newTop] : [oldTop, newTop];
47384
+ }
47385
+ case "setVariables": {
47386
+ const vars = op.replace ? op.variables : { ...store.variables(), ...op.variables };
47387
+ const themes = { ...store.themes() };
47388
+ for (const [axis, values] of Object.entries(op.themes)) {
47389
+ const cur = themes[axis] ?? [];
47390
+ themes[axis] = [...cur, ...values.filter((v) => !cur.includes(v))];
47391
+ }
47392
+ store.setVariables(vars, themes);
47393
+ return [];
47394
+ }
47395
+ }
47396
+ }
47397
+ function removeSubtree(store, id) {
47398
+ for (const c of store.children(id))
47399
+ removeSubtree(store, c);
47400
+ store.remove(id);
47401
+ }
47402
+ function retop(store, id, top, rev) {
47403
+ for (const c of store.children(id)) {
47404
+ const row = store.get(c);
47405
+ store.put({ ...row, top, rev });
47406
+ retop(store, c, top, rev);
47407
+ }
47408
+ }
47409
+ // ../../packages/canvas/document/src/expand.ts
47410
+ function defaultTheme(themes) {
47411
+ const t = {};
47412
+ for (const [axis, values] of Object.entries(themes))
47413
+ if (values.length)
47414
+ t[axis] = values[0];
47415
+ return t;
47416
+ }
47417
+ function resolveVariable(name, vars, theme, depth = 0) {
47418
+ const def = vars[name];
47419
+ if (!def || depth > 8)
47420
+ return;
47421
+ let v;
47422
+ if (Array.isArray(def.value)) {
47423
+ let best;
47424
+ for (const e of def.value) {
47425
+ const keys = Object.keys(e.theme ?? {});
47426
+ if (keys.every((k) => theme[k] === e.theme[k]) && (!best || keys.length > best.score))
47427
+ best = { value: e.value, score: keys.length };
47428
+ }
47429
+ v = best?.value ?? def.value[0]?.value;
47430
+ } else
47431
+ v = def.value;
47432
+ if (typeof v === "string" && v.startsWith("$") && vars[v.slice(1)])
47433
+ return resolveVariable(v.slice(1), vars, theme, depth + 1);
47434
+ return v;
47435
+ }
47436
+ function resolveDeep(value, vars, theme) {
47437
+ if (typeof value === "string") {
47438
+ if (value.startsWith("$") && vars[value.slice(1)] !== undefined)
47439
+ return resolveVariable(value.slice(1), vars, theme);
47440
+ return value;
47441
+ }
47442
+ if (Array.isArray(value))
47443
+ return value.map((v) => resolveDeep(v, vars, theme));
47444
+ if (value && typeof value === "object") {
47445
+ const out = {};
47446
+ for (const [k, v] of Object.entries(value))
47447
+ out[k] = resolveDeep(v, vars, theme);
47448
+ return out;
47449
+ }
47450
+ return value;
47451
+ }
47452
+ var SKIP_RESOLVE = new Set(["id", "type", "ref", "descendants", "name", "content", "children"]);
47453
+ function resolveProps(props, vars, theme) {
47454
+ const out = {};
47455
+ for (const [k, v] of Object.entries(props))
47456
+ out[k] = SKIP_RESOLVE.has(k) ? v : resolveDeep(v, vars, theme);
47457
+ if (typeof props.content === "string" && props.content.startsWith("$") && vars[props.content.slice(1)] !== undefined)
47458
+ out.content = String(resolveVariable(props.content.slice(1), vars, theme));
47459
+ return out;
47460
+ }
47461
+ function propsOf(store, src) {
47462
+ if (src.kind === "store")
47463
+ return store.get(src.id)?.props;
47464
+ const { children: _c, ...rest } = src.node;
47465
+ return rest;
47466
+ }
47467
+ function childrenOf(store, src) {
47468
+ if (src.kind === "store")
47469
+ return store.children(src.id).map((id) => ({ kind: "store", id }));
47470
+ return (src.node.children ?? []).map((node2) => ({ kind: "inline", node: node2 }));
47471
+ }
47472
+ function expandNode(store, id, parentTheme) {
47473
+ return expandSrc({ store, vars: store.variables(), stack: [] }, { kind: "store", id }, parentTheme, null, {});
47474
+ }
47475
+ function expandSrc(ctx, src, parentTheme, pathPrefix, overrides) {
47476
+ let props = propsOf(ctx.store, src);
47477
+ if (!props)
47478
+ return null;
47479
+ const ownId = props.id;
47480
+ const path = pathPrefix ? `${pathPrefix}/${ownId}` : ownId;
47481
+ const ov = pathPrefix ? overrides[ownId] : undefined;
47482
+ if (ov && typeof ov.type === "string") {
47483
+ const repl = ov;
47484
+ const replId = typeof repl.id === "string" ? repl.id : ownId;
47485
+ const e = expandSrc(ctx, { kind: "inline", node: { ...repl, id: replId } }, parentTheme, null, {});
47486
+ return e ? { ...e, role: "instance-child" } : null;
47487
+ }
47488
+ if (ov)
47489
+ props = { ...props, ...ov };
47490
+ const theme = props.theme && typeof props.theme === "object" ? { ...parentTheme, ...props.theme } : parentTheme;
47491
+ if (props.type === "ref")
47492
+ return expandRef(ctx, props, path, theme, pathPrefix ? childOverrides(overrides, ownId) : {});
47493
+ const resolved = resolveProps(props, ctx.vars, theme);
47494
+ const children = [];
47495
+ for (const c of childrenOf(ctx.store, src)) {
47496
+ const e = expandSrc(ctx, c, theme, pathPrefix, overrides);
47497
+ if (e)
47498
+ children.push(e);
47499
+ }
47500
+ return {
47501
+ path,
47502
+ type: props.type,
47503
+ props: resolved,
47504
+ children,
47505
+ theme,
47506
+ role: pathPrefix ? "instance-child" : props.reusable ? "component" : "plain"
47507
+ };
47508
+ }
47509
+ function childOverrides(overrides, id) {
47510
+ const out = {};
47511
+ const prefix = id + "/";
47512
+ for (const [k, v] of Object.entries(overrides))
47513
+ if (k.startsWith(prefix))
47514
+ out[k.slice(prefix.length)] = v;
47515
+ return out;
47516
+ }
47517
+ function expandRef(ctx, ref, path, theme, inherited) {
47518
+ const target = ref.ref;
47519
+ const comp = ctx.store.get(target);
47520
+ if (!comp || ctx.stack.includes(target))
47521
+ return null;
47522
+ const descendants = { ...ref.descendants ?? {} };
47523
+ for (const [id, override] of Object.entries(inherited)) {
47524
+ descendants[id] = typeof override.type === "string" ? override : { ...descendants[id], ...override };
47525
+ }
47526
+ const { id: _i, type: _t, ref: _r, descendants: _d, reusable: _re, ...refOwn } = ref;
47527
+ const root = { ...comp.props, ...refOwn, id: ref.id };
47528
+ delete root.reusable;
47529
+ ctx.stack.push(target);
47530
+ const rootTheme = root.theme && typeof root.theme === "object" ? { ...theme, ...root.theme } : theme;
47531
+ const children = [];
47532
+ for (const c of ctx.store.children(target)) {
47533
+ const e = expandSrc(ctx, { kind: "store", id: c }, rootTheme, path, descendants);
47534
+ if (e)
47535
+ children.push(e);
47536
+ }
47537
+ ctx.stack.pop();
47538
+ return { path, type: root.type, props: resolveProps(root, ctx.vars, rootTheme), children, theme: rootTheme, role: "instance" };
47539
+ }
47540
+ // ../../packages/canvas/document/src/known-props.ts
47541
+ var ENTITY = "id type name context reusable theme enabled opacity flipX flipY layoutPosition metadata rotation x y children";
47542
+ var SIZE = "width height";
47543
+ var STROKE = "stroke strokeWidth strokeLinecap strokeLinejoin strokeAlignment";
47544
+ var EFFECTS = "effect";
47545
+ var GRAPHICS = `${EFFECTS} ${STROKE} fill`;
47546
+ var TEXT = "fontFamily fontSize fontWeight letterSpacing fontStyle underline lineHeight textAlign textAlignVertical strikethrough href";
47547
+ var LAYOUT = "layout gap layoutIncludeStroke padding justifyContent alignItems";
47548
+ var RECTANGLE = `${SIZE} ${GRAPHICS} cornerRadius`;
47549
+ var keys = (extra) => new Set(`${ENTITY} ${extra}`.split(/\s+/));
47550
+ var KNOWN_PROPS = {
47551
+ rectangle: keys(RECTANGLE),
47552
+ ellipse: keys(`${SIZE} ${GRAPHICS} innerRadius startAngle sweepAngle`),
47553
+ polygon: keys(`${SIZE} ${GRAPHICS} polygonCount cornerRadius`),
47554
+ path: keys(`${SIZE} ${GRAPHICS} fillRule geometry viewBox`),
47555
+ text: keys(`${SIZE} ${GRAPHICS} ${TEXT} content textGrowth`),
47556
+ frame: keys(`${RECTANGLE} ${LAYOUT} clip placeholder slot`),
47557
+ group: keys(EFFECTS),
47558
+ note: keys(`${SIZE} ${TEXT} content`),
47559
+ prompt: keys(`${SIZE} ${TEXT} content model`),
47560
+ context: keys(`${SIZE} ${TEXT} content`),
47561
+ icon: keys(`${SIZE} ${EFFECTS} library icon weight fill`),
47562
+ script: keys(`${SIZE} clip scriptUri inputs`),
47563
+ browser: keys(`${SIZE} ${EFFECTS} ${STROKE} url deviceId zoom scrollX scrollY cornerRadius`),
47564
+ ref: keys("ref descendants")
47565
+ };
47566
+ function unknownProperties(node2, type) {
47567
+ if (type === "ref")
47568
+ return [];
47569
+ const allowed = Object.hasOwn(KNOWN_PROPS, type) ? KNOWN_PROPS[type] : keys("");
47570
+ return Object.keys(node2).filter((key) => !key.startsWith("__") && !allowed.has(key));
47571
+ }
47572
+ function iconNameOf(node2) {
47573
+ for (const key of ["icon", "iconName"]) {
47574
+ const value = node2[key];
47575
+ if (typeof value === "string" && value.trim() !== "")
47576
+ return value;
47577
+ }
47578
+ return "";
47579
+ }
47580
+ function hasUnsupportedImageUrl(node2) {
47581
+ const invalid = (paint) => {
47582
+ if (Array.isArray(paint))
47583
+ return paint.some(invalid);
47584
+ if (!paint || typeof paint !== "object")
47585
+ return false;
47586
+ const fill = paint;
47587
+ return fill.type === "image" && (typeof fill.url !== "string" || !/^file-[0-9A-Za-z]{24}$/.test(fill.url));
47588
+ };
47589
+ return invalid(node2.fill) || invalid(node2.stroke);
47590
+ }
47591
+
47592
+ // ../../packages/canvas/document/src/execute-api.ts
47593
+ var LIMITS = { ops: 5000, printBytes: 64 * 1024, screenshots: 4 };
47594
+ var ID_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
47595
+ class ExecuteApi {
47596
+ store;
47597
+ rec;
47598
+ bounds;
47599
+ rev;
47600
+ random;
47601
+ document = "document";
47602
+ layoutCache = new Map;
47603
+ constructor(store, rec, bounds, rev, random = Math.random) {
47604
+ this.store = store;
47605
+ this.rec = rec;
47606
+ this.bounds = bounds;
47607
+ this.rev = rev;
47608
+ this.random = random;
47609
+ }
47610
+ mint() {
47611
+ for (;; ) {
47612
+ let id = "";
47613
+ for (let i = 0;i < 5; i++)
47614
+ id += ID_CHARS[Math.floor(this.random() * ID_CHARS.length)];
47615
+ if (!this.store.get(id))
47616
+ return id;
47617
+ }
47618
+ }
47619
+ commit(op) {
47620
+ if (this.rec.ops.length >= LIMITS.ops)
47621
+ throw new Error(`SCRIPT_LIMIT: more than ${LIMITS.ops} operations in one execute`);
47622
+ const touched = applyOp(this.store, op, this.rev);
47623
+ this.mutations++;
47624
+ this.rec.ops.push(op);
47625
+ if (op.op === "setVariables")
47626
+ this.rec.allTouched = true;
47627
+ for (const t of touched) {
47628
+ this.rec.touchedTop.add(t);
47629
+ this.layoutCache.delete(t);
47630
+ }
47631
+ if (op.op === "setVariables")
47632
+ this.layoutCache.clear();
47633
+ }
47634
+ parentId(parent) {
47635
+ if (parent === "document" || parent === "" || parent == null)
47636
+ return null;
47637
+ if (parent.includes("/"))
47638
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "parent", reason: "cannot insert inside a component instance; use Replace on the instance child" });
47639
+ const row = this.store.get(parent);
47640
+ if (!row)
47641
+ throw new OpRejectedError({ code: "PARENT_NOT_FOUND", path: parent });
47642
+ if (!CONTAINER_TYPES.has(row.props.type))
47643
+ throw new OpRejectedError({ code: "CANNOT_HAVE_CHILDREN", parent, type: row.props.type });
47644
+ return parent;
47645
+ }
47646
+ lastOrd(parent) {
47647
+ const kids = this.store.children(parent);
47648
+ return kids.length ? this.store.get(kids[kids.length - 1]).ord : null;
47649
+ }
47650
+ withIds(node2) {
47651
+ if (typeof node2 !== "object" || node2 === null || typeof node2.type !== "string")
47652
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "type", reason: "node needs a type" });
47653
+ if (node2.type === "ref") {
47654
+ const target = node2.ref;
47655
+ if (!this.store.get(target))
47656
+ throw new OpRejectedError({ code: "UNKNOWN_REF", ref: target });
47657
+ }
47658
+ for (const k of ["width", "height"]) {
47659
+ const v = node2[k];
47660
+ if (typeof v === "number" && v < 0)
47661
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: k, reason: "negative size" });
47662
+ if (typeof v === "string" && /%|vh|vw|calc/.test(v))
47663
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: k, reason: "percentage and viewport sizes are not supported" });
47664
+ }
47665
+ const id = this.mint();
47666
+ const out = { ...node2, id };
47667
+ if (typeof node2.name === "string")
47668
+ this.rec.created[node2.name] = id;
47669
+ if (Array.isArray(node2.children)) {
47670
+ if (!CONTAINER_TYPES.has(node2.type))
47671
+ throw new OpRejectedError({ code: "CANNOT_HAVE_CHILDREN", parent: id, type: node2.type });
47672
+ out.children = node2.children.map((c) => this.withIds(c));
47673
+ }
47674
+ return out;
47675
+ }
47676
+ warnProps(data, type, nodeId) {
47677
+ if (hasUnsupportedImageUrl(data) && this.rec.warnings.length < 20 && !this.rec.warnings.some((w) => w.code === "UNSUPPORTED_IMAGE_URL" && w.nodeId === nodeId))
47678
+ this.rec.warnings.push({ code: "UNSUPPORTED_IMAGE_URL", nodeId, message: "image fill url must be a file id (file-…)" });
47679
+ if (data.type === "icon" && !iconNameOf(data) && this.rec.warnings.length < 20 && !this.rec.warnings.some((w) => w.code === "ICON_NAME_MISSING" && w.nodeId === nodeId))
47680
+ 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)" });
47681
+ for (const prop of unknownProperties(data, type)) {
47682
+ const message = `${prop} is not a .pen property`;
47683
+ if (this.rec.warnings.length >= 20)
47684
+ break;
47685
+ if (!this.rec.warnings.some((w) => w.code === "UNKNOWN_PROPERTY" && w.nodeId === nodeId && w.message === message))
47686
+ this.rec.warnings.push({ code: "UNKNOWN_PROPERTY", nodeId, message });
47687
+ }
47688
+ for (const child of Array.isArray(data.children) ? data.children : [])
47689
+ this.warnProps(child, child.type, child.id ?? nodeId);
47690
+ if (data.descendants && typeof data.descendants === "object") {
47691
+ const descendants = typeof data.ref === "string" ? this.resolveDescendantKeys(data.ref, data.descendants) : data.descendants;
47692
+ for (const [key, value] of Object.entries(descendants)) {
47693
+ if (!value || typeof value !== "object")
47694
+ continue;
47695
+ const patch = value;
47696
+ const target = this.store.get(key)?.props.type ?? (typeof data.ref === "string" ? this.expandedAt(`${data.ref}/${key}`, {})?.node.type : undefined);
47697
+ this.warnProps(patch, typeof patch.type === "string" ? patch.type : target ?? "ref", `${nodeId}/${key}`);
47698
+ }
47699
+ }
47700
+ }
47701
+ splitInstancePath(path) {
47702
+ const i = path.indexOf("/");
47703
+ if (i < 0)
47704
+ return null;
47705
+ return { owner: path.slice(0, i), rest: path.slice(i + 1) };
47706
+ }
47707
+ resolveDescendantKeys(rootId, desc) {
47708
+ const byName = new Map;
47709
+ const walk = (id) => {
47710
+ for (const c of this.store.children(id)) {
47711
+ const n = this.store.get(c).props;
47712
+ if (n.name)
47713
+ byName.set(n.name, [...byName.get(n.name) ?? [], c]);
47714
+ walk(c);
47715
+ }
47716
+ };
47717
+ walk(rootId);
47718
+ const out = {};
47719
+ for (const [k, v] of Object.entries(desc)) {
47720
+ let key = k;
47721
+ if (!k.includes("/") && !this.store.get(k)) {
47722
+ const hits = byName.get(k);
47723
+ if (hits?.length === 1)
47724
+ key = hits[0];
47725
+ }
47726
+ out[key] = v;
47727
+ }
47728
+ return out;
47729
+ }
47730
+ Insert(parent, nodeData) {
47731
+ const p = this.parentId(parent);
47732
+ let node2 = this.withIds(migrateLegacyProps(nodeData));
47733
+ if (node2.type === "ref" && node2.descendants && typeof node2.descendants === "object")
47734
+ node2 = { ...node2, descendants: this.resolveDescendantKeys(node2.ref, node2.descendants) };
47735
+ this.warnProps(node2, node2.type, node2.id);
47736
+ this.commit({ op: "insert", parent: p, ord: between(this.lastOrd(p), null), node: node2 });
47737
+ return node2.id;
47738
+ }
47739
+ Copy(path, parent, copyNodeData = {}) {
47740
+ if (path.includes("/"))
47741
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "path", reason: "copying an instance child is not supported in this spike" });
47742
+ const src = this.store.get(path);
47743
+ if (!src)
47744
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47745
+ const p = this.parentId(parent);
47746
+ const { descendants, ...over } = migrateLegacyProps(copyNodeData);
47747
+ let node2;
47748
+ if (src.props.reusable) {
47749
+ node2 = { type: "ref", ref: src.id, ...over };
47750
+ if (descendants)
47751
+ node2.descendants = this.resolveDescendantKeys(src.id, descendants);
47752
+ node2 = this.withIds(node2);
47753
+ } else {
47754
+ const tree = subtree(this.store, src.id);
47755
+ const descMap = descendants ? this.resolveDescendantKeys(src.id, descendants) : {};
47756
+ const apply = (n) => {
47757
+ const d = descMap[n.id];
47758
+ let out = d && typeof d.type === "string" ? { ...d } : { ...n, ...d ?? {} };
47759
+ if (Array.isArray(n.children) && !(d && typeof d.type === "string"))
47760
+ out = { ...out, children: n.children.map(apply) };
47761
+ return out;
47762
+ };
47763
+ node2 = this.withIds({ ...apply(tree), ...over });
47764
+ }
47765
+ this.warnProps(node2, node2.type, node2.id);
47766
+ this.commit({ op: "insert", parent: p, ord: between(this.lastOrd(p), null), node: node2 });
47767
+ return node2.id;
47768
+ }
47769
+ Update(path, updateData) {
47770
+ updateData = migrateLegacyProps(updateData);
47771
+ const inst = this.splitInstancePath(path);
47772
+ if (inst) {
47773
+ const owner = this.store.get(inst.owner);
47774
+ if (!owner || owner.props.type !== "ref")
47775
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47776
+ const desc = { ...owner.props.descendants ?? {} };
47777
+ this.warnProps(updateData, this.expandedAt(path, {})?.node.type ?? "ref", path);
47778
+ desc[inst.rest] = { ...desc[inst.rest] ?? {}, ...updateData };
47779
+ this.commit({ op: "update", id: owner.id, patch: { descendants: desc } });
47780
+ return;
47781
+ }
47782
+ const row = this.store.get(path);
47783
+ if (!row)
47784
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47785
+ for (const f of ["id", "type", "ref"])
47786
+ if (f in updateData && updateData[f] !== row.props[f])
47787
+ throw new OpRejectedError({ code: "IMMUTABLE_FIELD", field: f });
47788
+ if ("children" in updateData)
47789
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "children", reason: "use Replace to change children" });
47790
+ const { id: _i, type: _t, ref: _r, ...patch } = updateData;
47791
+ if (patch.descendants && row.props.type === "ref")
47792
+ patch.descendants = { ...row.props.descendants ?? {}, ...this.resolveDescendantKeys(row.props.ref, patch.descendants) };
47793
+ this.warnProps({ ...patch, ...row.props.type === "ref" ? { ref: row.props.ref } : {} }, row.props.type, row.id);
47794
+ this.commit({ op: "update", id: row.id, patch });
47795
+ }
47796
+ Replace(path, nodeData) {
47797
+ const inst = this.splitInstancePath(path);
47798
+ if (inst) {
47799
+ const owner = this.store.get(inst.owner);
47800
+ if (!owner || owner.props.type !== "ref")
47801
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47802
+ const node3 = this.withIds(migrateLegacyProps(nodeData));
47803
+ this.warnProps(node3, node3.type, node3.id);
47804
+ const desc = { ...owner.props.descendants ?? {}, [inst.rest]: node3 };
47805
+ this.commit({ op: "update", id: owner.id, patch: { descendants: desc } });
47806
+ return node3.id;
47807
+ }
47808
+ const row = this.store.get(path);
47809
+ if (!row)
47810
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47811
+ const node2 = this.withIds(migrateLegacyProps(nodeData));
47812
+ this.warnProps(node2, node2.type, node2.id);
47813
+ this.commit({ op: "delete", id: row.id });
47814
+ this.commit({ op: "insert", parent: row.parent, ord: row.ord, node: node2 });
47815
+ return node2.id;
47816
+ }
47817
+ Move(path, parent, index) {
47818
+ if (path.includes("/"))
47819
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: "path", reason: "instance children cannot be moved; edit the component" });
47820
+ const row = this.store.get(path);
47821
+ if (!row)
47822
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47823
+ const p = parent === undefined ? row.parent : this.parentId(parent);
47824
+ for (let cur = p;cur !== null; cur = this.store.get(cur)?.parent ?? null)
47825
+ if (cur === row.id)
47826
+ throw new OpRejectedError({ code: "CYCLE", id: row.id, parent: p });
47827
+ const siblings = this.store.children(p).filter((s) => s !== row.id);
47828
+ const i = index === undefined ? siblings.length : Math.max(0, Math.min(index, siblings.length));
47829
+ const before = i > 0 ? this.store.get(siblings[i - 1]).ord : null;
47830
+ const after = i < siblings.length ? this.store.get(siblings[i]).ord : null;
47831
+ this.commit({ op: "move", id: row.id, parent: p, ord: between(before, after) });
47832
+ }
47833
+ Delete(path) {
47834
+ if (path === "document")
47835
+ throw new OpRejectedError({ code: "ROOT_PROTECTED" });
47836
+ if (path.includes("/"))
47837
+ throw new OpRejectedError({ code: "INSTANCE_CHILD_DELETE", path });
47838
+ if (!this.store.get(path))
47839
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47840
+ this.commit({ op: "delete", id: path });
47841
+ }
47842
+ SetVariables(variables, replace = false) {
47843
+ const themes = {};
47844
+ for (const [name, def] of Object.entries(variables ?? {})) {
47845
+ if (name.startsWith("$"))
47846
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: name, reason: "variable names must not start with $" });
47847
+ if (!def || typeof def !== "object" || !("type" in def) || !("value" in def))
47848
+ throw new OpRejectedError({ code: "INVALID_VALUE", property: name, reason: "expected { type, value }" });
47849
+ if (Array.isArray(def.value))
47850
+ for (const e of def.value)
47851
+ for (const [axis, v] of Object.entries(e.theme ?? {}))
47852
+ themes[axis] = [...new Set([...themes[axis] ?? [], v])];
47853
+ }
47854
+ this.commit({ op: "setVariables", variables, themes, replace });
47855
+ }
47856
+ GetVariables() {
47857
+ return { variables: this.store.variables(), themes: this.store.themes() };
47858
+ }
47859
+ Get(a, b, c) {
47860
+ let path = null;
47861
+ let visit2 = null;
47862
+ let opts = {};
47863
+ for (const arg of [a, b, c]) {
47864
+ if (typeof arg === "string")
47865
+ path = arg;
47866
+ else if (typeof arg === "function")
47867
+ visit2 = arg;
47868
+ else if (arg && typeof arg === "object")
47869
+ opts = arg;
47870
+ }
47871
+ if (!path && !visit2)
47872
+ throw new Error("Reading the whole document without a visitor would return everything! Pass a visitor or target a specific node.");
47873
+ if (!visit2)
47874
+ return this.readNode(path, opts);
47875
+ const out = [];
47876
+ const roots = path && path !== "document" ? [path] : this.store.children(null);
47877
+ for (const r of roots)
47878
+ this.visitFrom(r, visit2, opts, out);
47879
+ return out;
47880
+ }
47881
+ readNode(path, opts) {
47882
+ if (opts.resolveInstances || opts.resolveVariables || path.includes("/")) {
47883
+ const e = this.expandedAt(path, opts);
47884
+ if (!e)
47885
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47886
+ return toPen(e.node, opts.depth ?? Infinity, !!opts.resolveVariables, opts.resolveInstances !== false || path.includes("/"));
47887
+ }
47888
+ if (!this.store.get(path))
47889
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path });
47890
+ return subtree(this.store, path, opts.depth ?? Infinity);
47891
+ }
47892
+ expandedCache = new Map;
47893
+ mutations = 0;
47894
+ expandedAt(path, _opts) {
47895
+ const first = path.split("/")[0];
47896
+ const row = this.store.get(first);
47897
+ if (!row)
47898
+ return null;
47899
+ let hit = this.expandedCache.get(row.top);
47900
+ if (!hit || hit.rev !== this.mutations) {
47901
+ const tree = expandNode(this.store, row.top, defaultTheme(this.store.themes()));
47902
+ if (!tree)
47903
+ return null;
47904
+ const index = new Map;
47905
+ const walk = (n) => {
47906
+ index.set(n.path, n);
47907
+ n.children.forEach(walk);
47908
+ };
47909
+ walk(tree);
47910
+ hit = { rev: this.mutations, index };
47911
+ this.expandedCache.set(row.top, hit);
47912
+ if (this.expandedCache.size > 8)
47913
+ this.expandedCache.delete(this.expandedCache.keys().next().value);
47914
+ }
47915
+ const node2 = hit.index.get(path);
47916
+ return node2 ? { node: node2, top: row.top } : null;
47917
+ }
47918
+ layoutOf(top) {
47919
+ let l = this.layoutCache.get(top);
47920
+ if (!l) {
47921
+ l = this.bounds.layout(top);
47922
+ this.layoutCache.set(top, l);
47923
+ if (this.layoutCache.size > 8)
47924
+ this.layoutCache.delete(this.layoutCache.keys().next().value);
47925
+ }
47926
+ return l;
47927
+ }
47928
+ visitFrom(startPath, visit2, opts, out) {
47929
+ const at = this.expandedAt(startPath, opts);
47930
+ if (!at)
47931
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: startPath });
47932
+ const self = this;
47933
+ const withInstances = !!opts.resolveInstances;
47934
+ const walk = (e, parentCtx, depth, index) => {
47935
+ if (opts.depth !== undefined && depth > opts.depth)
47936
+ return;
47937
+ let skip = false;
47938
+ const node2 = toPen(e, 0, !!opts.resolveVariables, withInstances, true);
47939
+ const ctx = {
47940
+ node: node2,
47941
+ parentCtx,
47942
+ depth,
47943
+ index,
47944
+ get bounds() {
47945
+ const b = self.layoutOf(at.top).boxes.get(e.path);
47946
+ return b ? { x: b.x, y: b.y, width: b.width, height: b.height } : { x: 0, y: 0, width: 0, height: 0 };
47947
+ },
47948
+ get problems() {
47949
+ const p = self.layoutOf(at.top).problems.find((q) => q.path === e.path && (q.code === "PARTIALLY_CLIPPED" || q.code === "FULLY_CLIPPED"));
47950
+ return p ? p.code === "FULLY_CLIPPED" ? "fully clipped" : "partially clipped" : undefined;
47951
+ },
47952
+ skipChildren() {
47953
+ skip = true;
47954
+ }
47955
+ };
47956
+ const r = visit2(node2, ctx);
47957
+ if (r !== undefined)
47958
+ out.push(r);
47959
+ if (skip)
47960
+ return;
47961
+ if (e.role === "instance" && !withInstances)
47962
+ return;
47963
+ e.children.forEach((c, i) => walk(c, ctx, depth + 1, i));
47964
+ };
47965
+ walk(at.node, undefined, 0, 0);
47966
+ }
47967
+ level(root, parent, opts) {
47968
+ const withInstances = !!opts.resolveInstances;
47969
+ const conv = (e) => ({
47970
+ node: toPen(e, 0, !!opts.resolveVariables, withInstances, true),
47971
+ path: e.path,
47972
+ more: e.children.length > 0 && !(e.role === "instance" && !withInstances)
47973
+ });
47974
+ if (parent === null) {
47975
+ const roots = root && root !== "document" ? [root] : this.store.children(null);
47976
+ return roots.map((r) => {
47977
+ const at2 = this.expandedAt(r, opts);
47978
+ if (!at2)
47979
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: r });
47980
+ return conv(at2.node);
47981
+ });
47982
+ }
47983
+ const at = this.expandedAt(parent, opts);
47984
+ return at ? at.node.children.map(conv) : [];
47985
+ }
47986
+ tree(path, opts) {
47987
+ const withInstances = !!opts.resolveInstances;
47988
+ const roots = path && path !== "document" ? [path] : this.store.children(null);
47989
+ const out = [];
47990
+ for (const r of roots) {
47991
+ const at = this.expandedAt(r, opts);
47992
+ if (!at)
47993
+ throw new OpRejectedError({ code: "NODE_NOT_FOUND", path: r });
47994
+ const conv = (e, depth) => ({
47995
+ node: toPen(e, 0, !!opts.resolveVariables, withInstances, true),
47996
+ path: e.path,
47997
+ children: e.role === "instance" && !withInstances || opts.depth !== undefined && depth >= opts.depth ? [] : e.children.map((c) => conv(c, depth + 1))
47998
+ });
47999
+ out.push(conv(at.node, 0));
48000
+ }
48001
+ return out;
48002
+ }
48003
+ boundsOf(path) {
48004
+ const first = path.split("/")[0];
48005
+ const row = this.store.get(first);
48006
+ if (!row)
48007
+ return { bounds: { x: 0, y: 0, width: 0, height: 0 } };
48008
+ const l = this.layoutOf(row.top);
48009
+ const b = l.boxes.get(path);
48010
+ const p = l.problems.find((q) => q.path === path && (q.code === "PARTIALLY_CLIPPED" || q.code === "FULLY_CLIPPED"));
48011
+ return {
48012
+ bounds: b ? { x: b.x, y: b.y, width: b.width, height: b.height } : { x: 0, y: 0, width: 0, height: 0 },
48013
+ problems: p ? p.code === "FULLY_CLIPPED" ? "fully clipped" : "partially clipped" : undefined
48014
+ };
48015
+ }
48016
+ FindEmptySpace(input) {
48017
+ const dir = input.direction ?? "right";
48018
+ const pad = input.padding ?? 0;
48019
+ const rects = [];
48020
+ const tops = input.nodeId ? [input.nodeId] : this.store.children(null);
48021
+ for (const t of tops) {
48022
+ const row = this.store.get(t);
48023
+ if (!row)
48024
+ continue;
48025
+ const b = this.layoutOf(row.top).boxes.get(t);
48026
+ if (b)
48027
+ rects.push({ x: b.wx, y: b.wy, width: b.width, height: b.height });
48028
+ }
48029
+ if (!rects.length)
48030
+ return { x: 0, y: 0 };
48031
+ const minX = Math.min(...rects.map((r) => r.x));
48032
+ const minY = Math.min(...rects.map((r) => r.y));
48033
+ const maxX = Math.max(...rects.map((r) => r.x + r.width));
48034
+ const maxY = Math.max(...rects.map((r) => r.y + r.height));
48035
+ if (dir === "right")
48036
+ return { x: maxX + pad, y: minY };
48037
+ if (dir === "left")
48038
+ return { x: minX - pad - input.width, y: minY };
48039
+ if (dir === "bottom")
48040
+ return { x: minX, y: maxY + pad };
48041
+ return { x: minX, y: minY - pad - input.height };
48042
+ }
48043
+ Print(...values) {
48044
+ const line = values.map((v) => typeof v === "string" ? v : JSON.stringify(v)).join(" ");
48045
+ this.rec.printBytes += line.length;
48046
+ if (this.rec.printBytes > LIMITS.printBytes)
48047
+ throw new Error(`SCRIPT_LIMIT: Print output over ${LIMITS.printBytes} bytes`);
48048
+ this.rec.prints.push(line);
48049
+ }
48050
+ TakeScreenshot(nodeIds) {
48051
+ for (const id of nodeIds)
48052
+ if (this.rec.screenshots.length < LIMITS.screenshots)
48053
+ this.rec.screenshots.push(id);
48054
+ }
48055
+ }
48056
+ function toPen(e, depth, _resolved, _instances, shallow = false) {
48057
+ const node2 = { ...e.props, id: e.path, type: e.type };
48058
+ if (!shallow && e.children.length) {
48059
+ if (depth <= 0)
48060
+ node2.children = "...";
48061
+ else
48062
+ node2.children = e.children.map((c) => toPen(c, depth - 1, _resolved, _instances));
48063
+ }
48064
+ return node2;
48065
+ }
48066
+ // ../../packages/canvas/document/src/pen-import.ts
48067
+ var FILE_ID = /^file-/;
48068
+ var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
48069
+ var isImage = (node2) => node2.type === "image" && typeof node2.url === "string";
48070
+ var isRef = (node2) => node2.type === "ref" && typeof node2.ref === "string";
48071
+ function visit2(value, nodeId, fn) {
48072
+ if (Array.isArray(value)) {
48073
+ for (const item of value)
48074
+ visit2(item, nodeId, fn);
48075
+ return;
48076
+ }
48077
+ const node2 = asRecord(value);
48078
+ if (!node2)
48079
+ return;
48080
+ const id = typeof node2.id === "string" ? node2.id : nodeId;
48081
+ fn(node2, id);
48082
+ for (const key of Object.keys(node2))
48083
+ visit2(node2[key], id, fn);
48084
+ }
48085
+ function indexTops(tops) {
48086
+ const owner = new Map;
48087
+ for (const top of tops) {
48088
+ visit2(top, top.id, (node2) => {
48089
+ if (typeof node2.id === "string")
48090
+ owner.set(node2.id, top.id);
48091
+ });
48092
+ }
48093
+ return owner;
48094
+ }
48095
+ var clone = (value) => JSON.parse(JSON.stringify(value));
48096
+ function penImageUrls(nodes) {
48097
+ const urls = [];
48098
+ const seen = new Set;
48099
+ for (const node2 of nodes) {
48100
+ visit2(node2, node2.id, (value) => {
48101
+ if (!isImage(value))
48102
+ return;
48103
+ const url = value.url;
48104
+ if (FILE_ID.test(url) || seen.has(url))
48105
+ return;
48106
+ seen.add(url);
48107
+ urls.push(url);
48108
+ });
48109
+ }
48110
+ return urls;
48111
+ }
48112
+ function planPenImport(doc, opts = {}) {
48113
+ const tops = Array.isArray(doc.children) ? doc.children : [];
48114
+ const warnings = [];
48115
+ const selected = new Set;
48116
+ const added = [];
48117
+ if (opts.frames === undefined) {
48118
+ for (const top of tops)
48119
+ selected.add(top.id);
48120
+ } else {
48121
+ const frames = new Set(opts.frames);
48122
+ for (const id of frames) {
48123
+ if (!tops.some((top) => top.id === id))
48124
+ warnings.push({ code: "FRAME_NOT_FOUND", id });
48125
+ else
48126
+ selected.add(id);
48127
+ }
48128
+ const owner = indexTops(tops);
48129
+ const byId = new Map(tops.map((top) => [top.id, top]));
48130
+ const dangling = new Set;
48131
+ for (let queue = [...selected];queue.length > 0; ) {
48132
+ const top = byId.get(queue.shift());
48133
+ if (!top)
48134
+ continue;
48135
+ visit2(top, top.id, (node2, nodeId) => {
48136
+ if (!isRef(node2))
48137
+ return;
48138
+ const ref = node2.ref;
48139
+ const target = owner.get(ref);
48140
+ if (target === undefined) {
48141
+ const key = `${ref}\x00${nodeId}`;
48142
+ if (dangling.has(key))
48143
+ return;
48144
+ dangling.add(key);
48145
+ warnings.push({ code: "REF_DANGLING", ref, nodeId });
48146
+ return;
48147
+ }
48148
+ if (selected.has(target))
48149
+ return;
48150
+ selected.add(target);
48151
+ queue.push(target);
48152
+ });
48153
+ }
48154
+ for (const top of tops)
48155
+ if (selected.has(top.id) && !frames.has(top.id))
48156
+ added.push(top.id);
48157
+ }
48158
+ const images = opts.images ?? {};
48159
+ const unmapped = new Map;
48160
+ const children = tops.filter((top) => selected.has(top.id)).map((top) => clone(top));
48161
+ for (const node2 of children) {
48162
+ visit2(node2, node2.id, (value, nodeId) => {
48163
+ if (!isImage(value))
48164
+ return;
48165
+ const url = value.url;
48166
+ if (FILE_ID.test(url))
48167
+ return;
48168
+ const fileId = Object.hasOwn(images, url) ? images[url] : undefined;
48169
+ if (typeof fileId === "string") {
48170
+ value.url = fileId;
48171
+ return;
48172
+ }
48173
+ const nodeIds = unmapped.get(url);
48174
+ if (nodeIds) {
48175
+ if (!nodeIds.includes(nodeId))
48176
+ nodeIds.push(nodeId);
48177
+ } else
48178
+ unmapped.set(url, [nodeId]);
48179
+ });
48180
+ }
48181
+ for (const [url, nodeIds] of unmapped)
48182
+ warnings.push({ code: "IMAGE_UNMAPPED", url, nodeIds });
48183
+ return {
48184
+ children,
48185
+ ...doc.variables ? { variables: clone(doc.variables) } : {},
48186
+ ...doc.themes ? { themes: clone(doc.themes) } : {},
48187
+ added,
48188
+ warnings
48189
+ };
48190
+ }
48191
+ // src/commands/canvas-import.ts
48192
+ var CHUNK_CHARS = 1500000;
48193
+ function countNodes(nodes) {
48194
+ let total = 0;
48195
+ const walk = (list) => {
48196
+ for (const node2 of list) {
48197
+ total++;
48198
+ if (Array.isArray(node2.children))
48199
+ walk(node2.children);
48200
+ }
48201
+ };
48202
+ walk(nodes);
48203
+ return total;
48204
+ }
48205
+ function chunkTopNodes(nodes, limit = CHUNK_CHARS) {
48206
+ const chunks = [];
48207
+ let current = [];
48208
+ let size = 0;
48209
+ for (const node2 of nodes) {
48210
+ const length = JSON.stringify(node2).length;
48211
+ if (current.length && size + length > limit) {
48212
+ chunks.push(current);
48213
+ current = [];
48214
+ size = 0;
48215
+ }
48216
+ current.push(node2);
48217
+ size += length;
48218
+ }
48219
+ if (current.length)
48220
+ chunks.push(current);
48221
+ return chunks;
48222
+ }
48223
+ var CONTENT_TYPES = {
48224
+ png: "image/png",
48225
+ jpg: "image/jpeg",
48226
+ jpeg: "image/jpeg",
48227
+ webp: "image/webp",
48228
+ gif: "image/gif",
48229
+ svg: "image/svg+xml",
48230
+ avif: "image/avif"
48231
+ };
48232
+ var contentTypeOf = (url) => CONTENT_TYPES[url.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
48233
+ var viewerUrlFor = (canvasId, env) => `https://console${env === "develop" ? "-develop" : ""}.deepraxis.com/canvases/${canvasId}`;
48234
+ function imageCandidates(url, penFile, roots) {
48235
+ const name = basename2(url);
48236
+ return [...new Set([
48237
+ join5(dirname2(penFile), url),
48238
+ ...roots.map((root) => join5(root, url)),
48239
+ ...roots.map((root) => join5(root, name))
48240
+ ])];
48241
+ }
48242
+ var isMissing = (error) => error?.code === "ENOENT";
48243
+ var reason = (error) => error instanceof Error ? error.message : String(error);
48244
+ async function findImage(url, candidates, ports) {
48245
+ for (const path of candidates) {
48246
+ try {
48247
+ return await ports.readBytes(path);
48248
+ } catch (error) {
48249
+ if (!isMissing(error))
48250
+ throw new UsageError(`cannot read ${path}, needed for image ${url}`, reason(error));
48251
+ }
48252
+ }
48253
+ return;
48254
+ }
48255
+ var warningKey = (warning) => `${warning.code}\x00${"url" in warning ? warning.url : ("id" in warning) ? warning.id : warning.ref}\x00${"nodeId" in warning ? warning.nodeId : ""}`;
48256
+ var warningLine = (warning) => {
48257
+ switch (warning.code) {
48258
+ case "IMAGE_UNMAPPED":
48259
+ return `${warning.code}: ${warning.url} (${warning.nodeIds.length} node(s))`;
48260
+ case "REF_DANGLING":
48261
+ return `${warning.code}: ${warning.ref} at ${warning.nodeId}`;
48262
+ case "FRAME_NOT_FOUND":
48263
+ return `${warning.code}: ${warning.id}`;
48264
+ default:
48265
+ return `${warning.code}: ${warning.url}`;
48266
+ }
48267
+ };
48268
+ async function canvasImport(args, ports) {
48269
+ if (args.canvas !== undefined && !args.yes) {
48270
+ 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.");
48271
+ }
48272
+ const file = resolve3(ports.cwd, args.file);
48273
+ let text;
48274
+ try {
48275
+ text = await ports.readFile(file);
48276
+ } catch (error) {
48277
+ throw new UsageError(`cannot read ${args.file}`, isMissing(error) ? "Check the path: `praxis canvas import <file.pen>`." : reason(error));
48278
+ }
48279
+ let doc;
48280
+ try {
48281
+ doc = JSON.parse(text);
48282
+ } catch (error) {
48283
+ throw new UsageError(`${args.file} is not valid JSON`, reason(error));
48284
+ }
48285
+ if (!Array.isArray(doc.children))
48286
+ throw new UsageError(`${args.file} has no children array`, "A .pen document is an object with a children array of top-level nodes.");
48287
+ const frames = args.frames?.filter((frame) => frame !== "");
48288
+ const roots = (args.imageRoots ?? []).map((root) => resolve3(ports.cwd, root));
48289
+ const selection = planPenImport(doc, frames ? { frames } : {});
48290
+ const urls = penImageUrls(selection.children);
48291
+ const found = new Map;
48292
+ const missing = [];
48293
+ for (const url of urls) {
48294
+ const bytes = await findImage(url, imageCandidates(url, file, roots), ports);
48295
+ if (bytes === undefined)
48296
+ missing.push(url);
48297
+ else
48298
+ found.set(url, { bytes, digest: await ports.hash(bytes) });
48299
+ }
48300
+ const images = {};
48301
+ let uploaded = 0;
48302
+ let reused = 0;
48303
+ if (!args.dryRun) {
48304
+ const byDigest = new Map;
48305
+ for (const [url, { bytes, digest }] of found) {
48306
+ const existing = byDigest.get(digest);
48307
+ if (existing !== undefined) {
48308
+ images[url] = existing;
48309
+ reused++;
48310
+ continue;
48311
+ }
48312
+ const id = await ports.upload({ filename: basename2(url), bytes, contentType: contentTypeOf(url) });
48313
+ byDigest.set(digest, id);
48314
+ images[url] = id;
48315
+ uploaded++;
48316
+ }
48317
+ }
48318
+ const plan = planPenImport(doc, { ...frames ? { frames } : {}, images });
48319
+ const chunks = chunkTopNodes(plan.children);
48320
+ const nodes = countNodes(plan.children);
48321
+ const warnings = plan.warnings.filter((warning) => !(args.dryRun && warning.code === "IMAGE_UNMAPPED" && !missing.includes(warning.url)));
48322
+ let canvasId = null;
48323
+ let revision = null;
48324
+ if (!args.dryRun) {
48325
+ canvasId = args.canvas ?? (await ports.rpc("canvas.canvases.create", { name: args.name ?? basename2(file).replace(/\.pen$/, "") })).id;
48326
+ for (let index = 0;index < chunks.length; index++) {
48327
+ const result2 = await ports.rpc("canvas.canvases.import", {
48328
+ canvasId,
48329
+ reset: index === 0,
48330
+ ...index === 0 && plan.variables ? { variables: plan.variables } : {},
48331
+ ...index === 0 && plan.themes ? { themes: plan.themes } : {},
48332
+ children: chunks[index]
48333
+ });
48334
+ revision = result2.revision;
48335
+ const seen = new Set(warnings.map(warningKey));
48336
+ for (const warning of result2.warnings ?? []) {
48337
+ if (seen.has(warningKey(warning)))
48338
+ continue;
48339
+ seen.add(warningKey(warning));
48340
+ warnings.push(warning);
48341
+ }
48342
+ }
48343
+ }
48344
+ const result = {
48345
+ canvas_id: canvasId,
48346
+ viewer_url: canvasId === null ? null : viewerUrlFor(canvasId, ports.env),
48347
+ revision,
48348
+ frames: plan.children.map((node2) => node2.id),
48349
+ added: plan.added,
48350
+ nodes,
48351
+ images: { uploaded, reused, missing },
48352
+ chunks: chunks.length,
48353
+ warnings,
48354
+ dry_run: args.dryRun
48355
+ };
48356
+ ports.emit({ kind: "object", data: result });
48357
+ const name = args.name ?? basename2(file).replace(/\.pen$/, "");
48358
+ const headline = `${plan.children.length} top-level nodes (${plan.added.length} added as component dependencies), ${nodes} nodes, ${chunks.length} chunk(s)`;
48359
+ ports.human([
48360
+ args.dryRun ? `${file}: ${headline}` : `${canvasId} ${name} — ${headline}, ${uploaded} image(s) uploaded${reused ? `, ${reused} reused` : ""}`,
48361
+ ...result.viewer_url ? [result.viewer_url] : [],
48362
+ ...plan.added.length ? [`added as dependencies: ${plan.added.join(", ")}`] : [],
48363
+ `${urls.length - missing.length}/${urls.length} image(s) found locally`,
48364
+ ...missing.length ? [`not found (they will not render): ${missing.join(", ")}`] : [],
48365
+ ...warnings.map(warningLine)
48366
+ ].join(`
48367
+ `));
48368
+ return 0;
48369
+ }
48370
+
46693
48371
  // src/main.ts
46694
48372
  import { spawnSync } from "node:child_process";
46695
48373
 
@@ -46749,13 +48427,13 @@ var groups = [["id"], ["name", "title", "display_name"], ["status", "state"], ["
46749
48427
  var isExtraColumn = (key) => !groups.some((group) => group.includes(key));
46750
48428
  function columnsFor(items) {
46751
48429
  const rows = items.map(record);
46752
- const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))];
48430
+ const keys2 = [...new Set(rows.flatMap((row) => Object.keys(row)))];
46753
48431
  const chosen = groups.flatMap((group) => {
46754
- const key = group.find((k) => keys.includes(k));
48432
+ const key = group.find((k) => keys2.includes(k));
46755
48433
  return key ? [key] : [];
46756
48434
  });
46757
48435
  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) => {
48436
+ const extra = keys2.filter((key) => !standard.has(key) && rows.some((row) => row[key] !== null && row[key] !== undefined) && rows.every((row) => {
46759
48437
  const v = row[key];
46760
48438
  return v === null || v === undefined || typeof v === "boolean" || typeof v === "number" || typeof v === "string" && [...v].length <= 24;
46761
48439
  })).slice(0, 2);
@@ -46810,9 +48488,9 @@ class ModelStream {
46810
48488
  const data = streamData(event), message = record(data.message), response = record(data.response);
46811
48489
  this.chunks.push(streamText(event));
46812
48490
  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;
48491
+ 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;
48492
+ if (typeof reason2 === "string" && reason2)
48493
+ this.finishReason = reason2;
46816
48494
  else if (["response.completed", "response.incomplete", "response.failed"].includes(String(data.type)))
46817
48495
  this.finishReason = String(data.type).slice("response.".length);
46818
48496
  for (const usage of [message.usage, data.usage, response.usage]) {
@@ -47323,7 +49001,7 @@ function startProgress(ctx, write = (text) => writeOutput({ stderr: text })) {
47323
49001
  }
47324
49002
 
47325
49003
  // src/main.ts
47326
- var version = "0.2.2-dev.1b23ee0";
49004
+ var version = "0.2.2-dev.29dd643";
47327
49005
  var commands = commandTree(operations);
47328
49006
  var manual = [...workflows.map((w) => w.words), [API_WORD]];
47329
49007
  function route(argv) {
@@ -47360,19 +49038,21 @@ var defaults = {
47360
49038
  stderrIsTTY: Boolean(process.stderr.isTTY),
47361
49039
  columns: process.stdout.columns ?? 100,
47362
49040
  readFile: (path) => readFile3(path, "utf8"),
49041
+ readBytes: (path) => readFile3(path),
49042
+ sha256: async (bytes) => createHash3("sha256").update(bytes).digest("hex"),
47363
49043
  async readStdin() {
47364
49044
  const chunks = [];
47365
49045
  for await (const chunk of process.stdin)
47366
49046
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
47367
49047
  return Buffer.concat(chunks).toString("utf8");
47368
49048
  },
47369
- ask: () => new Promise((resolve3) => {
49049
+ ask: () => new Promise((resolve4) => {
47370
49050
  const input = createInterface({ input: process.stdin, terminal: false });
47371
49051
  input.once("line", (line) => {
47372
- resolve3(/^(y|yes)$/i.test(line.trim()));
49052
+ resolve4(/^(y|yes)$/i.test(line.trim()));
47373
49053
  input.close();
47374
49054
  });
47375
- input.once("close", () => resolve3(false));
49055
+ input.once("close", () => resolve4(false));
47376
49056
  }),
47377
49057
  async openBrowser(url) {
47378
49058
  try {
@@ -47380,27 +49060,27 @@ var defaults = {
47380
49060
  if (!["https:", "http:"].includes(parsed.protocol))
47381
49061
  return;
47382
49062
  const cmd = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler", url] : ["xdg-open", url];
47383
- await new Promise((resolve3, reject) => {
49063
+ await new Promise((resolve4, reject) => {
47384
49064
  const child = spawn2(cmd[0], cmd.slice(1), { stdio: "ignore" });
47385
49065
  child.once("error", reject);
47386
- child.once("close", () => resolve3());
49066
+ child.once("close", () => resolve4());
47387
49067
  });
47388
49068
  } catch {}
47389
49069
  },
47390
- wait: (ms) => new Promise((resolve3) => setTimeout(resolve3, ms)),
49070
+ wait: (ms) => new Promise((resolve4) => setTimeout(resolve4, ms)),
47391
49071
  render,
47392
- spawn: (cmd, args, options) => new Promise((resolve3, reject) => {
49072
+ spawn: (cmd, args, options) => new Promise((resolve4, reject) => {
47393
49073
  const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
47394
49074
  child.once("error", reject);
47395
- child.once("close", (code) => resolve3(code ?? 1));
49075
+ child.once("close", (code) => resolve4(code ?? 1));
47396
49076
  }),
47397
- spawnCapture: (cmd, args, options) => new Promise((resolve3, reject) => {
49077
+ spawnCapture: (cmd, args, options) => new Promise((resolve4, reject) => {
47398
49078
  const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
47399
49079
  const chunks = [];
47400
49080
  child.stdout.on("data", (c) => chunks.push(c));
47401
49081
  child.stderr.on("data", (c) => chunks.push(c));
47402
49082
  child.once("error", reject);
47403
- child.once("close", (code) => resolve3({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
49083
+ child.once("close", (code) => resolve4({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
47404
49084
  }),
47405
49085
  has: (bin) => spawnSync(process.platform === "win32" ? "where" : "which", [bin], { stdio: "ignore" }).status === 0,
47406
49086
  cwd: process.cwd()
@@ -47419,6 +49099,13 @@ var appOptions = {
47419
49099
  { name: "no-wait", type: "boolean", description: "Return as soon as the run exists instead of waiting for a verdict." },
47420
49100
  { name: "repeat", type: "string", description: "How many times each selected case runs (default: 1)." },
47421
49101
  { 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>." }
49102
+ ],
49103
+ "canvas import": [
49104
+ { name: "name", type: "string", description: "Name for the new canvas (default: the file name without .pen)." },
49105
+ { 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." },
49106
+ { name: "frames", type: "string", description: "Comma-separated top-level node ids to import. The components they reference come along automatically." },
49107
+ { 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." },
49108
+ { name: "dry-run", type: "boolean", description: "Read the local file and print the plan. No login and no request." }
47422
49109
  ]
47423
49110
  };
47424
49111
  async function main(argv, injected = {}) {
@@ -47516,7 +49203,7 @@ Examples:
47516
49203
  return 0;
47517
49204
  }
47518
49205
  const path = ports.tokenPath ?? tokenPath(config.env);
47519
- const store = createTokenStore(config.env, path, selectSecretStore(ports.env, ports.secretStore));
49206
+ const store2 = createTokenStore(config.env, path, selectSecretStore(ports.env, ports.secretStore));
47520
49207
  const wireFetch = async (input, init) => {
47521
49208
  const request = new Request(input, init);
47522
49209
  request.headers.set("User-Agent", `praxis-cli/${version}${ctx.mode === "agent" ? ` agent/${ctx.agentName ?? "unknown"}` : ""}`);
@@ -47526,7 +49213,7 @@ Examples:
47526
49213
  }
47527
49214
  return ports.fetch(request);
47528
49215
  };
47529
- const auth = credentials(config, ports.env, { fetch: wireFetch, now: ports.now, path, store, remember: (s) => {
49216
+ const auth = credentials(config, ports.env, { fetch: wireFetch, now: ports.now, path, store: store2, remember: (s) => {
47530
49217
  secrets.push(s);
47531
49218
  } });
47532
49219
  ctx.credentialSource = auth.source;
@@ -47602,7 +49289,7 @@ Examples:
47602
49289
  return 0;
47603
49290
  }
47604
49291
  const name = selected.words.join(" ");
47605
- const arity = name === "api" ? 2 : name === "org switch" || name === "app create" ? 1 : 0;
49292
+ const arity = name === "api" ? 2 : name === "org switch" || name === "app create" || name === "canvas import" ? 1 : 0;
47606
49293
  if (parsed.positional.length !== arity)
47607
49294
  throw new UsageError(`${name} expects ${arity} positional argument(s)`);
47608
49295
  if (name === "devops deploy plan") {
@@ -47637,10 +49324,10 @@ Examples:
47637
49324
  if (flags["no-input"] || quiet)
47638
49325
  throw new UsageError("login requires displaying a device code", "Remove --no-input / --quiet or set PRAXIS_API_KEY for scripts.");
47639
49326
  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) });
49327
+ await login(config, path, { ...ports, source: auth.source, json: ctx.mode === "json", store: store2, fetch: wireFetch, emit, remember: (s) => secrets.push(s) });
47641
49328
  break;
47642
49329
  case "logout":
47643
- emit({ kind: "message", text: await store.delete() ? "Logged out." : "Not logged in." });
49330
+ emit({ kind: "message", text: await store2.delete() ? "Logged out." : "Not logged in." });
47644
49331
  break;
47645
49332
  case "whoami":
47646
49333
  emit({ kind: "object", data: await whoami(auth, config.env, org) });
@@ -47699,6 +49386,67 @@ Examples:
47699
49386
  cwd: ports.cwd
47700
49387
  });
47701
49388
  }
49389
+ case "canvas import": {
49390
+ const authorize = async () => {
49391
+ const credential = await auth.get(org);
49392
+ return { Authorization: `Bearer ${credential.token}`, ...credential.source === "api-key" ? { "X-API-Key": credential.token } : {} };
49393
+ };
49394
+ const rpc = async (method, params) => {
49395
+ const response = await wireFetch(`${config.apiUrl}/canvas/v1/rpc`, {
49396
+ method: "POST",
49397
+ headers: { ...await authorize(), "content-type": "application/json" },
49398
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
49399
+ signal: AbortSignal.timeout(120000),
49400
+ redirect: "error"
49401
+ });
49402
+ const reply = await response.json();
49403
+ if (!response.ok || reply.error)
49404
+ throw new PraxisError({ code: "CANVAS_RPC_ERROR", message: `${method}: ${reply.error?.message ?? `HTTP ${response.status}`}` });
49405
+ if (!Object.hasOwn(reply, "result"))
49406
+ throw new PraxisError({ code: "INVALID_RESPONSE", message: `${method} answered no result` });
49407
+ return reply.result;
49408
+ };
49409
+ const upload = async ({ filename, bytes, contentType }) => {
49410
+ const signed = await wireFetch(`${config.apiUrl}/file/v1/uploads/signed`, {
49411
+ method: "POST",
49412
+ headers: { ...await authorize(), "content-type": "application/json" },
49413
+ body: JSON.stringify({ filename, bytes: bytes.length, content_type: contentType, purpose: "user_data" }),
49414
+ signal: AbortSignal.timeout(60000),
49415
+ redirect: "error"
49416
+ });
49417
+ const session = await signed.json();
49418
+ if (!signed.ok || typeof session.url !== "string")
49419
+ throw new PraxisError({ code: "UPLOAD_REJECTED", message: `signed upload for ${filename} failed (HTTP ${signed.status})` });
49420
+ 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" });
49421
+ const file = await sent.json();
49422
+ if (!sent.ok || typeof file.id !== "string")
49423
+ throw new PraxisError({ code: "UPLOAD_FAILED", message: `uploading ${filename} failed (HTTP ${sent.status})` });
49424
+ return file.id;
49425
+ };
49426
+ return await canvasImport({
49427
+ file: parsed.positional[0],
49428
+ name: parsed.flags.name?.[0],
49429
+ canvas: parsed.flags.canvas?.[0],
49430
+ frames: typeof parsed.flags.frames?.[0] === "string" ? parsed.flags.frames[0].split(",").map((frame) => frame.trim()).filter(Boolean) : undefined,
49431
+ imageRoots: parsed.flags["image-root"],
49432
+ dryRun: Boolean(parsed.flags["dry-run"]?.[0]),
49433
+ yes: Boolean(flags.yes)
49434
+ }, {
49435
+ readFile: ports.readFile,
49436
+ readBytes: ports.readBytes,
49437
+ hash: ports.sha256,
49438
+ env: config.env,
49439
+ mode: ctx.mode,
49440
+ emit,
49441
+ cwd: ports.cwd,
49442
+ rpc,
49443
+ upload,
49444
+ human: (text) => {
49445
+ if (ctx.mode === "human")
49446
+ emit({ kind: "message", channel: "stdout", text });
49447
+ }
49448
+ });
49449
+ }
47702
49450
  case "api": {
47703
49451
  const method = parsed.positional[0];
47704
49452
  if (!HTTP_METHOD.test(method))