@tackup/cli 0.0.0 → 0.1.1-exp.pr144.g5661267

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 (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +16 -1
  3. package/dist/builtins/extensions/docs/guides/day-two.md +3 -0
  4. package/dist/builtins/extensions/docs/guides/onboarding-2.md +3 -0
  5. package/dist/builtins/extensions/docs/guides/onboarding-3.md +3 -0
  6. package/dist/builtins/extensions/docs/skills/use-tack-docs/SKILL.md +67 -0
  7. package/dist/builtins/extensions/docs/skills/use-tack-docs/references/declare-docs.md +71 -0
  8. package/dist/builtins/extensions/docs/skills/use-tack-docs/references/docs-in-profiles.md +25 -0
  9. package/dist/builtins/extensions/docs/skills/use-tack-docs/references/docs-maintenance.md +35 -0
  10. package/dist/builtins/extensions/docs/skills/use-tack-docs/references/review.md +34 -0
  11. package/dist/builtins/extensions/docs/skills/write-reader-figures/SKILL.md +66 -0
  12. package/dist/builtins/extensions/docs/skills/write-reader-figures/references/figure-components.md +20 -0
  13. package/dist/builtins/extensions/docs/skills/write-reader-figures/references/figures/architecture-map.md +86 -0
  14. package/dist/builtins/extensions/docs/skills/write-reader-figures/references/figures/chart.md +52 -0
  15. package/dist/builtins/extensions/docs/skills/write-reader-figures/references/figures/figure.md +79 -0
  16. package/dist/builtins/extensions/docs/skills/write-reader-figures/references/figures/file-tree.md +74 -0
  17. package/dist/builtins/extensions/docs/skills/write-reader-figures/references/figures/schema.md +116 -0
  18. package/dist/builtins/extensions/docs/skills/write-reader-figures/references/figures/system.md +81 -0
  19. package/dist/builtins/extensions/docs/skills/write-reader-figures/references/figures/walkthrough.md +45 -0
  20. package/dist/builtins/extensions/docs/skills/write-reader-figures/references/page-components.md +82 -0
  21. package/dist/builtins/extensions/docs/skills/write-reader-figures/references/rules.md +27 -0
  22. package/dist/builtins/extensions/docs/tack.yaml +10 -0
  23. package/dist/builtins/extensions/scripts/guides/day-two.md +3 -0
  24. package/dist/builtins/extensions/scripts/guides/onboarding-2.md +3 -0
  25. package/dist/builtins/extensions/scripts/skills/author-tack-scripts/SKILL.md +48 -0
  26. package/dist/builtins/extensions/scripts/skills/author-tack-scripts/references/run-scripts.md +23 -0
  27. package/dist/builtins/extensions/scripts/skills/author-tack-scripts/references/script-api.md +76 -0
  28. package/dist/builtins/extensions/scripts/skills/author-tack-scripts/references/scripts-in-profiles.md +35 -0
  29. package/dist/builtins/extensions/scripts/skills/author-tack-scripts/references/scripts-in-sources.md +56 -0
  30. package/dist/builtins/extensions/scripts/tack.yaml +10 -0
  31. package/dist/builtins/skills/author-tack-profiles/SKILL.md +68 -0
  32. package/dist/builtins/skills/author-tack-profiles/references/apply.md +33 -0
  33. package/dist/builtins/skills/author-tack-profiles/references/bundles.md +59 -0
  34. package/dist/builtins/skills/author-tack-profiles/references/copy-workflows.md +46 -0
  35. package/dist/builtins/skills/manage-tack-sources/SKILL.md +75 -0
  36. package/dist/builtins/skills/manage-tack-sources/references/catalog-issues.md +38 -0
  37. package/dist/builtins/skills/manage-tack-sources/references/metadata.md +35 -0
  38. package/dist/builtins/skills/manage-tack-sources/references/tack-yaml.md +114 -0
  39. package/dist/builtins/skills/manage-tack-sources/references/worked-source.md +126 -0
  40. package/dist/builtins/skills/prepare-tack-checkout/SKILL.md +52 -0
  41. package/dist/builtins/skills/use-tack/SKILL.md +65 -0
  42. package/dist/builtins/skills/use-tack/references/agent-instructions.md +38 -0
  43. package/dist/builtins/skills/use-tack/references/day-two.md +35 -0
  44. package/dist/builtins/skills/use-tack/references/explore.md +13 -0
  45. package/dist/builtins/skills/use-tack/references/imports.md +30 -0
  46. package/dist/builtins/skills/use-tack/references/maintenance.md +51 -0
  47. package/dist/builtins/skills/use-tack/references/onboarding-2.md +41 -0
  48. package/dist/builtins/skills/use-tack/references/onboarding-3.md +29 -0
  49. package/dist/builtins/skills/use-tack/references/onboarding.md +54 -0
  50. package/dist/builtins/skills/use-tack/references/output.md +15 -0
  51. package/dist/builtins/skills/use-tack/references/selection.md +61 -0
  52. package/dist/builtins/skills/use-tack/references/setup.md +69 -0
  53. package/dist/builtins/tack.yaml +10 -0
  54. package/dist/bundle-support-C7OD5JEG.js +16 -0
  55. package/dist/chunk-2RUJGM5D.js +56 -0
  56. package/dist/chunk-3KGEOW4B.js +225 -0
  57. package/dist/chunk-BDOOV5W7.js +26 -0
  58. package/dist/chunk-C3K3AFJD.js +16 -0
  59. package/dist/chunk-E2SJQHKZ.js +281 -0
  60. package/dist/chunk-EOACX6VI.js +12401 -0
  61. package/dist/chunk-I25CGFRW.js +36671 -0
  62. package/dist/chunk-QW47O677.js +162 -0
  63. package/dist/chunk-QXSQ5MEX.js +28 -0
  64. package/dist/chunk-RZQCGAJF.js +5733 -0
  65. package/dist/chunk-SMY7ZPQQ.js +52 -0
  66. package/dist/chunk-VV2YFWGB.js +1791 -0
  67. package/dist/chunk-W76JFI2G.js +18013 -0
  68. package/dist/chunk-XTWP3LBL.js +1017 -0
  69. package/dist/chunk-ZTKVYMVR.js +92 -0
  70. package/dist/corpus-effects-IKUFX5HQ.js +12069 -0
  71. package/dist/elk.bundled-A4NY77AZ.js +94125 -0
  72. package/dist/main-K4VB62TY.js +65517 -0
  73. package/dist/main.js +17 -0
  74. package/dist/reader/visuals.tsx +368 -0
  75. package/dist/script.d.ts +133 -0
  76. package/dist/script.js +90 -0
  77. package/dist/server-R3ERJ4GJ.js +308 -0
  78. package/dist/src-RDHNYJMO.js +1871 -0
  79. package/dist/src-XIWV5BGG.js +1126 -0
  80. package/dist/tack-env.d.ts +137 -0
  81. package/dist/third-party-licenses.txt +2467 -0
  82. package/dist/worker-XBNGNPT7.js +24246 -0
  83. package/package.json +29 -3
@@ -0,0 +1,1126 @@
1
+ import { createRequire as tackCreateRequire } from "node:module"; const require = tackCreateRequire(import.meta.url);
2
+ import {
3
+ ExecutionError,
4
+ ExecutionWorker,
5
+ RunHistory,
6
+ executionError,
7
+ executionFailureOutcome
8
+ } from "./chunk-SMY7ZPQQ.js";
9
+ import {
10
+ declarationFileName
11
+ } from "./chunk-C3K3AFJD.js";
12
+ import {
13
+ require_picomatch
14
+ } from "./chunk-VV2YFWGB.js";
15
+ import {
16
+ ExtensionFailure,
17
+ HistoryClearApplicationSchema,
18
+ HistoryClearPlanSchema,
19
+ RunFailureSchema,
20
+ RunResultSchema,
21
+ RunTargetSchema,
22
+ ScriptsHost,
23
+ compareCodeUnits,
24
+ executionLimits,
25
+ historyListBounds,
26
+ implementFor,
27
+ plural,
28
+ runFailure,
29
+ scriptHistoryClear,
30
+ scriptHistoryList,
31
+ scriptHistoryShow,
32
+ scriptRun,
33
+ scriptShow,
34
+ selectorFlags,
35
+ shellWord,
36
+ skippedCheck,
37
+ types
38
+ } from "./chunk-EOACX6VI.js";
39
+ import {
40
+ DateTime_exports,
41
+ Effect_exports,
42
+ FileSystem_exports,
43
+ Option_exports,
44
+ Path_exports,
45
+ Predicate_exports,
46
+ Schema_exports,
47
+ SecureRandom_exports
48
+ } from "./chunk-I25CGFRW.js";
49
+ import {
50
+ __toESM,
51
+ init_define_TACK_BUILD_INFO
52
+ } from "./chunk-2RUJGM5D.js";
53
+
54
+ // packages/extension-scripts/src/index.ts
55
+ init_define_TACK_BUILD_INFO();
56
+
57
+ // packages/extension-scripts/src/commands.ts
58
+ init_define_TACK_BUILD_INFO();
59
+
60
+ // packages/extension-scripts/src/execution.ts
61
+ init_define_TACK_BUILD_INFO();
62
+ var emptyResult = (runId, outcome) => ({
63
+ runId,
64
+ outcome,
65
+ logs: [],
66
+ logTruncation: { truncated: false, observedBytes: 0, observedEvents: 0, reasons: [] },
67
+ finalization: "not-started"
68
+ });
69
+ var safeFailure = (error) => {
70
+ if (error instanceof ExecutionError) return executionFailureOutcome(error);
71
+ const tag = typeof error === "object" && error !== null && "_tag" in error ? error._tag : void 0;
72
+ if (tag === "StateCorruptError" || tag === "StateStorageError" || tag === "StateMutationError" || tag === "ProjectStorageError")
73
+ return runFailure(
74
+ "resolution",
75
+ "state_storage_failed",
76
+ "Tack could not safely read persisted run configuration."
77
+ );
78
+ if (tag === "StateBusyError")
79
+ return runFailure("resolution", "state_busy", "Another command owns the state writer lock.");
80
+ return runFailure(
81
+ "resolution",
82
+ "run_resolution_failed",
83
+ "The script or target could not be resolved from initialized Tack state."
84
+ );
85
+ };
86
+ var inspectHint = "Run `tack project` to list registered projects and roots.";
87
+ var targetFlags = "Choose a target with --project <name>, --root <path>, or --user.";
88
+ var resolveRunTarget = Effect_exports.fnUntraced(function* (state, request) {
89
+ const host = yield* ScriptsHost;
90
+ const path = yield* Path_exports.Path;
91
+ const selector = request.selector;
92
+ if (selector._tag !== "bare") {
93
+ const projectName = selector._tag === "project" ? selector.projectName : void 0;
94
+ const targets = yield* host.selectTargets(state, selector, path.resolve(".")).pipe(
95
+ Effect_exports.mapError(
96
+ (error) => error._tag === "ProjectNotFoundError" && projectName !== void 0 ? executionError(
97
+ "resolution",
98
+ "run_project_not_registered",
99
+ `Project "${projectName}" is not registered. ${inspectHint}`,
100
+ { projectName }
101
+ ) : error
102
+ )
103
+ );
104
+ const scope = projectName === void 0 ? "The run target" : `Project "${projectName}"`;
105
+ const projectDetails = projectName === void 0 ? {} : { projectName };
106
+ const [selected] = targets;
107
+ if (selected === void 0)
108
+ return yield* executionError(
109
+ "resolution",
110
+ "run_target_unavailable",
111
+ `${scope} has no active registered root available for a run. ${inspectHint}`,
112
+ projectDetails
113
+ );
114
+ if (targets.length !== 1)
115
+ return yield* executionError(
116
+ "resolution",
117
+ "run_target_not_unique",
118
+ `${scope} has ${targets.length} active registered roots. Choose one with --root <path>.`,
119
+ { ...projectDetails, roots: targets.map((candidate) => candidate.canonicalPath) }
120
+ );
121
+ return selected;
122
+ }
123
+ const explicit = request.root !== void 0;
124
+ const lookup = path.resolve(request.root ?? request.cwd ?? ".");
125
+ const { canonicalCwd, containing } = yield* host.containingRoot(state, lookup).pipe(
126
+ Effect_exports.mapError((error) => {
127
+ if (error._tag !== "TargetSelectionError") return error;
128
+ return explicit === true ? executionError(
129
+ "resolution",
130
+ "run_root_unavailable",
131
+ `The --root path is not an accessible directory. ${inspectHint}`,
132
+ { root: lookup }
133
+ ) : executionError(
134
+ "resolution",
135
+ "run_cwd_unavailable",
136
+ `The current directory (or --cwd) is not an accessible directory. ${targetFlags}`,
137
+ { cwd: lookup }
138
+ );
139
+ })
140
+ );
141
+ if (containing === void 0)
142
+ return yield* explicit === true ? executionError(
143
+ "resolution",
144
+ "run_root_not_registered",
145
+ `The --root path is not a registered active project root. ${inspectHint}`,
146
+ { root: lookup }
147
+ ) : executionError(
148
+ "resolution",
149
+ "run_cwd_not_registered",
150
+ `The current directory (or --cwd) is not inside an active registered project root. ${targetFlags}`,
151
+ { cwd: lookup }
152
+ );
153
+ if (explicit === true && canonicalCwd !== containing.root)
154
+ return yield* executionError(
155
+ "resolution",
156
+ "run_root_not_registered",
157
+ `The --root path is inside registered root ${containing.root} but is not itself a registered root. Use --root ${containing.root}.`,
158
+ { root: lookup, containingRoot: containing.root }
159
+ );
160
+ return {
161
+ _tag: "project-root",
162
+ canonicalPath: containing.root,
163
+ projectName: containing.projectName
164
+ };
165
+ });
166
+ var declaredScript = Effect_exports.fnUntraced(function* (state, address) {
167
+ const platform = yield* ExecutionWorker;
168
+ const { duplicated, entries } = yield* (yield* ScriptsHost).scriptsAt(state, address);
169
+ if (duplicated === true)
170
+ return yield* executionError(
171
+ "resolution",
172
+ "script_address_ambiguous",
173
+ "More than one source declares the exact script address."
174
+ );
175
+ const entry = entries.length === 1 ? entries[0] : void 0;
176
+ if (entry === void 0)
177
+ return yield* executionError(
178
+ "resolution",
179
+ "script_not_found",
180
+ "The exact declared script address is unavailable or quarantined."
181
+ );
182
+ yield* platform.packageReady(entry.sourcePath, entry.filePath);
183
+ return entry;
184
+ });
185
+ var runWithCancellation = Effect_exports.fnUntraced(function* (state, request, cancellation) {
186
+ const platform = yield* ExecutionWorker;
187
+ const history = yield* RunHistory;
188
+ const random = yield* SecureRandom_exports.SecureRandom;
189
+ const runId = yield* random.uuidV4();
190
+ const host = yield* ScriptsHost;
191
+ const stateDirectory = yield* host.stateDirectory(state);
192
+ const observedState = yield* Effect_exports.result(host.requireState(state));
193
+ if (observedState._tag === "Failure" && observedState.failure._tag === "StateNotInitializedError")
194
+ return emptyResult(
195
+ runId,
196
+ runFailure(
197
+ "resolution",
198
+ "state_not_initialized",
199
+ "Tack is not initialized in the selected state directory. Run `tack state init` first, or check --state-dir and TACK_STATE_DIR.",
200
+ { stateDirectory }
201
+ )
202
+ );
203
+ const pending = {
204
+ version: 1,
205
+ runId,
206
+ status: "pending",
207
+ startedAt: DateTime_exports.formatIso(yield* DateTime_exports.now),
208
+ address: request.address
209
+ };
210
+ const initial = yield* history.createHistory(stateDirectory, pending).pipe(Effect_exports.result);
211
+ if (initial._tag === "Failure")
212
+ return emptyResult(runId, executionFailureOutcome(initial.failure));
213
+ let originalInput;
214
+ let target;
215
+ let diagnostics;
216
+ const interrupted = () => cancellation.signal.aborted;
217
+ const attempt = yield* Effect_exports.gen(function* () {
218
+ if (interrupted() === true)
219
+ return emptyResult(
220
+ runId,
221
+ runFailure("execution", "interrupted", "The run was interrupted before executable work.")
222
+ );
223
+ if (request.targetConflict === true)
224
+ return yield* executionError(
225
+ "invocation",
226
+ "run_targets_conflict",
227
+ "Choose exactly one run target."
228
+ );
229
+ if (request.timeoutMs !== void 0 && (Number.isFinite(request.timeoutMs) === false || Number.isInteger(request.timeoutMs) === false || request.timeoutMs <= 0))
230
+ return yield* executionError(
231
+ "invocation",
232
+ "timeout_invalid",
233
+ "The run timeout must be a positive duration."
234
+ );
235
+ originalInput = yield* platform.input(request, cancellation.signal);
236
+ yield* Effect_exports.fromResult(observedState);
237
+ const selected = yield* resolveRunTarget(state, request);
238
+ target = Schema_exports.decodeUnknownSync(Schema_exports.Json)(selected);
239
+ const entry = yield* declaredScript(state, request.address);
240
+ if (interrupted() === true)
241
+ return emptyResult(
242
+ runId,
243
+ runFailure("execution", "interrupted", "The run was interrupted before executable work.")
244
+ );
245
+ const executed = yield* platform.worker({
246
+ signal: cancellation.signal,
247
+ onRepeatSignal: cancellation.onRepeatSignal,
248
+ runId,
249
+ entrypoint: entry.filePath,
250
+ cwd: selected.canonicalPath,
251
+ input: originalInput,
252
+ ...request.words === void 0 ? {} : { words: request.words },
253
+ stateDirectory,
254
+ ...request.timeoutMs === void 0 ? {} : { timeoutMs: request.timeoutMs },
255
+ ...request.quiet === void 0 ? {} : { quiet: request.quiet }
256
+ });
257
+ diagnostics = executed.diagnostics;
258
+ return executed.result;
259
+ }).pipe(Effect_exports.result);
260
+ const result = attempt._tag === "Success" ? attempt.success : emptyResult(runId, safeFailure(attempt.failure));
261
+ const completed = {
262
+ ...pending,
263
+ status: "complete",
264
+ finishedAt: DateTime_exports.formatIso(yield* DateTime_exports.now),
265
+ result,
266
+ ...request.words === void 0 ? originalInput === void 0 ? {} : { originalInput } : { originalWords: request.words },
267
+ ...target === void 0 ? {} : { target },
268
+ ...diagnostics === void 0 ? {} : { diagnostics }
269
+ };
270
+ const persisted = yield* history.finishHistory(stateDirectory, completed).pipe(Effect_exports.result);
271
+ return persisted._tag === "Success" ? result : {
272
+ ...result,
273
+ outcome: {
274
+ ...executionFailureOutcome(persisted.failure),
275
+ details: { runOutcome: Schema_exports.decodeUnknownSync(Schema_exports.Json)(result.outcome) }
276
+ }
277
+ };
278
+ });
279
+ var runOperatorScript = Effect_exports.fn("execution.runOperatorScript")(function* (state, request) {
280
+ return yield* Effect_exports.acquireUseRelease(
281
+ Effect_exports.flatMap(ExecutionWorker, (platform) => platform.cancellation()),
282
+ (cancellation) => runWithCancellation(state, request, cancellation),
283
+ (cancellation) => Effect_exports.sync(() => cancellation.close())
284
+ );
285
+ });
286
+ var describeTimeoutMs = 15e3;
287
+ var describeScript = Effect_exports.fn("execution.describeScript")(function* (state, address) {
288
+ const platform = yield* ExecutionWorker;
289
+ const random = yield* SecureRandom_exports.SecureRandom;
290
+ const stateDirectory = yield* initializedStateDirectory(state);
291
+ const entry = yield* declaredScript(state, address);
292
+ const runId = yield* random.uuidV4();
293
+ const executed = yield* Effect_exports.acquireUseRelease(
294
+ platform.cancellation(),
295
+ (cancellation) => platform.worker({
296
+ runId,
297
+ entrypoint: entry.filePath,
298
+ cwd: entry.sourcePath,
299
+ input: {},
300
+ describe: true,
301
+ stateDirectory,
302
+ timeoutMs: describeTimeoutMs,
303
+ quiet: true,
304
+ signal: cancellation.signal
305
+ }),
306
+ (cancellation) => Effect_exports.sync(() => cancellation.close())
307
+ );
308
+ if (executed.described === void 0) {
309
+ const { outcome } = executed.result;
310
+ return yield* executionError(outcome.stage, outcome.code, outcome.message, outcome.details);
311
+ }
312
+ return {
313
+ address: entry.address,
314
+ description: entry.description,
315
+ filePath: entry.filePath,
316
+ sourcePath: entry.sourcePath,
317
+ // A list keeps the declaration order, which the help follows.
318
+ arguments: Object.entries(executed.described.args).map(([name, spec]) => ({ name, ...spec })),
319
+ secrets: executed.described.secrets
320
+ };
321
+ });
322
+ var HistoryNotFoundError = class extends Schema_exports.TaggedError()(
323
+ "HistoryNotFoundError",
324
+ { runId: Schema_exports.String }
325
+ ) {
326
+ };
327
+ var initializedStateDirectory = Effect_exports.fnUntraced(function* (state) {
328
+ const host = yield* ScriptsHost;
329
+ yield* host.requireState(state);
330
+ return yield* host.stateDirectory(state);
331
+ });
332
+ var newestFirst = (left, right) => compareCodeUnits(right.startedAt, left.startedAt) || compareCodeUnits(right.runId, left.runId);
333
+ var listScriptHistory = Effect_exports.fn("execution.listScriptHistory")(function* (state, page = {}) {
334
+ const limit = page.limit ?? historyListBounds.defaultLimit;
335
+ const offset = page.offset ?? 0;
336
+ const scanned = yield* (yield* RunHistory).listHistory(yield* initializedStateDirectory(state));
337
+ const runs = [...scanned.runs].sort(newestFirst).slice(offset, offset + limit);
338
+ return {
339
+ runs,
340
+ total: scanned.runs.length,
341
+ offset,
342
+ limit,
343
+ truncated: offset + runs.length < scanned.runs.length,
344
+ issues: [...scanned.issues].sort((left, right) => compareCodeUnits(left.path, right.path))
345
+ };
346
+ });
347
+ var showScriptHistory = Effect_exports.fn("execution.showScriptHistory")(function* (state, runId) {
348
+ const record = yield* (yield* RunHistory).showHistory(
349
+ yield* initializedStateDirectory(state),
350
+ runId
351
+ );
352
+ if (record === void 0) return yield* new HistoryNotFoundError({ runId });
353
+ return record;
354
+ });
355
+ var clearScriptHistory = Effect_exports.fn("execution.clearScriptHistory")(function* (state, apply = false) {
356
+ const history = yield* RunHistory;
357
+ const directory = yield* initializedStateDirectory(state);
358
+ const plan = {
359
+ kind: HistoryClearPlanSchema.fields.kind.literal,
360
+ count: yield* history.countHistory(directory)
361
+ };
362
+ if (apply === false) return { plan };
363
+ return {
364
+ plan,
365
+ applied: {
366
+ kind: HistoryClearApplicationSchema.fields.kind.literal,
367
+ removedCount: yield* history.clearHistory(directory)
368
+ }
369
+ };
370
+ });
371
+
372
+ // packages/extension-scripts/src/views/history-views.ts
373
+ init_define_TACK_BUILD_INFO();
374
+
375
+ // packages/extension-scripts/src/views/run-views.ts
376
+ init_define_TACK_BUILD_INFO();
377
+ var scriptRunViews = (kit) => {
378
+ const {
379
+ cell,
380
+ commandLine,
381
+ factRows,
382
+ formatBytes,
383
+ frameView,
384
+ isRecord,
385
+ isRunId,
386
+ oneLine,
387
+ paragraph,
388
+ plural: plural2,
389
+ timeOfDay,
390
+ truncate,
391
+ valueLines,
392
+ withoutPayload
393
+ } = kit;
394
+ const decodeFailure = Schema_exports.decodeUnknownOption(RunFailureSchema);
395
+ const markOf = (classification) => classification === "success" ? "\u2713" : classification === "interruption" ? "!" : "\u2717";
396
+ const paintOf = (classification, style) => classification === "success" ? style.green : classification === "interruption" ? style.yellow : style.red;
397
+ const outcomeText = (outcome) => `${markOf(outcome.classification)} ${outcome.code} at ${outcome.stage} stage${outcome.classification === "success" ? "" : ` (${outcome.classification})`}`;
398
+ const outcomeFact = (outcome, style) => [
399
+ "Outcome",
400
+ [cell(outcomeText(outcome), paintOf(outcome.classification, style))]
401
+ ];
402
+ const finalizationFacts = (result, style) => [
403
+ [
404
+ "Finalization",
405
+ [
406
+ cell(
407
+ result.finalization === "not-started" ? "not started" : result.finalization,
408
+ result.finalization === "incomplete" ? style.yellow : void 0
409
+ )
410
+ ]
411
+ ],
412
+ ...result.termination === void 0 ? [] : [
413
+ [
414
+ "Termination",
415
+ [cell(`${result.termination.reason}${result.termination.forced ? " (forced)" : ""}`)]
416
+ ]
417
+ ]
418
+ ];
419
+ const sourceOrder = ["stdout", "stderr", "script", "shell", "supervisor"];
420
+ const logSummary = (result, style) => {
421
+ const { logs, logTruncation } = result;
422
+ const perSource = sourceOrder.map((source) => [source, logs.filter((log) => log.source === source).length]).filter(([, count]) => count > 0).map(([source, count]) => `${source} ${count}`);
423
+ const limits = `${plural2(executionLimits.logEvents, "event")} and ${formatBytes(executionLimits.logBytes)}`;
424
+ const kept = `${logs.length} of ${plural2(logTruncation.observedEvents, "event")} kept, ${formatBytes(logTruncation.observedBytes)} observed${perSource.length === 0 ? "" : ` (${perSource.join(", ")})`}`;
425
+ const status = logTruncation.truncated ? `Truncated${logTruncation.reasons.length === 0 ? "" : ` (${logTruncation.reasons.join(", ")})`}; the limits are ${limits}.` : `Not truncated; the limits are ${limits}.`;
426
+ return [
427
+ ...paragraph(kept, { width: style.width, indent: 2 }),
428
+ ...paragraph(status, {
429
+ width: style.width,
430
+ indent: 2,
431
+ ...logTruncation.truncated ? { paint: style.yellow } : {}
432
+ })
433
+ ];
434
+ };
435
+ const valueBlock = (title, value, style) => {
436
+ const shown = valueLines(value, style, { indent: " ", maxLines: 12 });
437
+ return { lines: [style.bold(title), ...shown.lines], truncated: shown.truncated };
438
+ };
439
+ const decodePrimary = Schema_exports.decodeUnknownOption(
440
+ Schema_exports.Struct({
441
+ primary: Schema_exports.Struct({
442
+ status: Schema_exports.Literals(["success", "failure"]),
443
+ encoded: Schema_exports.optionalKey(Schema_exports.Json)
444
+ })
445
+ })
446
+ );
447
+ const primaryValueBlock = (core, style) => {
448
+ const primary = Option_exports.getOrUndefined(decodePrimary(core))?.primary;
449
+ if (primary === void 0 || Object.hasOwn(primary, "encoded") === false) return void 0;
450
+ return valueBlock(
451
+ primary.status === "success" ? "Value" : "Failure value",
452
+ primary.encoded,
453
+ style
454
+ );
455
+ };
456
+ const historyStatus = (result, style) => {
457
+ const { outcome } = result;
458
+ if (outcome.stage === "history")
459
+ return ["History", [cell("not saved; the history write failed", style.red)]];
460
+ if (outcome.code === "state_not_initialized")
461
+ return ["History", [cell("no record; Tack state is not initialized")]];
462
+ return ["History", [cell("full record saved")]];
463
+ };
464
+ const runOutcomeBeforeHistory = (result) => {
465
+ if (result.outcome.stage !== "history") return void 0;
466
+ const nested = result.outcome.details;
467
+ return isRecord(nested) ? Option_exports.getOrUndefined(decodeFailure(nested["runOutcome"])) : void 0;
468
+ };
469
+ const scriptRunView = (envelope, payloads, style) => {
470
+ if (envelope.result === null) return withoutPayload(envelope, style);
471
+ if (Option_exports.isNone(payloads.result) === true) return void 0;
472
+ const result = payloads.result.value;
473
+ const { outcome } = result;
474
+ const reported = envelope.diagnostics.some(
475
+ (diagnostic) => diagnostic.code === outcome.code && diagnostic.message === outcome.message
476
+ );
477
+ const before = runOutcomeBeforeHistory(result);
478
+ const saved = outcome.stage !== "history" && outcome.code !== "state_not_initialized";
479
+ const value = primaryValueBlock(result.core, style);
480
+ return frameView(envelope, style, {
481
+ body: [
482
+ factRows(
483
+ [
484
+ ["Run", [cell(result.runId)]],
485
+ outcomeFact(outcome, style),
486
+ ...reported ? [] : [["Message", [cell(outcome.message)]]],
487
+ ...before === void 0 ? [] : [
488
+ [
489
+ "Run outcome",
490
+ [
491
+ cell(
492
+ `${outcomeText(before)}: ${before.message}`,
493
+ paintOf(before.classification, style)
494
+ )
495
+ ]
496
+ ]
497
+ ],
498
+ ...finalizationFacts(result, style),
499
+ historyStatus(result, style)
500
+ ],
501
+ style
502
+ ),
503
+ value === void 0 ? void 0 : [
504
+ ...value.lines,
505
+ ...value.truncated ? paragraph("Value cut to fit; --json prints the whole report.", {
506
+ width: style.width,
507
+ indent: 2,
508
+ paint: style.dim
509
+ }) : []
510
+ ],
511
+ [style.bold("Logs"), ...logSummary(result, style)]
512
+ ],
513
+ hints: saved && isRunId(result.runId) ? [commandLine("script-history-show", result.runId)] : []
514
+ });
515
+ };
516
+ const shownLogCount = 20;
517
+ const logLines = (result, style) => result.logs.slice(0, shownLogCount).map((log) => {
518
+ const prefix = ` #${log.sequence} ${log.source} ${timeOfDay(log.timestamp)} `;
519
+ return `${prefix}${truncate(oneLine(log.content), Math.max(10, style.width - prefix.length))}`;
520
+ });
521
+ return {
522
+ markOf,
523
+ paintOf,
524
+ outcomeFact,
525
+ finalizationFacts,
526
+ logSummary,
527
+ valueBlock,
528
+ primaryValueBlock,
529
+ scriptRunView,
530
+ shownLogCount,
531
+ logLines
532
+ };
533
+ };
534
+
535
+ // packages/extension-scripts/src/views/history-views.ts
536
+ var historyViews = (kit) => {
537
+ const {
538
+ addressText,
539
+ cell,
540
+ commandLine,
541
+ factRows,
542
+ frameView,
543
+ instant,
544
+ isRunId,
545
+ paragraph,
546
+ period,
547
+ plural: plural2,
548
+ removalView,
549
+ shellWord: shellWord2,
550
+ statementLines,
551
+ table,
552
+ withoutPayload
553
+ } = kit;
554
+ const {
555
+ finalizationFacts,
556
+ logLines,
557
+ logSummary,
558
+ markOf,
559
+ outcomeFact,
560
+ paintOf,
561
+ primaryValueBlock,
562
+ shownLogCount,
563
+ valueBlock
564
+ } = scriptRunViews(kit);
565
+ const outcomeCell = (run, style) => {
566
+ if (run.outcome === void 0)
567
+ return cell(`\u2026 ${run.status === "pending" ? "pending" : "no outcome"}`, style.yellow);
568
+ const { classification, code } = run.outcome;
569
+ return cell(
570
+ `${markOf(classification)} ${classification === "success" ? code : `${code} (${classification})`}`,
571
+ paintOf(classification, style)
572
+ );
573
+ };
574
+ const runLines = (runs, style) => table(
575
+ runs.map((run) => [
576
+ outcomeCell(run, style),
577
+ cell(run.runId),
578
+ cell(addressText(run.address, style)),
579
+ cell(period(run.startedAt, run.finishedAt))
580
+ ]),
581
+ { width: style.width }
582
+ );
583
+ const pageFlags = (limit, offset) => [
584
+ ...limit === historyListBounds.defaultLimit ? [] : ["--limit", String(limit)],
585
+ ...offset === 0 ? [] : ["--offset", String(offset)]
586
+ ];
587
+ const historyListView = (envelope, { result }, style) => {
588
+ if (envelope.result === null) return withoutPayload(envelope, style);
589
+ if (Option_exports.isNone(result) === true) return void 0;
590
+ const list = result.value;
591
+ const first = list.runs[0];
592
+ const range = first === void 0 ? list.total === 0 ? "No retained runs." : `No runs at offset ${list.offset}; ${plural2(list.total, "run")} retained.` : `Runs ${list.offset + 1}-${list.offset + list.runs.length} of ${list.total}, newest first.`;
593
+ const paging = `limit ${list.limit}, offset ${list.offset}${list.truncated ? ", more runs follow" : ""}`;
594
+ const next = list.offset + list.runs.length;
595
+ const previous = Math.max(0, list.offset - list.limit);
596
+ const hints = [
597
+ ...list.truncated && first !== void 0 ? [commandLine("script-history-list", ...pageFlags(list.limit, next))] : [],
598
+ ...list.offset > 0 ? [commandLine("script-history-list", ...pageFlags(list.limit, previous))] : [],
599
+ ...first !== void 0 && isRunId(first.runId) ? [commandLine("script-history-show", first.runId)] : []
600
+ ];
601
+ return frameView(envelope, style, {
602
+ body: [
603
+ [
604
+ ...paragraph(range, { width: style.width }),
605
+ ...paragraph(`Page: ${paging}.`, { width: style.width, paint: style.dim })
606
+ ],
607
+ list.runs.length === 0 ? void 0 : runLines(list.runs, style),
608
+ list.issues.length === 0 ? void 0 : [
609
+ style.bold(`Skipped records (${list.issues.length})`),
610
+ ...list.issues.flatMap((issue) => [
611
+ ` ${style.yellow("!")} ${issue.reason}`,
612
+ ...paragraph(style.path(issue.path), { width: style.width, indent: 4 })
613
+ ])
614
+ ]
615
+ ],
616
+ hints
617
+ });
618
+ };
619
+ const decodeTarget = Schema_exports.decodeUnknownOption(RunTargetSchema);
620
+ const historyShowView = (envelope, payloads, style) => {
621
+ if (envelope.result === null)
622
+ return withoutPayload(
623
+ envelope,
624
+ style,
625
+ envelope.diagnostics.some((diagnostic) => diagnostic.code === "history-not-found") ? [commandLine("script-history-list")] : []
626
+ );
627
+ if (Option_exports.isNone(payloads.result) === true) return void 0;
628
+ const record = payloads.result.value;
629
+ const { result } = record;
630
+ const target = record.target === void 0 ? void 0 : Option_exports.getOrUndefined(decodeTarget(record.target));
631
+ const input = record.originalWords !== void 0 ? valueBlock("Arguments", record.originalWords.map(shellWord2).join(" "), style) : record.originalInput === void 0 ? void 0 : valueBlock("Input", record.originalInput, style);
632
+ const targetBlock = record.target === void 0 || target !== void 0 ? void 0 : valueBlock("Target", record.target, style);
633
+ const value = primaryValueBlock(result?.core, style);
634
+ const evidence = record.diagnostics === void 0 ? void 0 : valueBlock("Run diagnostics", record.diagnostics, style);
635
+ const moreLogs = result === void 0 ? 0 : Math.max(0, result.logs.length - shownLogCount);
636
+ const truncated = [input, targetBlock, value, evidence].some((block) => block?.truncated === true) || moreLogs > 0;
637
+ const rows = [
638
+ ["Run", [cell(record.runId)]],
639
+ ["Script", [cell(addressText(record.address, style))]],
640
+ [
641
+ "Status",
642
+ [
643
+ record.status === "pending" ? cell("pending; no result is recorded yet", style.yellow) : cell("complete")
644
+ ]
645
+ ],
646
+ ["Started", [cell(instant(record.startedAt))]],
647
+ ...record.finishedAt === void 0 ? [] : [["Finished", [cell(instant(record.finishedAt))]]],
648
+ ...target === void 0 ? [] : [
649
+ [
650
+ "Target",
651
+ [
652
+ cell(
653
+ target._tag === "user" ? `user \xB7 ${style.path(target.canonicalPath)}` : `project ${target.projectName} \xB7 ${style.path(target.canonicalPath)}`
654
+ )
655
+ ]
656
+ ]
657
+ ],
658
+ ...result === void 0 ? [] : [
659
+ outcomeFact(result.outcome, style),
660
+ ["Message", [cell(result.outcome.message)]],
661
+ ...finalizationFacts(result, style)
662
+ ]
663
+ ];
664
+ return frameView(envelope, style, {
665
+ body: [
666
+ factRows(rows, style),
667
+ input?.lines,
668
+ targetBlock?.lines,
669
+ value?.lines,
670
+ result === void 0 ? void 0 : [
671
+ style.bold("Logs"),
672
+ ...logSummary(result, style),
673
+ ...logLines(result, style),
674
+ ...moreLogs > 0 ? [` ${style.dim(`\u2026 ${plural2(moreLogs, "more event")} not shown`)}`] : []
675
+ ],
676
+ evidence?.lines,
677
+ truncated ? paragraph("Some values are cut to fit; --json prints the full record.", {
678
+ width: style.width
679
+ }) : void 0
680
+ ]
681
+ });
682
+ };
683
+ const historyClearView = removalView(
684
+ ({ plan, applied }, envelope, style) => frameView(envelope, style, {
685
+ body: [
686
+ statementLines(
687
+ applied !== void 0,
688
+ applied === void 0 ? plan.count === 0 ? [] : [`${plural2(plan.count, "run record")} would be removed`] : applied.removedCount === 0 ? [] : [
689
+ `${plural2(applied.removedCount, "run record")} removed${applied.removedCount === plan.count ? "" : ` (${plan.count} were planned)`}`
690
+ ],
691
+ applied === void 0 ? "There is no run history to clear." : plan.count === 0 ? "There was no run history to clear." : `No run records were removed (${plan.count} were planned).`,
692
+ style
693
+ )
694
+ ],
695
+ hints: applied === void 0 && plan.count > 0 ? [commandLine("script-history-clear", "--apply")] : []
696
+ })
697
+ );
698
+ return { historyListView, historyShowView, historyClearView };
699
+ };
700
+
701
+ // packages/extension-scripts/src/views/show-view.ts
702
+ init_define_TACK_BUILD_INFO();
703
+ var scriptShowViews = (kit) => {
704
+ const { cell, commandLine, factRows, frameView, table, withoutPayload } = kit;
705
+ const spelling = (argument) => {
706
+ const value = argument.type === "boolean" ? "" : argument.choices === void 0 ? ` <${argument.type}>` : ` ${argument.choices.join("|")}`;
707
+ return `--${argument.name}${value}${argument.multiple === true ? " ..." : ""}`;
708
+ };
709
+ const requirement = (argument) => argument.default !== void 0 ? `default ${typeof argument.default === "string" ? argument.default : JSON.stringify(argument.default)}` : argument.optional === true ? "optional" : "required";
710
+ const placeholder = (argument) => argument.type === "boolean" ? [`--${argument.name}`] : [
711
+ `--${argument.name}`,
712
+ argument.name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replaceAll("-", "_").toUpperCase()
713
+ ];
714
+ const isRequired = (argument) => argument.default === void 0 && argument.optional !== true;
715
+ const scriptShowView = (envelope, { result }, style) => {
716
+ if (envelope.result === null) return withoutPayload(envelope, style);
717
+ if (Option_exports.isNone(result) === true) return void 0;
718
+ const shown = result.value;
719
+ const required = shown.arguments.filter(isRequired);
720
+ return frameView(envelope, style, {
721
+ body: [
722
+ factRows(
723
+ [
724
+ ["Script", [cell(shown.address.name)]],
725
+ ["Description", [cell(shown.description)]],
726
+ ["File", [cell(shown.filePath)]]
727
+ ],
728
+ style
729
+ ),
730
+ [
731
+ style.bold("Arguments"),
732
+ ...shown.arguments.length === 0 ? [` ${style.dim("none")}`] : table(
733
+ shown.arguments.map((argument) => [
734
+ cell(spelling(argument)),
735
+ cell(requirement(argument)),
736
+ cell(argument.description ?? "")
737
+ ]),
738
+ { width: style.width }
739
+ )
740
+ ],
741
+ shown.secrets.length === 0 ? void 0 : [
742
+ style.bold("Secrets"),
743
+ ...table(
744
+ shown.secrets.map((secret) => [cell(secret), cell(`from TACK_${secret}`)]),
745
+ { width: style.width }
746
+ )
747
+ ]
748
+ ],
749
+ hints: [
750
+ commandLine(
751
+ "script-run",
752
+ shown.address.name,
753
+ ...required.length === 0 ? [] : ["--", ...required.flatMap(placeholder)]
754
+ )
755
+ ]
756
+ });
757
+ };
758
+ return { scriptShowView };
759
+ };
760
+
761
+ // packages/extension-scripts/src/failure.ts
762
+ init_define_TACK_BUILD_INFO();
763
+ var isScriptRunError = (error) => Predicate_exports.isTagged(error, "ExecutionError") || Predicate_exports.isTagged(error, "HistoryNotFoundError");
764
+ var scriptFailure = (error) => error._tag === "ExecutionError" ? new ExtensionFailure({
765
+ classification: (
766
+ // Coverage skip: only a clean run carries `success`, and a clean run raises no error.
767
+ /* v8 ignore next -- @preserve */
768
+ error.classification === "success" ? "internal" : error.classification
769
+ ),
770
+ code: error.code,
771
+ message: error.message,
772
+ details: {
773
+ stage: error.stage,
774
+ ...error.details === void 0 ? {} : { outcome: error.details }
775
+ }
776
+ }) : new ExtensionFailure({
777
+ classification: "domain",
778
+ code: "history-not-found",
779
+ message: "No retained run has this identifier.",
780
+ details: { runId: error.runId }
781
+ });
782
+ var withScriptFailures = (run) => run.pipe(Effect_exports.mapError((error) => isScriptRunError(error) ? scriptFailure(error) : error));
783
+
784
+ // packages/extension-scripts/src/commands.ts
785
+ var implement = implementFor();
786
+ var scriptTargetFlags = (request) => [
787
+ ...selectorFlags(request.selector),
788
+ ...request.root === void 0 ? [] : ["--root", request.root],
789
+ ...request.cwd === void 0 ? [] : ["--cwd", request.cwd]
790
+ ].map(shellWord);
791
+ var scriptRunOutcome = (outcome, result) => outcome.result(
792
+ result,
793
+ result.outcome.classification === "success" ? void 0 : {
794
+ failure: {
795
+ classification: result.outcome.classification,
796
+ code: result.outcome.code,
797
+ message: result.outcome.message,
798
+ details: {
799
+ stage: result.outcome.stage,
800
+ ...result.outcome.details === void 0 ? {} : { outcome: result.outcome.details }
801
+ }
802
+ }
803
+ }
804
+ );
805
+ var historyListOutcome = (outcome, list) => outcome.result(list, {
806
+ warnings: list.issues.length > 0 ? [
807
+ {
808
+ code: "history-partial",
809
+ details: { skipped: list.issues.length },
810
+ message: "Some retained run records could not be read; see the result issues."
811
+ }
812
+ ] : []
813
+ });
814
+ var scriptCommands = (kit) => {
815
+ const { historyClearView, historyListView, historyShowView } = historyViews(kit);
816
+ const { scriptRunView } = scriptRunViews(kit);
817
+ const { scriptShowView } = scriptShowViews(kit);
818
+ const showCommand = implement(scriptShow, {
819
+ run: (invocation, { stateOptions, outcome }) => withScriptFailures(
820
+ Effect_exports.gen(function* () {
821
+ const entry = yield* (yield* ScriptsHost).resolveScript(
822
+ stateOptions,
823
+ invocation.reference,
824
+ "tack script show"
825
+ );
826
+ return yield* describeScript(stateOptions, entry.address);
827
+ }).pipe(Effect_exports.map((described) => outcome.result(described)))
828
+ ),
829
+ view: scriptShowView
830
+ });
831
+ const runCommand = implement(scriptRun, {
832
+ // Its supervisor owns signals until history settles.
833
+ ownsInterruption: true,
834
+ run: (invocation, { stateOptions, outcome }) => withScriptFailures(
835
+ Effect_exports.gen(function* () {
836
+ const host = yield* ScriptsHost;
837
+ const selector = invocation.request.selector;
838
+ if (selector._tag === "project" && (yield* host.projectRegistered(stateOptions, selector.projectName)) === false)
839
+ return yield* new ExecutionError({
840
+ stage: "resolution",
841
+ code: "run_project_not_registered",
842
+ message: `Project "${selector.projectName}" is not registered. Run \`tack project\` to list registered projects and roots.`,
843
+ classification: "invalid-configuration",
844
+ details: { projectName: selector.projectName }
845
+ });
846
+ const entry = yield* host.resolveScript(
847
+ stateOptions,
848
+ invocation.reference,
849
+ "tack script run",
850
+ scriptTargetFlags(invocation.request)
851
+ );
852
+ return yield* runOperatorScript(stateOptions, {
853
+ ...invocation.request,
854
+ address: entry.address
855
+ });
856
+ }).pipe(
857
+ Effect_exports.flatMap(
858
+ (result) => Schema_exports.decodeUnknownEffect(RunResultSchema)(result).pipe(
859
+ Effect_exports.mapError(
860
+ () => new ExecutionError({
861
+ stage: "worker",
862
+ code: "run_result_invalid",
863
+ message: "The execution host returned an invalid run result.",
864
+ classification: "internal"
865
+ })
866
+ )
867
+ )
868
+ ),
869
+ Effect_exports.map((result) => scriptRunOutcome(outcome, result))
870
+ )
871
+ ),
872
+ view: scriptRunView
873
+ });
874
+ const historyListCommand = implement(scriptHistoryList, {
875
+ run: (invocation, { stateOptions, outcome }) => withScriptFailures(
876
+ listScriptHistory(stateOptions, {
877
+ limit: invocation.limit,
878
+ offset: invocation.offset
879
+ }).pipe(Effect_exports.map((list) => historyListOutcome(outcome, list)))
880
+ ),
881
+ view: historyListView
882
+ });
883
+ const historyShowCommand = implement(scriptHistoryShow, {
884
+ run: (invocation, { stateOptions, outcome }) => withScriptFailures(
885
+ showScriptHistory(stateOptions, invocation.runId).pipe(
886
+ Effect_exports.map((record) => outcome.result(record))
887
+ )
888
+ ),
889
+ view: historyShowView
890
+ });
891
+ const historyClearCommand = implement(scriptHistoryClear, {
892
+ run: (invocation, { stateOptions, outcome }) => withScriptFailures(
893
+ clearScriptHistory(stateOptions, invocation.apply).pipe(
894
+ Effect_exports.map((execution) => outcome.report(execution))
895
+ )
896
+ ),
897
+ view: historyClearView
898
+ });
899
+ return [
900
+ runCommand,
901
+ showCommand,
902
+ historyListCommand,
903
+ historyShowCommand,
904
+ historyClearCommand
905
+ ];
906
+ };
907
+
908
+ // packages/extension-scripts/src/slots.ts
909
+ init_define_TACK_BUILD_INFO();
910
+
911
+ // packages/extension-scripts/src/history-doctor.ts
912
+ init_define_TACK_BUILD_INFO();
913
+ var scriptsCheck = Effect_exports.fnUntraced(function* (state, next) {
914
+ const listed = yield* listScriptHistory(state, { limit: 1 }).pipe(
915
+ Effect_exports.map((history2) => ({ history: history2 })),
916
+ Effect_exports.catchTag("ExecutionError", (error) => Effect_exports.succeed({ error }))
917
+ );
918
+ if ("error" in listed)
919
+ return {
920
+ id: "scripts",
921
+ outcome: "failed",
922
+ message: `The retained script runs could not be listed: ${listed.error.message}`,
923
+ next: next(["tack", "script", "history"])
924
+ };
925
+ const { history } = listed;
926
+ if (history.issues.length > 0)
927
+ return {
928
+ id: "scripts",
929
+ outcome: "warning",
930
+ message: `${plural(history.issues.length, "retained script run record")} could not be read.`,
931
+ subjects: history.issues.map(({ path }) => path),
932
+ next: next(["tack", "script", "history"])
933
+ };
934
+ return history.total === 0 ? skippedCheck("scripts", "No script run is retained.") : {
935
+ id: "scripts",
936
+ outcome: "ok",
937
+ message: `${plural(history.total, "retained script run record")} can be read.`
938
+ };
939
+ });
940
+
941
+ // packages/extension-scripts/src/slots.ts
942
+ var scriptsSlots = {
943
+ id: "scripts",
944
+ doctorChecks: (state, _status, next) => Effect_exports.map(scriptsCheck(state, next), (check) => [check])
945
+ };
946
+
947
+ // packages/extension-scripts/src/types-command.ts
948
+ init_define_TACK_BUILD_INFO();
949
+
950
+ // packages/extension-scripts/src/script-types.ts
951
+ init_define_TACK_BUILD_INFO();
952
+ var import_picomatch = __toESM(require_picomatch(), 1);
953
+ var typesStubName = "tack-env.d.ts";
954
+ var typesStub = (api) => [
955
+ `// Generated by Tack ${api.version}: the script API that Tack provides at run time. Scripts import`,
956
+ `// "${api.packageName}" and install nothing. Run \`tack types --apply\` again after upgrading Tack.`,
957
+ `declare module "${api.packageName}" {`,
958
+ // Inside `declare module`, declarations are already ambient and take no `declare` keyword.
959
+ api.declarations.replace(/^(export )?declare /gm, "$1").trimEnd().replace(/^(?=.)/gm, " "),
960
+ "}",
961
+ ""
962
+ ].join("\n");
963
+ var generatedTsconfig = `${JSON.stringify(
964
+ {
965
+ compilerOptions: {
966
+ target: "es2022",
967
+ module: "preserve",
968
+ moduleResolution: "bundler",
969
+ allowImportingTsExtensions: true,
970
+ resolveJsonModule: true,
971
+ strict: true,
972
+ noEmit: true,
973
+ skipLibCheck: true
974
+ },
975
+ include: ["**/*.ts", typesStubName]
976
+ },
977
+ null,
978
+ 2
979
+ )}
980
+ `;
981
+ var TypesTargetError = class extends Schema_exports.TaggedError()("TypesTargetError", {
982
+ directory: Schema_exports.String
983
+ }) {
984
+ };
985
+ var TsconfigScopeSchema = Schema_exports.Struct({
986
+ include: Schema_exports.optionalKey(Schema_exports.Array(Schema_exports.String)),
987
+ files: Schema_exports.optionalKey(Schema_exports.Array(Schema_exports.String))
988
+ });
989
+ var tsconfigCovers = (text) => {
990
+ let parsed;
991
+ try {
992
+ parsed = JSON.parse(text);
993
+ } catch {
994
+ return void 0;
995
+ }
996
+ const scope = Schema_exports.decodeUnknownOption(TsconfigScopeSchema)(parsed);
997
+ if (scope._tag === "None") return void 0;
998
+ const { include, files } = scope.value;
999
+ if (include === void 0 && files === void 0) return true;
1000
+ return (files ?? []).some((file) => file.replace(/^\.\//, "") === typesStubName) || (include ?? []).some(
1001
+ (pattern) => import_picomatch.default.isMatch(typesStubName, pattern.replace(/^\.\//, ""), { dot: true })
1002
+ );
1003
+ };
1004
+ var writeTypes = Effect_exports.fn("execution.writeTypes")(
1005
+ function* (directory, api, apply) {
1006
+ const fs = yield* FileSystem_exports.FileSystem;
1007
+ const path = yield* Path_exports.Path;
1008
+ const root = path.resolve(directory);
1009
+ if ((yield* fs.exists(path.join(root, declarationFileName))) === false)
1010
+ return yield* new TypesTargetError({ directory: root });
1011
+ const stubPath = path.join(root, typesStubName);
1012
+ const stub = typesStub(api);
1013
+ const current = (yield* fs.exists(stubPath)) ? yield* fs.readFileString(stubPath) : void 0;
1014
+ const stubAction = current === void 0 ? "create" : current === stub ? "unchanged" : "update";
1015
+ const tsconfigPath = path.join(root, "tsconfig.json");
1016
+ const tsconfig = (yield* fs.exists(tsconfigPath)) ? yield* fs.readFileString(tsconfigPath) : void 0;
1017
+ if (apply === true) {
1018
+ if (stubAction !== "unchanged") yield* fs.writeFileString(stubPath, stub);
1019
+ if (tsconfig === void 0) yield* fs.writeFileString(tsconfigPath, generatedTsconfig);
1020
+ }
1021
+ return {
1022
+ directory: root,
1023
+ files: [
1024
+ { path: stubPath, action: stubAction },
1025
+ { path: tsconfigPath, action: tsconfig === void 0 ? "create" : "keep" }
1026
+ ],
1027
+ inScope: tsconfig === void 0 ? true : tsconfigCovers(tsconfig) ?? null
1028
+ };
1029
+ },
1030
+ (effect, directory) => effect.pipe(
1031
+ Effect_exports.catchTag(
1032
+ "PlatformError",
1033
+ (error) => Effect_exports.flatMap(
1034
+ ScriptsHost,
1035
+ (host) => Effect_exports.fail(host.sourceFileFailure("write editor types", directory, error))
1036
+ )
1037
+ )
1038
+ )
1039
+ );
1040
+
1041
+ // packages/extension-scripts/src/views/types-view.ts
1042
+ init_define_TACK_BUILD_INFO();
1043
+ var typesViews = (kit) => {
1044
+ const { cell, commandLine, factRows, frameView, table, withoutPayload } = kit;
1045
+ const planned = {
1046
+ create: "create",
1047
+ update: "update",
1048
+ unchanged: "unchanged",
1049
+ keep: "keep as is"
1050
+ };
1051
+ const done = {
1052
+ create: "created",
1053
+ update: "updated",
1054
+ unchanged: "unchanged",
1055
+ keep: "kept as is"
1056
+ };
1057
+ const typesView = (envelope, payloads, style) => {
1058
+ const applied = envelope.applied !== null;
1059
+ const plan = Option_exports.getOrUndefined(applied ? payloads.applied : payloads.plan);
1060
+ if (plan === void 0) return withoutPayload(envelope, style);
1061
+ const writes = plan.files.some(({ action }) => action === "create" || action === "update");
1062
+ return frameView(envelope, style, {
1063
+ body: [
1064
+ factRows([["Source", [cell(style.path(plan.directory))]]], style),
1065
+ [
1066
+ style.bold(applied ? "Files" : "Plan"),
1067
+ ...table(
1068
+ plan.files.map(({ path, action }) => [
1069
+ cell((applied ? done : planned)[action]),
1070
+ cell(style.path(path))
1071
+ ]),
1072
+ { width: style.width }
1073
+ )
1074
+ ]
1075
+ ],
1076
+ hints: applied || writes === false ? [] : [commandLine("types", plan.directory, "--apply")]
1077
+ });
1078
+ };
1079
+ return { typesView };
1080
+ };
1081
+
1082
+ // packages/extension-scripts/src/types-command.ts
1083
+ var implement2 = implementFor();
1084
+ var scopeWarnings = (plan) => plan.inScope === true ? [] : [
1085
+ {
1086
+ code: "types-stub-out-of-scope",
1087
+ message: plan.inScope === false ? `tsconfig.json does not include ${typesStubName}. Add "${typesStubName}" to its "include" list, or the editor will not know the "@tackup/cli" import.` : `Tack could not read tsconfig.json. Check that it includes ${typesStubName}, or the editor will not know the "@tackup/cli" import.`,
1088
+ details: { path: plan.files[1]?.path ?? null }
1089
+ }
1090
+ ];
1091
+ var typesCommand = (kit) => {
1092
+ const { typesView } = typesViews(kit);
1093
+ return implement2(types, {
1094
+ stateless: true,
1095
+ view: typesView,
1096
+ run: ({ path, apply }, { outcome }) => Effect_exports.gen(function* () {
1097
+ const plan = yield* writeTypes(path ?? ".", (yield* ScriptsHost).scriptApi, apply);
1098
+ return outcome.report(apply ? { plan, applied: plan } : { plan }, {
1099
+ warnings: scopeWarnings(plan)
1100
+ });
1101
+ }).pipe(
1102
+ Effect_exports.catchIf(
1103
+ (error) => error instanceof TypesTargetError,
1104
+ (error) => Effect_exports.fail(
1105
+ new ExtensionFailure({
1106
+ classification: "invalid-configuration",
1107
+ code: "types-not-a-source",
1108
+ message: `${error.directory} has no tack.yaml. Run tack types in a source folder, or pass its path.`,
1109
+ details: { directory: error.directory }
1110
+ })
1111
+ )
1112
+ )
1113
+ )
1114
+ });
1115
+ };
1116
+
1117
+ // packages/extension-scripts/src/index.ts
1118
+ var scriptsExtension = {
1119
+ id: "scripts",
1120
+ commands: (kit) => [...scriptCommands(kit), typesCommand(kit)],
1121
+ slots: scriptsSlots
1122
+ };
1123
+ var src_default = scriptsExtension;
1124
+ export {
1125
+ src_default as default
1126
+ };