@deepraxis/cli 0.3.0-dev.d38b647 → 0.3.0-dev.faa3b25

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 +5 -4
  2. package/dist/praxis.js +1752 -356
  3. package/package.json +1 -1
package/dist/praxis.js CHANGED
@@ -6945,9 +6945,9 @@ var require_public_api = __commonJS((exports) => {
6945
6945
  });
6946
6946
 
6947
6947
  // src/main.ts
6948
- import { readFile as readFile3 } from "node:fs/promises";
6949
- import { createHash as createHash3 } from "node:crypto";
6950
- import { spawn as spawn2 } from "node:child_process";
6948
+ import { readFile as readFile4 } from "node:fs/promises";
6949
+ import { createHash as createHash4 } from "node:crypto";
6950
+ import { spawn as spawn3 } from "node:child_process";
6951
6951
  import { createInterface } from "node:readline";
6952
6952
 
6953
6953
  // ../../packages/sdk/typescript/src/operations.generated.ts
@@ -29610,70 +29610,6 @@ for more details.`
29610
29610
  ],
29611
29611
  query: []
29612
29612
  },
29613
- {
29614
- resource: "studio.reviewers",
29615
- method: "list",
29616
- summary: "List the reviewers of the organization",
29617
- description: "List the reviewers this organization can draw on: one entry per reviewer agent, with its kind, its display name, the tags it matches seats on, the model family it runs and whether it is active. Pass kind to see only expert or only audience reviewers. Read it before setting a work's seats, so the seat conditions match reviewers that exist, and after REVIEWER_POOL_EMPTY to see which reviewers are missing or inactive. Entries are the organization's own reviewer agents; a reviewer of another organization is never listed. The answer is one page; keep following next_page_token while it is present.",
29618
- http: "GET",
29619
- path: "/studio/v1/reviewers",
29620
- streaming: "no",
29621
- pagination: false,
29622
- pathParams: [],
29623
- query: [
29624
- {
29625
- name: "kind",
29626
- type: "string",
29627
- enum: [
29628
- "expert",
29629
- "audience"
29630
- ],
29631
- required: false,
29632
- description: "Reviewer kind to filter by: expert draws reviewers that write a scored report, audience draws reviewers that fill a screening card. Omit it to list both kinds together."
29633
- },
29634
- {
29635
- name: "page_size",
29636
- type: "integer",
29637
- required: false,
29638
- 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."
29639
- },
29640
- {
29641
- name: "page_token",
29642
- type: "string",
29643
- required: false,
29644
- 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."
29645
- }
29646
- ]
29647
- },
29648
- {
29649
- resource: "studio.reviewers",
29650
- method: "update",
29651
- summary: "Activate or retire a reviewer",
29652
- description: "Take one reviewer in or out of the draw: active false keeps it in the library but stops it being drawn for future seats, and active true puts it back. Use it when a reviewer should stop judging, for example when its answers are consistently unusable, and set it back once that is dealt with. A round already sent is not affected, because its assignments were made when it was sent. A person makes this change, and an agent calling it is refused with PERMISSION_DENIED. The reviewer is addressed by the agent value the reviewer list returns; an unknown one answers REVIEWER_NOT_FOUND, which is also the answer for a reviewer of another organization.",
29653
- http: "PATCH",
29654
- path: "/studio/v1/reviewers/{agent}",
29655
- streaming: "no",
29656
- pagination: false,
29657
- pathParams: [
29658
- {
29659
- name: "agent",
29660
- sdkName: "agent",
29661
- description: "Reviewer being addressed, by the agent value the reviewer list returns for it; a reviewer is an agent of this organization's reviewer library, so it has no other address."
29662
- }
29663
- ],
29664
- query: [],
29665
- body: {
29666
- required: true,
29667
- fields: [
29668
- {
29669
- name: "active",
29670
- type: "boolean",
29671
- required: true,
29672
- description: "Set false to take this reviewer out of the draw for rounds sent from now on, true to put it back; rounds already sent keep the reviewers they drew."
29673
- }
29674
- ]
29675
- }
29676
- },
29677
29613
  {
29678
29614
  resource: "studio.styles",
29679
29615
  method: "list",
@@ -31282,7 +31218,7 @@ for more details.`
31282
31218
  resource: "studio.works.reviewSettings",
31283
31219
  method: "retrieve",
31284
31220
  summary: "Read the review settings of a work",
31285
- description: "Read how this work is reviewed: the seats that make up its review panel, each naming a reviewer kind, a tag and how many reviewers are drawn for it, the maximum number of rounds, and the revision the settings are at. Read it before sending a round, because a draft whose conditions the reviewer library cannot fill answers REVIEWER_POOL_EMPTY, and read it before changing it, because the update carries the revision it returns as its precondition. Settings are not part of the work body: they are read and written here.",
31221
+ description: "Read how this work is reviewed: the most rounds it may take and the revision the settings are at. Who reviews is not here but on the work's reviewer roster, which every round asks whole, and read that with the reviewer list. Read this before sending a round, because a draft past its max_rounds answers REVIEW_ROUND_LIMIT, and before changing it, because the update carries the revision it returns as its precondition. Settings are not part of the work body: they are read and written here.",
31286
31222
  http: "GET",
31287
31223
  path: "/studio/v1/works/{work}/review-settings",
31288
31224
  streaming: "no",
@@ -31299,8 +31235,8 @@ for more details.`
31299
31235
  {
31300
31236
  resource: "studio.works.reviewSettings",
31301
31237
  method: "update",
31302
- summary: "Change the review settings of a work",
31303
- description: "Change the review panel of a work: the seats, the maximum number of rounds, or both. Send expected_revision with the revision this settings read returned, so two writers cannot overwrite each other silently; a mismatch answers REVISION_CONFLICT and the settings are unchanged. A person makes this change, because widening who may judge a work is the owner's decision: an agent calling it is refused with PERMISSION_DENIED, which is this operation's answer for a caller without the organization's management identity. The settings are locked while a round of this work is reviewing, which answers REVIEW_IN_PROGRESS; change them after the round decides or is cancelled. Raising max_rounds is how a draft whose rounds are used up is sent again. The changed settings apply to rounds sent from now on and never rewrite a round already sent.",
31238
+ summary: "Change how many rounds a work may take",
31239
+ description: "Change how many rounds a work may take. Send expected_revision with the revision this settings read returned, so two writers cannot overwrite each other silently; a mismatch answers REVISION_CONFLICT and the settings are unchanged. A person makes this change: an agent calling it is refused with PERMISSION_DENIED. The settings are locked while a round of this work is reviewing, which answers REVIEW_IN_PROGRESS; change them after the round decides or is cancelled. Raising max_rounds is how a draft whose rounds are used up is sent again. The changed limit applies to rounds sent from now on and never rewrites a round already sent; who reviews is on the reviewer roster, not here.",
31304
31240
  http: "PATCH",
31305
31241
  path: "/studio/v1/works/{work}/review-settings",
31306
31242
  streaming: "no",
@@ -31322,13 +31258,6 @@ for more details.`
31322
31258
  required: true,
31323
31259
  description: "Revision the settings read returned; a mismatch means somebody else changed the panel in between and this call is refused, so read the settings again and repeat with the new revision."
31324
31260
  },
31325
- {
31326
- name: "seats",
31327
- type: "array",
31328
- itemType: "object",
31329
- required: false,
31330
- description: "Seats the panel should have from now on, replacing the current seats whole; leave the field out to keep the current panel."
31331
- },
31332
31261
  {
31333
31262
  name: "max_rounds",
31334
31263
  type: "number",
@@ -31338,11 +31267,142 @@ for more details.`
31338
31267
  ]
31339
31268
  }
31340
31269
  },
31270
+ {
31271
+ resource: "studio.works.reviewers",
31272
+ method: "list",
31273
+ summary: "List the reviewers of a work",
31274
+ description: "List the reviewers on this work's roster: every time a round of this work is sent, every reviewer on the roster whose kind the round asks for takes part, one seat each, in the order they were added, and the sender reads them as A, B, C. Each entry gives the agent, its kind on this roster, the service agent's display name and how many rounds of this work it has taken part in. Read it before sending a round, because a roster with nobody of the asked kind answers NO_REVIEWERS; read it after to see who has been judging. A reviewer of another work or another organization is never listed, and a work of another organization answers WORK_NOT_FOUND. The answer is one page; keep following next_page_token while it is present.",
31275
+ http: "GET",
31276
+ path: "/studio/v1/works/{work}/reviewers",
31277
+ streaming: "no",
31278
+ pagination: false,
31279
+ pathParams: [
31280
+ {
31281
+ name: "work",
31282
+ sdkName: "work",
31283
+ 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."
31284
+ }
31285
+ ],
31286
+ query: [
31287
+ {
31288
+ name: "page_size",
31289
+ type: "integer",
31290
+ required: false,
31291
+ 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."
31292
+ },
31293
+ {
31294
+ name: "page_token",
31295
+ type: "string",
31296
+ required: false,
31297
+ 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."
31298
+ }
31299
+ ]
31300
+ },
31301
+ {
31302
+ resource: "studio.works.reviewers",
31303
+ method: "create",
31304
+ summary: "Add a reviewer to a work",
31305
+ description: "Put one of this organization's service agents on the work's reviewer roster, with the kind it reviews as: expert writes a scored report, audience fills a screening card. Every round sent from now on asks every roster member of that round's kind, so add only agents that should judge every round of this work. A person makes this change, and an agent calling it is refused with PERMISSION_DENIED. The agent must be a service agent of this organization: anything else, including an absent id and another organization's agent, answers REVIEWER_NOT_SERVICE_AGENT. An agent already on the roster answers REVIEWER_ALREADY_ADDED; change its kind with the update operation instead.",
31306
+ http: "POST",
31307
+ path: "/studio/v1/works/{work}/reviewers",
31308
+ streaming: "no",
31309
+ pagination: false,
31310
+ pathParams: [
31311
+ {
31312
+ name: "work",
31313
+ sdkName: "work",
31314
+ 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."
31315
+ }
31316
+ ],
31317
+ query: [],
31318
+ body: {
31319
+ required: true,
31320
+ fields: [
31321
+ {
31322
+ name: "agent",
31323
+ type: "string",
31324
+ required: true,
31325
+ description: "Service agent of this organization to add, by its agt_ identifier; the agent must exist in this organization and be a service agent, or the call answers REVIEWER_NOT_SERVICE_AGENT."
31326
+ },
31327
+ {
31328
+ name: "kind",
31329
+ type: "string",
31330
+ enum: [
31331
+ "expert",
31332
+ "audience"
31333
+ ],
31334
+ required: true,
31335
+ description: "Kind this reviewer reviews as on this roster: expert writes a scored report, audience fills a screening card."
31336
+ }
31337
+ ]
31338
+ }
31339
+ },
31340
+ {
31341
+ resource: "studio.works.reviewers",
31342
+ method: "delete",
31343
+ summary: "Remove a reviewer from a work",
31344
+ description: "Take one agent off the work's reviewer roster, so rounds sent from now on no longer ask it. What it has already judged is kept: the rounds it took part in stay readable with their reports, and its round count is not reset by removing and adding it back. A person makes this change, and an agent calling it is refused with PERMISSION_DENIED. An agent that is not on this work's roster answers REVIEWER_NOT_FOUND.",
31345
+ http: "DELETE",
31346
+ path: "/studio/v1/works/{work}/reviewers/{agent}",
31347
+ streaming: "no",
31348
+ pagination: false,
31349
+ pathParams: [
31350
+ {
31351
+ name: "work",
31352
+ sdkName: "work",
31353
+ 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."
31354
+ },
31355
+ {
31356
+ name: "agent",
31357
+ sdkName: "agent",
31358
+ description: "Reviewer being addressed, by the agent value this work's reviewer list returns for it; a reviewer is a member of one work's roster, so it has no address outside that work."
31359
+ }
31360
+ ],
31361
+ query: []
31362
+ },
31363
+ {
31364
+ resource: "studio.works.reviewers",
31365
+ method: "update",
31366
+ summary: "Change a reviewer's kind",
31367
+ description: "Change the kind one roster member reviews as: expert or audience. Use it when a reviewer should judge a different way, rather than removing it and adding it back, because the roster position it holds decides its label and is kept. A person makes this change, and an agent calling it is refused with PERMISSION_DENIED. A round already sent is not affected, because its seats were fixed when it was sent. An agent that is not on this work's roster answers REVIEWER_NOT_FOUND, which is also the answer for another work's reviewer.",
31368
+ http: "PATCH",
31369
+ path: "/studio/v1/works/{work}/reviewers/{agent}",
31370
+ streaming: "no",
31371
+ pagination: false,
31372
+ pathParams: [
31373
+ {
31374
+ name: "work",
31375
+ sdkName: "work",
31376
+ 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."
31377
+ },
31378
+ {
31379
+ name: "agent",
31380
+ sdkName: "agent",
31381
+ description: "Reviewer being addressed, by the agent value this work's reviewer list returns for it; a reviewer is a member of one work's roster, so it has no address outside that work."
31382
+ }
31383
+ ],
31384
+ query: [],
31385
+ body: {
31386
+ required: true,
31387
+ fields: [
31388
+ {
31389
+ name: "kind",
31390
+ type: "string",
31391
+ enum: [
31392
+ "expert",
31393
+ "audience"
31394
+ ],
31395
+ required: true,
31396
+ description: "Kind this reviewer reviews as from now on; rounds already sent keep the kind they were sent with."
31397
+ }
31398
+ ]
31399
+ }
31400
+ },
31341
31401
  {
31342
31402
  resource: "studio.works.reviews",
31343
31403
  method: "list",
31344
31404
  summary: "List the blind review rounds of a work",
31345
- description: "List the review rounds of one work, newest round first, each with its draft, round number, status, decision and whether it was appealed. Pass draft to see the rounds of one draft only. Use it to find the round to read, to answer or to cancel, and to see whether the draft already has a round running before sending another: a running round answers REVIEW_IN_PROGRESS. The answer is one page; keep following next_page_token while it is present. Rounds of other organizations are not listed and a work of another organization answers WORK_NOT_FOUND.",
31405
+ description: "List the review rounds of one work, newest round first, each with its draft, round number, status and decision. Pass draft to see the rounds of one draft only. Use it to find the round to read, to answer or to cancel, and to see whether the draft already has a round running before sending another: a running round answers REVIEW_IN_PROGRESS. The answer is one page; keep following next_page_token while it is present. Rounds of other organizations are not listed and a work of another organization answers WORK_NOT_FOUND.",
31346
31406
  http: "GET",
31347
31407
  path: "/studio/v1/works/{work}/reviews",
31348
31408
  streaming: "no",
@@ -31379,7 +31439,7 @@ for more details.`
31379
31439
  resource: "studio.works.reviews",
31380
31440
  method: "create",
31381
31441
  summary: "Send a draft to blind review",
31382
- description: "Send one draft of this work to the blind review centre, which freezes the draft's content revision as it is now, draws reviewers for the work's review settings and asks them in. Use it once the draft is written; the centre chooses who reviews, and the sender only ever reads labels A, B, C, never the reviewer identities. Pass mode to narrow this round to expert reviewers, to audience reviewers or to both, which the settings do not decide. From the second round pass revision_of with the previous round's rv_ id and note with the change note that answers that round point by point. The answer is the new round in status reviewing; read it again with the review read until status becomes decided and then read decision, expert_reports and screening. Billing follows the reviewers' sessions, not the frame of this call. DRAFT_NOT_READY means the draft still has units without a body or fails a hard check, so finish it first; REVIEW_IN_PROGRESS means this draft already has a round running, so wait for it to decide or cancel it; REVIEW_ROUND_LIMIT means the work reached max_rounds and a person has to raise it in the review settings; REVIEWER_POOL_EMPTY means the reviewer library cannot fill the seats under these conditions, so a person registers or re-activates reviewers.",
31442
+ description: "Send one draft of this work to the blind review centre, which freezes the draft's content revision as it is now and asks in every reviewer on the work's roster whose kind this round asks. Use it once the draft is written; the roster decides who reviews, and the sender only ever reads labels A, B, C, never the reviewer identities. Pass mode to narrow this round to expert reviewers, to audience reviewers or to both, which the settings do not decide. From the second round pass revision_of with the previous round's rv_ id and note with the change note that answers that round point by point. The answer is the new round in status reviewing; read it again with the review read until status becomes decided and then read decision, expert_reports and screening. Billing follows the reviewers' sessions, not the frame of this call. DRAFT_NOT_READY means the draft still has units without a body or fails a hard check, so finish it first; REVIEW_IN_PROGRESS means this draft already has a round running, so wait for it to decide or cancel it; REVIEW_ROUND_LIMIT means the work reached max_rounds and a person has to raise it in the review settings; NO_REVIEWERS means the work's reviewer roster has nobody of the kind this round asks, so a person adds one to the work.",
31383
31443
  http: "POST",
31384
31444
  path: "/studio/v1/works/{work}/reviews",
31385
31445
  streaming: "no",
@@ -31431,7 +31491,7 @@ for more details.`
31431
31491
  resource: "studio.works.reviews",
31432
31492
  method: "retrieve",
31433
31493
  summary: "Read one blind review round",
31434
- description: "Read one round in the sender's view: its status, the seats as labels A, B, C with the state of each, the expert reports that have come back, the screening cards, the round decision and the audience tally. Reviewers appear only as labels; who they are is never part of this answer. Call it after sending a round and repeat while status is reviewing, because reviewers answer asynchronously and a round that is not decided yet carries fewer reports. status decided gives decision and screening; cancelled means a person stopped the round; failed means it could not be completed, for example when every reviewer timed out and no replacement could be drawn. Pass view=audit to also get the assignment record, the confidential editor notes and the reviewer sessions; that block is filled only for an organization administrator, and anyone else reads the same round without it.",
31494
+ description: "Read one round in the sender's view: its status, the seats as labels A, B, C with the state of each, the expert reports that have come back, the screening cards, the round decision and the audience tally. Reviewers appear only as labels; who they are is never part of this answer. Call it after sending a round and repeat while status is reviewing, because reviewers answer asynchronously and a round that is not decided yet carries fewer reports. status decided gives decision and screening; cancelled means a person stopped the round; failed means it could not be completed, for example when no reviewer on the roster answered at all. Pass view=audit to also get the assignment record, the confidential editor notes and the reviewer sessions; that block is filled only for an organization administrator, and anyone else reads the same round without it.",
31435
31495
  http: "GET",
31436
31496
  path: "/studio/v1/works/{work}/reviews/{review}",
31437
31497
  streaming: "no",
@@ -31445,7 +31505,7 @@ for more details.`
31445
31505
  {
31446
31506
  name: "review",
31447
31507
  sdkName: "review",
31448
- description: "Blind review round being addressed, by its rv_ identifier from the send answer or from the round list; the identifier stays the same when the round is appealed."
31508
+ description: "Blind review round being addressed, by its rv_ identifier from the send answer or from the round list."
31449
31509
  }
31450
31510
  ],
31451
31511
  query: [
@@ -31461,40 +31521,6 @@ for more details.`
31461
31521
  }
31462
31522
  ]
31463
31523
  },
31464
- {
31465
- resource: "studio.works.reviews",
31466
- method: "appeal",
31467
- summary: "Appeal a decided review round",
31468
- description: "Appeal the outcome of a round: the centre draws one more reviewer of the same kind and puts that reviewer's answer beside the existing ones, without telling them the earlier outcome. Use it once, when the sender disagrees with the decision; the reason is recorded for the review centre, and the sender cannot choose the new reviewer. The round goes back to status reviewing and its id stays the same, so read it again afterwards. Each round can be appealed once: a second call for the same round answers REVIEW_ALREADY_APPEALED. Only a decided round can be appealed, so a round that is still reviewing or was cancelled answers REVIEW_IN_PROGRESS or stays cancelled. The extra reviewer's session is billed like any other reviewer session.",
31469
- http: "POST",
31470
- path: "/studio/v1/works/{work}/reviews/{review}:appeal",
31471
- streaming: "no",
31472
- pagination: false,
31473
- pathParams: [
31474
- {
31475
- name: "work",
31476
- sdkName: "work",
31477
- 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."
31478
- },
31479
- {
31480
- name: "review",
31481
- sdkName: "review",
31482
- description: "Blind review round being addressed, by its rv_ identifier from the send answer or from the round list; the identifier stays the same when the round is appealed."
31483
- }
31484
- ],
31485
- query: [],
31486
- body: {
31487
- required: true,
31488
- fields: [
31489
- {
31490
- name: "reason",
31491
- type: "string",
31492
- required: true,
31493
- description: "Reason for the appeal, recorded for the review centre; it does not reach the reviewers and cannot name which reviewer to draw."
31494
- }
31495
- ]
31496
- }
31497
- },
31498
31524
  {
31499
31525
  resource: "studio.works.reviews",
31500
31526
  method: "cancel",
@@ -31513,7 +31539,7 @@ for more details.`
31513
31539
  {
31514
31540
  name: "review",
31515
31541
  sdkName: "review",
31516
- description: "Blind review round being addressed, by its rv_ identifier from the send answer or from the round list; the identifier stays the same when the round is appealed."
31542
+ description: "Blind review round being addressed, by its rv_ identifier from the send answer or from the round list."
31517
31543
  }
31518
31544
  ],
31519
31545
  query: []
@@ -32469,7 +32495,7 @@ for more details.`
32469
32495
  name: "filter",
32470
32496
  type: "string",
32471
32497
  required: false,
32472
- description: "Search qualifier subset: is/state, reason, label/-label, no, assignee, author, mentions, milestone, type, kind, assignee-kind, in and sort; write each qualifier as field:value (for example, is:open milestone:5), never field=value. Unknown qualifiers return INVALID_PARAMS. Passed unchanged to the service."
32498
+ description: "Search qualifier subset: is/state, reason, label/-label, no, assignee, owner, author, mentions, milestone, type, kind, assignee-kind, in and sort (owner:<subject>|none|*|me and no:owner match the single ticket owner; assignee: matches the GitHub-compatible assignees); write each qualifier as field:value (for example, is:open milestone:5), never field=value. Unknown qualifiers return INVALID_PARAMS. Passed unchanged to the service."
32473
32499
  }
32474
32500
  ]
32475
32501
  },
@@ -43507,7 +43533,7 @@ var studioWorksReviewsRetrieve = (options) => (options.client ?? client).get({
43507
43533
  url: "/studio/v1/works/{work}/reviews/{review}",
43508
43534
  ...options
43509
43535
  });
43510
- var studioWorksReviewsAppeal = (options) => (options.client ?? client).post({
43536
+ var studioWorksReviewsCancel = (options) => (options.client ?? client).post({
43511
43537
  security: [{
43512
43538
  key: "BearerAuth",
43513
43539
  scheme: "bearer",
@@ -43517,14 +43543,10 @@ var studioWorksReviewsAppeal = (options) => (options.client ?? client).post({
43517
43543
  name: "X-API-Key",
43518
43544
  type: "apiKey"
43519
43545
  }],
43520
- url: "/studio/v1/works/{work}/reviews/{review}:appeal",
43521
- ...options,
43522
- headers: {
43523
- "Content-Type": "application/json",
43524
- ...options.headers
43525
- }
43546
+ url: "/studio/v1/works/{work}/reviews/{review}:cancel",
43547
+ ...options
43526
43548
  });
43527
- var studioWorksReviewsCancel = (options) => (options.client ?? client).post({
43549
+ var studioWorksReviewSettingsRetrieve = (options) => (options.client ?? client).get({
43528
43550
  security: [{
43529
43551
  key: "BearerAuth",
43530
43552
  scheme: "bearer",
@@ -43534,10 +43556,10 @@ var studioWorksReviewsCancel = (options) => (options.client ?? client).post({
43534
43556
  name: "X-API-Key",
43535
43557
  type: "apiKey"
43536
43558
  }],
43537
- url: "/studio/v1/works/{work}/reviews/{review}:cancel",
43559
+ url: "/studio/v1/works/{work}/review-settings",
43538
43560
  ...options
43539
43561
  });
43540
- var studioWorksReviewSettingsRetrieve = (options) => (options.client ?? client).get({
43562
+ var studioWorksReviewSettingsUpdate = (options) => (options.client ?? client).patch({
43541
43563
  security: [{
43542
43564
  key: "BearerAuth",
43543
43565
  scheme: "bearer",
@@ -43548,9 +43570,26 @@ var studioWorksReviewSettingsRetrieve = (options) => (options.client ?? client).
43548
43570
  type: "apiKey"
43549
43571
  }],
43550
43572
  url: "/studio/v1/works/{work}/review-settings",
43573
+ ...options,
43574
+ headers: {
43575
+ "Content-Type": "application/json",
43576
+ ...options.headers
43577
+ }
43578
+ });
43579
+ var studioWorksReviewersList = (options) => (options.client ?? client).get({
43580
+ security: [{
43581
+ key: "BearerAuth",
43582
+ scheme: "bearer",
43583
+ type: "http"
43584
+ }, {
43585
+ key: "ApiKeyAuth",
43586
+ name: "X-API-Key",
43587
+ type: "apiKey"
43588
+ }],
43589
+ url: "/studio/v1/works/{work}/reviewers",
43551
43590
  ...options
43552
43591
  });
43553
- var studioWorksReviewSettingsUpdate = (options) => (options.client ?? client).patch({
43592
+ var studioWorksReviewersCreate = (options) => (options.client ?? client).post({
43554
43593
  security: [{
43555
43594
  key: "BearerAuth",
43556
43595
  scheme: "bearer",
@@ -43560,14 +43599,14 @@ var studioWorksReviewSettingsUpdate = (options) => (options.client ?? client).pa
43560
43599
  name: "X-API-Key",
43561
43600
  type: "apiKey"
43562
43601
  }],
43563
- url: "/studio/v1/works/{work}/review-settings",
43602
+ url: "/studio/v1/works/{work}/reviewers",
43564
43603
  ...options,
43565
43604
  headers: {
43566
43605
  "Content-Type": "application/json",
43567
43606
  ...options.headers
43568
43607
  }
43569
43608
  });
43570
- var studioReviewersList = (options) => (options?.client ?? client).get({
43609
+ var studioWorksReviewersDelete = (options) => (options.client ?? client).delete({
43571
43610
  security: [{
43572
43611
  key: "BearerAuth",
43573
43612
  scheme: "bearer",
@@ -43577,10 +43616,10 @@ var studioReviewersList = (options) => (options?.client ?? client).get({
43577
43616
  name: "X-API-Key",
43578
43617
  type: "apiKey"
43579
43618
  }],
43580
- url: "/studio/v1/reviewers",
43619
+ url: "/studio/v1/works/{work}/reviewers/{agent}",
43581
43620
  ...options
43582
43621
  });
43583
- var studioReviewersUpdate = (options) => (options.client ?? client).patch({
43622
+ var studioWorksReviewersUpdate = (options) => (options.client ?? client).patch({
43584
43623
  security: [{
43585
43624
  key: "BearerAuth",
43586
43625
  scheme: "bearer",
@@ -43590,7 +43629,7 @@ var studioReviewersUpdate = (options) => (options.client ?? client).patch({
43590
43629
  name: "X-API-Key",
43591
43630
  type: "apiKey"
43592
43631
  }],
43593
- url: "/studio/v1/reviewers/{agent}",
43632
+ url: "/studio/v1/works/{work}/reviewers/{agent}",
43594
43633
  ...options,
43595
43634
  headers: {
43596
43635
  "Content-Type": "application/json",
@@ -45612,10 +45651,6 @@ function createStudio(transport) {
45612
45651
  list: bind(transport, studioPlatformsList),
45613
45652
  retrieve: bind(transport, studioPlatformsGet)
45614
45653
  },
45615
- reviewers: {
45616
- list: bind(transport, studioReviewersList),
45617
- update: bind(transport, studioReviewersUpdate)
45618
- },
45619
45654
  styles: {
45620
45655
  create: bind(transport, studioStylesCreate),
45621
45656
  delete: bind(transport, studioStylesDelete),
@@ -45675,8 +45710,13 @@ function createStudio(transport) {
45675
45710
  retrieve: bind(transport, studioWorksReviewSettingsRetrieve),
45676
45711
  update: bind(transport, studioWorksReviewSettingsUpdate)
45677
45712
  },
45713
+ reviewers: {
45714
+ create: bind(transport, studioWorksReviewersCreate),
45715
+ delete: bind(transport, studioWorksReviewersDelete),
45716
+ list: bind(transport, studioWorksReviewersList),
45717
+ update: bind(transport, studioWorksReviewersUpdate)
45718
+ },
45678
45719
  reviews: {
45679
- appeal: bind(transport, studioWorksReviewsAppeal),
45680
45720
  cancel: bind(transport, studioWorksReviewsCancel),
45681
45721
  create: bind(transport, studioWorksReviewsCreate),
45682
45722
  list: bind(transport, studioWorksReviewsList),
@@ -47667,6 +47707,7 @@ var workflows = [
47667
47707
  { words: ["app", "publish"], usage: "app publish [--dir <path>] [--no-build]", summary: "Build the project, publish it, create declared secrets, run the health check and print the URL.", example: "praxis app publish --dir ./my-app" },
47668
47708
  { 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>" },
47669
47709
  { 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" },
47710
+ { words: ["devops", "deploy"], usage: "devops deploy --engine tofu --env <develop|production> --commit <sha> [--targets a,b] [--plan-only] [--plan-dir <dir>] [--apply-plans <dir>] [--events-file <path>]", summary: "Roll targets out through OpenTofu: build, generate, plan (--plan-only) or apply approved plans (--apply-plans), layer by layer, writing the ExecutorLine events DevOps folds.", example: "praxis devops deploy --engine tofu --env develop --commit $(git rev-parse HEAD) --events-file /tmp/deploy-events.ndjson" },
47670
47711
  { 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" },
47671
47712
  { 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"' },
47672
47713
  { words: ["skill"], usage: "skill [--install <dir>]", summary: "Print the AI skill, or write <dir>/praxis-cli/SKILL.md." }
@@ -48865,191 +48906,6 @@ async function appRollback(args, client2, ports) {
48865
48906
  // src/commands/devops.ts
48866
48907
  import { join as join4 } from "node:path";
48867
48908
 
48868
- // src/devops/pure.ts
48869
- import { createHash as createHash2 } from "node:crypto";
48870
- var PROJECT_ID = /^dvp_[a-z0-9]+$/;
48871
- var POLL_MS = 5000;
48872
- var FAILURE_LIMIT = 20;
48873
- var hint = 'Pass --project dvp_…, or add "devops": { "project": "dvp_…" } to praxis.jsonc in the current directory.';
48874
- function checkProject(value, hintText = hint) {
48875
- if (typeof value !== "string" || !value.trim())
48876
- throw new UsageError("A DevOps project id must be a non-empty string", hintText);
48877
- if (!PROJECT_ID.test(value.trim()))
48878
- throw new UsageError(`Not a DevOps project id: ${value}`, "A project id starts with dvp_ and comes from the project list. " + hintText);
48879
- return value.trim();
48880
- }
48881
- function parseDevopsProject(value) {
48882
- if (value === null || value === undefined || typeof value !== "object" || Array.isArray(value))
48883
- return;
48884
- const devops = value.devops;
48885
- if (devops === undefined)
48886
- return;
48887
- if (devops === null || typeof devops !== "object" || Array.isArray(devops))
48888
- throw new UsageError("praxis.jsonc devops must be an object", 'Write {"devops":{"project":"dvp_…"}}. ' + hint);
48889
- const project = devops.project;
48890
- if (project === undefined)
48891
- return;
48892
- return checkProject(project);
48893
- }
48894
- function resolveProject(flag, projectFile) {
48895
- if (flag !== undefined)
48896
- return checkProject(flag);
48897
- const fromFile = parseDevopsProject(projectFile);
48898
- if (fromFile !== undefined)
48899
- return fromFile;
48900
- throw new UsageError("No DevOps project named for this run", hint);
48901
- }
48902
- var sorted = (values) => [...values].sort();
48903
- var SELECT_KINDS = { tag: "anyTags", package: "packages", suite: "packages", file: "packages" };
48904
- function parseSelect(values) {
48905
- if (!values.length)
48906
- return;
48907
- const tags = [], packages = [];
48908
- for (const raw of values) {
48909
- const at = raw.indexOf(":");
48910
- const kind = at < 0 ? "tag" : raw.slice(0, at).trim().toLowerCase();
48911
- const value = (at < 0 ? raw : raw.slice(at + 1)).trim();
48912
- const kinds = Object.keys(SELECT_KINDS).join(", ");
48913
- if (!value)
48914
- throw new UsageError(`--select ${raw} names no value`, `Use --select <kind>:<value>, or a bare tag name; kinds are ${kinds}.`);
48915
- if (!Object.hasOwn(SELECT_KINDS, kind))
48916
- throw new UsageError(`--select ${raw}: unknown kind "${kind}"`, `Use one of: ${kinds}.`);
48917
- (SELECT_KINDS[kind] === "anyTags" ? tags : packages).push(value);
48918
- }
48919
- return { ...tags.length ? { anyTags: sorted(tags) } : {}, ...packages.length ? { packages: sorted(packages) } : {} };
48920
- }
48921
- function parseRepeat(value) {
48922
- if (value === undefined)
48923
- return 1;
48924
- const n = typeof value === "string" && value.trim() ? Number(value) : NaN;
48925
- if (!Number.isSafeInteger(n) || n < 1)
48926
- throw new UsageError("--repeat must be an integer of at least 1");
48927
- return n;
48928
- }
48929
- function requireRemote(remote) {
48930
- if (!remote)
48931
- throw new UsageError("Only remote test runs are available", "Add --remote to run the selected cases on the Praxis cloud executor.");
48932
- }
48933
- function requestIdFor(input) {
48934
- const selector = input.selector === undefined ? null : {
48935
- sizes: sorted(input.selector.sizes ?? []),
48936
- anyTags: sorted(input.selector.anyTags ?? []),
48937
- packages: sorted(input.selector.packages ?? []),
48938
- cases: sorted(input.selector.cases ?? [])
48939
- };
48940
- const material = JSON.stringify(["devops-test-run", input.project, input.commit, input.repeat, selector]);
48941
- return `req_${createHash2("sha256").update(material).digest("hex").slice(0, 32)}`;
48942
- }
48943
- var isTerminal = (state) => state === "finished";
48944
- function shortSha(commit) {
48945
- return commit.slice(0, 7);
48946
- }
48947
- function headBranch(output) {
48948
- const name = output.trim();
48949
- return !name || name === "HEAD" ? undefined : name;
48950
- }
48951
- function requirePushed(remoteContains, commit, branch) {
48952
- if (remoteContains.trim())
48953
- return;
48954
- throw new UsageError(`Commit ${shortSha(commit)}${branch ? ` on ${branch}` : ""} is not on any remote branch`, `Push it first (git push${branch ? ` origin ${branch}` : ""}); the run tests the pushed commit, and this command never pushes for you.`);
48955
- }
48956
- function dirtyNotice(status, commit) {
48957
- const files = status.split(`
48958
- `).filter((line) => line.trim()).length;
48959
- if (files === 0)
48960
- return;
48961
- return `Warning: ${files} uncommitted change${files === 1 ? "" : "s"}; the run tests the pushed commit ${shortSha(commit)}, not this working tree.`;
48962
- }
48963
- function exitCodeFor(result) {
48964
- return result === "passed" || result === "pending" ? 0 : 1;
48965
- }
48966
- var wantsFailures = (result) => result !== "passed" && result !== "pending";
48967
- function failedList(items, nextPageToken2, url) {
48968
- const shown = items.slice(0, FAILURE_LIMIT);
48969
- if (items.length <= FAILURE_LIMIT && !nextPageToken2)
48970
- return { shown };
48971
- return { shown, hint: `Showing ${FAILURE_LIMIT} of the failed cases; the run page lists them all: ${url}` };
48972
- }
48973
- var CONSOLE = { develop: "https://console-develop.deepraxis.com", production: "https://console.deepraxis.com" };
48974
- function runUrl(env, project, id, viewerUrl) {
48975
- return viewerUrl?.trim() || `${CONSOLE[env]}/devops/projects/${project}/test-runs/${id}`;
48976
- }
48977
-
48978
- // src/commands/devops.ts
48979
- async function projectFile(cwd, ports) {
48980
- let text;
48981
- try {
48982
- text = await ports.readFile(join4(cwd, "praxis.jsonc"));
48983
- } catch (error) {
48984
- if (error.code === "ENOENT")
48985
- return;
48986
- throw error;
48987
- }
48988
- try {
48989
- return parseJsonc(text);
48990
- } catch (error) {
48991
- throw new UsageError(`praxis.jsonc is not valid JSONC: ${error.message}`);
48992
- }
48993
- }
48994
- var COUNT_ORDER = ["passed", "failed", "flaky", "skipped", "pending", "other"];
48995
- var countLine = (counts) => COUNT_ORDER.filter((key) => counts?.[key]).map((key) => `${counts[key]} ${key}`).join(", ") || "no counts reported";
48996
- async function devopsTestRun(args, connect, env, ports) {
48997
- requireRemote(args.remote);
48998
- const project = resolveProject(args.project, await projectFile(ports.cwd, ports));
48999
- const selector = parseSelect(args.select ?? []);
49000
- const repeat = parseRepeat(args.repeat);
49001
- const git = async (gitArgs) => (await ports.git(gitArgs, ports.cwd)).output;
49002
- const commit = (await git(["rev-parse", "HEAD"])).trim();
49003
- if (!commit)
49004
- throw new UsageError("git rev-parse HEAD answered no commit", "Run this command inside a git repository.");
49005
- const branch = headBranch(await git(["rev-parse", "--abbrev-ref", "HEAD"]));
49006
- requirePushed(await git(["branch", "-r", "--contains", "HEAD"]), commit, branch);
49007
- const notice = dirtyNotice(await git(["status", "--porcelain"]), commit);
49008
- if (notice)
49009
- ports.emit({ kind: "message", channel: "stderr", text: notice });
49010
- const client2 = await connect();
49011
- const requestId = requestIdFor({ project, commit, selector, repeat });
49012
- let run = await client2.devops.projects.testRuns.create({ path: { project }, body: { ref: { ...branch ? { branch } : {}, commit }, ...selector ? { selector } : {}, repeat, executor: "cloud", requestId } });
49013
- while (args.wait && !isTerminal(run.state)) {
49014
- await ports.wait(POLL_MS);
49015
- run = await client2.devops.testRuns.retrieve({ path: { id: run.id } });
49016
- }
49017
- const url = runUrl(env, project, run.id, run.viewerUrl);
49018
- let failures = [], failureHint;
49019
- if (wantsFailures(run.result)) {
49020
- const page = await client2.devops.testRuns.executions.list({ path: { run: run.id }, query: { pageSize: FAILURE_LIMIT, filter: "result=failed" } });
49021
- ({ shown: failures, hint: failureHint } = failedList(page.items, page.nextPageToken, url));
49022
- }
49023
- const data = {
49024
- id: run.id,
49025
- url,
49026
- project,
49027
- state: run.state,
49028
- result: run.result,
49029
- repeat,
49030
- commit,
49031
- ...branch ? { branch } : {},
49032
- selected: run.selection?.selectedCount ?? null,
49033
- counts: run.counts ?? null,
49034
- request_id: requestId,
49035
- failures: failures.map((execution) => ({ case: execution.case, title: execution.title, package: execution.package ?? null, status: execution.status })),
49036
- ...failureHint ? { failures_hint: failureHint } : {}
49037
- };
49038
- ports.emit({ kind: "object", data });
49039
- ports.human([
49040
- `${run.result} — ${project} @ ${commit.slice(0, 7)}${branch ? ` (${branch})` : ""}`,
49041
- `state ${run.state}, ${countLine(run.counts)}`,
49042
- url,
49043
- ...failures.map((execution) => ` failed ${execution.title}`),
49044
- ...failureHint ? [failureHint] : []
49045
- ].join(`
49046
- `));
49047
- return exitCodeFor(run.result);
49048
- }
49049
-
49050
- // src/commands/devops-deploy-plan.ts
49051
- import { resolve as resolve2 } from "node:path";
49052
-
49053
48909
  // ../../packages/praxis/deploy-core/src/jsonc.ts
49054
48910
  function parseJsonc2(text) {
49055
48911
  let parsed;
@@ -49557,6 +49413,15 @@ function isDeployToolDependency(name, path) {
49557
49413
  function targetsFor(plan, environment2) {
49558
49414
  return plan.targets.filter((target) => target.environments === undefined || target.environments.includes(environment2));
49559
49415
  }
49416
+ function deploysTo(target, environment2, options) {
49417
+ if (target.environments !== undefined && !target.environments.includes(environment2))
49418
+ return false;
49419
+ if (environment2 === "production" && !target.production)
49420
+ return false;
49421
+ if (!target.onTrain && !options.named)
49422
+ return false;
49423
+ return true;
49424
+ }
49560
49425
  var TARGET_EXTERNAL_INPUTS = {
49561
49426
  "apps/docs": [
49562
49427
  "apps/api/openapi/openapi.yaml",
@@ -49640,6 +49505,708 @@ function stronglyConnected(count2, edges) {
49640
49505
  visit2(node2);
49641
49506
  return components;
49642
49507
  }
49508
+ // ../../packages/praxis/deploy-core/src/job-events.ts
49509
+ var DEFAULT_EXPIRE_MINUTES = 60;
49510
+ var DEFAULT_PHASE_ID = "stable";
49511
+ function jobStatesOf(outcome) {
49512
+ switch (outcome.kind) {
49513
+ case "succeeded":
49514
+ return { jobState: "succeeded", jobRunState: "succeeded" };
49515
+ case "failed":
49516
+ return { jobState: "failed", jobRunState: "failed" };
49517
+ case "disabled":
49518
+ return { jobState: "disabled", jobRunState: "unspecified" };
49519
+ case "skipped":
49520
+ return { jobState: "skipped", jobRunState: "unspecified" };
49521
+ }
49522
+ }
49523
+ function formatDeployEvent(event) {
49524
+ return `${JSON.stringify(event)}
49525
+ `;
49526
+ }
49527
+ function expireTimeOf(startedAt, expireMinutes = DEFAULT_EXPIRE_MINUTES) {
49528
+ const start = Date.parse(startedAt);
49529
+ if (Number.isNaN(start))
49530
+ throw new Error(`--events-file needs a parseable start time, got ${JSON.stringify(startedAt)}`);
49531
+ const minutes = Number(expireMinutes);
49532
+ if (!Number.isFinite(minutes) || minutes <= 0)
49533
+ throw new Error(`--expire-minutes must be a positive number, got ${JSON.stringify(expireMinutes)}`);
49534
+ return new Date(start + minutes * 60000).toISOString();
49535
+ }
49536
+ function decidePhaseState(states) {
49537
+ if (states.length === 0)
49538
+ return "unspecified";
49539
+ if (states.some((state) => state === "failed" || state === "aborted"))
49540
+ return "failed";
49541
+ if (states.some((state) => state === "in_progress" || state === "pending"))
49542
+ return "in_progress";
49543
+ const neverRan = states.every((state) => state === "skipped" || state === "disabled");
49544
+ return neverRan ? "skipped" : "succeeded";
49545
+ }
49546
+ function decideRolloutState(jobs) {
49547
+ const states = [...jobs.values()];
49548
+ if (states.some((state) => state === "failed" || state === "aborted"))
49549
+ return "failed";
49550
+ const deploy = jobs.get("deploy");
49551
+ if (deploy === undefined || deploy === "pending" || deploy === "in_progress" || deploy === "skipped" || deploy === "disabled")
49552
+ return "pending";
49553
+ if (states.every((state) => state === "succeeded" || state === "skipped" || state === "disabled" || state === "ignored")) {
49554
+ return "succeeded";
49555
+ }
49556
+ return "pending";
49557
+ }
49558
+ function decideFinishedState(rollouts) {
49559
+ if (rollouts.length === 0)
49560
+ return "failed";
49561
+ const count2 = (wanted) => rollouts.filter((state) => wanted.includes(state)).length;
49562
+ const succeeded = count2(["succeeded", "skipped"]);
49563
+ const failed = count2(["failed"]);
49564
+ const waiting = count2(["pending"]);
49565
+ if (failed === 0)
49566
+ return succeeded === rollouts.length ? "succeeded" : "failed";
49567
+ return succeeded > 0 && waiting > 0 ? "halted" : "failed";
49568
+ }
49569
+ // ../../packages/praxis/deploy-core/src/tofu/contract.ts
49570
+ var CLOUDFLARE_PROVIDER_VERSION = "5.28.1";
49571
+ var OPENTOFU_REQUIRED_VERSION = ">= 1.10.0";
49572
+ function stateKeyOf(environment2, target) {
49573
+ return `env/${environment2}/${target}/terraform.tfstate`;
49574
+ }
49575
+ // ../../packages/praxis/deploy-core/src/tofu/generate.ts
49576
+ var WORKER_ADDRESS = "cloudflare_workers_script.worker";
49577
+ var WORKER_REF = "${cloudflare_workers_script.worker.script_name}";
49578
+ var INHERITABLE = [
49579
+ "main",
49580
+ "compatibility_date",
49581
+ "compatibility_flags",
49582
+ "observability",
49583
+ "placement",
49584
+ "limits",
49585
+ "logpush",
49586
+ "tail_consumers",
49587
+ "preview_urls"
49588
+ ];
49589
+ var NON_BINDING_KEYS = new Set([
49590
+ "$schema",
49591
+ "name",
49592
+ "main",
49593
+ "compatibility_date",
49594
+ "compatibility_flags",
49595
+ "observability",
49596
+ "placement",
49597
+ "limits",
49598
+ "logpush",
49599
+ "tail_consumers",
49600
+ "preview_urls",
49601
+ "routes",
49602
+ "route",
49603
+ "workers_dev",
49604
+ "triggers",
49605
+ "migrations",
49606
+ "containers",
49607
+ "rules",
49608
+ "alias",
49609
+ "build",
49610
+ "define",
49611
+ "minify",
49612
+ "keep_names",
49613
+ "send_metrics",
49614
+ "upload_source_maps",
49615
+ "node_compat",
49616
+ "tsconfig",
49617
+ "base_dir",
49618
+ "no_bundle",
49619
+ "find_additional_modules",
49620
+ "usage_model",
49621
+ "account_id",
49622
+ "dev",
49623
+ "site",
49624
+ "env",
49625
+ "legacy_env",
49626
+ "jsx_factory",
49627
+ "jsx_fragment",
49628
+ "first_party_worker",
49629
+ "workers_dev",
49630
+ "assets",
49631
+ "queues",
49632
+ "vars",
49633
+ "ai",
49634
+ "analytics_engine_datasets",
49635
+ "browser",
49636
+ "d1_databases",
49637
+ "dispatch_namespaces",
49638
+ "durable_objects",
49639
+ "flagship",
49640
+ "images",
49641
+ "kv_namespaces",
49642
+ "media",
49643
+ "pipelines",
49644
+ "r2_buckets",
49645
+ "ratelimits",
49646
+ "secrets_store_secrets",
49647
+ "send_email",
49648
+ "services",
49649
+ "vectorize",
49650
+ "version_metadata",
49651
+ "worker_loaders",
49652
+ "workflows"
49653
+ ]);
49654
+ var KNOWN_UNSUPPORTED = ["hyperdrive", "mtls_certificates", "unsafe", "text_blobs", "data_blobs", "wasm_modules", "vpc_services"];
49655
+ var isRec = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
49656
+ var recs = (value) => Array.isArray(value) ? value.filter(isRec) : [];
49657
+ var str = (value) => typeof value === "string" && value !== "" ? value : undefined;
49658
+ function projectEnvironment(wrangler, environment2) {
49659
+ if (environment2 === "develop") {
49660
+ const { env: _env, ...rest } = wrangler;
49661
+ return rest;
49662
+ }
49663
+ const block = isRec(wrangler.env) ? wrangler.env.production : undefined;
49664
+ if (!isRec(block))
49665
+ return null;
49666
+ const projected = { ...block };
49667
+ for (const key of INHERITABLE)
49668
+ if (!(key in projected) && key in wrangler)
49669
+ projected[key] = wrangler[key];
49670
+ if (str(projected.name) === undefined) {
49671
+ const base = str(wrangler.name);
49672
+ if (base !== undefined)
49673
+ projected.name = `${base}-production`;
49674
+ }
49675
+ return projected;
49676
+ }
49677
+ function collectBindings(config, own, assetsDir) {
49678
+ const bindings = [];
49679
+ const refs = [];
49680
+ const gaps = [];
49681
+ const refusals = [];
49682
+ const unresolved = (binding, detail) => {
49683
+ refusals.push({ kind: "unresolved-resource", binding, detail });
49684
+ };
49685
+ if (isRec(config.vars)) {
49686
+ for (const [name, value] of Object.entries(config.vars)) {
49687
+ bindings.push(typeof value === "string" ? { type: "plain_text", name, text: value } : { type: "json", name, json: JSON.stringify(value) });
49688
+ }
49689
+ }
49690
+ if (isRec(config.ai) && str(config.ai.binding))
49691
+ bindings.push({ type: "ai", name: config.ai.binding });
49692
+ for (const entry of recs(config.analytics_engine_datasets)) {
49693
+ const name = str(entry.binding) ?? "?";
49694
+ const dataset = str(entry.dataset);
49695
+ if (dataset === undefined) {
49696
+ unresolved(name, "analytics engine binding has no dataset");
49697
+ continue;
49698
+ }
49699
+ bindings.push({ type: "analytics_engine", name, dataset });
49700
+ gaps.push({ kind: "analytics-engine-dataset", binding: name, dataset });
49701
+ }
49702
+ if (isRec(config.browser) && str(config.browser.binding))
49703
+ bindings.push({ type: "browser", name: config.browser.binding });
49704
+ for (const entry of recs(config.d1_databases)) {
49705
+ const name = str(entry.binding) ?? "?";
49706
+ const id = str(entry.database_id);
49707
+ if (id === undefined) {
49708
+ unresolved(name, "d1 binding has no database_id");
49709
+ continue;
49710
+ }
49711
+ bindings.push({ type: "d1", name, database_id: id });
49712
+ gaps.push({
49713
+ kind: "d1-migrations",
49714
+ binding: name,
49715
+ databaseName: str(entry.database_name) ?? id,
49716
+ migrationsDir: str(entry.migrations_dir) ?? "migrations"
49717
+ });
49718
+ }
49719
+ for (const entry of recs(config.dispatch_namespaces)) {
49720
+ const name = str(entry.binding) ?? "?";
49721
+ const namespace = str(entry.namespace);
49722
+ if (namespace === undefined) {
49723
+ unresolved(name, "dispatch namespace binding has no namespace");
49724
+ continue;
49725
+ }
49726
+ const binding = { type: "dispatch_namespace", name, namespace };
49727
+ const outbound = isRec(entry.outbound) ? entry.outbound : undefined;
49728
+ const service = str(outbound?.service);
49729
+ if (outbound && service !== undefined) {
49730
+ binding.outbound = {
49731
+ worker: { service, environment: "production" },
49732
+ ...Array.isArray(outbound.parameters) ? { params: outbound.parameters } : {}
49733
+ };
49734
+ refs.push(service);
49735
+ }
49736
+ bindings.push(binding);
49737
+ }
49738
+ const objectBindings = isRec(config.durable_objects) ? recs(config.durable_objects.bindings) : [];
49739
+ for (const entry of objectBindings) {
49740
+ const script = str(entry.script_name);
49741
+ const binding = { type: "durable_object_namespace", name: str(entry.name) ?? "?", class_name: str(entry.class_name) ?? "?" };
49742
+ if (script !== undefined && script !== own) {
49743
+ binding.script_name = script;
49744
+ refs.push(script);
49745
+ }
49746
+ bindings.push(binding);
49747
+ }
49748
+ for (const entry of recs(config.flagship)) {
49749
+ const name = str(entry.binding) ?? "?";
49750
+ const appId = str(entry.app_id);
49751
+ if (appId === undefined) {
49752
+ unresolved(name, "flagship binding has no app_id");
49753
+ continue;
49754
+ }
49755
+ bindings.push({ type: "flagship", name, app_id: appId });
49756
+ }
49757
+ if (isRec(config.images) && str(config.images.binding))
49758
+ bindings.push({ type: "images", name: config.images.binding });
49759
+ for (const entry of recs(config.kv_namespaces)) {
49760
+ const name = str(entry.binding) ?? "?";
49761
+ const id = str(entry.id);
49762
+ if (id === undefined) {
49763
+ unresolved(name, "kv binding has no id");
49764
+ continue;
49765
+ }
49766
+ bindings.push({ type: "kv_namespace", name, namespace_id: id });
49767
+ }
49768
+ if (isRec(config.media) && str(config.media.binding))
49769
+ bindings.push({ type: "media", name: config.media.binding });
49770
+ for (const entry of recs(config.pipelines)) {
49771
+ const name = str(entry.binding) ?? "?";
49772
+ const pipeline = str(entry.stream) ?? str(entry.pipeline);
49773
+ if (pipeline === undefined) {
49774
+ unresolved(name, "pipeline binding has no stream");
49775
+ continue;
49776
+ }
49777
+ bindings.push({ type: "pipelines", name, pipeline });
49778
+ }
49779
+ const producers = isRec(config.queues) ? recs(config.queues.producers) : [];
49780
+ for (const entry of producers) {
49781
+ const name = str(entry.binding) ?? "?";
49782
+ const queue = str(entry.queue);
49783
+ if (queue === undefined) {
49784
+ unresolved(name, "queue producer has no queue");
49785
+ continue;
49786
+ }
49787
+ bindings.push({ type: "queue", name, queue_name: queue });
49788
+ }
49789
+ for (const entry of recs(config.r2_buckets)) {
49790
+ const name = str(entry.binding) ?? "?";
49791
+ const bucket = str(entry.bucket_name);
49792
+ if (bucket === undefined) {
49793
+ unresolved(name, "r2 binding has no bucket_name");
49794
+ continue;
49795
+ }
49796
+ bindings.push({
49797
+ type: "r2_bucket",
49798
+ name,
49799
+ bucket_name: bucket,
49800
+ ...str(entry.jurisdiction) ? { jurisdiction: entry.jurisdiction } : {}
49801
+ });
49802
+ }
49803
+ for (const entry of recs(config.ratelimits)) {
49804
+ const name = str(entry.name) ?? "?";
49805
+ const namespaceId = entry.namespace_id;
49806
+ const simple = isRec(entry.simple) ? entry.simple : undefined;
49807
+ if (namespaceId === undefined || simple === undefined) {
49808
+ unresolved(name, "ratelimit binding has no namespace_id or simple");
49809
+ continue;
49810
+ }
49811
+ bindings.push({ type: "ratelimit", name, namespace_id: String(namespaceId), simple: { limit: simple.limit, period: simple.period } });
49812
+ }
49813
+ for (const entry of recs(config.secrets_store_secrets)) {
49814
+ const name = str(entry.binding) ?? "?";
49815
+ const store = str(entry.store_id);
49816
+ const secret = str(entry.secret_name);
49817
+ if (store === undefined || secret === undefined) {
49818
+ unresolved(name, "secrets store binding has no store_id or secret_name");
49819
+ continue;
49820
+ }
49821
+ bindings.push({ type: "secrets_store_secret", name, store_id: store, secret_name: secret });
49822
+ }
49823
+ for (const entry of recs(config.send_email)) {
49824
+ bindings.push({
49825
+ type: "send_email",
49826
+ name: str(entry.name) ?? "?",
49827
+ ...str(entry.destination_address) ? { destination_address: entry.destination_address } : {},
49828
+ ...Array.isArray(entry.allowed_destination_addresses) ? { allowed_destination_addresses: entry.allowed_destination_addresses } : {},
49829
+ ...Array.isArray(entry.allowed_sender_addresses) ? { allowed_sender_addresses: entry.allowed_sender_addresses } : {}
49830
+ });
49831
+ }
49832
+ for (const entry of recs(config.services)) {
49833
+ const name = str(entry.binding) ?? "?";
49834
+ const service = str(entry.service);
49835
+ if (service === undefined) {
49836
+ unresolved(name, "service binding has no service");
49837
+ continue;
49838
+ }
49839
+ bindings.push({
49840
+ type: "service",
49841
+ name,
49842
+ service,
49843
+ ...str(entry.entrypoint) ? { entrypoint: entry.entrypoint } : {},
49844
+ environment: "production"
49845
+ });
49846
+ if (service !== own)
49847
+ refs.push(service);
49848
+ }
49849
+ for (const entry of recs(config.vectorize)) {
49850
+ const name = str(entry.binding) ?? "?";
49851
+ const index = str(entry.index_name);
49852
+ if (index === undefined) {
49853
+ unresolved(name, "vectorize binding has no index_name");
49854
+ continue;
49855
+ }
49856
+ bindings.push({ type: "vectorize", name, index_name: index });
49857
+ gaps.push({ kind: "vectorize-index", binding: name, indexName: index });
49858
+ }
49859
+ if (isRec(config.version_metadata) && str(config.version_metadata.binding))
49860
+ bindings.push({ type: "version_metadata", name: config.version_metadata.binding });
49861
+ for (const entry of recs(config.worker_loaders))
49862
+ bindings.push({ type: "worker_loader", name: str(entry.binding) ?? "?" });
49863
+ for (const entry of recs(config.workflows)) {
49864
+ const name = str(entry.binding) ?? "?";
49865
+ const workflowName = str(entry.name);
49866
+ const className = str(entry.class_name);
49867
+ if (workflowName === undefined || className === undefined) {
49868
+ unresolved(name, "workflow binding has no name or class_name");
49869
+ continue;
49870
+ }
49871
+ const script = str(entry.script_name);
49872
+ const binding = { type: "workflow", name, workflow_name: workflowName, class_name: className };
49873
+ if (script !== undefined && script !== own) {
49874
+ binding.script_name = script;
49875
+ refs.push(script);
49876
+ }
49877
+ bindings.push(binding);
49878
+ }
49879
+ if (isRec(config.assets) && str(config.assets.binding)) {
49880
+ if (assetsDir === null)
49881
+ unresolved(String(config.assets.binding), "assets declared but the bundle has no assets directory");
49882
+ else
49883
+ bindings.push({ type: "assets", name: config.assets.binding });
49884
+ }
49885
+ for (const entry of recs(config.containers)) {
49886
+ const className = str(entry.class_name);
49887
+ const image = str(entry.image);
49888
+ if (className !== undefined && image !== undefined)
49889
+ gaps.push({ kind: "container", className, image });
49890
+ }
49891
+ for (const key of KNOWN_UNSUPPORTED) {
49892
+ if (config[key] !== undefined)
49893
+ refusals.push({ kind: "unsupported-binding", binding: key, type: key });
49894
+ }
49895
+ for (const [key, value] of Object.entries(config)) {
49896
+ if (NON_BINDING_KEYS.has(key) || KNOWN_UNSUPPORTED.includes(key))
49897
+ continue;
49898
+ const shaped = Array.isArray(value) ? recs(value).some((entry) => ("binding" in entry)) : isRec(value) && (("binding" in value) || ("bindings" in value));
49899
+ if (shaped)
49900
+ refusals.push({ kind: "unsupported-binding", binding: key, type: key });
49901
+ }
49902
+ return { bindings, refs, gaps, refusals };
49903
+ }
49904
+ function migrationsOf(config, live) {
49905
+ const declared = recs(config.migrations);
49906
+ if (declared.length === 0)
49907
+ return { value: null, refusal: null };
49908
+ const tags = declared.map((step) => str(step.tag) ?? "");
49909
+ const last = tags[tags.length - 1] ?? "";
49910
+ let pending = declared;
49911
+ if (live !== null) {
49912
+ const index = tags.indexOf(live);
49913
+ if (index === -1)
49914
+ return {
49915
+ value: null,
49916
+ refusal: { kind: "unresolved-resource", binding: "migrations", detail: `live migration tag ${live} is not in the declared migrations` }
49917
+ };
49918
+ pending = declared.slice(index + 1);
49919
+ }
49920
+ if (pending.length === 0)
49921
+ return { value: { old_tag: live, new_tag: live }, refusal: null };
49922
+ const stepOf = (step) => {
49923
+ const { tag: _tag, ...rest } = step;
49924
+ return rest;
49925
+ };
49926
+ const value = { ...live !== null ? { old_tag: live } : {}, new_tag: last };
49927
+ if (pending.length === 1)
49928
+ Object.assign(value, stepOf(pending[0]));
49929
+ else
49930
+ value.steps = pending.map(stepOf);
49931
+ return { value, refusal: null };
49932
+ }
49933
+ function observabilityOf(value) {
49934
+ if (!isRec(value))
49935
+ return;
49936
+ const out = { enabled: value.enabled === true };
49937
+ if (typeof value.head_sampling_rate === "number")
49938
+ out.head_sampling_rate = value.head_sampling_rate;
49939
+ const section = (raw, withInvocation) => {
49940
+ if (!isRec(raw))
49941
+ return;
49942
+ const result = { enabled: raw.enabled === true };
49943
+ if (typeof raw.head_sampling_rate === "number")
49944
+ result.head_sampling_rate = raw.head_sampling_rate;
49945
+ if (typeof raw.persist === "boolean")
49946
+ result.persist = raw.persist;
49947
+ if (Array.isArray(raw.destinations))
49948
+ result.destinations = raw.destinations;
49949
+ if (withInvocation)
49950
+ result.invocation_logs = raw.invocation_logs !== false;
49951
+ return result;
49952
+ };
49953
+ const logs = section(value.logs, true);
49954
+ const traces = section(value.traces, false);
49955
+ if (logs)
49956
+ out.logs = logs;
49957
+ if (traces)
49958
+ out.traces = traces;
49959
+ return out;
49960
+ }
49961
+ var sanitize = (text) => text.replace(/[^A-Za-z0-9_]/g, "_");
49962
+ var contentTypeOf = (file) => file.endsWith(".wasm") ? "application/wasm" : file.endsWith(".json") ? "application/json" : file.endsWith(".txt") ? "text/plain" : "application/javascript+module";
49963
+ function generateTargetTf(input) {
49964
+ const config = projectEnvironment(input.wrangler, input.environment);
49965
+ if (config === null)
49966
+ return { ok: false, refusals: [{ kind: "missing-environment-block", target: input.target }] };
49967
+ const scriptName = str(config.name);
49968
+ if (scriptName === undefined)
49969
+ return { ok: false, refusals: [{ kind: "unresolved-resource", binding: "name", detail: "wrangler config names no Worker" }] };
49970
+ const collected = collectBindings(config, scriptName, input.bundle.assetsDir);
49971
+ const migrations = migrationsOf(config, input.liveMigrationTag);
49972
+ const refusals = [...collected.refusals, ...migrations.refusal ? [migrations.refusal] : []];
49973
+ const routes = [];
49974
+ const rawRoutes = [...Array.isArray(config.routes) ? config.routes : [], ...config.route !== undefined ? [config.route] : []];
49975
+ for (const raw of rawRoutes) {
49976
+ const entry = typeof raw === "string" ? { pattern: raw } : isRec(raw) ? raw : {};
49977
+ const pattern = str(entry.pattern);
49978
+ if (pattern === undefined) {
49979
+ refusals.push({ kind: "unresolved-resource", binding: "routes", detail: "route has no pattern" });
49980
+ continue;
49981
+ }
49982
+ if (entry.custom_domain !== true && str(entry.zone_name) === undefined && str(entry.zone_id) === undefined)
49983
+ refusals.push({ kind: "unresolved-resource", binding: `route ${pattern}`, detail: "route has neither zone_name nor zone_id" });
49984
+ routes.push({ ...entry, pattern });
49985
+ }
49986
+ if (refusals.length > 0)
49987
+ return { ok: false, refusals };
49988
+ const dependsOn = [...new Set(collected.refs.filter((name) => name !== scriptName && (name in input.callees)).map((name) => input.callees[name]))].sort();
49989
+ const worker = {
49990
+ account_id: "${var.account_id}",
49991
+ script_name: scriptName,
49992
+ content_file: input.bundle.mainFile,
49993
+ content_sha256: input.bundle.sha256,
49994
+ content_type: "application/javascript+module",
49995
+ main_module: input.bundle.mainModule,
49996
+ bindings: collected.bindings
49997
+ };
49998
+ if (str(config.compatibility_date))
49999
+ worker.compatibility_date = config.compatibility_date;
50000
+ if (Array.isArray(config.compatibility_flags) && config.compatibility_flags.length > 0)
50001
+ worker.compatibility_flags = config.compatibility_flags;
50002
+ if (migrations.value)
50003
+ worker.migrations = migrations.value;
50004
+ if (input.exports.length > 0)
50005
+ worker.exports = Object.fromEntries([...new Set(input.exports)].sort().map((name) => [name, { type: "worker" }]));
50006
+ const observability = observabilityOf(config.observability);
50007
+ if (observability)
50008
+ worker.observability = observability;
50009
+ if (typeof config.logpush === "boolean")
50010
+ worker.logpush = config.logpush;
50011
+ if (isRec(config.limits)) {
50012
+ const limits = {};
50013
+ if (typeof config.limits.cpu_ms === "number")
50014
+ limits.cpu_ms = config.limits.cpu_ms;
50015
+ if (typeof config.limits.subrequests === "number")
50016
+ limits.subrequests = config.limits.subrequests;
50017
+ if (Object.keys(limits).length > 0)
50018
+ worker.limits = limits;
50019
+ }
50020
+ const tails = recs(config.tail_consumers).filter((entry) => str(entry.service));
50021
+ if (tails.length > 0)
50022
+ worker.tail_consumers = tails.map((entry) => ({ service: entry.service }));
50023
+ if (input.bundle.extraModules.length > 0) {
50024
+ worker.files = Object.fromEntries(input.bundle.extraModules.map((file) => [file, { content_file: file, content_type: contentTypeOf(file) }]));
50025
+ }
50026
+ if (isRec(config.assets) && input.bundle.assetsDir !== null) {
50027
+ const assetConfig = {};
50028
+ for (const key of ["html_handling", "not_found_handling", "run_worker_first"])
50029
+ if (config.assets[key] !== undefined)
50030
+ assetConfig[key] = config.assets[key];
50031
+ worker.assets = { directory: input.bundle.assetsDir, ...Object.keys(assetConfig).length > 0 ? { config: assetConfig } : {} };
50032
+ }
50033
+ if (dependsOn.length > 0)
50034
+ worker.depends_on = dependsOn;
50035
+ const resource = { cloudflare_workers_script: { worker } };
50036
+ const data = {};
50037
+ const addResource = (type, key, body) => {
50038
+ const group = resource[type] ?? {};
50039
+ group[key] = body;
50040
+ resource[type] = group;
50041
+ };
50042
+ if (config.workers_dev === true)
50043
+ addResource("cloudflare_workers_script_subdomain", "worker", {
50044
+ account_id: "${var.account_id}",
50045
+ script_name: WORKER_REF,
50046
+ enabled: true,
50047
+ ...typeof config.preview_urls === "boolean" ? { previews_enabled: config.preview_urls } : {}
50048
+ });
50049
+ routes.forEach((entry, index) => {
50050
+ const pattern = entry.pattern;
50051
+ const zoneName = str(entry.zone_name);
50052
+ if (entry.custom_domain === true) {
50053
+ addResource("cloudflare_workers_custom_domain", `domain_${index}`, {
50054
+ account_id: "${var.account_id}",
50055
+ hostname: pattern.replace(/\/\*$/, ""),
50056
+ service: WORKER_REF,
50057
+ ...zoneName ? { zone_name: zoneName } : {},
50058
+ ...str(entry.zone_id) ? { zone_id: entry.zone_id } : {}
50059
+ });
50060
+ return;
50061
+ }
50062
+ let zoneId;
50063
+ if (str(entry.zone_id))
50064
+ zoneId = entry.zone_id;
50065
+ else {
50066
+ const key = `zone_${sanitize(zoneName)}`;
50067
+ const zones = data.cloudflare_zone ?? {};
50068
+ zones[key] = { filter: { name: zoneName } };
50069
+ data.cloudflare_zone = zones;
50070
+ zoneId = `\${data.cloudflare_zone.${key}.zone_id}`;
50071
+ }
50072
+ addResource("cloudflare_workers_route", `route_${index}`, { zone_id: zoneId, pattern, script: WORKER_REF });
50073
+ });
50074
+ const crons = isRec(config.triggers) && Array.isArray(config.triggers.crons) ? config.triggers.crons.filter((c) => typeof c === "string") : [];
50075
+ if (crons.length > 0)
50076
+ addResource("cloudflare_workers_cron_trigger", "worker", {
50077
+ account_id: "${var.account_id}",
50078
+ script_name: WORKER_REF,
50079
+ schedules: crons.map((cron) => ({ cron }))
50080
+ });
50081
+ const gaps = [...collected.gaps];
50082
+ if (isRec(config.placement))
50083
+ gaps.push({ kind: "placement", scriptName, placement: config.placement });
50084
+ for (const entry of isRec(config.queues) ? recs(config.queues.consumers) : []) {
50085
+ const queue = str(entry.queue);
50086
+ if (queue === undefined)
50087
+ continue;
50088
+ const { queue: _queue, ...settings } = entry;
50089
+ gaps.push({ kind: "queue-consumer", scriptName, queue, settings });
50090
+ }
50091
+ const tf = {
50092
+ terraform: {
50093
+ required_version: OPENTOFU_REQUIRED_VERSION,
50094
+ required_providers: { cloudflare: { source: "cloudflare/cloudflare", version: CLOUDFLARE_PROVIDER_VERSION } }
50095
+ },
50096
+ provider: { cloudflare: {} },
50097
+ variable: { account_id: { type: "string", sensitive: true } },
50098
+ resource,
50099
+ ...Object.keys(data).length > 0 ? { data } : {}
50100
+ };
50101
+ return { ok: true, tf, workerAddress: WORKER_ADDRESS, scriptName, gaps };
50102
+ }
50103
+ // ../../packages/praxis/deploy-core/src/job-events-file.ts
50104
+ import { appendFileSync, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
50105
+ import { dirname as dirname2 } from "node:path";
50106
+ function openDeployJobEvents(options) {
50107
+ const phaseId = options.phaseId ?? DEFAULT_PHASE_ID;
50108
+ const expireTime = expireTimeOf(options.startedAt, options.expireMinutes);
50109
+ const written = [];
50110
+ const jobs = new Map;
50111
+ let finishedState;
50112
+ mkdirSync3(dirname2(options.file), { recursive: true });
50113
+ writeFileSync3(options.file, "", { mode: 384 });
50114
+ const write = (event) => {
50115
+ written.push(event);
50116
+ appendFileSync(options.file, formatDeployEvent(event), { mode: 384 });
50117
+ };
50118
+ const statesOf = (target) => {
50119
+ let states = jobs.get(target);
50120
+ if (!states) {
50121
+ states = new Map;
50122
+ jobs.set(target, states);
50123
+ }
50124
+ return states;
50125
+ };
50126
+ const phaseStateOf = (target) => decidePhaseState([...statesOf(target).values()]);
50127
+ const jobRunEvent = (target, jobType, jobState, jobRunState, extra) => ({
50128
+ type: "jobrun",
50129
+ targetPath: target,
50130
+ phaseId,
50131
+ jobId: jobType,
50132
+ jobRun: `${phaseId}/${jobType}/1`,
50133
+ jobType,
50134
+ jobState,
50135
+ jobRunState,
50136
+ phaseState: phaseStateOf(target),
50137
+ ...extra.skipMessage !== undefined ? { skipMessage: extra.skipMessage } : {},
50138
+ ...extra.failure !== undefined ? { failure: extra.failure } : {},
50139
+ ...extra.eventLogPath !== undefined ? { eventLogPath: extra.eventLogPath } : {},
50140
+ ...extra.artifactUri !== undefined ? { artifactUri: extra.artifactUri } : {},
50141
+ ...extra.durationMs !== undefined ? { durationMs: extra.durationMs } : {}
50142
+ });
50143
+ write({ type: "started", startedAt: new Date(Date.parse(options.startedAt)).toISOString(), expireTime, phaseId });
50144
+ return {
50145
+ file: options.file,
50146
+ expireTime,
50147
+ startedAt: options.startedAt,
50148
+ phaseId,
50149
+ written,
50150
+ get finishedState() {
50151
+ return finishedState;
50152
+ },
50153
+ jobs,
50154
+ start(target, jobType) {
50155
+ statesOf(target).set(jobType, "in_progress");
50156
+ write(jobRunEvent(target, jobType, "in_progress", "in_progress", {}));
50157
+ },
50158
+ end(target, jobType, outcome) {
50159
+ const { jobState, jobRunState } = jobStatesOf(outcome);
50160
+ statesOf(target).set(jobType, jobState);
50161
+ write(jobRunEvent(target, jobType, jobState, jobRunState, {
50162
+ ...outcome.kind === "failed" ? { failure: { cause: outcome.cause ?? "execution_failed", ...outcome.message ? { message: outcome.message } : {} } } : {},
50163
+ ...outcome.kind === "disabled" || outcome.kind === "skipped" ? { skipMessage: outcome.message } : {},
50164
+ ...outcome.eventLogPath !== undefined ? { eventLogPath: outcome.eventLogPath } : {},
50165
+ ...outcome.artifactUri !== undefined ? { artifactUri: outcome.artifactUri } : {},
50166
+ ...outcome.durationMs !== undefined ? { durationMs: outcome.durationMs } : {}
50167
+ }));
50168
+ },
50169
+ finish(options2 = {}) {
50170
+ if (finishedState !== undefined)
50171
+ return;
50172
+ const rollouts = [...jobs.keys()].map((target) => decideRolloutState(jobs.get(target)));
50173
+ finishedState = decideFinishedState(rollouts);
50174
+ const cause = options2.deployFailureCause ?? firstFailureCause(written) ?? (finishedState === "succeeded" ? undefined : "execution_failed");
50175
+ write({
50176
+ type: "finished",
50177
+ state: finishedState,
50178
+ ...options2.message !== undefined ? { stateDescription: options2.message } : {},
50179
+ ...finishedState === "succeeded" || cause === undefined ? {} : { deployFailureCause: cause }
50180
+ });
50181
+ }
50182
+ };
50183
+ }
50184
+ function firstFailureCause(written) {
50185
+ for (let index = written.length - 1;index >= 0; index--) {
50186
+ const event = written[index];
50187
+ if (event.type === "jobrun" && event.jobState === "failed" && event.failure?.cause) {
50188
+ return event.failure.cause;
50189
+ }
50190
+ }
50191
+ return;
50192
+ }
50193
+ function reportJobRun(events, target, jobType, outcome) {
50194
+ if (outcome.kind === "disabled") {
50195
+ events.end(target, jobType, outcome);
50196
+ return;
50197
+ }
50198
+ events.start(target, jobType);
50199
+ events.end(target, jobType, outcome);
50200
+ }
50201
+ function reportBlockedTarget(events, target, message) {
50202
+ for (const jobType of ["deploy", "verify", "postdeploy"]) {
50203
+ reportJobRun(events, target, jobType, { kind: "skipped", message });
50204
+ }
50205
+ }
50206
+
50207
+ // src/commands/devops-deploy-plan.ts
50208
+ import { resolve as resolve2 } from "node:path";
50209
+
49643
50210
  // src/devops/deploy-plan.ts
49644
50211
  function deployPlanView(input) {
49645
50212
  const targets = input.environment === undefined ? input.plan.targets : targetsFor(input.plan, input.environment);
@@ -49707,10 +50274,10 @@ function renderDeployPlan(view) {
49707
50274
  }
49708
50275
 
49709
50276
  // src/commands/devops-deploy-plan.ts
49710
- async function git(args, ports, what, hint2) {
50277
+ async function git(args, ports, what, hint) {
49711
50278
  const result = await ports.git([...args], ports.cwd);
49712
50279
  if (result.code !== 0)
49713
- throw new UsageError(`${what} failed: ${result.output.trim() || `git ${args.join(" ")} exited ${result.code}`}`, hint2);
50280
+ throw new UsageError(`${what} failed: ${result.output.trim() || `git ${args.join(" ")} exited ${result.code}`}`, hint);
49714
50281
  return result.output;
49715
50282
  }
49716
50283
  async function localFacts(ports) {
@@ -49749,8 +50316,788 @@ async function devopsDeployPlan(args, ports) {
49749
50316
  ports.human(renderDeployPlan(view));
49750
50317
  }
49751
50318
 
50319
+ // src/devops/tofu/adapters.ts
50320
+ import { spawn as spawn2 } from "node:child_process";
50321
+ import { createHash as createHash2 } from "node:crypto";
50322
+ import { createReadStream } from "node:fs";
50323
+ import { mkdir as mkdir2, readFile as readFile3, stat, writeFile as writeFile2 } from "node:fs/promises";
50324
+ import { dirname as dirname3 } from "node:path";
50325
+ var nodeExec = {
50326
+ run: (cmd, args, { cwd, env, onLine }) => new Promise((resolveRun, reject) => {
50327
+ const child = spawn2(cmd, [...args], { cwd, env: { ...process.env, ...env ?? {} }, stdio: ["ignore", "pipe", "pipe"] });
50328
+ const pump = (stream) => {
50329
+ let rest = "";
50330
+ stream.setEncoding("utf8");
50331
+ stream.on("data", (chunk) => {
50332
+ rest += chunk;
50333
+ const lines = rest.split(`
50334
+ `);
50335
+ rest = lines.pop() ?? "";
50336
+ for (const line of lines)
50337
+ onLine(line);
50338
+ });
50339
+ stream.on("end", () => {
50340
+ if (rest !== "")
50341
+ onLine(rest);
50342
+ });
50343
+ };
50344
+ pump(child.stdout);
50345
+ pump(child.stderr);
50346
+ child.once("error", reject);
50347
+ child.once("close", (code) => resolveRun(code ?? 1));
50348
+ })
50349
+ };
50350
+ var nodeFs = {
50351
+ read: async (path) => {
50352
+ try {
50353
+ return await readFile3(path, "utf8");
50354
+ } catch (e) {
50355
+ if (e.code === "ENOENT")
50356
+ return null;
50357
+ throw e;
50358
+ }
50359
+ },
50360
+ write: async (path, content) => {
50361
+ await mkdir2(dirname3(path), { recursive: true });
50362
+ await writeFile2(path, content);
50363
+ },
50364
+ mkdirp: async (path) => {
50365
+ await mkdir2(path, { recursive: true });
50366
+ },
50367
+ exists: async (path) => {
50368
+ try {
50369
+ await stat(path);
50370
+ return true;
50371
+ } catch {
50372
+ return false;
50373
+ }
50374
+ },
50375
+ sha256: (path) => new Promise((resolveHash, reject) => {
50376
+ const hash = createHash2("sha256");
50377
+ const stream = createReadStream(path);
50378
+ stream.on("data", (c) => hash.update(c));
50379
+ stream.once("error", (e) => e.code === "ENOENT" ? resolveHash(null) : reject(e));
50380
+ stream.once("end", () => resolveHash(hash.digest("hex")));
50381
+ })
50382
+ };
50383
+
50384
+ // src/devops/tofu/cloudflare.ts
50385
+ var API = "https://api.cloudflare.com/client/v4";
50386
+ function cloudflareApi(fetchFn, env) {
50387
+ const token = env.CLOUDFLARE_API_TOKEN;
50388
+ let account = env.CLOUDFLARE_ACCOUNT_ID;
50389
+ let scripts;
50390
+ const call = async (path, init = {}) => {
50391
+ if (!token)
50392
+ throw new Error("CLOUDFLARE_API_TOKEN is not set");
50393
+ const response = await fetchFn(`${API}${path}`, { ...init, headers: { authorization: `Bearer ${token}`, ...init.headers ?? {} } });
50394
+ const body = await response.json().catch(() => ({}));
50395
+ if (response.status !== 404 && (!response.ok || body.success === false)) {
50396
+ throw new Error(`Cloudflare API ${init.method ?? "GET"} ${path} failed: ${response.status} ${body.errors?.map((e) => e.message).join("; ") ?? ""}`.trim());
50397
+ }
50398
+ return { status: response.status, result: body.result };
50399
+ };
50400
+ const accountId = async () => {
50401
+ if (account)
50402
+ return account;
50403
+ const { result } = await call("/accounts?per_page=2");
50404
+ const accounts = Array.isArray(result) ? result : [];
50405
+ if (accounts.length !== 1 || !accounts[0]?.id)
50406
+ throw new Error(`set CLOUDFLARE_ACCOUNT_ID: the token sees ${accounts.length} accounts`);
50407
+ account = accounts[0].id;
50408
+ return account;
50409
+ };
50410
+ return {
50411
+ accountId,
50412
+ async liveMigrationTag(scriptName) {
50413
+ scripts ??= (async () => {
50414
+ const tags = new Map;
50415
+ for (let page = 1;page <= 20; page++) {
50416
+ const { result } = await call(`/accounts/${await accountId()}/workers/scripts?per_page=100&page=${page}`);
50417
+ const entries = Array.isArray(result) ? result : [];
50418
+ for (const entry of entries)
50419
+ if (entry.id && entry.migration_tag)
50420
+ tags.set(entry.id, entry.migration_tag);
50421
+ if (entries.length < 100)
50422
+ break;
50423
+ }
50424
+ return tags;
50425
+ })();
50426
+ return (await scripts).get(scriptName) ?? null;
50427
+ },
50428
+ async attachQueueConsumer(queueName, scriptName, settings) {
50429
+ const base = `/accounts/${await accountId()}/queues`;
50430
+ const { result: queues } = await call(`${base}?per_page=100&name=${encodeURIComponent(queueName)}`);
50431
+ const queue = (Array.isArray(queues) ? queues : []).find((q) => q.queue_name === queueName);
50432
+ if (!queue?.queue_id)
50433
+ throw new Error(`queue ${queueName} does not exist`);
50434
+ const { result: consumers } = await call(`${base}/${queue.queue_id}/consumers`);
50435
+ const existing = (Array.isArray(consumers) ? consumers : []).find((c) => (c.script ?? c.script_name) === scriptName);
50436
+ const body = JSON.stringify({
50437
+ type: "worker",
50438
+ script_name: scriptName,
50439
+ settings: consumerSettings(settings),
50440
+ ...typeof settings.dead_letter_queue === "string" ? { dead_letter_queue: settings.dead_letter_queue } : {}
50441
+ });
50442
+ const headers = { "content-type": "application/json" };
50443
+ if (existing?.consumer_id)
50444
+ await call(`${base}/${queue.queue_id}/consumers/${existing.consumer_id}`, { method: "PUT", body, headers });
50445
+ else
50446
+ await call(`${base}/${queue.queue_id}/consumers`, { method: "POST", body, headers });
50447
+ },
50448
+ async setPlacement(scriptName, placement) {
50449
+ const form = new FormData;
50450
+ form.set("settings", JSON.stringify({ placement }));
50451
+ await call(`/accounts/${await accountId()}/workers/scripts/${encodeURIComponent(scriptName)}/settings`, { method: "PATCH", body: form });
50452
+ }
50453
+ };
50454
+ }
50455
+ function consumerSettings(settings) {
50456
+ const map = {
50457
+ max_batch_size: "batch_size",
50458
+ max_batch_timeout: "max_wait_time_ms",
50459
+ max_retries: "max_retries",
50460
+ max_concurrency: "max_concurrency",
50461
+ retry_delay: "retry_delay"
50462
+ };
50463
+ const out = {};
50464
+ for (const [key, value] of Object.entries(settings)) {
50465
+ if (!(key in map) || value === undefined)
50466
+ continue;
50467
+ out[map[key]] = key === "max_batch_timeout" && typeof value === "number" ? value * 1000 : value;
50468
+ }
50469
+ return out;
50470
+ }
50471
+
50472
+ // src/devops/tofu/pure.ts
50473
+ function parseTofuDeployArgs(flags) {
50474
+ const environment2 = flags.env?.trim();
50475
+ if (environment2 !== "develop" && environment2 !== "production") {
50476
+ throw new UsageError(`--env must be develop or production, got ${JSON.stringify(flags.env ?? "")}`, "Pass --env develop or --env production.");
50477
+ }
50478
+ const commit = flags.commit?.trim();
50479
+ if (!commit || !/^[0-9a-f]{7,64}$/i.test(commit))
50480
+ throw new UsageError("--commit needs a commit sha", "Pass --commit <sha> of the commit being rolled out.");
50481
+ const targets = flags.targets === undefined ? undefined : flags.targets.split(",").map((t) => t.trim().replace(/\/+$/, "")).filter((t) => t !== "");
50482
+ if (flags.targets !== undefined && (targets ?? []).length === 0)
50483
+ throw new UsageError("--targets is empty", "Pass --targets a,b or leave it out for every target.");
50484
+ const planOnly = flags["plan-only"] === true;
50485
+ const applyPlans = flags["apply-plans"]?.trim();
50486
+ if (planOnly && flags["apply-plans"] !== undefined)
50487
+ throw new UsageError("--plan-only and --apply-plans exclude each other", "Plan first (--plan-only), then apply the approved plans (--apply-plans <dir>).");
50488
+ if (flags["apply-plans"] !== undefined && !applyPlans)
50489
+ throw new UsageError("--apply-plans needs a directory", "Pass --apply-plans <dir> holding the approved <target>.bin files.");
50490
+ const mode = planOnly ? "plan-only" : applyPlans !== undefined ? "apply-plans" : "plan-and-apply";
50491
+ if (environment2 === "production" && mode === "plan-and-apply") {
50492
+ throw new UsageError("production applies only an approved plan", "Run with --plan-only, have the plan approved, then run with --apply-plans <dir>.");
50493
+ }
50494
+ if (mode !== "plan-only" && !flags["events-file"])
50495
+ throw new UsageError("--events-file is required when applying", "DevOps folds the ExecutorLine stream this file carries; pass --events-file <path>.");
50496
+ return {
50497
+ environment: environment2,
50498
+ commit,
50499
+ mode,
50500
+ ...targets === undefined ? {} : { targets },
50501
+ ...applyPlans !== undefined ? { planDir: applyPlans } : flags["plan-dir"] ? { planDir: flags["plan-dir"] } : {},
50502
+ ...flags["events-file"] ? { eventsFile: flags["events-file"] } : {},
50503
+ ...flags.workdir ? { workdir: flags.workdir } : {}
50504
+ };
50505
+ }
50506
+ function selectTargets(plan, environment2, requested) {
50507
+ const named = requested !== undefined;
50508
+ let targets = targetsFor(plan, environment2).filter((t) => t.destination === "cloudflare" && deploysTo(t, environment2, { named }));
50509
+ if (requested !== undefined) {
50510
+ const known = new Set(plan.targets.map((t) => t.path));
50511
+ const missing = requested.filter((r) => !known.has(r));
50512
+ if (missing.length > 0)
50513
+ throw new UsageError(`unknown target(s): ${missing.join(", ")}`, "Run `praxis devops deploy plan` to list the targets.");
50514
+ const refused = requested.filter((r) => !targets.some((t) => t.path === r));
50515
+ if (refused.length > 0)
50516
+ throw new UsageError(`${refused.join(", ")} does not deploy to ${environment2}`, "Check the target's environments and its env.production block.");
50517
+ targets = targets.filter((t) => requested.includes(t.path));
50518
+ }
50519
+ const selected = { commit: plan.commit, targets };
50520
+ return { targets, layers: layersOf(selected).map((layer) => [...layer]) };
50521
+ }
50522
+ function blockedBy(targets, broken) {
50523
+ const blocked = new Set;
50524
+ let grew = true;
50525
+ while (grew) {
50526
+ grew = false;
50527
+ for (const t of targets) {
50528
+ if (blocked.has(t.path) || broken.has(t.path))
50529
+ continue;
50530
+ if (t.dependsOn.some((d) => broken.has(d) || blocked.has(d))) {
50531
+ blocked.add(t.path);
50532
+ grew = true;
50533
+ }
50534
+ }
50535
+ }
50536
+ return blocked;
50537
+ }
50538
+ var LAYER_CONCURRENCY = 4;
50539
+ async function pool(items, limit, work) {
50540
+ let next = 0;
50541
+ const lane = async () => {
50542
+ for (;; ) {
50543
+ const at = next++;
50544
+ if (at >= items.length)
50545
+ return;
50546
+ await work(items[at]);
50547
+ }
50548
+ };
50549
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, lane));
50550
+ }
50551
+ function parseDenylist(text) {
50552
+ return text.split(`
50553
+ `).map((l) => l.trim()).filter((l) => l !== "" && !l.startsWith("#"));
50554
+ }
50555
+ function denylistMatch(name, entries) {
50556
+ return entries.find((e) => e.endsWith("*") ? name.startsWith(e.slice(0, -1)) : name === e);
50557
+ }
50558
+ function effectiveConfig(wrangler, environment2) {
50559
+ if (environment2 !== "production")
50560
+ return wrangler;
50561
+ const env = wrangler.env;
50562
+ const block = env !== null && typeof env === "object" ? env.production : undefined;
50563
+ return block !== null && typeof block === "object" ? block : {};
50564
+ }
50565
+ function scriptNameOf(wrangler, environment2) {
50566
+ const name = effectiveConfig(wrangler, environment2).name;
50567
+ return typeof name === "string" && name !== "" ? name : undefined;
50568
+ }
50569
+ var objects = (value) => Array.isArray(value) ? value.filter((v) => v !== null && typeof v === "object") : [];
50570
+ var str2 = (value) => typeof value === "string" && value !== "" ? [value] : [];
50571
+ function namesOf(wrangler, environment2) {
50572
+ const c = effectiveConfig(wrangler, environment2);
50573
+ const queues = c.queues !== null && typeof c.queues === "object" ? c.queues : {};
50574
+ return [...new Set([
50575
+ ...str2(c.name),
50576
+ ...objects(c.d1_databases).flatMap((d) => str2(d.database_name)),
50577
+ ...objects(c.r2_buckets).flatMap((b) => str2(b.bucket_name)),
50578
+ ...objects(queues.producers).flatMap((q) => str2(q.queue)),
50579
+ ...objects(queues.consumers).flatMap((q) => str2(q.queue)),
50580
+ ...objects(c.services).flatMap((s) => str2(s.service)),
50581
+ ...objects(c.vectorize).flatMap((v) => str2(v.index_name)),
50582
+ ...objects(c.workflows).flatMap((w) => str2(w.name))
50583
+ ])];
50584
+ }
50585
+ function denylistHits(names, entries) {
50586
+ const hits = [];
50587
+ for (const [target, list] of names)
50588
+ for (const name of list) {
50589
+ const entry = denylistMatch(name, entries);
50590
+ if (entry !== undefined)
50591
+ hits.push({ target, name, entry });
50592
+ }
50593
+ return hits;
50594
+ }
50595
+ var targetDir = (workdir, target) => `${workdir}/${target}`;
50596
+ var planFileOf = (planDir, target) => `${planDir}/${target}.bin`;
50597
+ function wranglerBuildArgs(environment2, outdir) {
50598
+ return ["wrangler", "deploy", "--dry-run", "--outdir", outdir, ...environment2 === "production" ? ["--env", "production"] : []];
50599
+ }
50600
+ function wranglerD1Args(databaseName, environment2) {
50601
+ return ["wrangler", "d1", "migrations", "apply", databaseName, "--remote", ...environment2 === "production" ? ["--env", "production"] : []];
50602
+ }
50603
+ function bundleModuleName(wrangler, environment2) {
50604
+ const main = effectiveConfig(wrangler, environment2).main ?? wrangler.main;
50605
+ const base = typeof main === "string" ? main.split("/").pop() : "index.js";
50606
+ return base.replace(/\.(?:[cm]?[jt]sx?)$/, ".js");
50607
+ }
50608
+ function backendDocument(environment2, target, accountId) {
50609
+ return {
50610
+ terraform: {
50611
+ backend: {
50612
+ s3: {
50613
+ bucket: `praxis-tofu-state-${environment2}`,
50614
+ key: stateKeyOf(environment2, target),
50615
+ region: "auto",
50616
+ endpoints: { s3: `https://${accountId}.r2.cloudflarestorage.com` },
50617
+ skip_credentials_validation: true,
50618
+ skip_region_validation: true,
50619
+ skip_requesting_account_id: true,
50620
+ skip_s3_checksum: true,
50621
+ use_path_style: true,
50622
+ use_lockfile: true
50623
+ }
50624
+ }
50625
+ }
50626
+ };
50627
+ }
50628
+ function d1Moment(environment2, mode) {
50629
+ if (mode === "apply-plans")
50630
+ return "before-apply";
50631
+ if (environment2 === "develop")
50632
+ return "before-plan";
50633
+ return "listed-only";
50634
+ }
50635
+ function scheduleGaps(gaps) {
50636
+ const d1 = [];
50637
+ const placement = [];
50638
+ const queueConsumers = [];
50639
+ const warnings = [];
50640
+ for (const gap of gaps) {
50641
+ switch (gap.kind) {
50642
+ case "d1-migrations":
50643
+ d1.push(gap);
50644
+ break;
50645
+ case "placement":
50646
+ placement.push(gap);
50647
+ break;
50648
+ case "queue-consumer":
50649
+ queueConsumers.push(gap);
50650
+ break;
50651
+ case "vectorize-index":
50652
+ warnings.push(`gap not filled: vectorize index ${gap.indexName} (${gap.binding}) must exist; create it by API`);
50653
+ break;
50654
+ case "container":
50655
+ warnings.push(`gap not filled: container ${gap.className} (${gap.image})`);
50656
+ break;
50657
+ case "analytics-engine-dataset":
50658
+ warnings.push(`gap not filled: analytics engine dataset ${gap.dataset} (${gap.binding})`);
50659
+ break;
50660
+ }
50661
+ }
50662
+ return { d1, placement, queueConsumers, warnings };
50663
+ }
50664
+ function exportsOf(scriptName, configs, environment2) {
50665
+ const names = new Set;
50666
+ for (const wrangler of configs.values()) {
50667
+ const services = effectiveConfig(wrangler, environment2).services;
50668
+ for (const entry of Array.isArray(services) ? services : []) {
50669
+ if (entry && entry.service === scriptName && typeof entry.entrypoint === "string" && entry.entrypoint !== "")
50670
+ names.add(entry.entrypoint);
50671
+ }
50672
+ }
50673
+ return [...names].sort();
50674
+ }
50675
+
50676
+ // src/devops/tofu/run.ts
50677
+ import { dirname as dirname4, isAbsolute, relative, resolve as resolve3 } from "node:path";
50678
+ var DENYLIST = "spec/legacy-production.denylist";
50679
+ async function runTofuDeploy(args, plan, ports) {
50680
+ const { fs, exec, cloudflare, out } = ports;
50681
+ const startedAt = ports.clock.iso();
50682
+ const root = resolve3(ports.repoRoot);
50683
+ const absolute = (p) => isAbsolute(p) ? p : resolve3(p);
50684
+ const workdir = absolute(args.workdir ?? `${root}/.tofu-work`);
50685
+ const planDir = absolute(args.planDir ?? `${workdir}/plans`);
50686
+ const applying = args.mode !== "plan-only";
50687
+ const events = applying && args.eventsFile !== undefined ? ports.openEvents(args.eventsFile, startedAt) : undefined;
50688
+ const reports = new Map;
50689
+ const selection = selectTargets(plan, args.environment, args.targets);
50690
+ const byPath = new Map(selection.targets.map((t) => [t.path, t]));
50691
+ const finish = (finished2, message2) => {
50692
+ if (events)
50693
+ events.finish(message2 === undefined ? {} : { message: message2 });
50694
+ const summary = {
50695
+ commit: args.commit,
50696
+ environment: args.environment,
50697
+ mode: args.mode,
50698
+ layers: selection.layers,
50699
+ targets: selection.targets.map((t) => reports.get(t.path) ?? { target: t.path, status: "blocked", message: message2 ?? "not started", d1Pending: [], warnings: [] }),
50700
+ finished: events?.finishedState ?? finished2
50701
+ };
50702
+ return { exitCode: finished2 === "succeeded" || finished2 === "planned" ? 0 : 1, summary };
50703
+ };
50704
+ const refuseAll = async (message2) => {
50705
+ out(`REFUSED: ${message2}`);
50706
+ for (const t of selection.targets) {
50707
+ reports.set(t.path, { target: t.path, status: "blocked", message: message2, d1Pending: [], warnings: [] });
50708
+ if (events)
50709
+ reportBlockedTarget(events, t.path, message2);
50710
+ }
50711
+ const result2 = finish("failed", message2);
50712
+ await writeSummary(result2.summary);
50713
+ return result2;
50714
+ };
50715
+ const writeSummary = async (summary) => {
50716
+ await fs.write(`${planDir}/summary.json`, `${JSON.stringify(summary, null, 2)}
50717
+ `);
50718
+ out(`SUMMARY ${JSON.stringify(summary)}`);
50719
+ };
50720
+ const configs = new Map;
50721
+ for (const t of selection.targets) {
50722
+ const text = await fs.read(`${root}/${t.path}/wrangler.jsonc`);
50723
+ const parsed = text === null ? null : parseJsonc2(text);
50724
+ if (parsed === null)
50725
+ return await refuseAll(`${t.path}: wrangler.jsonc is missing or not valid JSONC`);
50726
+ configs.set(t.path, parsed);
50727
+ }
50728
+ const callerConfigs = new Map(configs);
50729
+ for (const t of plan.targets) {
50730
+ if (callerConfigs.has(t.path))
50731
+ continue;
50732
+ const text = await fs.read(`${root}/${t.path}/wrangler.jsonc`);
50733
+ const parsed = text === null ? null : parseJsonc2(text);
50734
+ if (parsed !== null)
50735
+ callerConfigs.set(t.path, parsed);
50736
+ }
50737
+ const denylistText = await fs.read(`${root}/${DENYLIST}`);
50738
+ if (denylistText === null)
50739
+ return await refuseAll(`${DENYLIST} is missing; the legacy preflight cannot run`);
50740
+ const hits = denylistHits(new Map(selection.targets.map((t) => [t.path, namesOf(configs.get(t.path), args.environment)])), parseDenylist(denylistText));
50741
+ if (hits.length > 0) {
50742
+ return await refuseAll(`legacy production names refused: ${hits.map((h) => `${h.target} uses ${h.name} (denylist ${h.entry})`).join("; ")}`);
50743
+ }
50744
+ const accountId = await cloudflare.accountId();
50745
+ const results = new Map;
50746
+ const broken = new Set;
50747
+ const reported = new Set;
50748
+ let aborted;
50749
+ const block = (t, message2) => {
50750
+ if (reported.has(t.path))
50751
+ return;
50752
+ reported.add(t.path);
50753
+ broken.add(t.path);
50754
+ reports.set(t.path, { target: t.path, status: "blocked", message: message2, d1Pending: [], warnings: [] });
50755
+ if (events)
50756
+ reportBlockedTarget(events, t.path, message2);
50757
+ out(`[${t.path}] blocked: ${message2}`);
50758
+ };
50759
+ const processTarget = async (t) => {
50760
+ const target = t.path;
50761
+ const tdir = targetDir(workdir, target);
50762
+ const say = (line) => out(`[${target}] ${line}`);
50763
+ const step = async (cmd, cmdArgs, cwd, env) => {
50764
+ say(`$ ${cmd} ${cmdArgs.join(" ")}`);
50765
+ const code = await exec.run(cmd, cmdArgs, { cwd, ...env ? { env } : {}, onLine: say });
50766
+ if (code !== 0)
50767
+ throw new StepFailed(`${cmd} ${cmdArgs.slice(0, 2).join(" ")} exited ${code}`);
50768
+ };
50769
+ const began = ports.clock.now();
50770
+ if (events)
50771
+ events.start(target, "deploy");
50772
+ reported.add(target);
50773
+ const d1Pending = [];
50774
+ let warnings = [];
50775
+ let planFile;
50776
+ try {
50777
+ const wrangler = configs.get(target);
50778
+ const scriptName = scriptNameOf(wrangler, args.environment);
50779
+ if (scriptName === undefined)
50780
+ throw new StepFailed("the wrangler config names no Worker for this environment");
50781
+ const wantsPlan = args.mode !== "apply-plans";
50782
+ planFile = planFileOf(planDir, target);
50783
+ if (args.mode === "apply-plans" && !await fs.exists(planFile))
50784
+ throw new StepFailed(`plan file ${planFile} is missing; refusing to apply without it`);
50785
+ const outdir = `${tdir}/dist`;
50786
+ await fs.mkdirp(tdir);
50787
+ await step("npx", wranglerBuildArgs(args.environment, outdir), `${root}/${target}`);
50788
+ const mainModule = bundleModuleName(wrangler, args.environment);
50789
+ const mainFile = `dist/${mainModule}`;
50790
+ const sha256 = await fs.sha256(`${tdir}/${mainFile}`);
50791
+ if (sha256 === null)
50792
+ throw new StepFailed(`the wrangler bundle has no ${mainFile}`);
50793
+ const assets = effectiveConfig(wrangler, args.environment).assets;
50794
+ const assetsDirectory = assets !== null && typeof assets === "object" ? assets.directory : undefined;
50795
+ const liveMigrationTag = await cloudflare.liveMigrationTag(scriptName);
50796
+ const callees = {};
50797
+ const generated = ports.generate({
50798
+ target,
50799
+ environment: args.environment,
50800
+ wrangler,
50801
+ bundle: {
50802
+ mainFile,
50803
+ mainModule,
50804
+ sha256,
50805
+ extraModules: [],
50806
+ assetsDir: typeof assetsDirectory === "string" ? relative(tdir, resolve3(root, target, assetsDirectory)) : null
50807
+ },
50808
+ liveMigrationTag,
50809
+ callees,
50810
+ exports: exportsOf(scriptName, callerConfigs, args.environment)
50811
+ });
50812
+ if (!generated.ok) {
50813
+ aborted = `${target}: generator refused: ${generated.refusals.map((r) => JSON.stringify(r)).join(", ")}`;
50814
+ throw new StepFailed(aborted);
50815
+ }
50816
+ results.set(target, generated);
50817
+ await fs.write(`${tdir}/main.tf.json`, `${JSON.stringify(generated.tf, null, 2)}
50818
+ `);
50819
+ await fs.write(`${tdir}/backend.tf.json`, `${JSON.stringify(backendDocument(args.environment, target, accountId), null, 2)}
50820
+ `);
50821
+ const schedule = scheduleGaps(generated.gaps);
50822
+ warnings = schedule.warnings;
50823
+ for (const w of warnings)
50824
+ say(`WARNING ${w}`);
50825
+ const moment = d1Moment(args.environment, args.mode);
50826
+ const runD1 = async () => {
50827
+ for (const gap of schedule.d1)
50828
+ await step("npx", wranglerD1Args(gap.databaseName, args.environment), `${root}/${target}`);
50829
+ };
50830
+ for (const gap of schedule.d1) {
50831
+ d1Pending.push(gap.databaseName);
50832
+ say(`d1 migrations (${gap.binding}): ${gap.databaseName} from ${gap.migrationsDir}`);
50833
+ }
50834
+ if (moment === "before-plan")
50835
+ await runD1();
50836
+ else if (moment === "listed-only")
50837
+ say("d1 migrations are listed only; production migrates when an approved plan is applied");
50838
+ const env = { TF_VAR_account_id: accountId };
50839
+ await step("tofu", ["init", "-input=false"], tdir, env);
50840
+ if (wantsPlan) {
50841
+ await fs.mkdirp(dirname4(planFile));
50842
+ await step("tofu", ["plan", "-input=false", "-no-color", `-out=${planFile}`], tdir, env);
50843
+ }
50844
+ if (applying) {
50845
+ if (moment === "before-apply")
50846
+ await runD1();
50847
+ await step("tofu", ["apply", "-input=false", "-no-color", planFile], tdir, env);
50848
+ for (const gap of schedule.placement) {
50849
+ say(`placement ${JSON.stringify(gap.placement)} -> ${gap.scriptName}`);
50850
+ await cloudflare.setPlacement(gap.scriptName, gap.placement);
50851
+ }
50852
+ for (const gap of schedule.queueConsumers) {
50853
+ say(`queue consumer ${gap.queue} -> ${gap.scriptName}`);
50854
+ await cloudflare.attachQueueConsumer(gap.queue, gap.scriptName, gap.settings);
50855
+ }
50856
+ }
50857
+ reports.set(target, { target, status: applying ? "succeeded" : "planned", planFile, d1Pending, warnings });
50858
+ if (events)
50859
+ events.end(target, "deploy", { kind: "succeeded", durationMs: ports.clock.now() - began });
50860
+ } catch (error) {
50861
+ const message2 = error instanceof Error ? error.message : String(error);
50862
+ say(`FAILED ${message2}`);
50863
+ broken.add(target);
50864
+ reports.set(target, { target, status: "failed", message: message2, ...planFile ? { planFile } : {}, d1Pending, warnings });
50865
+ if (events)
50866
+ events.end(target, "deploy", { kind: "failed", message: message2, cause: "execution_failed", durationMs: ports.clock.now() - began });
50867
+ }
50868
+ };
50869
+ for (const layer of selection.layers) {
50870
+ const blocked = blockedBy(selection.targets, broken);
50871
+ const runnable = [];
50872
+ for (const path of layer) {
50873
+ const t = byPath.get(path);
50874
+ if (aborted !== undefined)
50875
+ block(t, `run aborted: ${aborted}`);
50876
+ else if (blocked.has(path))
50877
+ block(t, "a target it depends on did not finish");
50878
+ else
50879
+ runnable.push(t);
50880
+ }
50881
+ await pool(runnable, LAYER_CONCURRENCY, async (t) => {
50882
+ if (aborted !== undefined) {
50883
+ block(t, `run aborted: ${aborted}`);
50884
+ return;
50885
+ }
50886
+ await processTarget(t);
50887
+ });
50888
+ }
50889
+ const failed = [...reports.values()].filter((r) => r.status === "failed");
50890
+ const blockedCount = [...reports.values()].filter((r) => r.status === "blocked").length;
50891
+ const finished = failed.length === 0 && blockedCount === 0 ? applying ? "succeeded" : "planned" : "failed";
50892
+ const message = finished === "failed" ? `${failed.length} failed, ${blockedCount} blocked` : undefined;
50893
+ const result = finish(finished, message);
50894
+ await writeSummary(result.summary);
50895
+ return result;
50896
+ }
50897
+
50898
+ class StepFailed extends Error {
50899
+ }
50900
+
50901
+ // src/devops/pure.ts
50902
+ import { createHash as createHash3 } from "node:crypto";
50903
+ var PROJECT_ID = /^dvp_[a-z0-9]+$/;
50904
+ var POLL_MS = 5000;
50905
+ var FAILURE_LIMIT = 20;
50906
+ var hint = 'Pass --project dvp_…, or add "devops": { "project": "dvp_…" } to praxis.jsonc in the current directory.';
50907
+ function checkProject(value, hintText = hint) {
50908
+ if (typeof value !== "string" || !value.trim())
50909
+ throw new UsageError("A DevOps project id must be a non-empty string", hintText);
50910
+ if (!PROJECT_ID.test(value.trim()))
50911
+ throw new UsageError(`Not a DevOps project id: ${value}`, "A project id starts with dvp_ and comes from the project list. " + hintText);
50912
+ return value.trim();
50913
+ }
50914
+ function parseDevopsProject(value) {
50915
+ if (value === null || value === undefined || typeof value !== "object" || Array.isArray(value))
50916
+ return;
50917
+ const devops = value.devops;
50918
+ if (devops === undefined)
50919
+ return;
50920
+ if (devops === null || typeof devops !== "object" || Array.isArray(devops))
50921
+ throw new UsageError("praxis.jsonc devops must be an object", 'Write {"devops":{"project":"dvp_…"}}. ' + hint);
50922
+ const project = devops.project;
50923
+ if (project === undefined)
50924
+ return;
50925
+ return checkProject(project);
50926
+ }
50927
+ function resolveProject(flag, projectFile) {
50928
+ if (flag !== undefined)
50929
+ return checkProject(flag);
50930
+ const fromFile = parseDevopsProject(projectFile);
50931
+ if (fromFile !== undefined)
50932
+ return fromFile;
50933
+ throw new UsageError("No DevOps project named for this run", hint);
50934
+ }
50935
+ var sorted = (values) => [...values].sort();
50936
+ var SELECT_KINDS = { tag: "anyTags", package: "packages", suite: "packages", file: "packages" };
50937
+ function parseSelect(values) {
50938
+ if (!values.length)
50939
+ return;
50940
+ const tags = [], packages = [];
50941
+ for (const raw of values) {
50942
+ const at = raw.indexOf(":");
50943
+ const kind = at < 0 ? "tag" : raw.slice(0, at).trim().toLowerCase();
50944
+ const value = (at < 0 ? raw : raw.slice(at + 1)).trim();
50945
+ const kinds = Object.keys(SELECT_KINDS).join(", ");
50946
+ if (!value)
50947
+ throw new UsageError(`--select ${raw} names no value`, `Use --select <kind>:<value>, or a bare tag name; kinds are ${kinds}.`);
50948
+ if (!Object.hasOwn(SELECT_KINDS, kind))
50949
+ throw new UsageError(`--select ${raw}: unknown kind "${kind}"`, `Use one of: ${kinds}.`);
50950
+ (SELECT_KINDS[kind] === "anyTags" ? tags : packages).push(value);
50951
+ }
50952
+ return { ...tags.length ? { anyTags: sorted(tags) } : {}, ...packages.length ? { packages: sorted(packages) } : {} };
50953
+ }
50954
+ function parseRepeat(value) {
50955
+ if (value === undefined)
50956
+ return 1;
50957
+ const n = typeof value === "string" && value.trim() ? Number(value) : NaN;
50958
+ if (!Number.isSafeInteger(n) || n < 1)
50959
+ throw new UsageError("--repeat must be an integer of at least 1");
50960
+ return n;
50961
+ }
50962
+ function requireRemote(remote) {
50963
+ if (!remote)
50964
+ throw new UsageError("Only remote test runs are available", "Add --remote to run the selected cases on the Praxis cloud executor.");
50965
+ }
50966
+ function requestIdFor(input) {
50967
+ const selector = input.selector === undefined ? null : {
50968
+ sizes: sorted(input.selector.sizes ?? []),
50969
+ anyTags: sorted(input.selector.anyTags ?? []),
50970
+ packages: sorted(input.selector.packages ?? []),
50971
+ cases: sorted(input.selector.cases ?? [])
50972
+ };
50973
+ const material = JSON.stringify(["devops-test-run", input.project, input.commit, input.repeat, selector]);
50974
+ return `req_${createHash3("sha256").update(material).digest("hex").slice(0, 32)}`;
50975
+ }
50976
+ var isTerminal = (state) => state === "finished";
50977
+ function shortSha(commit) {
50978
+ return commit.slice(0, 7);
50979
+ }
50980
+ function headBranch(output) {
50981
+ const name = output.trim();
50982
+ return !name || name === "HEAD" ? undefined : name;
50983
+ }
50984
+ function requirePushed(remoteContains, commit, branch) {
50985
+ if (remoteContains.trim())
50986
+ return;
50987
+ throw new UsageError(`Commit ${shortSha(commit)}${branch ? ` on ${branch}` : ""} is not on any remote branch`, `Push it first (git push${branch ? ` origin ${branch}` : ""}); the run tests the pushed commit, and this command never pushes for you.`);
50988
+ }
50989
+ function dirtyNotice(status, commit) {
50990
+ const files = status.split(`
50991
+ `).filter((line) => line.trim()).length;
50992
+ if (files === 0)
50993
+ return;
50994
+ return `Warning: ${files} uncommitted change${files === 1 ? "" : "s"}; the run tests the pushed commit ${shortSha(commit)}, not this working tree.`;
50995
+ }
50996
+ function exitCodeFor(result) {
50997
+ return result === "passed" || result === "pending" ? 0 : 1;
50998
+ }
50999
+ var wantsFailures = (result) => result !== "passed" && result !== "pending";
51000
+ function failedList(items, nextPageToken2, url) {
51001
+ const shown = items.slice(0, FAILURE_LIMIT);
51002
+ if (items.length <= FAILURE_LIMIT && !nextPageToken2)
51003
+ return { shown };
51004
+ return { shown, hint: `Showing ${FAILURE_LIMIT} of the failed cases; the run page lists them all: ${url}` };
51005
+ }
51006
+ var CONSOLE = { develop: "https://console-develop.deepraxis.com", production: "https://console.deepraxis.com" };
51007
+ function runUrl(env, project, id, viewerUrl) {
51008
+ return viewerUrl?.trim() || `${CONSOLE[env]}/devops/projects/${project}/test-runs/${id}`;
51009
+ }
51010
+
51011
+ // src/commands/devops.ts
51012
+ async function projectFile(cwd, ports) {
51013
+ let text;
51014
+ try {
51015
+ text = await ports.readFile(join4(cwd, "praxis.jsonc"));
51016
+ } catch (error) {
51017
+ if (error.code === "ENOENT")
51018
+ return;
51019
+ throw error;
51020
+ }
51021
+ try {
51022
+ return parseJsonc(text);
51023
+ } catch (error) {
51024
+ throw new UsageError(`praxis.jsonc is not valid JSONC: ${error.message}`);
51025
+ }
51026
+ }
51027
+ var COUNT_ORDER = ["passed", "failed", "flaky", "skipped", "pending", "other"];
51028
+ var countLine = (counts) => COUNT_ORDER.filter((key) => counts?.[key]).map((key) => `${counts[key]} ${key}`).join(", ") || "no counts reported";
51029
+ async function devopsTestRun(args, connect, env, ports) {
51030
+ requireRemote(args.remote);
51031
+ const project = resolveProject(args.project, await projectFile(ports.cwd, ports));
51032
+ const selector = parseSelect(args.select ?? []);
51033
+ const repeat = parseRepeat(args.repeat);
51034
+ const git2 = async (gitArgs) => (await ports.git(gitArgs, ports.cwd)).output;
51035
+ const commit = (await git2(["rev-parse", "HEAD"])).trim();
51036
+ if (!commit)
51037
+ throw new UsageError("git rev-parse HEAD answered no commit", "Run this command inside a git repository.");
51038
+ const branch = headBranch(await git2(["rev-parse", "--abbrev-ref", "HEAD"]));
51039
+ requirePushed(await git2(["branch", "-r", "--contains", "HEAD"]), commit, branch);
51040
+ const notice = dirtyNotice(await git2(["status", "--porcelain"]), commit);
51041
+ if (notice)
51042
+ ports.emit({ kind: "message", channel: "stderr", text: notice });
51043
+ const client2 = await connect();
51044
+ const requestId = requestIdFor({ project, commit, selector, repeat });
51045
+ let run = await client2.devops.projects.testRuns.create({ path: { project }, body: { ref: { ...branch ? { branch } : {}, commit }, ...selector ? { selector } : {}, repeat, executor: "cloud", requestId } });
51046
+ while (args.wait && !isTerminal(run.state)) {
51047
+ await ports.wait(POLL_MS);
51048
+ run = await client2.devops.testRuns.retrieve({ path: { id: run.id } });
51049
+ }
51050
+ const url = runUrl(env, project, run.id, run.viewerUrl);
51051
+ let failures = [], failureHint;
51052
+ if (wantsFailures(run.result)) {
51053
+ const page = await client2.devops.testRuns.executions.list({ path: { run: run.id }, query: { pageSize: FAILURE_LIMIT, filter: "result=failed" } });
51054
+ ({ shown: failures, hint: failureHint } = failedList(page.items, page.nextPageToken, url));
51055
+ }
51056
+ const data = {
51057
+ id: run.id,
51058
+ url,
51059
+ project,
51060
+ state: run.state,
51061
+ result: run.result,
51062
+ repeat,
51063
+ commit,
51064
+ ...branch ? { branch } : {},
51065
+ selected: run.selection?.selectedCount ?? null,
51066
+ counts: run.counts ?? null,
51067
+ request_id: requestId,
51068
+ failures: failures.map((execution) => ({ case: execution.case, title: execution.title, package: execution.package ?? null, status: execution.status })),
51069
+ ...failureHint ? { failures_hint: failureHint } : {}
51070
+ };
51071
+ ports.emit({ kind: "object", data });
51072
+ ports.human([
51073
+ `${run.result} — ${project} @ ${commit.slice(0, 7)}${branch ? ` (${branch})` : ""}`,
51074
+ `state ${run.state}, ${countLine(run.counts)}`,
51075
+ url,
51076
+ ...failures.map((execution) => ` failed ${execution.title}`),
51077
+ ...failureHint ? [failureHint] : []
51078
+ ].join(`
51079
+ `));
51080
+ return exitCodeFor(run.result);
51081
+ }
51082
+ async function devopsDeployTofu(flags, ports) {
51083
+ const args = parseTofuDeployArgs(flags);
51084
+ const plan = await planRepository(await localFacts(ports));
51085
+ const result = await runTofuDeploy(args, plan, {
51086
+ repoRoot: ports.cwd,
51087
+ exec: nodeExec,
51088
+ fs: nodeFs,
51089
+ cloudflare: cloudflareApi(ports.fetch, ports.env),
51090
+ generate: generateTargetTf,
51091
+ clock: { now: () => Date.now(), iso: () => new Date().toISOString() },
51092
+ openEvents: (file, startedAt) => openDeployJobEvents({ file, startedAt }),
51093
+ out: ports.stdout
51094
+ });
51095
+ ports.emit({ kind: "object", data: result.summary });
51096
+ return result.exitCode;
51097
+ }
51098
+
49752
51099
  // src/commands/canvas-import.ts
49753
- import { basename as basename2, dirname as dirname2, join as join5, resolve as resolve3 } from "node:path";
51100
+ import { basename as basename2, dirname as dirname5, join as join5, resolve as resolve4 } from "node:path";
49754
51101
 
49755
51102
  // ../../packages/canvas/document/src/types.ts
49756
51103
  class OpRejectedError extends Error {
@@ -50482,7 +51829,7 @@ function pathLineBounds(geometry) {
50482
51829
  }
50483
51830
  if (command === null)
50484
51831
  return null;
50485
- const relative = command === command.toLowerCase();
51832
+ const relative2 = command === command.toLowerCase();
50486
51833
  const upper = command.toUpperCase();
50487
51834
  if (upper === "H" || upper === "V") {
50488
51835
  const value = tokens[i];
@@ -50490,9 +51837,9 @@ function pathLineBounds(geometry) {
50490
51837
  return null;
50491
51838
  i++;
50492
51839
  if (upper === "H")
50493
- x = relative ? x + value : value;
51840
+ x = relative2 ? x + value : value;
50494
51841
  else
50495
- y = relative ? y + value : value;
51842
+ y = relative2 ? y + value : value;
50496
51843
  add(x, y);
50497
51844
  continue;
50498
51845
  }
@@ -50500,8 +51847,8 @@ function pathLineBounds(geometry) {
50500
51847
  if (typeof nx !== "number" || typeof ny !== "number")
50501
51848
  return null;
50502
51849
  i += 2;
50503
- x = relative ? x + nx : nx;
50504
- y = relative ? y + ny : ny;
51850
+ x = relative2 ? x + nx : nx;
51851
+ y = relative2 ? y + ny : ny;
50505
51852
  if (upper === "M") {
50506
51853
  startX = x;
50507
51854
  startY = y;
@@ -52195,12 +53542,12 @@ var CONTENT_TYPES = {
52195
53542
  svg: "image/svg+xml",
52196
53543
  avif: "image/avif"
52197
53544
  };
52198
- var contentTypeOf = (url) => CONTENT_TYPES[url.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
53545
+ var contentTypeOf2 = (url) => CONTENT_TYPES[url.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
52199
53546
  var viewerUrlFor = (canvasId, env) => `https://console${env === "develop" ? "-develop" : ""}.deepraxis.com/canvases/${canvasId}`;
52200
53547
  function imageCandidates(url, penFile, roots) {
52201
53548
  const name = basename2(url);
52202
53549
  return [...new Set([
52203
- join5(dirname2(penFile), url),
53550
+ join5(dirname5(penFile), url),
52204
53551
  ...roots.map((root) => join5(root, url)),
52205
53552
  ...roots.map((root) => join5(root, name))
52206
53553
  ])];
@@ -52235,7 +53582,7 @@ async function canvasImport(args, ports) {
52235
53582
  if (args.canvas !== undefined && !args.yes) {
52236
53583
  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.");
52237
53584
  }
52238
- const file = resolve3(ports.cwd, args.file);
53585
+ const file = resolve4(ports.cwd, args.file);
52239
53586
  let text;
52240
53587
  try {
52241
53588
  text = await ports.readFile(file);
@@ -52251,7 +53598,7 @@ async function canvasImport(args, ports) {
52251
53598
  if (!Array.isArray(doc.children))
52252
53599
  throw new UsageError(`${args.file} has no children array`, "A .pen document is an object with a children array of top-level nodes.");
52253
53600
  const frames = args.frames?.filter((frame) => frame !== "");
52254
- const roots = (args.imageRoots ?? []).map((root) => resolve3(ports.cwd, root));
53601
+ const roots = (args.imageRoots ?? []).map((root) => resolve4(ports.cwd, root));
52255
53602
  const selection = planPenImport(doc, frames ? { frames } : {});
52256
53603
  const urls = penImageUrls(selection.children);
52257
53604
  const found = new Map;
@@ -52275,7 +53622,7 @@ async function canvasImport(args, ports) {
52275
53622
  reused++;
52276
53623
  continue;
52277
53624
  }
52278
- const id = await ports.upload({ filename: basename2(url), bytes, contentType: contentTypeOf(url) });
53625
+ const id = await ports.upload({ filename: basename2(url), bytes, contentType: contentTypeOf2(url) });
52279
53626
  byDigest.set(digest, id);
52280
53627
  images[url] = id;
52281
53628
  uploaded++;
@@ -52411,7 +53758,7 @@ function timestamp(key, value) {
52411
53758
  const time = typeof value === "number" ? Math.abs(value) < 100000000000 ? value * 1000 : value : typeof value === "string" && /^\d{4}-\d\d-\d\d[T ]/.test(value) ? Date.parse(value) : NaN;
52412
53759
  return Number.isFinite(time) ? new Date(time).toISOString() : undefined;
52413
53760
  }
52414
- function relative(iso, now) {
53761
+ function relative2(iso, now) {
52415
53762
  const delta = now - Date.parse(iso), seconds = Math.floor(Math.abs(delta) / 1000);
52416
53763
  if (Math.abs(delta) < 60000)
52417
53764
  return "just now";
@@ -52550,7 +53897,7 @@ function table(items, ctx, paint) {
52550
53897
  const now = ctx.now ?? Date.now();
52551
53898
  let rows = items.map((item) => columns.map((key) => {
52552
53899
  const v = record(item)[key], iso = timestamp(key, v);
52553
- return plain(iso ? relative(iso, now) : scalar(v));
53900
+ return plain(iso ? relative2(iso, now) : scalar(v));
52554
53901
  }));
52555
53902
  let headers = columns.map((key) => key.toUpperCase());
52556
53903
  let sizes = columns.map((_, i) => Math.max(width(headers[i]), ...rows.map((row) => width(row[i]))));
@@ -52590,7 +53937,7 @@ function objectView(data, resource, id, ctx, paint) {
52590
53937
  function value(key, v, depth) {
52591
53938
  const iso = timestamp(key, v);
52592
53939
  if (iso)
52593
- return `${iso} (${relative(iso, now)})`;
53940
+ return `${iso} (${relative2(iso, now)})`;
52594
53941
  if (Array.isArray(v)) {
52595
53942
  if (v.every((x) => x === null || typeof x !== "object"))
52596
53943
  return v.map(scalar).map(plain).join(", ");
@@ -52970,7 +54317,7 @@ function startProgress(ctx, write = (text) => writeOutput({ stderr: text })) {
52970
54317
  }
52971
54318
 
52972
54319
  // src/main.ts
52973
- var version = "0.3.0-dev.d38b647";
54320
+ var version = "0.3.0-dev.faa3b25";
52974
54321
  var commands = commandTree(operations);
52975
54322
  var manual = [...workflows.map((w) => w.words), [API_WORD]];
52976
54323
  function route(argv) {
@@ -52993,6 +54340,8 @@ function route(argv) {
52993
54340
  const command = commands.find((c) => c.words.length === words.length && c.words.every((w, n2) => w === words[n2]));
52994
54341
  if (words.length === 1 && words[0] === API_WORD && argv[i + 1] !== undefined && !argv[i + 1].startsWith("-"))
52995
54342
  continue;
54343
+ if (manual.some((c) => c.length === words.length + 1 && c.every((w, n2) => n2 < words.length ? w === words[n2] : w === argv[i + 1])))
54344
+ continue;
52996
54345
  if (command || manual.some((c) => c.length === words.length && c.every((w, n2) => w === words[n2])))
52997
54346
  return { words, args: [...args, ...argv.slice(i + 1)], command };
52998
54347
  }
@@ -53006,22 +54355,22 @@ var defaults = {
53006
54355
  stdoutIsTTY: Boolean(process.stdout.isTTY),
53007
54356
  stderrIsTTY: Boolean(process.stderr.isTTY),
53008
54357
  columns: process.stdout.columns ?? 100,
53009
- readFile: (path) => readFile3(path, "utf8"),
53010
- readBytes: (path) => readFile3(path),
53011
- sha256: async (bytes) => createHash3("sha256").update(bytes).digest("hex"),
54358
+ readFile: (path) => readFile4(path, "utf8"),
54359
+ readBytes: (path) => readFile4(path),
54360
+ sha256: async (bytes) => createHash4("sha256").update(bytes).digest("hex"),
53012
54361
  async readStdin() {
53013
54362
  const chunks = [];
53014
54363
  for await (const chunk of process.stdin)
53015
54364
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
53016
54365
  return Buffer.concat(chunks).toString("utf8");
53017
54366
  },
53018
- ask: () => new Promise((resolve4) => {
54367
+ ask: () => new Promise((resolve5) => {
53019
54368
  const input = createInterface({ input: process.stdin, terminal: false });
53020
54369
  input.once("line", (line) => {
53021
- resolve4(/^(y|yes)$/i.test(line.trim()));
54370
+ resolve5(/^(y|yes)$/i.test(line.trim()));
53022
54371
  input.close();
53023
54372
  });
53024
- input.once("close", () => resolve4(false));
54373
+ input.once("close", () => resolve5(false));
53025
54374
  }),
53026
54375
  async openBrowser(url) {
53027
54376
  try {
@@ -53029,27 +54378,27 @@ var defaults = {
53029
54378
  if (!["https:", "http:"].includes(parsed.protocol))
53030
54379
  return;
53031
54380
  const cmd = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["rundll32", "url.dll,FileProtocolHandler", url] : ["xdg-open", url];
53032
- await new Promise((resolve4, reject) => {
53033
- const child = spawn2(cmd[0], cmd.slice(1), { stdio: "ignore" });
54381
+ await new Promise((resolve5, reject) => {
54382
+ const child = spawn3(cmd[0], cmd.slice(1), { stdio: "ignore" });
53034
54383
  child.once("error", reject);
53035
- child.once("close", () => resolve4());
54384
+ child.once("close", () => resolve5());
53036
54385
  });
53037
54386
  } catch {}
53038
54387
  },
53039
- wait: (ms) => new Promise((resolve4) => setTimeout(resolve4, ms)),
54388
+ wait: (ms) => new Promise((resolve5) => setTimeout(resolve5, ms)),
53040
54389
  render,
53041
- spawn: (cmd, args, options) => new Promise((resolve4, reject) => {
53042
- const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
54390
+ spawn: (cmd, args, options) => new Promise((resolve5, reject) => {
54391
+ const child = spawn3(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
53043
54392
  child.once("error", reject);
53044
- child.once("close", (code) => resolve4(code ?? 1));
54393
+ child.once("close", (code) => resolve5(code ?? 1));
53045
54394
  }),
53046
- spawnCapture: (cmd, args, options) => new Promise((resolve4, reject) => {
53047
- const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
54395
+ spawnCapture: (cmd, args, options) => new Promise((resolve5, reject) => {
54396
+ const child = spawn3(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
53048
54397
  const chunks = [];
53049
54398
  child.stdout.on("data", (c) => chunks.push(c));
53050
54399
  child.stderr.on("data", (c) => chunks.push(c));
53051
54400
  child.once("error", reject);
53052
- child.once("close", (code) => resolve4({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
54401
+ child.once("close", (code) => resolve5({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
53053
54402
  }),
53054
54403
  has: (bin) => spawnSync(process.platform === "win32" ? "where" : "which", [bin], { stdio: "ignore" }).status === 0,
53055
54404
  cwd: process.cwd()
@@ -53062,6 +54411,17 @@ var appOptions = {
53062
54411
  { name: "env", type: "string", description: "Plan only the targets this environment deploys (default: every environment)." },
53063
54412
  { name: "since", type: "string", description: "Mark the targets a change since this commit touches: git diff <since>...HEAD." }
53064
54413
  ],
54414
+ "devops deploy": [
54415
+ { name: "engine", type: "string", description: "Deploy engine; only tofu (OpenTofu, ADR-110)." },
54416
+ { name: "env", type: "string", description: "develop or production." },
54417
+ { name: "targets", type: "string", description: "Comma-separated target paths (default: every deployable target)." },
54418
+ { name: "commit", type: "string", description: "The commit being rolled out." },
54419
+ { name: "plan-only", type: "boolean", description: "Write plan files and a summary, apply nothing." },
54420
+ { name: "plan-dir", type: "string", description: "Directory the plan files are written to." },
54421
+ { name: "apply-plans", type: "string", description: "Apply the approved plan files in this directory." },
54422
+ { name: "events-file", type: "string", description: "NDJSON file the ExecutorLine events are written to." },
54423
+ { name: "workdir", type: "string", description: "Working directory for bundles and generated documents." }
54424
+ ],
53065
54425
  "devops test run": [
53066
54426
  { name: "project", type: "string", description: "DevOps project id (dvp_…); default: the devops.project field of praxis.jsonc in the current directory." },
53067
54427
  { name: "remote", type: "boolean", description: "Run the cases on the Praxis cloud executor. Required; local execution does not exist yet." },
@@ -53263,6 +54623,42 @@ Examples:
53263
54623
  const arity = name === "api" ? 2 : name === "org switch" || name === "app create" || name === "canvas import" ? 1 : 0;
53264
54624
  if (parsed.positional.length !== arity)
53265
54625
  throw new UsageError(`${name} expects ${arity} positional argument(s)`);
54626
+ if (name === "devops deploy") {
54627
+ if (parsed.flags.engine?.[0] !== "tofu")
54628
+ throw new UsageError("devops deploy needs --engine tofu", "Pass --engine tofu (ADR-110).");
54629
+ const f = (key) => parsed.flags[key]?.[0];
54630
+ return await devopsDeployTofu({
54631
+ env: f("env"),
54632
+ targets: f("targets"),
54633
+ commit: f("commit"),
54634
+ "plan-only": Boolean(parsed.flags["plan-only"]),
54635
+ "plan-dir": f("plan-dir"),
54636
+ "apply-plans": f("apply-plans"),
54637
+ "events-file": f("events-file"),
54638
+ workdir: f("workdir")
54639
+ }, {
54640
+ git: (args, cwd) => ports.spawnCapture("git", args, { cwd }),
54641
+ readFile: async (path2) => {
54642
+ try {
54643
+ return await ports.readFile(path2);
54644
+ } catch (error) {
54645
+ if (error.code === "ENOENT")
54646
+ return null;
54647
+ throw error;
54648
+ }
54649
+ },
54650
+ mode: ctx.mode,
54651
+ emit,
54652
+ human: () => {},
54653
+ cwd: ports.cwd,
54654
+ env: ports.env,
54655
+ fetch: wireFetch,
54656
+ stdout: (line) => {
54657
+ process.stdout.write(`${line}
54658
+ `);
54659
+ }
54660
+ });
54661
+ }
53266
54662
  if (name === "devops deploy plan") {
53267
54663
  await devopsDeployPlan({
53268
54664
  environment: parsed.flags.env?.[0],