@deepraxis/cli 0.3.0-dev.7d6e891 → 0.3.0-dev.80cda87

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 +1924 -357
  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
@@ -22535,7 +22535,7 @@ The default is return=minimal: success returns HTTP 201 with an empty body. Send
22535
22535
  resource: "media.speech",
22536
22536
  method: "create",
22537
22537
  summary: "Create speech",
22538
- description: "Synthesise speech from text and store the recording straight into the library. Use library_id from creation or listing; the path segment {library_id} also accepts the literal default, which resolves to the organization’s default library before the credential check, so an agent that has never listed a library can still synthesise. input is the text to speak and voice is required; speed is passed to the provider unchanged, and instructions and language are refused with OPERATION_NOT_SUPPORTED in this release. A voice that names a voice material of this library is refused the same way — voice cloning opens with voices.create. The provider caps one request at a short stretch of text, so a long input is cut into segments at paragraph and sentence boundaries and synthesised in order, then joined into the single recording the library receives: nothing is spoken twice and nothing is dropped. Because the segments are joined byte for byte, a multi-segment input accepts only response_format mp3 (the default) or pcm; opus is available for a single-segment input. A speech job has one result however many segments it took. Synthesis is billed by the model usage it consumes, at the same prices as the model API, and the job records the charge in usage; a request refused before it starts costs nothing. The response is 202 with a queued Job whose type is speech and whose operation is generate; poll GET /media/v1/libraries/{library_id}/jobs/{job_id} until its status is completed or failed, then read the produced asset from the library — the recording carries material_type audio, audio_role voice, ai_generated true, and provenance naming this job, the text spoken and the model. Send Idempotency-Key, or idempotency_key in the body, to retry without synthesising and charging twice. Example: POST /media/v1/libraries/default/audio/speech with {\"input\":\"A red kite above a calm sea at sunrise.\",\"voice\":\"alloy\"}.",
22538
+ description: "Synthesise speech from text and store the recording straight into the library. Use library_id from creation or listing; the path segment {library_id} also accepts the literal default, which resolves to the organization’s default library before the credential check, so an agent that has never listed a library can still synthesise. input is the text to speak and voice is required; speed is passed to the provider unchanged, and instructions and language are refused with OPERATION_NOT_SUPPORTED in this release. Voice cloning is not available yet, so voice is a platform voice name of the chosen model. The provider caps one request at a short stretch of text, so a long input is cut into segments at paragraph and sentence boundaries and synthesised in order, then joined into the single recording the library receives: nothing is spoken twice and nothing is dropped. Because the segments are joined byte for byte, a multi-segment input accepts only response_format mp3 (the default) or pcm; opus is available for a single-segment input. A speech job has one result however many segments it took. Synthesis is billed by the model usage it consumes, at the same prices as the model API, and the job records the charge in usage; a request refused before it starts costs nothing. The response is 202 with a queued Job whose type is speech and whose operation is generate; poll GET /media/v1/libraries/{library_id}/jobs/{job_id} until its status is completed or failed, then read the produced asset from the library — the recording carries material_type audio, audio_role voice, ai_generated true, and provenance naming this job, the text spoken and the model. Send Idempotency-Key, or idempotency_key in the body, to retry without synthesising and charging twice. Example: POST /media/v1/libraries/default/audio/speech with {\"input\":\"A red kite above a calm sea at sunrise.\",\"voice\":\"alloy\"}.",
22539
22539
  http: "POST",
22540
22540
  path: "/media/v1/libraries/{library_id}/audio/speech",
22541
22541
  streaming: "no",
@@ -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 --env <develop|production> --commit <sha> [--targets a,b] [--plan-only] [--plan-dir <dir>] [--apply-plans <dir>] [--events-file <path>]", summary: "Roll targets out: build, generate, plan (--plan-only) or apply approved plans (--apply-plans), layer by layer, writing the ExecutorLine events DevOps folds. Advanced: PRAXIS_TOFU_BIN points at a pre-installed engine binary (air-gapped builders).", example: "praxis devops deploy --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,709 @@ 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_VERSION = "1.10.6";
49572
+ var OPENTOFU_REQUIRED_VERSION = ">= 1.10.0";
49573
+ function stateKeyOf(environment2, target) {
49574
+ return `env/${environment2}/${target}/terraform.tfstate`;
49575
+ }
49576
+ // ../../packages/praxis/deploy-core/src/tofu/generate.ts
49577
+ var WORKER_ADDRESS = "cloudflare_workers_script.worker";
49578
+ var WORKER_REF = "${cloudflare_workers_script.worker.script_name}";
49579
+ var INHERITABLE = [
49580
+ "main",
49581
+ "compatibility_date",
49582
+ "compatibility_flags",
49583
+ "observability",
49584
+ "placement",
49585
+ "limits",
49586
+ "logpush",
49587
+ "tail_consumers",
49588
+ "preview_urls"
49589
+ ];
49590
+ var NON_BINDING_KEYS = new Set([
49591
+ "$schema",
49592
+ "name",
49593
+ "main",
49594
+ "compatibility_date",
49595
+ "compatibility_flags",
49596
+ "observability",
49597
+ "placement",
49598
+ "limits",
49599
+ "logpush",
49600
+ "tail_consumers",
49601
+ "preview_urls",
49602
+ "routes",
49603
+ "route",
49604
+ "workers_dev",
49605
+ "triggers",
49606
+ "migrations",
49607
+ "containers",
49608
+ "rules",
49609
+ "alias",
49610
+ "build",
49611
+ "define",
49612
+ "minify",
49613
+ "keep_names",
49614
+ "send_metrics",
49615
+ "upload_source_maps",
49616
+ "node_compat",
49617
+ "tsconfig",
49618
+ "base_dir",
49619
+ "no_bundle",
49620
+ "find_additional_modules",
49621
+ "usage_model",
49622
+ "account_id",
49623
+ "dev",
49624
+ "site",
49625
+ "env",
49626
+ "legacy_env",
49627
+ "jsx_factory",
49628
+ "jsx_fragment",
49629
+ "first_party_worker",
49630
+ "workers_dev",
49631
+ "assets",
49632
+ "queues",
49633
+ "vars",
49634
+ "ai",
49635
+ "analytics_engine_datasets",
49636
+ "browser",
49637
+ "d1_databases",
49638
+ "dispatch_namespaces",
49639
+ "durable_objects",
49640
+ "flagship",
49641
+ "images",
49642
+ "kv_namespaces",
49643
+ "media",
49644
+ "pipelines",
49645
+ "r2_buckets",
49646
+ "ratelimits",
49647
+ "secrets_store_secrets",
49648
+ "send_email",
49649
+ "services",
49650
+ "vectorize",
49651
+ "version_metadata",
49652
+ "worker_loaders",
49653
+ "workflows"
49654
+ ]);
49655
+ var KNOWN_UNSUPPORTED = ["hyperdrive", "mtls_certificates", "unsafe", "text_blobs", "data_blobs", "wasm_modules", "vpc_services"];
49656
+ var isRec = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
49657
+ var recs = (value) => Array.isArray(value) ? value.filter(isRec) : [];
49658
+ var str = (value) => typeof value === "string" && value !== "" ? value : undefined;
49659
+ function projectEnvironment(wrangler, environment2) {
49660
+ if (environment2 === "develop") {
49661
+ const { env: _env, ...rest } = wrangler;
49662
+ return rest;
49663
+ }
49664
+ const block = isRec(wrangler.env) ? wrangler.env.production : undefined;
49665
+ if (!isRec(block))
49666
+ return null;
49667
+ const projected = { ...block };
49668
+ for (const key of INHERITABLE)
49669
+ if (!(key in projected) && key in wrangler)
49670
+ projected[key] = wrangler[key];
49671
+ if (str(projected.name) === undefined) {
49672
+ const base = str(wrangler.name);
49673
+ if (base !== undefined)
49674
+ projected.name = `${base}-production`;
49675
+ }
49676
+ return projected;
49677
+ }
49678
+ function collectBindings(config, own, assetsDir) {
49679
+ const bindings = [];
49680
+ const refs = [];
49681
+ const gaps = [];
49682
+ const refusals = [];
49683
+ const unresolved = (binding, detail) => {
49684
+ refusals.push({ kind: "unresolved-resource", binding, detail });
49685
+ };
49686
+ if (isRec(config.vars)) {
49687
+ for (const [name, value] of Object.entries(config.vars)) {
49688
+ bindings.push(typeof value === "string" ? { type: "plain_text", name, text: value } : { type: "json", name, json: JSON.stringify(value) });
49689
+ }
49690
+ }
49691
+ if (isRec(config.ai) && str(config.ai.binding))
49692
+ bindings.push({ type: "ai", name: config.ai.binding });
49693
+ for (const entry of recs(config.analytics_engine_datasets)) {
49694
+ const name = str(entry.binding) ?? "?";
49695
+ const dataset = str(entry.dataset);
49696
+ if (dataset === undefined) {
49697
+ unresolved(name, "analytics engine binding has no dataset");
49698
+ continue;
49699
+ }
49700
+ bindings.push({ type: "analytics_engine", name, dataset });
49701
+ gaps.push({ kind: "analytics-engine-dataset", binding: name, dataset });
49702
+ }
49703
+ if (isRec(config.browser) && str(config.browser.binding))
49704
+ bindings.push({ type: "browser", name: config.browser.binding });
49705
+ for (const entry of recs(config.d1_databases)) {
49706
+ const name = str(entry.binding) ?? "?";
49707
+ const id = str(entry.database_id);
49708
+ if (id === undefined) {
49709
+ unresolved(name, "d1 binding has no database_id");
49710
+ continue;
49711
+ }
49712
+ bindings.push({ type: "d1", name, database_id: id });
49713
+ gaps.push({
49714
+ kind: "d1-migrations",
49715
+ binding: name,
49716
+ databaseName: str(entry.database_name) ?? id,
49717
+ migrationsDir: str(entry.migrations_dir) ?? "migrations"
49718
+ });
49719
+ }
49720
+ for (const entry of recs(config.dispatch_namespaces)) {
49721
+ const name = str(entry.binding) ?? "?";
49722
+ const namespace = str(entry.namespace);
49723
+ if (namespace === undefined) {
49724
+ unresolved(name, "dispatch namespace binding has no namespace");
49725
+ continue;
49726
+ }
49727
+ const binding = { type: "dispatch_namespace", name, namespace };
49728
+ const outbound = isRec(entry.outbound) ? entry.outbound : undefined;
49729
+ const service = str(outbound?.service);
49730
+ if (outbound && service !== undefined) {
49731
+ binding.outbound = {
49732
+ worker: { service, environment: "production" },
49733
+ ...Array.isArray(outbound.parameters) ? { params: outbound.parameters } : {}
49734
+ };
49735
+ refs.push(service);
49736
+ }
49737
+ bindings.push(binding);
49738
+ }
49739
+ const objectBindings = isRec(config.durable_objects) ? recs(config.durable_objects.bindings) : [];
49740
+ for (const entry of objectBindings) {
49741
+ const script = str(entry.script_name);
49742
+ const binding = { type: "durable_object_namespace", name: str(entry.name) ?? "?", class_name: str(entry.class_name) ?? "?" };
49743
+ if (script !== undefined && script !== own) {
49744
+ binding.script_name = script;
49745
+ refs.push(script);
49746
+ }
49747
+ bindings.push(binding);
49748
+ }
49749
+ for (const entry of recs(config.flagship)) {
49750
+ const name = str(entry.binding) ?? "?";
49751
+ const appId = str(entry.app_id);
49752
+ if (appId === undefined) {
49753
+ unresolved(name, "flagship binding has no app_id");
49754
+ continue;
49755
+ }
49756
+ bindings.push({ type: "flagship", name, app_id: appId });
49757
+ }
49758
+ if (isRec(config.images) && str(config.images.binding))
49759
+ bindings.push({ type: "images", name: config.images.binding });
49760
+ for (const entry of recs(config.kv_namespaces)) {
49761
+ const name = str(entry.binding) ?? "?";
49762
+ const id = str(entry.id);
49763
+ if (id === undefined) {
49764
+ unresolved(name, "kv binding has no id");
49765
+ continue;
49766
+ }
49767
+ bindings.push({ type: "kv_namespace", name, namespace_id: id });
49768
+ }
49769
+ if (isRec(config.media) && str(config.media.binding))
49770
+ bindings.push({ type: "media", name: config.media.binding });
49771
+ for (const entry of recs(config.pipelines)) {
49772
+ const name = str(entry.binding) ?? "?";
49773
+ const pipeline = str(entry.stream) ?? str(entry.pipeline);
49774
+ if (pipeline === undefined) {
49775
+ unresolved(name, "pipeline binding has no stream");
49776
+ continue;
49777
+ }
49778
+ bindings.push({ type: "pipelines", name, pipeline });
49779
+ }
49780
+ const producers = isRec(config.queues) ? recs(config.queues.producers) : [];
49781
+ for (const entry of producers) {
49782
+ const name = str(entry.binding) ?? "?";
49783
+ const queue = str(entry.queue);
49784
+ if (queue === undefined) {
49785
+ unresolved(name, "queue producer has no queue");
49786
+ continue;
49787
+ }
49788
+ bindings.push({ type: "queue", name, queue_name: queue });
49789
+ }
49790
+ for (const entry of recs(config.r2_buckets)) {
49791
+ const name = str(entry.binding) ?? "?";
49792
+ const bucket = str(entry.bucket_name);
49793
+ if (bucket === undefined) {
49794
+ unresolved(name, "r2 binding has no bucket_name");
49795
+ continue;
49796
+ }
49797
+ bindings.push({
49798
+ type: "r2_bucket",
49799
+ name,
49800
+ bucket_name: bucket,
49801
+ ...str(entry.jurisdiction) ? { jurisdiction: entry.jurisdiction } : {}
49802
+ });
49803
+ }
49804
+ for (const entry of recs(config.ratelimits)) {
49805
+ const name = str(entry.name) ?? "?";
49806
+ const namespaceId = entry.namespace_id;
49807
+ const simple = isRec(entry.simple) ? entry.simple : undefined;
49808
+ if (namespaceId === undefined || simple === undefined) {
49809
+ unresolved(name, "ratelimit binding has no namespace_id or simple");
49810
+ continue;
49811
+ }
49812
+ bindings.push({ type: "ratelimit", name, namespace_id: String(namespaceId), simple: { limit: simple.limit, period: simple.period } });
49813
+ }
49814
+ for (const entry of recs(config.secrets_store_secrets)) {
49815
+ const name = str(entry.binding) ?? "?";
49816
+ const store = str(entry.store_id);
49817
+ const secret = str(entry.secret_name);
49818
+ if (store === undefined || secret === undefined) {
49819
+ unresolved(name, "secrets store binding has no store_id or secret_name");
49820
+ continue;
49821
+ }
49822
+ bindings.push({ type: "secrets_store_secret", name, store_id: store, secret_name: secret });
49823
+ }
49824
+ for (const entry of recs(config.send_email)) {
49825
+ bindings.push({
49826
+ type: "send_email",
49827
+ name: str(entry.name) ?? "?",
49828
+ ...str(entry.destination_address) ? { destination_address: entry.destination_address } : {},
49829
+ ...Array.isArray(entry.allowed_destination_addresses) ? { allowed_destination_addresses: entry.allowed_destination_addresses } : {},
49830
+ ...Array.isArray(entry.allowed_sender_addresses) ? { allowed_sender_addresses: entry.allowed_sender_addresses } : {}
49831
+ });
49832
+ }
49833
+ for (const entry of recs(config.services)) {
49834
+ const name = str(entry.binding) ?? "?";
49835
+ const service = str(entry.service);
49836
+ if (service === undefined) {
49837
+ unresolved(name, "service binding has no service");
49838
+ continue;
49839
+ }
49840
+ bindings.push({
49841
+ type: "service",
49842
+ name,
49843
+ service,
49844
+ ...str(entry.entrypoint) ? { entrypoint: entry.entrypoint } : {},
49845
+ environment: "production"
49846
+ });
49847
+ if (service !== own)
49848
+ refs.push(service);
49849
+ }
49850
+ for (const entry of recs(config.vectorize)) {
49851
+ const name = str(entry.binding) ?? "?";
49852
+ const index = str(entry.index_name);
49853
+ if (index === undefined) {
49854
+ unresolved(name, "vectorize binding has no index_name");
49855
+ continue;
49856
+ }
49857
+ bindings.push({ type: "vectorize", name, index_name: index });
49858
+ gaps.push({ kind: "vectorize-index", binding: name, indexName: index });
49859
+ }
49860
+ if (isRec(config.version_metadata) && str(config.version_metadata.binding))
49861
+ bindings.push({ type: "version_metadata", name: config.version_metadata.binding });
49862
+ for (const entry of recs(config.worker_loaders))
49863
+ bindings.push({ type: "worker_loader", name: str(entry.binding) ?? "?" });
49864
+ for (const entry of recs(config.workflows)) {
49865
+ const name = str(entry.binding) ?? "?";
49866
+ const workflowName = str(entry.name);
49867
+ const className = str(entry.class_name);
49868
+ if (workflowName === undefined || className === undefined) {
49869
+ unresolved(name, "workflow binding has no name or class_name");
49870
+ continue;
49871
+ }
49872
+ const script = str(entry.script_name);
49873
+ const binding = { type: "workflow", name, workflow_name: workflowName, class_name: className };
49874
+ if (script !== undefined && script !== own) {
49875
+ binding.script_name = script;
49876
+ refs.push(script);
49877
+ }
49878
+ bindings.push(binding);
49879
+ }
49880
+ if (isRec(config.assets) && str(config.assets.binding)) {
49881
+ if (assetsDir === null)
49882
+ unresolved(String(config.assets.binding), "assets declared but the bundle has no assets directory");
49883
+ else
49884
+ bindings.push({ type: "assets", name: config.assets.binding });
49885
+ }
49886
+ for (const entry of recs(config.containers)) {
49887
+ const className = str(entry.class_name);
49888
+ const image = str(entry.image);
49889
+ if (className !== undefined && image !== undefined)
49890
+ gaps.push({ kind: "container", className, image });
49891
+ }
49892
+ for (const key of KNOWN_UNSUPPORTED) {
49893
+ if (config[key] !== undefined)
49894
+ refusals.push({ kind: "unsupported-binding", binding: key, type: key });
49895
+ }
49896
+ for (const [key, value] of Object.entries(config)) {
49897
+ if (NON_BINDING_KEYS.has(key) || KNOWN_UNSUPPORTED.includes(key))
49898
+ continue;
49899
+ const shaped = Array.isArray(value) ? recs(value).some((entry) => ("binding" in entry)) : isRec(value) && (("binding" in value) || ("bindings" in value));
49900
+ if (shaped)
49901
+ refusals.push({ kind: "unsupported-binding", binding: key, type: key });
49902
+ }
49903
+ return { bindings, refs, gaps, refusals };
49904
+ }
49905
+ function migrationsOf(config, live) {
49906
+ const declared = recs(config.migrations);
49907
+ if (declared.length === 0)
49908
+ return { value: null, refusal: null };
49909
+ const tags = declared.map((step) => str(step.tag) ?? "");
49910
+ const last = tags[tags.length - 1] ?? "";
49911
+ let pending = declared;
49912
+ if (live !== null) {
49913
+ const index = tags.indexOf(live);
49914
+ if (index === -1)
49915
+ return {
49916
+ value: null,
49917
+ refusal: { kind: "unresolved-resource", binding: "migrations", detail: `live migration tag ${live} is not in the declared migrations` }
49918
+ };
49919
+ pending = declared.slice(index + 1);
49920
+ }
49921
+ if (pending.length === 0)
49922
+ return { value: { old_tag: live, new_tag: live }, refusal: null };
49923
+ const stepOf = (step) => {
49924
+ const { tag: _tag, ...rest } = step;
49925
+ return rest;
49926
+ };
49927
+ const value = { ...live !== null ? { old_tag: live } : {}, new_tag: last };
49928
+ if (pending.length === 1)
49929
+ Object.assign(value, stepOf(pending[0]));
49930
+ else
49931
+ value.steps = pending.map(stepOf);
49932
+ return { value, refusal: null };
49933
+ }
49934
+ function observabilityOf(value) {
49935
+ if (!isRec(value))
49936
+ return;
49937
+ const out = { enabled: value.enabled === true };
49938
+ if (typeof value.head_sampling_rate === "number")
49939
+ out.head_sampling_rate = value.head_sampling_rate;
49940
+ const section = (raw, withInvocation) => {
49941
+ if (!isRec(raw))
49942
+ return;
49943
+ const result = { enabled: raw.enabled === true };
49944
+ if (typeof raw.head_sampling_rate === "number")
49945
+ result.head_sampling_rate = raw.head_sampling_rate;
49946
+ if (typeof raw.persist === "boolean")
49947
+ result.persist = raw.persist;
49948
+ if (Array.isArray(raw.destinations))
49949
+ result.destinations = raw.destinations;
49950
+ if (withInvocation)
49951
+ result.invocation_logs = raw.invocation_logs !== false;
49952
+ return result;
49953
+ };
49954
+ const logs = section(value.logs, true);
49955
+ const traces = section(value.traces, false);
49956
+ if (logs)
49957
+ out.logs = logs;
49958
+ if (traces)
49959
+ out.traces = traces;
49960
+ return out;
49961
+ }
49962
+ var sanitize = (text) => text.replace(/[^A-Za-z0-9_]/g, "_");
49963
+ var contentTypeOf = (file) => file.endsWith(".wasm") ? "application/wasm" : file.endsWith(".json") ? "application/json" : file.endsWith(".txt") ? "text/plain" : "application/javascript+module";
49964
+ function generateTargetTf(input) {
49965
+ const config = projectEnvironment(input.wrangler, input.environment);
49966
+ if (config === null)
49967
+ return { ok: false, refusals: [{ kind: "missing-environment-block", target: input.target }] };
49968
+ const scriptName = str(config.name);
49969
+ if (scriptName === undefined)
49970
+ return { ok: false, refusals: [{ kind: "unresolved-resource", binding: "name", detail: "wrangler config names no Worker" }] };
49971
+ const collected = collectBindings(config, scriptName, input.bundle.assetsDir);
49972
+ const migrations = migrationsOf(config, input.liveMigrationTag);
49973
+ const refusals = [...collected.refusals, ...migrations.refusal ? [migrations.refusal] : []];
49974
+ const routes = [];
49975
+ const rawRoutes = [...Array.isArray(config.routes) ? config.routes : [], ...config.route !== undefined ? [config.route] : []];
49976
+ for (const raw of rawRoutes) {
49977
+ const entry = typeof raw === "string" ? { pattern: raw } : isRec(raw) ? raw : {};
49978
+ const pattern = str(entry.pattern);
49979
+ if (pattern === undefined) {
49980
+ refusals.push({ kind: "unresolved-resource", binding: "routes", detail: "route has no pattern" });
49981
+ continue;
49982
+ }
49983
+ if (entry.custom_domain !== true && str(entry.zone_name) === undefined && str(entry.zone_id) === undefined)
49984
+ refusals.push({ kind: "unresolved-resource", binding: `route ${pattern}`, detail: "route has neither zone_name nor zone_id" });
49985
+ routes.push({ ...entry, pattern });
49986
+ }
49987
+ if (refusals.length > 0)
49988
+ return { ok: false, refusals };
49989
+ const dependsOn = [...new Set(collected.refs.filter((name) => name !== scriptName && (name in input.callees)).map((name) => input.callees[name]))].sort();
49990
+ const worker = {
49991
+ account_id: "${var.account_id}",
49992
+ script_name: scriptName,
49993
+ content_file: input.bundle.mainFile,
49994
+ content_sha256: input.bundle.sha256,
49995
+ content_type: "application/javascript+module",
49996
+ main_module: input.bundle.mainModule,
49997
+ bindings: collected.bindings
49998
+ };
49999
+ if (str(config.compatibility_date))
50000
+ worker.compatibility_date = config.compatibility_date;
50001
+ if (Array.isArray(config.compatibility_flags) && config.compatibility_flags.length > 0)
50002
+ worker.compatibility_flags = config.compatibility_flags;
50003
+ if (migrations.value)
50004
+ worker.migrations = migrations.value;
50005
+ if (input.exports.length > 0)
50006
+ worker.exports = Object.fromEntries([...new Set(input.exports)].sort().map((name) => [name, { type: "worker" }]));
50007
+ const observability = observabilityOf(config.observability);
50008
+ if (observability)
50009
+ worker.observability = observability;
50010
+ if (typeof config.logpush === "boolean")
50011
+ worker.logpush = config.logpush;
50012
+ if (isRec(config.limits)) {
50013
+ const limits = {};
50014
+ if (typeof config.limits.cpu_ms === "number")
50015
+ limits.cpu_ms = config.limits.cpu_ms;
50016
+ if (typeof config.limits.subrequests === "number")
50017
+ limits.subrequests = config.limits.subrequests;
50018
+ if (Object.keys(limits).length > 0)
50019
+ worker.limits = limits;
50020
+ }
50021
+ const tails = recs(config.tail_consumers).filter((entry) => str(entry.service));
50022
+ if (tails.length > 0)
50023
+ worker.tail_consumers = tails.map((entry) => ({ service: entry.service }));
50024
+ if (input.bundle.extraModules.length > 0) {
50025
+ worker.files = Object.fromEntries(input.bundle.extraModules.map((file) => [file, { content_file: file, content_type: contentTypeOf(file) }]));
50026
+ }
50027
+ if (isRec(config.assets) && input.bundle.assetsDir !== null) {
50028
+ const assetConfig = {};
50029
+ for (const key of ["html_handling", "not_found_handling", "run_worker_first"])
50030
+ if (config.assets[key] !== undefined)
50031
+ assetConfig[key] = config.assets[key];
50032
+ worker.assets = { directory: input.bundle.assetsDir, ...Object.keys(assetConfig).length > 0 ? { config: assetConfig } : {} };
50033
+ }
50034
+ if (dependsOn.length > 0)
50035
+ worker.depends_on = dependsOn;
50036
+ const resource = { cloudflare_workers_script: { worker } };
50037
+ const data = {};
50038
+ const addResource = (type, key, body) => {
50039
+ const group = resource[type] ?? {};
50040
+ group[key] = body;
50041
+ resource[type] = group;
50042
+ };
50043
+ if (config.workers_dev === true)
50044
+ addResource("cloudflare_workers_script_subdomain", "worker", {
50045
+ account_id: "${var.account_id}",
50046
+ script_name: WORKER_REF,
50047
+ enabled: true,
50048
+ ...typeof config.preview_urls === "boolean" ? { previews_enabled: config.preview_urls } : {}
50049
+ });
50050
+ routes.forEach((entry, index) => {
50051
+ const pattern = entry.pattern;
50052
+ const zoneName = str(entry.zone_name);
50053
+ if (entry.custom_domain === true) {
50054
+ addResource("cloudflare_workers_custom_domain", `domain_${index}`, {
50055
+ account_id: "${var.account_id}",
50056
+ hostname: pattern.replace(/\/\*$/, ""),
50057
+ service: WORKER_REF,
50058
+ ...zoneName ? { zone_name: zoneName } : {},
50059
+ ...str(entry.zone_id) ? { zone_id: entry.zone_id } : {}
50060
+ });
50061
+ return;
50062
+ }
50063
+ let zoneId;
50064
+ if (str(entry.zone_id))
50065
+ zoneId = entry.zone_id;
50066
+ else {
50067
+ const key = `zone_${sanitize(zoneName)}`;
50068
+ const zones = data.cloudflare_zone ?? {};
50069
+ zones[key] = { filter: { name: zoneName } };
50070
+ data.cloudflare_zone = zones;
50071
+ zoneId = `\${data.cloudflare_zone.${key}.zone_id}`;
50072
+ }
50073
+ addResource("cloudflare_workers_route", `route_${index}`, { zone_id: zoneId, pattern, script: WORKER_REF });
50074
+ });
50075
+ const crons = isRec(config.triggers) && Array.isArray(config.triggers.crons) ? config.triggers.crons.filter((c) => typeof c === "string") : [];
50076
+ if (crons.length > 0)
50077
+ addResource("cloudflare_workers_cron_trigger", "worker", {
50078
+ account_id: "${var.account_id}",
50079
+ script_name: WORKER_REF,
50080
+ schedules: crons.map((cron) => ({ cron }))
50081
+ });
50082
+ const gaps = [...collected.gaps];
50083
+ if (isRec(config.placement))
50084
+ gaps.push({ kind: "placement", scriptName, placement: config.placement });
50085
+ for (const entry of isRec(config.queues) ? recs(config.queues.consumers) : []) {
50086
+ const queue = str(entry.queue);
50087
+ if (queue === undefined)
50088
+ continue;
50089
+ const { queue: _queue, ...settings } = entry;
50090
+ gaps.push({ kind: "queue-consumer", scriptName, queue, settings });
50091
+ }
50092
+ const tf = {
50093
+ terraform: {
50094
+ required_version: OPENTOFU_REQUIRED_VERSION,
50095
+ required_providers: { cloudflare: { source: "cloudflare/cloudflare", version: CLOUDFLARE_PROVIDER_VERSION } }
50096
+ },
50097
+ provider: { cloudflare: {} },
50098
+ variable: { account_id: { type: "string", sensitive: true } },
50099
+ resource,
50100
+ ...Object.keys(data).length > 0 ? { data } : {}
50101
+ };
50102
+ return { ok: true, tf, workerAddress: WORKER_ADDRESS, scriptName, gaps };
50103
+ }
50104
+ // ../../packages/praxis/deploy-core/src/job-events-file.ts
50105
+ import { appendFileSync, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
50106
+ import { dirname as dirname2 } from "node:path";
50107
+ function openDeployJobEvents(options) {
50108
+ const phaseId = options.phaseId ?? DEFAULT_PHASE_ID;
50109
+ const expireTime = expireTimeOf(options.startedAt, options.expireMinutes);
50110
+ const written = [];
50111
+ const jobs = new Map;
50112
+ let finishedState;
50113
+ mkdirSync3(dirname2(options.file), { recursive: true });
50114
+ writeFileSync3(options.file, "", { mode: 384 });
50115
+ const write = (event) => {
50116
+ written.push(event);
50117
+ appendFileSync(options.file, formatDeployEvent(event), { mode: 384 });
50118
+ };
50119
+ const statesOf = (target) => {
50120
+ let states = jobs.get(target);
50121
+ if (!states) {
50122
+ states = new Map;
50123
+ jobs.set(target, states);
50124
+ }
50125
+ return states;
50126
+ };
50127
+ const phaseStateOf = (target) => decidePhaseState([...statesOf(target).values()]);
50128
+ const jobRunEvent = (target, jobType, jobState, jobRunState, extra) => ({
50129
+ type: "jobrun",
50130
+ targetPath: target,
50131
+ phaseId,
50132
+ jobId: jobType,
50133
+ jobRun: `${phaseId}/${jobType}/1`,
50134
+ jobType,
50135
+ jobState,
50136
+ jobRunState,
50137
+ phaseState: phaseStateOf(target),
50138
+ ...extra.skipMessage !== undefined ? { skipMessage: extra.skipMessage } : {},
50139
+ ...extra.failure !== undefined ? { failure: extra.failure } : {},
50140
+ ...extra.eventLogPath !== undefined ? { eventLogPath: extra.eventLogPath } : {},
50141
+ ...extra.artifactUri !== undefined ? { artifactUri: extra.artifactUri } : {},
50142
+ ...extra.durationMs !== undefined ? { durationMs: extra.durationMs } : {}
50143
+ });
50144
+ write({ type: "started", startedAt: new Date(Date.parse(options.startedAt)).toISOString(), expireTime, phaseId });
50145
+ return {
50146
+ file: options.file,
50147
+ expireTime,
50148
+ startedAt: options.startedAt,
50149
+ phaseId,
50150
+ written,
50151
+ get finishedState() {
50152
+ return finishedState;
50153
+ },
50154
+ jobs,
50155
+ start(target, jobType) {
50156
+ statesOf(target).set(jobType, "in_progress");
50157
+ write(jobRunEvent(target, jobType, "in_progress", "in_progress", {}));
50158
+ },
50159
+ end(target, jobType, outcome) {
50160
+ const { jobState, jobRunState } = jobStatesOf(outcome);
50161
+ statesOf(target).set(jobType, jobState);
50162
+ write(jobRunEvent(target, jobType, jobState, jobRunState, {
50163
+ ...outcome.kind === "failed" ? { failure: { cause: outcome.cause ?? "execution_failed", ...outcome.message ? { message: outcome.message } : {} } } : {},
50164
+ ...outcome.kind === "disabled" || outcome.kind === "skipped" ? { skipMessage: outcome.message } : {},
50165
+ ...outcome.eventLogPath !== undefined ? { eventLogPath: outcome.eventLogPath } : {},
50166
+ ...outcome.artifactUri !== undefined ? { artifactUri: outcome.artifactUri } : {},
50167
+ ...outcome.durationMs !== undefined ? { durationMs: outcome.durationMs } : {}
50168
+ }));
50169
+ },
50170
+ finish(options2 = {}) {
50171
+ if (finishedState !== undefined)
50172
+ return;
50173
+ const rollouts = [...jobs.keys()].map((target) => decideRolloutState(jobs.get(target)));
50174
+ finishedState = decideFinishedState(rollouts);
50175
+ const cause = options2.deployFailureCause ?? firstFailureCause(written) ?? (finishedState === "succeeded" ? undefined : "execution_failed");
50176
+ write({
50177
+ type: "finished",
50178
+ state: finishedState,
50179
+ ...options2.message !== undefined ? { stateDescription: options2.message } : {},
50180
+ ...finishedState === "succeeded" || cause === undefined ? {} : { deployFailureCause: cause }
50181
+ });
50182
+ }
50183
+ };
50184
+ }
50185
+ function firstFailureCause(written) {
50186
+ for (let index = written.length - 1;index >= 0; index--) {
50187
+ const event = written[index];
50188
+ if (event.type === "jobrun" && event.jobState === "failed" && event.failure?.cause) {
50189
+ return event.failure.cause;
50190
+ }
50191
+ }
50192
+ return;
50193
+ }
50194
+ function reportJobRun(events, target, jobType, outcome) {
50195
+ if (outcome.kind === "disabled") {
50196
+ events.end(target, jobType, outcome);
50197
+ return;
50198
+ }
50199
+ events.start(target, jobType);
50200
+ events.end(target, jobType, outcome);
50201
+ }
50202
+ function reportBlockedTarget(events, target, message) {
50203
+ for (const jobType of ["deploy", "verify", "postdeploy"]) {
50204
+ reportJobRun(events, target, jobType, { kind: "skipped", message });
50205
+ }
50206
+ }
50207
+
50208
+ // src/commands/devops-deploy-plan.ts
50209
+ import { resolve as resolve2 } from "node:path";
50210
+
49643
50211
  // src/devops/deploy-plan.ts
49644
50212
  function deployPlanView(input) {
49645
50213
  const targets = input.environment === undefined ? input.plan.targets : targetsFor(input.plan, input.environment);
@@ -49707,10 +50275,10 @@ function renderDeployPlan(view) {
49707
50275
  }
49708
50276
 
49709
50277
  // src/commands/devops-deploy-plan.ts
49710
- async function git(args, ports, what, hint2) {
50278
+ async function git(args, ports, what, hint) {
49711
50279
  const result = await ports.git([...args], ports.cwd);
49712
50280
  if (result.code !== 0)
49713
- throw new UsageError(`${what} failed: ${result.output.trim() || `git ${args.join(" ")} exited ${result.code}`}`, hint2);
50281
+ throw new UsageError(`${what} failed: ${result.output.trim() || `git ${args.join(" ")} exited ${result.code}`}`, hint);
49714
50282
  return result.output;
49715
50283
  }
49716
50284
  async function localFacts(ports) {
@@ -49749,8 +50317,957 @@ async function devopsDeployPlan(args, ports) {
49749
50317
  ports.human(renderDeployPlan(view));
49750
50318
  }
49751
50319
 
50320
+ // src/devops/tofu/adapters.ts
50321
+ import { execFile, spawn as spawn2 } from "node:child_process";
50322
+ import { createHash as createHash2 } from "node:crypto";
50323
+ import { createReadStream } from "node:fs";
50324
+ import { chmod, mkdir as mkdir2, readFile as readFile3, rename, rm, stat, writeFile as writeFile2 } from "node:fs/promises";
50325
+ import { homedir as homedir2 } from "node:os";
50326
+ import { dirname as dirname3 } from "node:path";
50327
+ var nodeExec = {
50328
+ run: (cmd, args, { cwd, env, onLine }) => new Promise((resolveRun, reject) => {
50329
+ const child = spawn2(cmd, [...args], { cwd, env: { ...process.env, ...env ?? {} }, stdio: ["ignore", "pipe", "pipe"] });
50330
+ const pump = (stream) => {
50331
+ let rest = "";
50332
+ stream.setEncoding("utf8");
50333
+ stream.on("data", (chunk) => {
50334
+ rest += chunk;
50335
+ const lines = rest.split(`
50336
+ `);
50337
+ rest = lines.pop() ?? "";
50338
+ for (const line of lines)
50339
+ onLine(line);
50340
+ });
50341
+ stream.on("end", () => {
50342
+ if (rest !== "")
50343
+ onLine(rest);
50344
+ });
50345
+ };
50346
+ pump(child.stdout);
50347
+ pump(child.stderr);
50348
+ child.once("error", reject);
50349
+ child.once("close", (code) => resolveRun(code ?? 1));
50350
+ })
50351
+ };
50352
+ var nodeFs = {
50353
+ read: async (path) => {
50354
+ try {
50355
+ return await readFile3(path, "utf8");
50356
+ } catch (e) {
50357
+ if (e.code === "ENOENT")
50358
+ return null;
50359
+ throw e;
50360
+ }
50361
+ },
50362
+ write: async (path, content) => {
50363
+ await mkdir2(dirname3(path), { recursive: true });
50364
+ await writeFile2(path, content);
50365
+ },
50366
+ mkdirp: async (path) => {
50367
+ await mkdir2(path, { recursive: true });
50368
+ },
50369
+ exists: async (path) => {
50370
+ try {
50371
+ await stat(path);
50372
+ return true;
50373
+ } catch {
50374
+ return false;
50375
+ }
50376
+ },
50377
+ sha256: (path) => new Promise((resolveHash, reject) => {
50378
+ const hash = createHash2("sha256");
50379
+ const stream = createReadStream(path);
50380
+ stream.on("data", (c) => hash.update(c));
50381
+ stream.once("error", (e) => e.code === "ENOENT" ? resolveHash(null) : reject(e));
50382
+ stream.once("end", () => resolveHash(hash.digest("hex")));
50383
+ })
50384
+ };
50385
+ function nodeToolchainPorts(env, fetchImpl = fetch, home = homedir2()) {
50386
+ return {
50387
+ platform: process.platform,
50388
+ arch: process.arch,
50389
+ home,
50390
+ env,
50391
+ download: async (url) => {
50392
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(180000) });
50393
+ if (!res.ok)
50394
+ throw new Error(`download of ${url} failed: ${res.status}`);
50395
+ return new Uint8Array(await res.arrayBuffer());
50396
+ },
50397
+ sha256: (bytes) => createHash2("sha256").update(bytes).digest("hex"),
50398
+ versionOutput: (binary) => new Promise((resolveOut) => {
50399
+ execFile(binary, ["version"], { timeout: 15000 }, (error, stdout) => resolveOut(error ? null : stdout));
50400
+ }),
50401
+ fs: {
50402
+ exists: async (path) => {
50403
+ try {
50404
+ await stat(path);
50405
+ return true;
50406
+ } catch {
50407
+ return false;
50408
+ }
50409
+ },
50410
+ mkdirp: async (path) => {
50411
+ await mkdir2(path, { recursive: true });
50412
+ },
50413
+ writeFile: async (path, bytes, mode) => {
50414
+ await mkdir2(dirname3(path), { recursive: true });
50415
+ await writeFile2(path, bytes, { mode });
50416
+ await chmod(path, mode);
50417
+ },
50418
+ rename: (from, to) => rename(from, to),
50419
+ rm: (path) => rm(path, { recursive: true, force: true })
50420
+ },
50421
+ nonce: () => `${process.pid}-${Date.now().toString(36)}`
50422
+ };
50423
+ }
50424
+
50425
+ // src/devops/tofu/cloudflare.ts
50426
+ var API = "https://api.cloudflare.com/client/v4";
50427
+ function cloudflareApi(fetchFn, env) {
50428
+ const token = env.CLOUDFLARE_API_TOKEN;
50429
+ let account = env.CLOUDFLARE_ACCOUNT_ID;
50430
+ let scripts;
50431
+ const call = async (path, init = {}) => {
50432
+ if (!token)
50433
+ throw new Error("CLOUDFLARE_API_TOKEN is not set");
50434
+ const response = await fetchFn(`${API}${path}`, { ...init, headers: { authorization: `Bearer ${token}`, ...init.headers ?? {} } });
50435
+ const body = await response.json().catch(() => ({}));
50436
+ if (response.status !== 404 && (!response.ok || body.success === false)) {
50437
+ throw new Error(`Cloudflare API ${init.method ?? "GET"} ${path} failed: ${response.status} ${body.errors?.map((e) => e.message).join("; ") ?? ""}`.trim());
50438
+ }
50439
+ return { status: response.status, result: body.result };
50440
+ };
50441
+ const accountId = async () => {
50442
+ if (account)
50443
+ return account;
50444
+ const { result } = await call("/accounts?per_page=2");
50445
+ const accounts = Array.isArray(result) ? result : [];
50446
+ if (accounts.length !== 1 || !accounts[0]?.id)
50447
+ throw new Error(`set CLOUDFLARE_ACCOUNT_ID: the token sees ${accounts.length} accounts`);
50448
+ account = accounts[0].id;
50449
+ return account;
50450
+ };
50451
+ return {
50452
+ accountId,
50453
+ async liveMigrationTag(scriptName) {
50454
+ scripts ??= (async () => {
50455
+ const tags = new Map;
50456
+ for (let page = 1;page <= 20; page++) {
50457
+ const { result } = await call(`/accounts/${await accountId()}/workers/scripts?per_page=100&page=${page}`);
50458
+ const entries = Array.isArray(result) ? result : [];
50459
+ for (const entry of entries)
50460
+ if (entry.id && entry.migration_tag)
50461
+ tags.set(entry.id, entry.migration_tag);
50462
+ if (entries.length < 100)
50463
+ break;
50464
+ }
50465
+ return tags;
50466
+ })();
50467
+ return (await scripts).get(scriptName) ?? null;
50468
+ },
50469
+ async attachQueueConsumer(queueName, scriptName, settings) {
50470
+ const base = `/accounts/${await accountId()}/queues`;
50471
+ const { result: queues } = await call(`${base}?per_page=100&name=${encodeURIComponent(queueName)}`);
50472
+ const queue = (Array.isArray(queues) ? queues : []).find((q) => q.queue_name === queueName);
50473
+ if (!queue?.queue_id)
50474
+ throw new Error(`queue ${queueName} does not exist`);
50475
+ const { result: consumers } = await call(`${base}/${queue.queue_id}/consumers`);
50476
+ const existing = (Array.isArray(consumers) ? consumers : []).find((c) => (c.script ?? c.script_name) === scriptName);
50477
+ const body = JSON.stringify({
50478
+ type: "worker",
50479
+ script_name: scriptName,
50480
+ settings: consumerSettings(settings),
50481
+ ...typeof settings.dead_letter_queue === "string" ? { dead_letter_queue: settings.dead_letter_queue } : {}
50482
+ });
50483
+ const headers = { "content-type": "application/json" };
50484
+ if (existing?.consumer_id)
50485
+ await call(`${base}/${queue.queue_id}/consumers/${existing.consumer_id}`, { method: "PUT", body, headers });
50486
+ else
50487
+ await call(`${base}/${queue.queue_id}/consumers`, { method: "POST", body, headers });
50488
+ },
50489
+ async setPlacement(scriptName, placement) {
50490
+ const form = new FormData;
50491
+ form.set("settings", JSON.stringify({ placement }));
50492
+ await call(`/accounts/${await accountId()}/workers/scripts/${encodeURIComponent(scriptName)}/settings`, { method: "PATCH", body: form });
50493
+ }
50494
+ };
50495
+ }
50496
+ function consumerSettings(settings) {
50497
+ const map = {
50498
+ max_batch_size: "batch_size",
50499
+ max_batch_timeout: "max_wait_time_ms",
50500
+ max_retries: "max_retries",
50501
+ max_concurrency: "max_concurrency",
50502
+ retry_delay: "retry_delay"
50503
+ };
50504
+ const out = {};
50505
+ for (const [key, value] of Object.entries(settings)) {
50506
+ if (!(key in map) || value === undefined)
50507
+ continue;
50508
+ out[map[key]] = key === "max_batch_timeout" && typeof value === "number" ? value * 1000 : value;
50509
+ }
50510
+ return out;
50511
+ }
50512
+
50513
+ // src/devops/tofu/pure.ts
50514
+ function parseTofuDeployArgs(flags) {
50515
+ const environment2 = flags.env?.trim();
50516
+ if (environment2 !== "develop" && environment2 !== "production") {
50517
+ throw new UsageError(`--env must be develop or production, got ${JSON.stringify(flags.env ?? "")}`, "Pass --env develop or --env production.");
50518
+ }
50519
+ const commit = flags.commit?.trim();
50520
+ if (!commit || !/^[0-9a-f]{7,64}$/i.test(commit))
50521
+ throw new UsageError("--commit needs a commit sha", "Pass --commit <sha> of the commit being rolled out.");
50522
+ const targets = flags.targets === undefined ? undefined : flags.targets.split(",").map((t) => t.trim().replace(/\/+$/, "")).filter((t) => t !== "");
50523
+ if (flags.targets !== undefined && (targets ?? []).length === 0)
50524
+ throw new UsageError("--targets is empty", "Pass --targets a,b or leave it out for every target.");
50525
+ const planOnly = flags["plan-only"] === true;
50526
+ const applyPlans = flags["apply-plans"]?.trim();
50527
+ if (planOnly && flags["apply-plans"] !== undefined)
50528
+ throw new UsageError("--plan-only and --apply-plans exclude each other", "Plan first (--plan-only), then apply the approved plans (--apply-plans <dir>).");
50529
+ if (flags["apply-plans"] !== undefined && !applyPlans)
50530
+ throw new UsageError("--apply-plans needs a directory", "Pass --apply-plans <dir> holding the approved <target>.bin files.");
50531
+ const mode = planOnly ? "plan-only" : applyPlans !== undefined ? "apply-plans" : "plan-and-apply";
50532
+ if (environment2 === "production" && mode === "plan-and-apply") {
50533
+ throw new UsageError("production applies only an approved plan", "Run with --plan-only, have the plan approved, then run with --apply-plans <dir>.");
50534
+ }
50535
+ if (mode !== "plan-only" && !flags["events-file"])
50536
+ throw new UsageError("--events-file is required when applying", "DevOps folds the ExecutorLine stream this file carries; pass --events-file <path>.");
50537
+ return {
50538
+ environment: environment2,
50539
+ commit,
50540
+ mode,
50541
+ ...targets === undefined ? {} : { targets },
50542
+ ...applyPlans !== undefined ? { planDir: applyPlans } : flags["plan-dir"] ? { planDir: flags["plan-dir"] } : {},
50543
+ ...flags["events-file"] ? { eventsFile: flags["events-file"] } : {},
50544
+ ...flags.workdir ? { workdir: flags.workdir } : {}
50545
+ };
50546
+ }
50547
+ function selectTargets(plan, environment2, requested) {
50548
+ const named = requested !== undefined;
50549
+ let targets = targetsFor(plan, environment2).filter((t) => t.destination === "cloudflare" && deploysTo(t, environment2, { named }));
50550
+ if (requested !== undefined) {
50551
+ const known = new Set(plan.targets.map((t) => t.path));
50552
+ const missing = requested.filter((r) => !known.has(r));
50553
+ if (missing.length > 0)
50554
+ throw new UsageError(`unknown target(s): ${missing.join(", ")}`, "Run `praxis devops deploy plan` to list the targets.");
50555
+ const refused = requested.filter((r) => !targets.some((t) => t.path === r));
50556
+ if (refused.length > 0)
50557
+ throw new UsageError(`${refused.join(", ")} does not deploy to ${environment2}`, "Check the target's environments and its env.production block.");
50558
+ targets = targets.filter((t) => requested.includes(t.path));
50559
+ }
50560
+ const selected = { commit: plan.commit, targets };
50561
+ return { targets, layers: layersOf(selected).map((layer) => [...layer]) };
50562
+ }
50563
+ function blockedBy(targets, broken) {
50564
+ const blocked = new Set;
50565
+ let grew = true;
50566
+ while (grew) {
50567
+ grew = false;
50568
+ for (const t of targets) {
50569
+ if (blocked.has(t.path) || broken.has(t.path))
50570
+ continue;
50571
+ if (t.dependsOn.some((d) => broken.has(d) || blocked.has(d))) {
50572
+ blocked.add(t.path);
50573
+ grew = true;
50574
+ }
50575
+ }
50576
+ }
50577
+ return blocked;
50578
+ }
50579
+ var LAYER_CONCURRENCY = 4;
50580
+ async function pool(items, limit, work) {
50581
+ let next = 0;
50582
+ const lane = async () => {
50583
+ for (;; ) {
50584
+ const at = next++;
50585
+ if (at >= items.length)
50586
+ return;
50587
+ await work(items[at]);
50588
+ }
50589
+ };
50590
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, lane));
50591
+ }
50592
+ function parseDenylist(text) {
50593
+ return text.split(`
50594
+ `).map((l) => l.trim()).filter((l) => l !== "" && !l.startsWith("#"));
50595
+ }
50596
+ function denylistMatch(name, entries) {
50597
+ return entries.find((e) => e.endsWith("*") ? name.startsWith(e.slice(0, -1)) : name === e);
50598
+ }
50599
+ function effectiveConfig(wrangler, environment2) {
50600
+ if (environment2 !== "production")
50601
+ return wrangler;
50602
+ const env = wrangler.env;
50603
+ const block = env !== null && typeof env === "object" ? env.production : undefined;
50604
+ return block !== null && typeof block === "object" ? block : {};
50605
+ }
50606
+ function scriptNameOf(wrangler, environment2) {
50607
+ const name = effectiveConfig(wrangler, environment2).name;
50608
+ return typeof name === "string" && name !== "" ? name : undefined;
50609
+ }
50610
+ var objects = (value) => Array.isArray(value) ? value.filter((v) => v !== null && typeof v === "object") : [];
50611
+ var str2 = (value) => typeof value === "string" && value !== "" ? [value] : [];
50612
+ function namesOf(wrangler, environment2) {
50613
+ const c = effectiveConfig(wrangler, environment2);
50614
+ const queues = c.queues !== null && typeof c.queues === "object" ? c.queues : {};
50615
+ return [...new Set([
50616
+ ...str2(c.name),
50617
+ ...objects(c.d1_databases).flatMap((d) => str2(d.database_name)),
50618
+ ...objects(c.r2_buckets).flatMap((b) => str2(b.bucket_name)),
50619
+ ...objects(queues.producers).flatMap((q) => str2(q.queue)),
50620
+ ...objects(queues.consumers).flatMap((q) => str2(q.queue)),
50621
+ ...objects(c.services).flatMap((s) => str2(s.service)),
50622
+ ...objects(c.vectorize).flatMap((v) => str2(v.index_name)),
50623
+ ...objects(c.workflows).flatMap((w) => str2(w.name))
50624
+ ])];
50625
+ }
50626
+ function denylistHits(names, entries) {
50627
+ const hits = [];
50628
+ for (const [target, list] of names)
50629
+ for (const name of list) {
50630
+ const entry = denylistMatch(name, entries);
50631
+ if (entry !== undefined)
50632
+ hits.push({ target, name, entry });
50633
+ }
50634
+ return hits;
50635
+ }
50636
+ var targetDir = (workdir, target) => `${workdir}/${target}`;
50637
+ var planFileOf = (planDir, target) => `${planDir}/${target}.bin`;
50638
+ function wranglerBuildArgs(environment2, outdir) {
50639
+ return ["wrangler", "deploy", "--dry-run", "--outdir", outdir, ...environment2 === "production" ? ["--env", "production"] : []];
50640
+ }
50641
+ function wranglerD1Args(databaseName, environment2) {
50642
+ return ["wrangler", "d1", "migrations", "apply", databaseName, "--remote", ...environment2 === "production" ? ["--env", "production"] : []];
50643
+ }
50644
+ function bundleModuleName(wrangler, environment2) {
50645
+ const main = effectiveConfig(wrangler, environment2).main ?? wrangler.main;
50646
+ const base = typeof main === "string" ? main.split("/").pop() : "index.js";
50647
+ return base.replace(/\.(?:[cm]?[jt]sx?)$/, ".js");
50648
+ }
50649
+ function backendDocument(environment2, target, accountId) {
50650
+ return {
50651
+ terraform: {
50652
+ backend: {
50653
+ s3: {
50654
+ bucket: `praxis-tofu-state-${environment2}`,
50655
+ key: stateKeyOf(environment2, target),
50656
+ region: "auto",
50657
+ endpoints: { s3: `https://${accountId}.r2.cloudflarestorage.com` },
50658
+ skip_credentials_validation: true,
50659
+ skip_region_validation: true,
50660
+ skip_requesting_account_id: true,
50661
+ skip_s3_checksum: true,
50662
+ use_path_style: true,
50663
+ use_lockfile: true
50664
+ }
50665
+ }
50666
+ }
50667
+ };
50668
+ }
50669
+ function d1Moment(environment2, mode) {
50670
+ if (mode === "apply-plans")
50671
+ return "before-apply";
50672
+ if (environment2 === "develop")
50673
+ return "before-plan";
50674
+ return "listed-only";
50675
+ }
50676
+ function scheduleGaps(gaps) {
50677
+ const d1 = [];
50678
+ const placement = [];
50679
+ const queueConsumers = [];
50680
+ const warnings = [];
50681
+ for (const gap of gaps) {
50682
+ switch (gap.kind) {
50683
+ case "d1-migrations":
50684
+ d1.push(gap);
50685
+ break;
50686
+ case "placement":
50687
+ placement.push(gap);
50688
+ break;
50689
+ case "queue-consumer":
50690
+ queueConsumers.push(gap);
50691
+ break;
50692
+ case "vectorize-index":
50693
+ warnings.push(`gap not filled: vectorize index ${gap.indexName} (${gap.binding}) must exist; create it by API`);
50694
+ break;
50695
+ case "container":
50696
+ warnings.push(`gap not filled: container ${gap.className} (${gap.image})`);
50697
+ break;
50698
+ case "analytics-engine-dataset":
50699
+ warnings.push(`gap not filled: analytics engine dataset ${gap.dataset} (${gap.binding})`);
50700
+ break;
50701
+ }
50702
+ }
50703
+ return { d1, placement, queueConsumers, warnings };
50704
+ }
50705
+ function exportsOf(scriptName, configs, environment2) {
50706
+ const names = new Set;
50707
+ for (const wrangler of configs.values()) {
50708
+ const services = effectiveConfig(wrangler, environment2).services;
50709
+ for (const entry of Array.isArray(services) ? services : []) {
50710
+ if (entry && entry.service === scriptName && typeof entry.entrypoint === "string" && entry.entrypoint !== "")
50711
+ names.add(entry.entrypoint);
50712
+ }
50713
+ }
50714
+ return [...names].sort();
50715
+ }
50716
+
50717
+ // src/devops/tofu/run.ts
50718
+ import { dirname as dirname4, isAbsolute, relative, resolve as resolve3 } from "node:path";
50719
+ var ENGINE = "tofu";
50720
+ var DENYLIST = "spec/legacy-production.denylist";
50721
+ async function runTofuDeploy(args, plan, ports) {
50722
+ const { fs, exec, cloudflare, out } = ports;
50723
+ const startedAt = ports.clock.iso();
50724
+ const root = resolve3(ports.repoRoot);
50725
+ const absolute = (p) => isAbsolute(p) ? p : resolve3(p);
50726
+ const workdir = absolute(args.workdir ?? `${root}/.tofu-work`);
50727
+ const planDir = absolute(args.planDir ?? `${workdir}/plans`);
50728
+ const applying = args.mode !== "plan-only";
50729
+ const events = applying && args.eventsFile !== undefined ? ports.openEvents(args.eventsFile, startedAt) : undefined;
50730
+ const reports = new Map;
50731
+ const selection = selectTargets(plan, args.environment, args.targets);
50732
+ const byPath = new Map(selection.targets.map((t) => [t.path, t]));
50733
+ const finish = (finished2, message2) => {
50734
+ if (events)
50735
+ events.finish(message2 === undefined ? {} : { message: message2 });
50736
+ const summary = {
50737
+ commit: args.commit,
50738
+ environment: args.environment,
50739
+ mode: args.mode,
50740
+ layers: selection.layers,
50741
+ targets: selection.targets.map((t) => reports.get(t.path) ?? { target: t.path, status: "blocked", message: message2 ?? "not started", d1Pending: [], warnings: [] }),
50742
+ finished: events?.finishedState ?? finished2
50743
+ };
50744
+ return { exitCode: finished2 === "succeeded" || finished2 === "planned" ? 0 : 1, summary };
50745
+ };
50746
+ const refuseAll = async (message2) => {
50747
+ out(`REFUSED: ${message2}`);
50748
+ for (const t of selection.targets) {
50749
+ reports.set(t.path, { target: t.path, status: "blocked", message: message2, d1Pending: [], warnings: [] });
50750
+ if (events)
50751
+ reportBlockedTarget(events, t.path, message2);
50752
+ }
50753
+ const result2 = finish("failed", message2);
50754
+ await writeSummary(result2.summary);
50755
+ return result2;
50756
+ };
50757
+ const writeSummary = async (summary) => {
50758
+ await fs.write(`${planDir}/summary.json`, `${JSON.stringify(summary, null, 2)}
50759
+ `);
50760
+ out(`SUMMARY ${JSON.stringify(summary)}`);
50761
+ };
50762
+ const configs = new Map;
50763
+ for (const t of selection.targets) {
50764
+ const text = await fs.read(`${root}/${t.path}/wrangler.jsonc`);
50765
+ const parsed = text === null ? null : parseJsonc2(text);
50766
+ if (parsed === null)
50767
+ return await refuseAll(`${t.path}: wrangler.jsonc is missing or not valid JSONC`);
50768
+ configs.set(t.path, parsed);
50769
+ }
50770
+ const callerConfigs = new Map(configs);
50771
+ for (const t of plan.targets) {
50772
+ if (callerConfigs.has(t.path))
50773
+ continue;
50774
+ const text = await fs.read(`${root}/${t.path}/wrangler.jsonc`);
50775
+ const parsed = text === null ? null : parseJsonc2(text);
50776
+ if (parsed !== null)
50777
+ callerConfigs.set(t.path, parsed);
50778
+ }
50779
+ const denylistText = await fs.read(`${root}/${DENYLIST}`);
50780
+ if (denylistText === null)
50781
+ return await refuseAll(`${DENYLIST} is missing; the legacy preflight cannot run`);
50782
+ const hits = denylistHits(new Map(selection.targets.map((t) => [t.path, namesOf(configs.get(t.path), args.environment)])), parseDenylist(denylistText));
50783
+ if (hits.length > 0) {
50784
+ return await refuseAll(`legacy production names refused: ${hits.map((h) => `${h.target} uses ${h.name} (denylist ${h.entry})`).join("; ")}`);
50785
+ }
50786
+ const accountId = await cloudflare.accountId();
50787
+ const results = new Map;
50788
+ const broken = new Set;
50789
+ const reported = new Set;
50790
+ let aborted;
50791
+ const block = (t, message2) => {
50792
+ if (reported.has(t.path))
50793
+ return;
50794
+ reported.add(t.path);
50795
+ broken.add(t.path);
50796
+ reports.set(t.path, { target: t.path, status: "blocked", message: message2, d1Pending: [], warnings: [] });
50797
+ if (events)
50798
+ reportBlockedTarget(events, t.path, message2);
50799
+ out(`[${t.path}] blocked: ${message2}`);
50800
+ };
50801
+ const processTarget = async (t) => {
50802
+ const target = t.path;
50803
+ const tdir = targetDir(workdir, target);
50804
+ const say = (line) => out(`[${target}] ${line}`);
50805
+ const step = async (cmd, cmdArgs, cwd, env) => {
50806
+ const engine = cmd === ENGINE;
50807
+ let bin = cmd;
50808
+ let stepEnv = env;
50809
+ if (engine) {
50810
+ const resolved = await ports.toolchain.ensure().catch((error) => {
50811
+ throw new StepFailed(`rollout engine unavailable: ${error instanceof Error ? error.message : String(error)}`);
50812
+ });
50813
+ bin = resolved.binary;
50814
+ stepEnv = { ...resolved.env, ...env ?? {} };
50815
+ }
50816
+ say(engine ? `> ${cmdArgs[0]}` : `$ ${cmd} ${cmdArgs.join(" ")}`);
50817
+ const code = await exec.run(bin, cmdArgs, { cwd, ...stepEnv ? { env: stepEnv } : {}, onLine: say });
50818
+ if (code !== 0)
50819
+ throw new StepFailed(engine ? `rollout step ${cmdArgs[0]} exited ${code}` : `${cmd} ${cmdArgs.slice(0, 2).join(" ")} exited ${code}`);
50820
+ };
50821
+ const began = ports.clock.now();
50822
+ if (events)
50823
+ events.start(target, "deploy");
50824
+ reported.add(target);
50825
+ const d1Pending = [];
50826
+ let warnings = [];
50827
+ let planFile;
50828
+ try {
50829
+ const wrangler = configs.get(target);
50830
+ const scriptName = scriptNameOf(wrangler, args.environment);
50831
+ if (scriptName === undefined)
50832
+ throw new StepFailed("the wrangler config names no Worker for this environment");
50833
+ const wantsPlan = args.mode !== "apply-plans";
50834
+ planFile = planFileOf(planDir, target);
50835
+ if (args.mode === "apply-plans" && !await fs.exists(planFile))
50836
+ throw new StepFailed(`plan file ${planFile} is missing; refusing to apply without it`);
50837
+ const outdir = `${tdir}/dist`;
50838
+ await fs.mkdirp(tdir);
50839
+ await step("npx", wranglerBuildArgs(args.environment, outdir), `${root}/${target}`);
50840
+ const mainModule = bundleModuleName(wrangler, args.environment);
50841
+ const mainFile = `dist/${mainModule}`;
50842
+ const sha256 = await fs.sha256(`${tdir}/${mainFile}`);
50843
+ if (sha256 === null)
50844
+ throw new StepFailed(`the wrangler bundle has no ${mainFile}`);
50845
+ const assets = effectiveConfig(wrangler, args.environment).assets;
50846
+ const assetsDirectory = assets !== null && typeof assets === "object" ? assets.directory : undefined;
50847
+ const liveMigrationTag = await cloudflare.liveMigrationTag(scriptName);
50848
+ const callees = {};
50849
+ const generated = ports.generate({
50850
+ target,
50851
+ environment: args.environment,
50852
+ wrangler,
50853
+ bundle: {
50854
+ mainFile,
50855
+ mainModule,
50856
+ sha256,
50857
+ extraModules: [],
50858
+ assetsDir: typeof assetsDirectory === "string" ? relative(tdir, resolve3(root, target, assetsDirectory)) : null
50859
+ },
50860
+ liveMigrationTag,
50861
+ callees,
50862
+ exports: exportsOf(scriptName, callerConfigs, args.environment)
50863
+ });
50864
+ if (!generated.ok) {
50865
+ aborted = `${target}: generator refused: ${generated.refusals.map((r) => JSON.stringify(r)).join(", ")}`;
50866
+ throw new StepFailed(aborted);
50867
+ }
50868
+ results.set(target, generated);
50869
+ await fs.write(`${tdir}/main.tf.json`, `${JSON.stringify(generated.tf, null, 2)}
50870
+ `);
50871
+ await fs.write(`${tdir}/backend.tf.json`, `${JSON.stringify(backendDocument(args.environment, target, accountId), null, 2)}
50872
+ `);
50873
+ const schedule = scheduleGaps(generated.gaps);
50874
+ warnings = schedule.warnings;
50875
+ for (const w of warnings)
50876
+ say(`WARNING ${w}`);
50877
+ const moment = d1Moment(args.environment, args.mode);
50878
+ const runD1 = async () => {
50879
+ for (const gap of schedule.d1)
50880
+ await step("npx", wranglerD1Args(gap.databaseName, args.environment), `${root}/${target}`);
50881
+ };
50882
+ for (const gap of schedule.d1) {
50883
+ d1Pending.push(gap.databaseName);
50884
+ say(`d1 migrations (${gap.binding}): ${gap.databaseName} from ${gap.migrationsDir}`);
50885
+ }
50886
+ if (moment === "before-plan")
50887
+ await runD1();
50888
+ else if (moment === "listed-only")
50889
+ say("d1 migrations are listed only; production migrates when an approved plan is applied");
50890
+ const env = { TF_VAR_account_id: accountId };
50891
+ await step("tofu", ["init", "-input=false"], tdir, env);
50892
+ if (wantsPlan) {
50893
+ await fs.mkdirp(dirname4(planFile));
50894
+ await step("tofu", ["plan", "-input=false", "-no-color", `-out=${planFile}`], tdir, env);
50895
+ }
50896
+ if (applying) {
50897
+ if (moment === "before-apply")
50898
+ await runD1();
50899
+ await step("tofu", ["apply", "-input=false", "-no-color", planFile], tdir, env);
50900
+ for (const gap of schedule.placement) {
50901
+ say(`placement ${JSON.stringify(gap.placement)} -> ${gap.scriptName}`);
50902
+ await cloudflare.setPlacement(gap.scriptName, gap.placement);
50903
+ }
50904
+ for (const gap of schedule.queueConsumers) {
50905
+ say(`queue consumer ${gap.queue} -> ${gap.scriptName}`);
50906
+ await cloudflare.attachQueueConsumer(gap.queue, gap.scriptName, gap.settings);
50907
+ }
50908
+ }
50909
+ reports.set(target, { target, status: applying ? "succeeded" : "planned", planFile, d1Pending, warnings });
50910
+ if (events)
50911
+ events.end(target, "deploy", { kind: "succeeded", durationMs: ports.clock.now() - began });
50912
+ } catch (error) {
50913
+ const message2 = error instanceof Error ? error.message : String(error);
50914
+ say(`FAILED ${message2}`);
50915
+ broken.add(target);
50916
+ reports.set(target, { target, status: "failed", message: message2, ...planFile ? { planFile } : {}, d1Pending, warnings });
50917
+ if (events)
50918
+ events.end(target, "deploy", { kind: "failed", message: message2, cause: "execution_failed", durationMs: ports.clock.now() - began });
50919
+ }
50920
+ };
50921
+ for (const layer of selection.layers) {
50922
+ const blocked = blockedBy(selection.targets, broken);
50923
+ const runnable = [];
50924
+ for (const path of layer) {
50925
+ const t = byPath.get(path);
50926
+ if (aborted !== undefined)
50927
+ block(t, `run aborted: ${aborted}`);
50928
+ else if (blocked.has(path))
50929
+ block(t, "a target it depends on did not finish");
50930
+ else
50931
+ runnable.push(t);
50932
+ }
50933
+ await pool(runnable, LAYER_CONCURRENCY, async (t) => {
50934
+ if (aborted !== undefined) {
50935
+ block(t, `run aborted: ${aborted}`);
50936
+ return;
50937
+ }
50938
+ await processTarget(t);
50939
+ });
50940
+ }
50941
+ const failed = [...reports.values()].filter((r) => r.status === "failed");
50942
+ const blockedCount = [...reports.values()].filter((r) => r.status === "blocked").length;
50943
+ const finished = failed.length === 0 && blockedCount === 0 ? applying ? "succeeded" : "planned" : "failed";
50944
+ const message = finished === "failed" ? `${failed.length} failed, ${blockedCount} blocked` : undefined;
50945
+ const result = finish(finished, message);
50946
+ await writeSummary(result.summary);
50947
+ return result;
50948
+ }
50949
+
50950
+ class StepFailed extends Error {
50951
+ }
50952
+
50953
+ // src/devops/tofu/toolchain.ts
50954
+ import { inflateRawSync } from "node:zlib";
50955
+ var OS = { linux: "linux", darwin: "darwin" };
50956
+ var ARCH = { x64: "amd64", arm64: "arm64" };
50957
+ var pluginCacheDirOf = (home) => `${home}/.praxis/tools/opentofu/plugins`;
50958
+ function toolchainPlan(r) {
50959
+ const os = OS[r.platform];
50960
+ const arch = ARCH[r.arch];
50961
+ if (os === undefined || arch === undefined) {
50962
+ return { ok: false, reason: `the rollout engine is not available for ${r.platform}/${r.arch}; supported: linux and macOS on x64 or arm64` };
50963
+ }
50964
+ const root = `${r.home}/.praxis/tools/opentofu`;
50965
+ const base = `https://github.com/opentofu/opentofu/releases/download/v${r.version}`;
50966
+ const assetName = `tofu_${r.version}_${os}_${arch}.zip`;
50967
+ return {
50968
+ ok: true,
50969
+ plan: {
50970
+ cacheDir: `${root}/${r.version}`,
50971
+ binary: `${root}/${r.version}/tofu`,
50972
+ pluginCacheDir: pluginCacheDirOf(r.home),
50973
+ assetName,
50974
+ assetUrl: `${base}/${assetName}`,
50975
+ sumsUrl: `${base}/tofu_${r.version}_SHA256SUMS`
50976
+ }
50977
+ };
50978
+ }
50979
+ function toolchainEnv(pluginCacheDir) {
50980
+ return { TF_PLUGIN_CACHE_DIR: pluginCacheDir, TF_IN_AUTOMATION: "1", CHECKPOINT_DISABLE: "1" };
50981
+ }
50982
+ function parseVersion(output) {
50983
+ return /OpenTofu v(\d+\.\d+\.\d+\S*)/.exec(output)?.[1] ?? null;
50984
+ }
50985
+ function checksumOf(sums, assetName) {
50986
+ for (const line of sums.split(`
50987
+ `)) {
50988
+ const m = /^([0-9a-fA-F]{64})\s+\*?(\S+)\s*$/.exec(line.trim());
50989
+ if (m && m[2] === assetName)
50990
+ return m[1].toLowerCase();
50991
+ }
50992
+ return null;
50993
+ }
50994
+ function extractZip(zip) {
50995
+ const buf = Buffer.from(zip.buffer, zip.byteOffset, zip.byteLength);
50996
+ let eocd = -1;
50997
+ for (let i = buf.length - 22;i >= Math.max(0, buf.length - 65557); i--)
50998
+ if (buf.readUInt32LE(i) === 101010256) {
50999
+ eocd = i;
51000
+ break;
51001
+ }
51002
+ if (eocd < 0)
51003
+ throw new Error("not a zip archive");
51004
+ const count2 = buf.readUInt16LE(eocd + 10);
51005
+ let p = buf.readUInt32LE(eocd + 16);
51006
+ const files = [];
51007
+ for (let n = 0;n < count2; n++) {
51008
+ if (buf.readUInt32LE(p) !== 33639248)
51009
+ throw new Error("corrupt zip directory");
51010
+ const method = buf.readUInt16LE(p + 10), csize = buf.readUInt32LE(p + 20), nlen = buf.readUInt16LE(p + 28);
51011
+ const xlen = buf.readUInt16LE(p + 30), clen = buf.readUInt16LE(p + 32), local = buf.readUInt32LE(p + 42);
51012
+ const name = buf.toString("utf8", p + 46, p + 46 + nlen);
51013
+ p += 46 + nlen + xlen + clen;
51014
+ if (name.endsWith("/"))
51015
+ continue;
51016
+ const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
51017
+ const raw = buf.subarray(start, start + csize);
51018
+ if (method === 0)
51019
+ files.push({ name, data: new Uint8Array(raw) });
51020
+ else if (method === 8)
51021
+ files.push({ name, data: new Uint8Array(inflateRawSync(raw)) });
51022
+ else
51023
+ throw new Error(`unsupported zip compression ${method}`);
51024
+ }
51025
+ return files;
51026
+ }
51027
+
51028
+ class ToolchainError extends Error {
51029
+ }
51030
+ async function ensureTofu(ports, version = OPENTOFU_VERSION) {
51031
+ const env = toolchainEnv(pluginCacheDirOf(ports.home));
51032
+ const override = ports.env.PRAXIS_TOFU_BIN;
51033
+ if (override)
51034
+ return { binary: override, env };
51035
+ const planned = toolchainPlan({ version, platform: ports.platform, arch: ports.arch, home: ports.home });
51036
+ if (!planned.ok)
51037
+ throw new ToolchainError(planned.reason);
51038
+ const plan = planned.plan;
51039
+ if (await ports.fs.exists(plan.binary)) {
51040
+ const found = parseVersion(await ports.versionOutput(plan.binary) ?? "");
51041
+ if (found === version)
51042
+ return { binary: plan.binary, env };
51043
+ }
51044
+ const [zip, sumsBytes] = await Promise.all([ports.download(plan.assetUrl), ports.download(plan.sumsUrl)]);
51045
+ const expected = checksumOf(new TextDecoder().decode(sumsBytes), plan.assetName);
51046
+ if (expected === null)
51047
+ throw new ToolchainError(`the release checksums list no ${plan.assetName}; refusing to install the rollout engine`);
51048
+ if (ports.sha256(zip) !== expected)
51049
+ throw new ToolchainError(`the downloaded ${plan.assetName} does not match its published checksum; refusing to install the rollout engine`);
51050
+ const binary = extractZip(zip).find((f) => f.name === "tofu");
51051
+ if (!binary)
51052
+ throw new ToolchainError(`${plan.assetName} contains no engine binary`);
51053
+ const tmp = `${plan.cacheDir}.tmp-${ports.nonce()}`;
51054
+ try {
51055
+ await ports.fs.writeFile(`${tmp}/tofu`, binary.data, 493);
51056
+ await ports.fs.rm(plan.cacheDir);
51057
+ await ports.fs.rename(tmp, plan.cacheDir);
51058
+ } catch (error) {
51059
+ await ports.fs.rm(tmp).catch(() => {});
51060
+ throw error;
51061
+ }
51062
+ await ports.fs.mkdirp(plan.pluginCacheDir);
51063
+ return { binary: plan.binary, env };
51064
+ }
51065
+ function createToolchain(ports, version = OPENTOFU_VERSION) {
51066
+ let pending;
51067
+ return { ensure: () => pending ??= ensureTofu(ports, version) };
51068
+ }
51069
+
51070
+ // src/devops/pure.ts
51071
+ import { createHash as createHash3 } from "node:crypto";
51072
+ var PROJECT_ID = /^dvp_[a-z0-9]+$/;
51073
+ var POLL_MS = 5000;
51074
+ var FAILURE_LIMIT = 20;
51075
+ var hint = 'Pass --project dvp_…, or add "devops": { "project": "dvp_…" } to praxis.jsonc in the current directory.';
51076
+ function checkProject(value, hintText = hint) {
51077
+ if (typeof value !== "string" || !value.trim())
51078
+ throw new UsageError("A DevOps project id must be a non-empty string", hintText);
51079
+ if (!PROJECT_ID.test(value.trim()))
51080
+ throw new UsageError(`Not a DevOps project id: ${value}`, "A project id starts with dvp_ and comes from the project list. " + hintText);
51081
+ return value.trim();
51082
+ }
51083
+ function parseDevopsProject(value) {
51084
+ if (value === null || value === undefined || typeof value !== "object" || Array.isArray(value))
51085
+ return;
51086
+ const devops = value.devops;
51087
+ if (devops === undefined)
51088
+ return;
51089
+ if (devops === null || typeof devops !== "object" || Array.isArray(devops))
51090
+ throw new UsageError("praxis.jsonc devops must be an object", 'Write {"devops":{"project":"dvp_…"}}. ' + hint);
51091
+ const project = devops.project;
51092
+ if (project === undefined)
51093
+ return;
51094
+ return checkProject(project);
51095
+ }
51096
+ function resolveProject(flag, projectFile) {
51097
+ if (flag !== undefined)
51098
+ return checkProject(flag);
51099
+ const fromFile = parseDevopsProject(projectFile);
51100
+ if (fromFile !== undefined)
51101
+ return fromFile;
51102
+ throw new UsageError("No DevOps project named for this run", hint);
51103
+ }
51104
+ var sorted = (values) => [...values].sort();
51105
+ var SELECT_KINDS = { tag: "anyTags", package: "packages", suite: "packages", file: "packages" };
51106
+ function parseSelect(values) {
51107
+ if (!values.length)
51108
+ return;
51109
+ const tags = [], packages = [];
51110
+ for (const raw of values) {
51111
+ const at = raw.indexOf(":");
51112
+ const kind = at < 0 ? "tag" : raw.slice(0, at).trim().toLowerCase();
51113
+ const value = (at < 0 ? raw : raw.slice(at + 1)).trim();
51114
+ const kinds = Object.keys(SELECT_KINDS).join(", ");
51115
+ if (!value)
51116
+ throw new UsageError(`--select ${raw} names no value`, `Use --select <kind>:<value>, or a bare tag name; kinds are ${kinds}.`);
51117
+ if (!Object.hasOwn(SELECT_KINDS, kind))
51118
+ throw new UsageError(`--select ${raw}: unknown kind "${kind}"`, `Use one of: ${kinds}.`);
51119
+ (SELECT_KINDS[kind] === "anyTags" ? tags : packages).push(value);
51120
+ }
51121
+ return { ...tags.length ? { anyTags: sorted(tags) } : {}, ...packages.length ? { packages: sorted(packages) } : {} };
51122
+ }
51123
+ function parseRepeat(value) {
51124
+ if (value === undefined)
51125
+ return 1;
51126
+ const n = typeof value === "string" && value.trim() ? Number(value) : NaN;
51127
+ if (!Number.isSafeInteger(n) || n < 1)
51128
+ throw new UsageError("--repeat must be an integer of at least 1");
51129
+ return n;
51130
+ }
51131
+ function requireRemote(remote) {
51132
+ if (!remote)
51133
+ throw new UsageError("Only remote test runs are available", "Add --remote to run the selected cases on the Praxis cloud executor.");
51134
+ }
51135
+ function requestIdFor(input) {
51136
+ const selector = input.selector === undefined ? null : {
51137
+ sizes: sorted(input.selector.sizes ?? []),
51138
+ anyTags: sorted(input.selector.anyTags ?? []),
51139
+ packages: sorted(input.selector.packages ?? []),
51140
+ cases: sorted(input.selector.cases ?? [])
51141
+ };
51142
+ const material = JSON.stringify(["devops-test-run", input.project, input.commit, input.repeat, selector]);
51143
+ return `req_${createHash3("sha256").update(material).digest("hex").slice(0, 32)}`;
51144
+ }
51145
+ var isTerminal = (state) => state === "finished";
51146
+ function shortSha(commit) {
51147
+ return commit.slice(0, 7);
51148
+ }
51149
+ function headBranch(output) {
51150
+ const name = output.trim();
51151
+ return !name || name === "HEAD" ? undefined : name;
51152
+ }
51153
+ function requirePushed(remoteContains, commit, branch) {
51154
+ if (remoteContains.trim())
51155
+ return;
51156
+ 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.`);
51157
+ }
51158
+ function dirtyNotice(status, commit) {
51159
+ const files = status.split(`
51160
+ `).filter((line) => line.trim()).length;
51161
+ if (files === 0)
51162
+ return;
51163
+ return `Warning: ${files} uncommitted change${files === 1 ? "" : "s"}; the run tests the pushed commit ${shortSha(commit)}, not this working tree.`;
51164
+ }
51165
+ function exitCodeFor(result) {
51166
+ return result === "passed" || result === "pending" ? 0 : 1;
51167
+ }
51168
+ var wantsFailures = (result) => result !== "passed" && result !== "pending";
51169
+ function failedList(items, nextPageToken2, url) {
51170
+ const shown = items.slice(0, FAILURE_LIMIT);
51171
+ if (items.length <= FAILURE_LIMIT && !nextPageToken2)
51172
+ return { shown };
51173
+ return { shown, hint: `Showing ${FAILURE_LIMIT} of the failed cases; the run page lists them all: ${url}` };
51174
+ }
51175
+ var CONSOLE = { develop: "https://console-develop.deepraxis.com", production: "https://console.deepraxis.com" };
51176
+ function runUrl(env, project, id, viewerUrl) {
51177
+ return viewerUrl?.trim() || `${CONSOLE[env]}/devops/projects/${project}/test-runs/${id}`;
51178
+ }
51179
+
51180
+ // src/commands/devops.ts
51181
+ async function projectFile(cwd, ports) {
51182
+ let text;
51183
+ try {
51184
+ text = await ports.readFile(join4(cwd, "praxis.jsonc"));
51185
+ } catch (error) {
51186
+ if (error.code === "ENOENT")
51187
+ return;
51188
+ throw error;
51189
+ }
51190
+ try {
51191
+ return parseJsonc(text);
51192
+ } catch (error) {
51193
+ throw new UsageError(`praxis.jsonc is not valid JSONC: ${error.message}`);
51194
+ }
51195
+ }
51196
+ var COUNT_ORDER = ["passed", "failed", "flaky", "skipped", "pending", "other"];
51197
+ var countLine = (counts) => COUNT_ORDER.filter((key) => counts?.[key]).map((key) => `${counts[key]} ${key}`).join(", ") || "no counts reported";
51198
+ async function devopsTestRun(args, connect, env, ports) {
51199
+ requireRemote(args.remote);
51200
+ const project = resolveProject(args.project, await projectFile(ports.cwd, ports));
51201
+ const selector = parseSelect(args.select ?? []);
51202
+ const repeat = parseRepeat(args.repeat);
51203
+ const git2 = async (gitArgs) => (await ports.git(gitArgs, ports.cwd)).output;
51204
+ const commit = (await git2(["rev-parse", "HEAD"])).trim();
51205
+ if (!commit)
51206
+ throw new UsageError("git rev-parse HEAD answered no commit", "Run this command inside a git repository.");
51207
+ const branch = headBranch(await git2(["rev-parse", "--abbrev-ref", "HEAD"]));
51208
+ requirePushed(await git2(["branch", "-r", "--contains", "HEAD"]), commit, branch);
51209
+ const notice = dirtyNotice(await git2(["status", "--porcelain"]), commit);
51210
+ if (notice)
51211
+ ports.emit({ kind: "message", channel: "stderr", text: notice });
51212
+ const client2 = await connect();
51213
+ const requestId = requestIdFor({ project, commit, selector, repeat });
51214
+ let run = await client2.devops.projects.testRuns.create({ path: { project }, body: { ref: { ...branch ? { branch } : {}, commit }, ...selector ? { selector } : {}, repeat, executor: "cloud", requestId } });
51215
+ while (args.wait && !isTerminal(run.state)) {
51216
+ await ports.wait(POLL_MS);
51217
+ run = await client2.devops.testRuns.retrieve({ path: { id: run.id } });
51218
+ }
51219
+ const url = runUrl(env, project, run.id, run.viewerUrl);
51220
+ let failures = [], failureHint;
51221
+ if (wantsFailures(run.result)) {
51222
+ const page = await client2.devops.testRuns.executions.list({ path: { run: run.id }, query: { pageSize: FAILURE_LIMIT, filter: "result=failed" } });
51223
+ ({ shown: failures, hint: failureHint } = failedList(page.items, page.nextPageToken, url));
51224
+ }
51225
+ const data = {
51226
+ id: run.id,
51227
+ url,
51228
+ project,
51229
+ state: run.state,
51230
+ result: run.result,
51231
+ repeat,
51232
+ commit,
51233
+ ...branch ? { branch } : {},
51234
+ selected: run.selection?.selectedCount ?? null,
51235
+ counts: run.counts ?? null,
51236
+ request_id: requestId,
51237
+ failures: failures.map((execution) => ({ case: execution.case, title: execution.title, package: execution.package ?? null, status: execution.status })),
51238
+ ...failureHint ? { failures_hint: failureHint } : {}
51239
+ };
51240
+ ports.emit({ kind: "object", data });
51241
+ ports.human([
51242
+ `${run.result} — ${project} @ ${commit.slice(0, 7)}${branch ? ` (${branch})` : ""}`,
51243
+ `state ${run.state}, ${countLine(run.counts)}`,
51244
+ url,
51245
+ ...failures.map((execution) => ` failed ${execution.title}`),
51246
+ ...failureHint ? [failureHint] : []
51247
+ ].join(`
51248
+ `));
51249
+ return exitCodeFor(run.result);
51250
+ }
51251
+ async function devopsDeployTofu(flags, ports) {
51252
+ const args = parseTofuDeployArgs(flags);
51253
+ const plan = await planRepository(await localFacts(ports));
51254
+ const result = await runTofuDeploy(args, plan, {
51255
+ repoRoot: ports.cwd,
51256
+ exec: nodeExec,
51257
+ toolchain: createToolchain(nodeToolchainPorts(ports.env, ports.fetch)),
51258
+ fs: nodeFs,
51259
+ cloudflare: cloudflareApi(ports.fetch, ports.env),
51260
+ generate: generateTargetTf,
51261
+ clock: { now: () => Date.now(), iso: () => new Date().toISOString() },
51262
+ openEvents: (file, startedAt) => openDeployJobEvents({ file, startedAt }),
51263
+ out: ports.stdout
51264
+ });
51265
+ ports.emit({ kind: "object", data: result.summary });
51266
+ return result.exitCode;
51267
+ }
51268
+
49752
51269
  // src/commands/canvas-import.ts
49753
- import { basename as basename2, dirname as dirname2, join as join5, resolve as resolve3 } from "node:path";
51270
+ import { basename as basename2, dirname as dirname5, join as join5, resolve as resolve4 } from "node:path";
49754
51271
 
49755
51272
  // ../../packages/canvas/document/src/types.ts
49756
51273
  class OpRejectedError extends Error {
@@ -50482,7 +51999,7 @@ function pathLineBounds(geometry) {
50482
51999
  }
50483
52000
  if (command === null)
50484
52001
  return null;
50485
- const relative = command === command.toLowerCase();
52002
+ const relative2 = command === command.toLowerCase();
50486
52003
  const upper = command.toUpperCase();
50487
52004
  if (upper === "H" || upper === "V") {
50488
52005
  const value = tokens[i];
@@ -50490,9 +52007,9 @@ function pathLineBounds(geometry) {
50490
52007
  return null;
50491
52008
  i++;
50492
52009
  if (upper === "H")
50493
- x = relative ? x + value : value;
52010
+ x = relative2 ? x + value : value;
50494
52011
  else
50495
- y = relative ? y + value : value;
52012
+ y = relative2 ? y + value : value;
50496
52013
  add(x, y);
50497
52014
  continue;
50498
52015
  }
@@ -50500,8 +52017,8 @@ function pathLineBounds(geometry) {
50500
52017
  if (typeof nx !== "number" || typeof ny !== "number")
50501
52018
  return null;
50502
52019
  i += 2;
50503
- x = relative ? x + nx : nx;
50504
- y = relative ? y + ny : ny;
52020
+ x = relative2 ? x + nx : nx;
52021
+ y = relative2 ? y + ny : ny;
50505
52022
  if (upper === "M") {
50506
52023
  startX = x;
50507
52024
  startY = y;
@@ -52195,12 +53712,12 @@ var CONTENT_TYPES = {
52195
53712
  svg: "image/svg+xml",
52196
53713
  avif: "image/avif"
52197
53714
  };
52198
- var contentTypeOf = (url) => CONTENT_TYPES[url.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
53715
+ var contentTypeOf2 = (url) => CONTENT_TYPES[url.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
52199
53716
  var viewerUrlFor = (canvasId, env) => `https://console${env === "develop" ? "-develop" : ""}.deepraxis.com/canvases/${canvasId}`;
52200
53717
  function imageCandidates(url, penFile, roots) {
52201
53718
  const name = basename2(url);
52202
53719
  return [...new Set([
52203
- join5(dirname2(penFile), url),
53720
+ join5(dirname5(penFile), url),
52204
53721
  ...roots.map((root) => join5(root, url)),
52205
53722
  ...roots.map((root) => join5(root, name))
52206
53723
  ])];
@@ -52235,7 +53752,7 @@ async function canvasImport(args, ports) {
52235
53752
  if (args.canvas !== undefined && !args.yes) {
52236
53753
  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
53754
  }
52238
- const file = resolve3(ports.cwd, args.file);
53755
+ const file = resolve4(ports.cwd, args.file);
52239
53756
  let text;
52240
53757
  try {
52241
53758
  text = await ports.readFile(file);
@@ -52251,7 +53768,7 @@ async function canvasImport(args, ports) {
52251
53768
  if (!Array.isArray(doc.children))
52252
53769
  throw new UsageError(`${args.file} has no children array`, "A .pen document is an object with a children array of top-level nodes.");
52253
53770
  const frames = args.frames?.filter((frame) => frame !== "");
52254
- const roots = (args.imageRoots ?? []).map((root) => resolve3(ports.cwd, root));
53771
+ const roots = (args.imageRoots ?? []).map((root) => resolve4(ports.cwd, root));
52255
53772
  const selection = planPenImport(doc, frames ? { frames } : {});
52256
53773
  const urls = penImageUrls(selection.children);
52257
53774
  const found = new Map;
@@ -52275,7 +53792,7 @@ async function canvasImport(args, ports) {
52275
53792
  reused++;
52276
53793
  continue;
52277
53794
  }
52278
- const id = await ports.upload({ filename: basename2(url), bytes, contentType: contentTypeOf(url) });
53795
+ const id = await ports.upload({ filename: basename2(url), bytes, contentType: contentTypeOf2(url) });
52279
53796
  byDigest.set(digest, id);
52280
53797
  images[url] = id;
52281
53798
  uploaded++;
@@ -52411,7 +53928,7 @@ function timestamp(key, value) {
52411
53928
  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
53929
  return Number.isFinite(time) ? new Date(time).toISOString() : undefined;
52413
53930
  }
52414
- function relative(iso, now) {
53931
+ function relative2(iso, now) {
52415
53932
  const delta = now - Date.parse(iso), seconds = Math.floor(Math.abs(delta) / 1000);
52416
53933
  if (Math.abs(delta) < 60000)
52417
53934
  return "just now";
@@ -52550,7 +54067,7 @@ function table(items, ctx, paint) {
52550
54067
  const now = ctx.now ?? Date.now();
52551
54068
  let rows = items.map((item) => columns.map((key) => {
52552
54069
  const v = record(item)[key], iso = timestamp(key, v);
52553
- return plain(iso ? relative(iso, now) : scalar(v));
54070
+ return plain(iso ? relative2(iso, now) : scalar(v));
52554
54071
  }));
52555
54072
  let headers = columns.map((key) => key.toUpperCase());
52556
54073
  let sizes = columns.map((_, i) => Math.max(width(headers[i]), ...rows.map((row) => width(row[i]))));
@@ -52590,7 +54107,7 @@ function objectView(data, resource, id, ctx, paint) {
52590
54107
  function value(key, v, depth) {
52591
54108
  const iso = timestamp(key, v);
52592
54109
  if (iso)
52593
- return `${iso} (${relative(iso, now)})`;
54110
+ return `${iso} (${relative2(iso, now)})`;
52594
54111
  if (Array.isArray(v)) {
52595
54112
  if (v.every((x) => x === null || typeof x !== "object"))
52596
54113
  return v.map(scalar).map(plain).join(", ");
@@ -52970,7 +54487,7 @@ function startProgress(ctx, write = (text) => writeOutput({ stderr: text })) {
52970
54487
  }
52971
54488
 
52972
54489
  // src/main.ts
52973
- var version = "0.3.0-dev.7d6e891";
54490
+ var version = "0.3.0-dev.80cda87";
52974
54491
  var commands = commandTree(operations);
52975
54492
  var manual = [...workflows.map((w) => w.words), [API_WORD]];
52976
54493
  function route(argv) {
@@ -52993,6 +54510,8 @@ function route(argv) {
52993
54510
  const command = commands.find((c) => c.words.length === words.length && c.words.every((w, n2) => w === words[n2]));
52994
54511
  if (words.length === 1 && words[0] === API_WORD && argv[i + 1] !== undefined && !argv[i + 1].startsWith("-"))
52995
54512
  continue;
54513
+ if (manual.some((c) => c.length === words.length + 1 && c.every((w, n2) => n2 < words.length ? w === words[n2] : w === argv[i + 1])))
54514
+ continue;
52996
54515
  if (command || manual.some((c) => c.length === words.length && c.every((w, n2) => w === words[n2])))
52997
54516
  return { words, args: [...args, ...argv.slice(i + 1)], command };
52998
54517
  }
@@ -53006,22 +54525,22 @@ var defaults = {
53006
54525
  stdoutIsTTY: Boolean(process.stdout.isTTY),
53007
54526
  stderrIsTTY: Boolean(process.stderr.isTTY),
53008
54527
  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"),
54528
+ readFile: (path) => readFile4(path, "utf8"),
54529
+ readBytes: (path) => readFile4(path),
54530
+ sha256: async (bytes) => createHash4("sha256").update(bytes).digest("hex"),
53012
54531
  async readStdin() {
53013
54532
  const chunks = [];
53014
54533
  for await (const chunk of process.stdin)
53015
54534
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
53016
54535
  return Buffer.concat(chunks).toString("utf8");
53017
54536
  },
53018
- ask: () => new Promise((resolve4) => {
54537
+ ask: () => new Promise((resolve5) => {
53019
54538
  const input = createInterface({ input: process.stdin, terminal: false });
53020
54539
  input.once("line", (line) => {
53021
- resolve4(/^(y|yes)$/i.test(line.trim()));
54540
+ resolve5(/^(y|yes)$/i.test(line.trim()));
53022
54541
  input.close();
53023
54542
  });
53024
- input.once("close", () => resolve4(false));
54543
+ input.once("close", () => resolve5(false));
53025
54544
  }),
53026
54545
  async openBrowser(url) {
53027
54546
  try {
@@ -53029,27 +54548,27 @@ var defaults = {
53029
54548
  if (!["https:", "http:"].includes(parsed.protocol))
53030
54549
  return;
53031
54550
  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" });
54551
+ await new Promise((resolve5, reject) => {
54552
+ const child = spawn3(cmd[0], cmd.slice(1), { stdio: "ignore" });
53034
54553
  child.once("error", reject);
53035
- child.once("close", () => resolve4());
54554
+ child.once("close", () => resolve5());
53036
54555
  });
53037
54556
  } catch {}
53038
54557
  },
53039
- wait: (ms) => new Promise((resolve4) => setTimeout(resolve4, ms)),
54558
+ wait: (ms) => new Promise((resolve5) => setTimeout(resolve5, ms)),
53040
54559
  render,
53041
- spawn: (cmd, args, options) => new Promise((resolve4, reject) => {
53042
- const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
54560
+ spawn: (cmd, args, options) => new Promise((resolve5, reject) => {
54561
+ const child = spawn3(cmd, args, { cwd: options.cwd, stdio: ["ignore", 2, 2] });
53043
54562
  child.once("error", reject);
53044
- child.once("close", (code) => resolve4(code ?? 1));
54563
+ child.once("close", (code) => resolve5(code ?? 1));
53045
54564
  }),
53046
- spawnCapture: (cmd, args, options) => new Promise((resolve4, reject) => {
53047
- const child = spawn2(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
54565
+ spawnCapture: (cmd, args, options) => new Promise((resolve5, reject) => {
54566
+ const child = spawn3(cmd, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] });
53048
54567
  const chunks = [];
53049
54568
  child.stdout.on("data", (c) => chunks.push(c));
53050
54569
  child.stderr.on("data", (c) => chunks.push(c));
53051
54570
  child.once("error", reject);
53052
- child.once("close", (code) => resolve4({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
54571
+ child.once("close", (code) => resolve5({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
53053
54572
  }),
53054
54573
  has: (bin) => spawnSync(process.platform === "win32" ? "where" : "which", [bin], { stdio: "ignore" }).status === 0,
53055
54574
  cwd: process.cwd()
@@ -53062,6 +54581,17 @@ var appOptions = {
53062
54581
  { name: "env", type: "string", description: "Plan only the targets this environment deploys (default: every environment)." },
53063
54582
  { name: "since", type: "string", description: "Mark the targets a change since this commit touches: git diff <since>...HEAD." }
53064
54583
  ],
54584
+ "devops deploy": [
54585
+ { name: "engine", type: "string", description: "Deploy engine (default: built-in)." },
54586
+ { name: "env", type: "string", description: "develop or production." },
54587
+ { name: "targets", type: "string", description: "Comma-separated target paths (default: every deployable target)." },
54588
+ { name: "commit", type: "string", description: "The commit being rolled out." },
54589
+ { name: "plan-only", type: "boolean", description: "Write plan files and a summary, apply nothing." },
54590
+ { name: "plan-dir", type: "string", description: "Directory the plan files are written to." },
54591
+ { name: "apply-plans", type: "string", description: "Apply the approved plan files in this directory." },
54592
+ { name: "events-file", type: "string", description: "NDJSON file the ExecutorLine events are written to." },
54593
+ { name: "workdir", type: "string", description: "Working directory for bundles and generated documents." }
54594
+ ],
53065
54595
  "devops test run": [
53066
54596
  { name: "project", type: "string", description: "DevOps project id (dvp_…); default: the devops.project field of praxis.jsonc in the current directory." },
53067
54597
  { name: "remote", type: "boolean", description: "Run the cases on the Praxis cloud executor. Required; local execution does not exist yet." },
@@ -53263,6 +54793,43 @@ Examples:
53263
54793
  const arity = name === "api" ? 2 : name === "org switch" || name === "app create" || name === "canvas import" ? 1 : 0;
53264
54794
  if (parsed.positional.length !== arity)
53265
54795
  throw new UsageError(`${name} expects ${arity} positional argument(s)`);
54796
+ if (name === "devops deploy") {
54797
+ const engine = parsed.flags.engine?.[0];
54798
+ if (engine !== undefined && engine !== "tofu")
54799
+ throw new UsageError(`unknown deploy engine ${String(engine)}`, "Omit --engine; the built-in engine is the default (ADR-110).");
54800
+ const f = (key) => parsed.flags[key]?.[0];
54801
+ return await devopsDeployTofu({
54802
+ env: f("env"),
54803
+ targets: f("targets"),
54804
+ commit: f("commit"),
54805
+ "plan-only": Boolean(parsed.flags["plan-only"]),
54806
+ "plan-dir": f("plan-dir"),
54807
+ "apply-plans": f("apply-plans"),
54808
+ "events-file": f("events-file"),
54809
+ workdir: f("workdir")
54810
+ }, {
54811
+ git: (args, cwd) => ports.spawnCapture("git", args, { cwd }),
54812
+ readFile: async (path2) => {
54813
+ try {
54814
+ return await ports.readFile(path2);
54815
+ } catch (error) {
54816
+ if (error.code === "ENOENT")
54817
+ return null;
54818
+ throw error;
54819
+ }
54820
+ },
54821
+ mode: ctx.mode,
54822
+ emit,
54823
+ human: () => {},
54824
+ cwd: ports.cwd,
54825
+ env: ports.env,
54826
+ fetch: wireFetch,
54827
+ stdout: (line) => {
54828
+ process.stdout.write(`${line}
54829
+ `);
54830
+ }
54831
+ });
54832
+ }
53266
54833
  if (name === "devops deploy plan") {
53267
54834
  await devopsDeployPlan({
53268
54835
  environment: parsed.flags.env?.[0],