Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6923a71376 | ||
|
|
44499ae62f | ||
|
|
76f7bd1e57 | ||
|
|
0273d5d63b | ||
|
|
b4680cbfd0 | ||
|
|
f7bcc489f9 | ||
|
|
d60f6e971f | ||
|
|
ad25d0b247 | ||
|
|
89c5a192f4 | ||
|
|
23b5502217 | ||
|
|
a17cbc3b40 | ||
|
|
5719e8ac40 | ||
|
|
c8cf535780 | ||
|
|
38cfc25e54 | ||
|
|
41a430a88e | ||
|
|
9b5063bcd4 | ||
|
|
0ed495a122 | ||
|
|
ece05087a7 | ||
|
|
a7ee3092c3 | ||
|
|
f7cc776488 | ||
|
|
15e875a2d9 | ||
|
|
5d173547ff | ||
|
|
202e5609ff | ||
|
|
bb38c3320d | ||
|
|
6b9a5987f6 | ||
|
|
fc3f78f5d9 | ||
|
|
2f41c073a2 | ||
|
|
51672b6ecb | ||
|
|
67a7b1a1d3 | ||
|
|
ce467da9cf | ||
|
|
6ef7aa8399 | ||
|
|
193e3c62e6 | ||
|
|
91dfe60a99 | ||
|
|
edb12401e5 | ||
|
|
79fe11bc1c | ||
|
|
b3e51317e4 | ||
|
|
ddd5a46f39 | ||
|
|
88c69ffff6 | ||
|
|
979854895c | ||
|
|
9cbe50d10d | ||
|
|
9d9208cec5 | ||
|
|
57100fba85 | ||
|
|
3afb4a9ef9 | ||
|
|
315b27385d | ||
|
|
719c905eac | ||
|
|
0542abc75e | ||
|
|
7609495bf7 | ||
|
|
b41e89eba9 | ||
|
|
4d83436415 | ||
|
|
e51538b812 | ||
|
|
1c9a6de26e | ||
|
|
fbd77420f2 | ||
|
|
16491a84b9 | ||
|
|
b44ed835c6 | ||
|
|
9c9916aefe | ||
|
|
936394b6f2 | ||
|
|
c38225ef1c | ||
|
|
39cd15b954 | ||
|
|
160d97f403 | ||
|
|
d330759f58 | ||
|
|
5961d36769 | ||
|
|
0b1ce58824 | ||
|
|
10da67b9da | ||
|
|
6e5df67f15 | ||
|
|
29b1abc45e | ||
|
|
14b6bfdf15 | ||
|
|
b6a2563db7 | ||
|
|
c5ff51ec1f | ||
|
|
2d31cb022d | ||
|
|
bc9428a06a | ||
|
|
593289c3c7 | ||
|
|
ab4a88386d | ||
|
|
78a0ea55c1 | ||
|
|
9a0a07167f | ||
|
|
9fe4832a3f | ||
|
|
376c149eac | ||
|
|
7e2bb47504 | ||
|
|
18fa89c4ad | ||
|
|
f74eb62661 | ||
|
|
e5fba263e6 | ||
|
|
18b468871e | ||
|
|
020179c19a | ||
|
|
571a8b44bd | ||
|
|
b6e1b39335 | ||
|
|
c7b21ff172 | ||
|
|
4e09cddb40 | ||
|
|
783692afc1 | ||
|
|
aa5ec80364 | ||
|
|
282ecb3178 | ||
|
|
32c6012dab | ||
|
|
6f34ad3e87 | ||
|
|
62cf461759 | ||
|
|
23c18fda7a | ||
|
|
c0bb237345 | ||
|
|
5d34f9ff23 | ||
|
|
c8a04bd59b | ||
|
|
db4b2d8a0f | ||
|
|
2c199aacac | ||
|
|
8ca4eec9ca | ||
|
|
0936fd271f | ||
|
|
fa69f05b69 | ||
|
|
c710167bde | ||
|
|
a135f2c2d3 | ||
|
|
946b867666 | ||
|
|
0ca3240691 | ||
|
|
f4da4f3b40 | ||
|
|
b6d9ce325c | ||
|
|
8e3467fe60 | ||
|
|
2fae0d0ac3 | ||
|
|
08993a5ec8 | ||
|
|
501ce27b81 | ||
|
|
40c0ab0883 | ||
|
|
33f1cb4224 | ||
|
|
d266c068d0 | ||
|
|
5fcfe242c1 | ||
|
|
df65a6c3ad | ||
|
|
3235658c08 | ||
|
|
749baec353 | ||
|
|
d7baa37e5c | ||
|
|
68ea280388 | ||
|
|
dfbda84362 | ||
|
|
78485e6d50 | ||
|
|
63b6b44627 | ||
|
|
3795dbb017 | ||
|
|
2640e6dcfc | ||
|
|
e34250df46 | ||
|
|
7e1a0d551c | ||
|
|
b511227b7a | ||
|
|
69c8be2ee5 | ||
|
|
271454cbd2 | ||
|
|
e8ff6bc7f8 | ||
|
|
398140a9bd | ||
|
|
2b180a2b2d | ||
|
|
7a820abfdd | ||
|
|
53e3c98a55 | ||
|
|
4f11740510 | ||
|
|
1735e27d9e | ||
|
|
ebe8afb1df | ||
|
|
bf76535fe4 | ||
|
|
5c66110e26 | ||
|
|
da3c2030f7 | ||
|
|
0506508e9b | ||
|
|
b859a575d1 | ||
|
|
e63403fe92 | ||
|
|
c0e161af06 | ||
|
|
d0b9f8d40d | ||
|
|
d8b12ae801 | ||
|
|
31caa5652b | ||
|
|
e350c0a07b | ||
|
|
38e0bb07bb | ||
|
|
765e1b5fc0 | ||
|
|
03e20c875c | ||
|
|
2318e00270 | ||
|
|
4cfec8c128 | ||
|
|
1bd2fa25e2 | ||
|
|
5ca32661b7 | ||
|
|
8b33799523 | ||
|
|
24f9c2a08e | ||
|
|
31ca9e5531 | ||
|
|
73bf127d71 | ||
|
|
43e2aeab38 | ||
|
|
b655a9f183 | ||
|
|
4e3f2f04d5 | ||
|
|
1047dac0c5 | ||
|
|
143b9c9280 | ||
|
|
cf58cadd02 | ||
|
|
6a17629670 | ||
|
|
7b8d12618b | ||
|
|
bcd640bf4d | ||
|
|
b49a2e677c | ||
|
|
ed81c156da | ||
|
|
7dc75127c2 | ||
|
|
e057e2e985 | ||
|
|
a7f6d97b94 | ||
|
|
f9a4f59930 | ||
|
|
7f1cb61031 | ||
|
|
c49d424e3a | ||
|
|
4804a9824f | ||
|
|
0748134cec | ||
|
|
6e9987cf17 | ||
|
|
8b5469863a | ||
|
|
58302b2010 | ||
|
|
1f2797325b | ||
|
|
c14a5ca492 | ||
|
|
eb733c10f2 | ||
|
|
8a02c71861 | ||
|
|
fdca15471d | ||
|
|
5d68fca8f2 | ||
|
|
2a33a18716 | ||
|
|
bde0a4c0dd | ||
|
|
54f167e2e0 | ||
|
|
d114e2772d | ||
|
|
0418301de7 | ||
|
|
5e8b2c800e | ||
|
|
b98233702c | ||
|
|
ecb35f7583 | ||
|
|
d359789ed4 | ||
|
|
462442667e | ||
|
|
c69120f484 | ||
|
|
7b928d5488 | ||
|
|
2fdc704bbb | ||
|
|
3513fa04fb | ||
|
|
735240f316 | ||
|
|
8de254a685 | ||
|
|
c1ec1915fc | ||
|
|
619b0ece94 | ||
|
|
ef943a26ab | ||
|
|
f61fa9499d | ||
|
|
8619ef22e9 | ||
|
|
843cf176ea | ||
|
|
ca1e08b5a0 | ||
|
|
2250e3ee7a | ||
|
|
3201e00ad4 | ||
|
|
e9127658a6 | ||
|
|
18a41388eb | ||
|
|
0c66565854 | ||
|
|
e775bc6228 | ||
|
|
03ac1f0cd9 | ||
|
|
7778a1cea7 | ||
|
|
dad0889766 | ||
|
|
b9cc8d6ef1 | ||
|
|
0e0040832c | ||
|
|
cd8b9fc8b3 | ||
|
|
fa6073e2e1 | ||
|
|
4eb1b57933 | ||
|
|
4414f922fe | ||
|
|
6e42231cb1 | ||
|
|
bdf5aed665 | ||
|
|
0b62e2eb11 | ||
|
|
f9727d0853 | ||
|
|
d8e0ba3ea0 | ||
|
|
32e7844837 | ||
|
|
482d56233d | ||
|
|
6009720844 | ||
|
|
e26e55f389 | ||
|
|
4ac094fef6 | ||
|
|
a7e43b2281 | ||
|
|
cabc93bad3 | ||
|
|
5cda815626 | ||
|
|
32d17d3db5 | ||
|
|
6d35a87c5d | ||
|
|
7b9eef7ac2 | ||
|
|
9d66b104fe | ||
|
|
51ea084c87 | ||
|
|
0615fd7df1 | ||
|
|
2448212367 | ||
|
|
fda6486233 | ||
|
|
a9b1190a11 | ||
|
|
44fb34ad53 | ||
|
|
6245c547c2 | ||
|
|
24abab789e | ||
|
|
52b04b947e | ||
|
|
e9ed70c5b9 | ||
|
|
ffae5410e8 | ||
|
|
31dfe3596e | ||
|
|
c2776c2336 | ||
|
|
22f021ed69 | ||
|
|
a4964b3b36 | ||
|
|
c6c64918f8 | ||
|
|
4abf8b46c5 | ||
|
|
3083d712ee | ||
|
|
6672a1d210 | ||
|
|
92e54fb96c | ||
|
|
8cc9a6fa6b | ||
|
|
b2d17b7108 | ||
|
|
fb1034546f | ||
|
|
f5f98cf0ae | ||
|
|
37ac970e28 | ||
|
|
8919ae7c53 | ||
|
|
c1e2408e1f | ||
|
|
8b993bc9ff | ||
|
|
ea52bb1dbd | ||
|
|
28107e89c2 | ||
|
|
82a9bcc7f4 | ||
|
|
61f8d46fa2 | ||
|
|
0debebafbb | ||
|
|
2a29de7502 | ||
|
|
8c1605b383 | ||
|
|
90074e359f | ||
|
|
6155f5cf64 | ||
|
|
e3970e755b | ||
|
|
3c246f56b4 | ||
|
|
cebbe6ff19 | ||
|
|
e4a84a348e | ||
|
|
61e6d89d69 | ||
|
|
1b2f39d018 | ||
|
|
8c2d33abde | ||
|
|
60dc4af916 | ||
|
|
d389cfd4e3 | ||
|
|
6fc79737c3 | ||
|
|
cdd03591ef | ||
|
|
2fbb0565d7 | ||
|
|
a3dadc04bf | ||
|
|
1a59277dc8 | ||
|
|
6424197a19 | ||
|
|
8d4a8b4f31 | ||
|
|
23ab75e84a | ||
|
|
0488e47d9c | ||
|
|
0eba548282 | ||
|
|
68c0dd3b70 | ||
|
|
4cd958445f | ||
|
|
9f7861aadd | ||
|
|
9243ead1c3 | ||
|
|
803c2b7738 | ||
|
|
28e7c9ae17 | ||
|
|
a9460bb772 | ||
|
|
5edf7c56ba | ||
|
|
90dc76b11e | ||
|
|
57d25c934b | ||
|
|
a26f0dc89f | ||
|
|
6ff6c13fc8 | ||
|
|
60c9ca0e33 | ||
|
|
ad2cb1dd57 | ||
|
|
674590e009 | ||
|
|
f2cb14e774 | ||
|
|
e042c25f56 | ||
|
|
90f1936fad | ||
|
|
42ff43915a | ||
|
|
834e5db458 | ||
|
|
8ce627ba91 | ||
|
|
9a78c6f2ba | ||
|
|
aab72f10c1 | ||
|
|
a76b7bbfb5 | ||
|
|
a51691a9b0 | ||
|
|
97de7d7e15 | ||
|
|
d7718e81e0 | ||
|
|
b88873508e | ||
|
|
58053d146b | ||
|
|
50767683b3 | ||
|
|
d1339f3846 | ||
|
|
faccdd4ca9 | ||
|
|
dd48bfd98c | ||
|
|
6d8d995621 | ||
|
|
b6c590af38 | ||
|
|
b51aef10c4 | ||
|
|
fc2cdeceb9 | ||
|
|
c637dfc454 | ||
|
|
6e9b43cb84 | ||
|
|
be56fa43b0 | ||
|
|
eb5eb0d9fa | ||
|
|
621616268a | ||
|
|
630df6b986 | ||
|
|
569b3e5959 | ||
|
|
d7ff7e7333 | ||
|
|
bd8e3ee008 | ||
|
|
c1d8a22f07 | ||
|
|
7b791895ad | ||
|
|
4c16c66368 | ||
|
|
4407a5a6b7 | ||
|
|
c7b375e9b0 | ||
|
|
abc253d97d | ||
|
|
ce11e6facd | ||
|
|
f1052dd8b1 | ||
|
|
e85144a58c | ||
|
|
defd9dfe20 | ||
|
|
8c03188c1c | ||
|
|
3e5f9f2cdd | ||
|
|
6888276f19 | ||
|
|
e06c33c38d | ||
|
|
5f860439e9 | ||
|
|
c9159b67b3 | ||
|
|
a1b727f62d | ||
|
|
fdc1e8b3a2 | ||
|
|
c8454ad88a | ||
|
|
336d176027 | ||
|
|
204984bf8c | ||
|
|
be4a38e578 | ||
|
|
f50a7cddc1 | ||
|
|
97487d9959 | ||
|
|
d2e38c5373 | ||
|
|
90bd5ee0c1 | ||
|
|
430ece4c0a | ||
|
|
4238a0e769 | ||
|
|
ff0f702c7c | ||
|
|
1cbe8a7a90 | ||
|
|
46fdc769d9 | ||
|
|
0cd0ed1a3d | ||
|
|
d53237cbd1 | ||
|
|
0e718855b8 | ||
|
|
731b1a67ac | ||
|
|
cdfecb36a6 | ||
|
|
f4ef356215 | ||
|
|
d60f5c6101 | ||
|
|
eacceb9e7b | ||
|
|
13a4789a5d | ||
|
|
b6e384fb27 | ||
|
|
d8bf307d22 | ||
|
|
d512deac84 | ||
|
|
32c7f90d9e | ||
|
|
2c16edd0cb | ||
|
|
708bc7091d | ||
|
|
7eb7b4f4a3 | ||
|
|
e01b1903de | ||
|
|
1dc36cef73 | ||
|
|
833c8ab7c6 | ||
|
|
5b1b35c773 | ||
|
|
ee3e2dae78 | ||
|
|
9c98cd60e8 | ||
|
|
48f88d5220 | ||
|
|
2910d9ff01 | ||
|
|
2b8e012924 | ||
|
|
49c23221d8 | ||
|
|
5ca7676661 | ||
|
|
c3e3e26844 | ||
|
|
1486a4a2b9 | ||
|
|
1e5f62801b | ||
|
|
ed6ba7439d | ||
|
|
f98448e872 | ||
|
|
bfe61741b8 | ||
|
|
4d3fcacd84 | ||
|
|
4d790f0064 | ||
|
|
3ecf3685ba | ||
|
|
716ae73c40 | ||
|
|
300d4d566a | ||
|
|
53a477c2e9 | ||
|
|
d84ebe8319 | ||
|
|
5a2c92e86d | ||
|
|
61aade9ea4 | ||
|
|
04f82ae1f3 | ||
|
|
ce0c20b840 | ||
|
|
fccecd8749 | ||
|
|
30a084c463 | ||
|
|
9d5ca2cb7c | ||
|
|
ac77fe452b | ||
|
|
4fbc4f9b20 | ||
|
|
779c237487 | ||
|
|
350e229f7a | ||
|
|
8112aff7c2 | ||
|
|
b9e22de6a3 | ||
|
|
f3b43a148b | ||
|
|
8331511b97 | ||
|
|
08650a7424 | ||
|
|
40d14647db | ||
|
|
cc69aef4dd | ||
|
|
71608142c2 | ||
|
|
bf1a6501c7 | ||
|
|
f7867addbe | ||
|
|
7a8bab5d9d | ||
|
|
06752526b3 | ||
|
|
d87ec967bf | ||
|
|
e55dd0067d | ||
|
|
8c3755aecc | ||
|
|
b4fe8faa1d | ||
|
|
515303edf2 | ||
|
|
20734d4a78 | ||
|
|
86db35ca61 | ||
|
|
97e5cd3bf7 | ||
|
|
b19fc1b87b | ||
|
|
2fa37ec183 | ||
|
|
db27502aff | ||
|
|
6c5fb7930d | ||
|
|
30acfa9c51 | ||
|
|
f58b6da230 | ||
|
|
9a1c4875a3 | ||
|
|
7eda6ba5fc | ||
|
|
c00e721c04 | ||
|
|
b0a3a50448 | ||
|
|
79c57170c7 | ||
|
|
3900c45f25 | ||
|
|
8d61172f8b | ||
|
|
dc82f792c3 | ||
|
|
335e0b59ea | ||
|
|
2fbbe68c24 | ||
|
|
65385c0281 | ||
|
|
6d2dae0627 | ||
|
|
10a8d3fbd9 | ||
|
|
0ad1e9d9e4 | ||
|
|
2f8d3baa88 | ||
|
|
6b74476322 | ||
|
|
d9e9539862 | ||
|
|
7118e43d16 | ||
|
|
4e8ee13d8f | ||
|
|
b17b6d50c5 | ||
|
|
ccf8331600 | ||
|
|
ffae12f329 | ||
|
|
01cd564557 | ||
|
|
4ee719a094 | ||
|
|
01492ebd3b | ||
|
|
93fd972108 | ||
|
|
df1540f3ac | ||
|
|
d5a72d5be1 | ||
|
|
742dd7af0d | ||
|
|
5c1ac92257 | ||
|
|
8bfdacf206 | ||
|
|
b6302784f8 | ||
|
|
9544e72d08 | ||
|
|
938b19a6bb | ||
|
|
3b56dc17a5 | ||
|
|
d2c0a6a48f | ||
|
|
1cf3647da6 | ||
|
|
53d0107759 | ||
|
|
60b16d1f28 | ||
|
|
ab0baaa886 | ||
|
|
753bc4672d | ||
|
|
e29ad7604b | ||
|
|
cdaba7fa8b | ||
|
|
fbf6263876 | ||
|
|
c08b968f4e | ||
|
|
d9f59be704 | ||
|
|
a4446e263d | ||
|
|
494350cc0b | ||
|
|
7dc182337c | ||
|
|
13917df1fe | ||
|
|
5d4e2fae01 | ||
|
|
3e01c4bc57 | ||
|
|
20f37f367a | ||
|
|
804d44cfb1 | ||
|
|
0651af92b8 | ||
|
|
52a24c8902 | ||
|
|
30034ecedc | ||
|
|
1fcc57af13 | ||
|
|
e95b57dc26 | ||
|
|
3bdaa6e100 | ||
|
|
b7b00bfb9d | ||
|
|
ae2b523503 | ||
|
|
75b3b3c48a | ||
|
|
b489ea52a8 | ||
|
|
3a5ec9464b | ||
|
|
e56bb200fa | ||
|
|
c2ca9de33a | ||
|
|
60b546cf01 | ||
|
|
4b73827334 | ||
|
|
a5efb7cb6b | ||
|
|
8f9911f79d | ||
|
|
689a882045 | ||
|
|
85fe62d402 | ||
|
|
708d5383a9 | ||
|
|
5cd2744100 | ||
|
|
d12da198ad | ||
|
|
d0a7d18cdb | ||
|
|
71ea5fa1ab | ||
|
|
9d5e632d4d | ||
|
|
c2d44a312c | ||
|
|
de8bdc10fa | ||
|
|
477795697d | ||
|
|
a23b83314e | ||
|
|
ce90563709 | ||
|
|
31e68229d6 | ||
|
|
1db585878e | ||
|
|
56e57de947 | ||
|
|
3a0623f1cd | ||
|
|
cd91ec75f3 | ||
|
|
d4ba9e9618 | ||
|
|
c1792bc9a6 | ||
|
|
1b4317ec35 | ||
|
|
f452d63fef | ||
|
|
18a49abcec | ||
|
|
85d5df6256 | ||
|
|
b5b769dddf | ||
|
|
3c7862edd7 | ||
|
|
d8fe3d72c8 | ||
|
|
70ec39ae80 | ||
|
|
3d9e8dea7d | ||
|
|
f7c422d581 | ||
|
|
dd739c880d | ||
|
|
6c6740e381 | ||
|
|
29150b5736 | ||
|
|
07c6d70b91 | ||
|
|
50bc18b208 | ||
|
|
63d42a5e58 | ||
|
|
9b43123ba2 | ||
|
|
17fb0e4a9a | ||
|
|
43e8bbd7ae | ||
|
|
52c77c1ec4 | ||
|
|
d6eb386e3d | ||
|
|
d25090cf6d | ||
|
|
ae39bacf0e | ||
|
|
1ea17026ee | ||
|
|
649f4328ea | ||
|
|
7db034905b | ||
|
|
57f6bf7edb | ||
|
|
0baf1986e8 | ||
|
|
ae7e88b0e0 | ||
|
|
1916ac6d55 | ||
|
|
343061a053 | ||
|
|
0b40ea62e1 | ||
|
|
a4757c2656 | ||
|
|
3efabdcd3a | ||
|
|
c5f7cd40ba | ||
|
|
e2db800f7c | ||
|
|
31533466b0 | ||
|
|
7f741a56d1 | ||
|
|
cc9e81ac93 | ||
|
|
238715fd6f | ||
|
|
b03bc4b52d | ||
|
|
aca14507f7 | ||
|
|
04f7f32ace | ||
|
|
a3422a9bb5 | ||
|
|
22f9f3058b | ||
|
|
983a8c7fa6 | ||
|
|
de58ec8e24 | ||
|
|
8e6f4229da | ||
|
|
38ea6d483e | ||
|
|
0e4a43519f | ||
|
|
3ea6adf17d | ||
|
|
a56496c7f2 | ||
|
|
b76f161d55 | ||
|
|
75257d64e9 | ||
|
|
e1ce9f8500 | ||
|
|
602148f8fe | ||
|
|
92be60e7c1 | ||
|
|
0d6e9e9add | ||
|
|
8ab58a0b26 | ||
|
|
6f42bd9c88 | ||
|
|
5b26bd408b | ||
|
|
c04d15d3be | ||
|
|
9da430c828 | ||
|
|
a084fbbc0a | ||
|
|
b870a6e349 | ||
|
|
e1cb19b55b | ||
|
|
94fc117561 | ||
|
|
113b9d84c7 | ||
|
|
f60def2054 | ||
|
|
eda163ca17 | ||
|
|
3579005114 | ||
|
|
af3dfd229e | ||
|
|
969e6d274c | ||
|
|
769bdd251d | ||
|
|
295b9db113 | ||
|
|
b5a62504d4 | ||
|
|
ec18938bf9 | ||
|
|
5ae77c0d63 | ||
|
|
300f7fd11d | ||
|
|
53042f47f8 | ||
|
|
6ce6f678b5 | ||
|
|
a74dfd4f3c | ||
|
|
49c1b64687 | ||
|
|
dfdb5a46db | ||
|
|
b0fa60a121 | ||
|
|
348a9140e9 | ||
|
|
9fc485afaf | ||
|
|
a6edad1974 | ||
|
|
203f58e456 | ||
|
|
52ae8e88df | ||
|
|
80b40ce96a | ||
|
|
4c262c4b4e | ||
|
|
4f3d00f063 | ||
|
|
37bf0f0d1d | ||
|
|
6a1c4da528 | ||
|
|
dca93d0ee8 | ||
|
|
1288909b66 | ||
|
|
30d36b8c48 | ||
|
|
e4643eccc7 | ||
|
|
4956415f7f | ||
|
|
f5849f7d78 | ||
|
|
6e6163255d | ||
|
|
b440dd1812 | ||
|
|
d78e02cd0b | ||
|
|
f0116e44b6 | ||
|
|
bd851c0203 | ||
|
|
a04c09a190 | ||
|
|
e3f1405884 | ||
|
|
b3e8c0334b | ||
|
|
e3accd6e95 | ||
|
|
cf07d06321 | ||
|
|
31268945f8 | ||
|
|
6b3050ee74 | ||
|
|
83f0cc9e31 | ||
|
|
e6330ead82 | ||
|
|
4f0f24f055 | ||
|
|
d1e85c4e8f | ||
|
|
ea20e80021 | ||
|
|
9e632f5cec | ||
|
|
4120e94598 | ||
|
|
34bb18c8cf | ||
|
|
90eea047a9 | ||
|
|
f92e1e1b06 | ||
|
|
556c42452c | ||
|
|
7e20b23e7e | ||
|
|
b83e9c95e4 | ||
|
|
a41f4895ce | ||
|
|
d15909af15 | ||
|
|
447236d51f | ||
|
|
5165b8c333 | ||
|
|
8fc317939f | ||
|
|
16c69ba7ff | ||
|
|
e64c19f1af | ||
|
|
6ab8f93a23 | ||
|
|
b793401aee | ||
|
|
3c32bc8fd1 | ||
|
|
6efdf67e15 | ||
|
|
39371c6012 | ||
|
|
99efaa0faa | ||
|
|
6b9feb1bd3 | ||
|
|
e0f3abd1a4 | ||
|
|
34ec8a86fb | ||
|
|
932df4ed17 | ||
|
|
63859aa072 | ||
|
|
7bfacd55d8 | ||
|
|
271d65e047 | ||
|
|
aa8b9f2286 | ||
|
|
073eb389d3 | ||
|
|
825263b6f9 | ||
|
|
25b02f4ba2 |
No files matched your search
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) OpenAI
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
name: ios-debugger-agent
|
||||
description: Build, launch, inspect, and drive iOS apps with the repository-configured XcodeBuildMCP server. Use on macOS for iOS Simulator builds, focused native test runs, semantic UI automation, screenshots, logs, or debugging, including T3 Code Mobile verification.
|
||||
---
|
||||
|
||||
# iOS Debugger Agent
|
||||
|
||||
Use the repository-configured `xcodebuildmcp` tools instead of requiring a globally installed Codex plugin. Prefer MCP tools over raw `xcodebuild`, `xcrun`, or `simctl` when the client exposes them.
|
||||
|
||||
## Confirm availability
|
||||
|
||||
This workflow requires macOS 14.5 or newer, Xcode 16 or newer, and Node.js 18 or newer. The repository pins XcodeBuildMCP in both `.mcp.json` for Claude Code and `.codex/config.toml` for Codex. Project MCP servers may require one-time trust or approval followed by a new session.
|
||||
|
||||
If the tools are missing:
|
||||
|
||||
1. Confirm the repository is trusted and its project MCP server was approved.
|
||||
2. Restart or recreate the agent session after approving configuration.
|
||||
3. Run `npx --yes [email protected] doctor` when the server starts but simulator or UI-automation tools are unavailable. Follow its actionable Xcode or AXe setup guidance.
|
||||
4. Fall back to the pinned XcodeBuildMCP CLI or native Apple CLIs only when the current agent client cannot expose project MCP tools.
|
||||
|
||||
Do not ask contributors to install the OpenAI `build-ios-apps` plugin globally.
|
||||
|
||||
## Establish one simulator context
|
||||
|
||||
1. Call `session_show_defaults` before discovery, build, launch, or UI work.
|
||||
2. Call `list_sims` and select one explicit simulator UDID. Prefer a simulator that is already booted; boot an installed simulator when verification requires it, but do not create or download runtimes without user authorization.
|
||||
3. Call `session_set_defaults` with the project or workspace, scheme, Debug configuration, simulator ID, and bundle identifier when known.
|
||||
4. Keep every subsequent build, launch, screenshot, log capture, and UI action pinned to that same UDID.
|
||||
|
||||
Avoid generic Mac window automation for switching among Simulator windows. Explicit device identity is more reliable.
|
||||
|
||||
## Choose build or launch
|
||||
|
||||
- Use `build_run_sim` when native source, native dependencies, entitlements, or project configuration changed.
|
||||
- Use `test_sim` for the smallest relevant native test target or test cases; do not run an entire workspace test matrix routinely.
|
||||
- Use `launch_app_sim` when a compatible app is already installed and no native rebuild is needed.
|
||||
- To reuse an existing build artifact, use `get_sim_app_path` or `get_app_bundle_id`, install it with `install_app_sim` when necessary, and then launch it.
|
||||
- Do not run a build-only action immediately before `build_run_sim` unless the task requires both artifacts.
|
||||
|
||||
After launch, call `snapshot_ui` or `screenshot` before interacting. An open Simulator window alone is not evidence that the intended app launched.
|
||||
|
||||
## Drive the UI semantically
|
||||
|
||||
1. Call `snapshot_ui` to obtain the current accessibility hierarchy and element references.
|
||||
2. Use only current `elementRef` values whose snapshot entries list the intended action. XcodeBuildMCP `2.6.2` does not accept coordinates for `tap`; when the app exposes no actionable reference, prefer a registered deep link or another app-supported route and otherwise report the accessibility blocker.
|
||||
3. Refresh with `snapshot_ui` after navigation or layout changes. Element references are snapshot-specific.
|
||||
4. Use `wait_for_ui` for asynchronous transitions when available rather than fixed sleeps.
|
||||
5. Capture a final `screenshot` for the state that proves the affected flow.
|
||||
|
||||
Use `gesture` or scoped swipe actions when needed. If a gesture is unreliable, return to a known route or relaunch rather than switching to generic desktop automation.
|
||||
|
||||
## Capture logs and debug
|
||||
|
||||
- Use `start_sim_log_cap` and `stop_sim_log_cap` with the exact bundle identifier for focused runtime logs.
|
||||
- Use debugger tools only when the task requires runtime diagnosis; attach to the selected simulator and app rather than an ambiguous process.
|
||||
- Summarize relevant errors instead of returning unbounded logs.
|
||||
|
||||
## Clean up
|
||||
|
||||
Stop only log captures, debugger sessions, apps, or simulators started for the current test. Leave pre-existing simulators and unrelated sessions alone.
|
||||
|
||||
## Upstream
|
||||
|
||||
Adapted from OpenAI's [`build-ios-apps`](https://github.com/openai/plugins/tree/main/plugins/build-ios-apps) plugin version `0.1.2` (`ios-debugger-agent`, MIT) and aligned with XcodeBuildMCP `2.6.2` tool names.
|
||||
@@ -0,0 +1,9 @@
|
||||
interface:
|
||||
display_name: "iOS Debugger Agent"
|
||||
short_description: "Build and drive iOS Simulator apps"
|
||||
default_prompt: "Use $ios-debugger-agent to build, launch, and inspect the current iOS app on Simulator."
|
||||
dependencies:
|
||||
tools:
|
||||
- type: "mcp"
|
||||
value: "xcodebuildmcp"
|
||||
description: "Repository-configured Xcode build, simulator, logging, debugging, and semantic UI tools"
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) OpenAI
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
name: ios-simulator-browser
|
||||
description: Stream an explicit iOS Simulator through pinned serve-sim into the T3 Code in-app browser or another agent browser. Use on Apple Silicon macOS when the user should watch simulator verification live or when browser-visible simulator evidence is needed.
|
||||
---
|
||||
|
||||
# iOS Simulator Browser
|
||||
|
||||
Use serve-sim as the shared visual feed for an iOS Simulator. Use `ios-debugger-agent` and XcodeBuildMCP semantic UI tools to drive the app; do not treat browser-canvas coordinates as a substitute for missing app accessibility.
|
||||
|
||||
## Confirm availability
|
||||
|
||||
serve-sim `0.1.45` requires Apple Silicon macOS, Xcode command-line tools, and Node.js 20 or newer. If the host is unsupported, continue with XcodeBuildMCP screenshots and report that live streaming was unavailable.
|
||||
|
||||
When running inside T3 Code, use its product-native browser MCP to open the stream. Other agent hosts may use their own browser or preview surface.
|
||||
|
||||
Keep serve-sim on its default `127.0.0.1` binding. Do not expose its preview to a LAN or tunnel unless the user explicitly requests that access and the network is trusted; the preview includes a token-gated shell-execution route.
|
||||
|
||||
## Start one owned stream
|
||||
|
||||
1. Obtain the exact simulator UDID from the iOS build or launch workflow.
|
||||
2. Check whether an existing serve-sim stream for that UDID belongs to another task. Reuse it only when explicitly shared; never kill another task's stream.
|
||||
3. Otherwise, clear only a stale stream for that UDID and start the pinned version with scoped cleanup:
|
||||
|
||||
```bash
|
||||
SIMULATOR_ID=<simulator-udid>
|
||||
cleanup_serve_sim() {
|
||||
npx --yes [email protected] --kill "$SIMULATOR_ID" >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup_serve_sim EXIT INT TERM HUP
|
||||
cleanup_serve_sim
|
||||
npx --yes [email protected] "$SIMULATOR_ID"
|
||||
```
|
||||
|
||||
4. Keep the terminal alive and open the exact local URL printed by serve-sim in the agent's browser.
|
||||
5. Verify that a live simulator frame renders. A loaded wrapper page is not sufficient evidence.
|
||||
|
||||
## Observe while driving semantically
|
||||
|
||||
- Let the user watch the serve-sim stream while XcodeBuildMCP performs `snapshot_ui`, semantic taps, typing, gestures, and screenshots.
|
||||
- Keep the browser and Xcode tooling pinned to the same simulator UDID.
|
||||
- Do not switch to generic desktop automation or browser-canvas clicking merely because the stream is visible.
|
||||
|
||||
If the in-app browser explicitly reports that previews are unavailable, do not install unrelated browser automation. Continue through XcodeBuildMCP, capture a simulator screenshot, report the unavailable live stream, and clean up the owned serve-sim process.
|
||||
|
||||
## Finish
|
||||
|
||||
Stop the long-running terminal and wait for its cleanup trap to finish. If it disappeared without cleanup, run `npx --yes serve-sim@0.1.45 --kill <simulator-udid>` for that exact simulator. Never run an unscoped `--kill`.
|
||||
|
||||
## Upstream
|
||||
|
||||
Adapted from OpenAI's [`build-ios-apps`](https://github.com/openai/plugins/tree/main/plugins/build-ios-apps) plugin version `0.1.2` (`ios-simulator-browser`, MIT). It invokes serve-sim `0.1.45` under its Apache-2.0 license without vendoring the package.
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "iOS Simulator Browser"
|
||||
short_description: "Stream iOS Simulator in the browser"
|
||||
default_prompt: "Use $ios-simulator-browser to stream the selected iOS Simulator into the T3 Code in-app browser."
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
name: test-t3-app
|
||||
description: Launch, retain, and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, cross-turn dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, iteratively test UI behavior with a human, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
|
||||
---
|
||||
|
||||
# Test T3 App
|
||||
|
||||
Use this skill for the web client. For iOS Simulator, Android Emulator, or physical-device testing against an isolated T3 backend, use the sibling [`test-t3-mobile`](../test-t3-mobile/SKILL.md) skill.
|
||||
|
||||
## Start an isolated web environment
|
||||
|
||||
1. Run commands from the repository root.
|
||||
2. Choose a base directory that belongs only to the current worktree or test:
|
||||
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
|
||||
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
|
||||
3. Start the full web stack with `vp run dev`. Add `--share` when the user needs to open it from another tailnet device. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir <base-dir>` only when the test needs a different isolated directory.
|
||||
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
|
||||
|
||||
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
|
||||
|
||||
The worktree-local default deliberately outranks an ambient `T3CODE_HOME`; do not pass the shared home through to a worktree dev server.
|
||||
|
||||
Ports are derived from the worktree path but can shift when occupied. Always read the actual values from the `[dev-runner]` line.
|
||||
|
||||
Shared browser dev is single-origin: Vite proxies the backend paths, so never set `VITE_HTTP_URL` or `VITE_WS_URL` for `dev`/`dev:web`.
|
||||
|
||||
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
|
||||
|
||||
### Verify a shared environment before human handoff
|
||||
|
||||
When another person will use the printed pairing URL, first open the shared origin without the pairing path or fragment in the controlled browser and confirm the T3 Code app loads. This browser navigation is required even when curl succeeds because browsers block some otherwise reachable ports before making a network request.
|
||||
|
||||
Do not open the other person's complete pairing URL during this reachability check; doing so consumes its one-time token. If the agent also needs an authenticated browser, create and consume a separate pairing token, then leave a fresh token for the other person.
|
||||
|
||||
## Preserve the environment while iterating
|
||||
|
||||
Treat the overall testing or implementation loop—not an assistant turn or one verification pass—as the environment lifecycle boundary.
|
||||
|
||||
- Keep the dev process, base directory, selected ports, authenticated browser tab, registered projects, and seeded fixtures alive while the user may inspect the result or request follow-up changes.
|
||||
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
|
||||
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
|
||||
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
|
||||
|
||||
## Authenticate the browser on the first navigation
|
||||
|
||||
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
|
||||
2. Use the controlled in-app browser or browser-automation surface available to the agent. Do not use a system-browser launch command during automated testing.
|
||||
3. Open that complete URL exactly once as the controlled browser's first navigation. Preserve the fragment and token verbatim.
|
||||
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
|
||||
5. Continue in the same browser context so its stored bearer session remains available.
|
||||
|
||||
Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
|
||||
|
||||
## Recover a consumed or expired pairing token
|
||||
|
||||
Create another token against the same database and web URL as the running dev server:
|
||||
|
||||
```bash
|
||||
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir <base-dir> \
|
||||
--dev-url <web-url> \
|
||||
--base-url <web-url> \
|
||||
--ttl 15m \
|
||||
--label agent-ui-test
|
||||
```
|
||||
|
||||
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
|
||||
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before changing the database.
|
||||
|
||||
- Use `node apps/server/scripts/t3-sqlite-state.ts query` for schema discovery and read-only checks.
|
||||
- Stop the dev server before using `node apps/server/scripts/t3-sqlite-state.ts exec`, then restart it with the same base directory.
|
||||
- Seed projection tables only for disposable UI fixtures. Use application commands and APIs when testing business behavior or projection correctness.
|
||||
- Use the auth CLI, not direct `auth_*` table edits, for pairing and sessions.
|
||||
|
||||
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
|
||||
|
||||
## Tear down only when the testing loop is finished
|
||||
|
||||
Tear down when the user explicitly asks, confirms the iteration is finished, or the overall task is genuinely complete with no pending human review. Do not infer completion from the end of an assistant turn.
|
||||
|
||||
When teardown is appropriate:
|
||||
|
||||
1. Stop the dev process with its terminal interrupt.
|
||||
2. Preserve the isolated base directory when it contains useful reproduction evidence or state for a likely follow-up.
|
||||
3. Otherwise remove only a path created for this test after resolving and verifying the exact target.
|
||||
|
||||
If completion is uncertain, keep the environment alive and mention that it is retained for further iteration. A fresh isolated base directory remains the safest reset when authentication, migrations, or fixture state becomes ambiguous.
|
||||
|
||||
## Troubleshoot predictably
|
||||
|
||||
- If the browser shows an unauthenticated pairing screen, issue a new token instead of retrying the consumed URL.
|
||||
- If the pairing URL is no longer visible, create a replacement token with both `--dev-url` and `--base-url`.
|
||||
- If the replacement token is rejected, verify that the CLI and server use the identical absolute base directory and web URL.
|
||||
- If the UI shows unexpected data, verify that every command uses the identical explicit base directory before editing anything.
|
||||
- If ports move because another instance is running, trust the current dev-runner output rather than assuming ports `13773` and `5733`.
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "T3 App Testing"
|
||||
short_description: "Launch and retain isolated T3 test environments"
|
||||
default_prompt: "Use $test-t3-app to launch an isolated T3 environment and iteratively test it in the browser while preserving state."
|
||||
@@ -0,0 +1,58 @@
|
||||
# SQLite fixtures
|
||||
|
||||
Load this reference only when inspecting or seeding local T3 state directly.
|
||||
|
||||
## Select the correct database
|
||||
|
||||
When `--base-dir` or `--home-dir` is explicit, runtime state lives under `<base-dir>/userdata` and the database path is `<base-dir>/userdata/state.sqlite`. The `<base-dir>/dev` state directory is only the fallback for an implicit development home, preventing an ordinary `vp run dev` from touching production state.
|
||||
|
||||
Start the target runtime once before seeding so all migrations have run. Use an isolated base directory. Stop the server before writes to avoid racing application state or an active projection.
|
||||
|
||||
## Use the helper
|
||||
|
||||
List tables:
|
||||
|
||||
```bash
|
||||
node apps/server/scripts/t3-sqlite-state.ts query \
|
||||
--base-dir <base-dir> \
|
||||
--sql "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
|
||||
```
|
||||
|
||||
Inspect current columns before writing a fixture:
|
||||
|
||||
```bash
|
||||
node apps/server/scripts/t3-sqlite-state.ts query \
|
||||
--base-dir <base-dir> \
|
||||
--sql "PRAGMA table_info(projection_threads)"
|
||||
```
|
||||
|
||||
Apply a SQL fixture from a file:
|
||||
|
||||
```bash
|
||||
node apps/server/scripts/t3-sqlite-state.ts exec \
|
||||
--base-dir <base-dir> \
|
||||
--file /tmp/t3-seed.sql
|
||||
```
|
||||
|
||||
Use one statement per invocation for both `query` and `exec`; the helper wraps writes in a transaction and prints the backup path after a successful mutation. Use a single insert with multiple value rows when a fixture needs several records.
|
||||
|
||||
## Seed projection data carefully
|
||||
|
||||
The web UI primarily reads these projection tables:
|
||||
|
||||
- `projection_projects`
|
||||
- `projection_threads`
|
||||
- `projection_thread_messages`
|
||||
- `projection_thread_activities`
|
||||
- `projection_thread_sessions`
|
||||
- `projection_turns`
|
||||
- `projection_pending_approvals`
|
||||
- `projection_thread_proposed_plans`
|
||||
|
||||
Inspect `PRAGMA table_info(<table>)` and the current migrations under `apps/server/src/persistence/Migrations/` before constructing inserts. Keep identifiers unique, timestamps as ISO strings, JSON columns valid, and related project/thread/turn IDs consistent.
|
||||
|
||||
For a substantial current example, inspect `seedDatabase` in `scripts/mobile-showcase-environment.ts`. Adapt its column set to the target database instead of assuming copied SQL remains current.
|
||||
|
||||
Direct projection writes are appropriate for ephemeral visual states, edge-case counts, long titles, activity lists, and similar UI fixtures. They do not create a coherent orchestration event history. Do not modify `orchestration_events` unless the test specifically exercises projector internals, and do not use direct projection writes to claim backend business behavior works.
|
||||
|
||||
Use the app's commands or APIs for behavior tests. Use `node apps/server/src/bin.ts auth ...` for auth state rather than editing `auth_pairing_links` or `auth_sessions`.
|
||||
@@ -0,0 +1,188 @@
|
||||
---
|
||||
name: test-t3-mobile
|
||||
description: Launch and test T3 Code Mobile on an iOS Simulator or Android Emulator against disposable local T3 environments, including Metro and dev-client reuse, native rebuild decisions, per-client pairing, seeded projects, semantic UI control, screenshots, and iOS serve-sim streaming. Use after mobile UI or native changes, when reproducing phone or tablet behavior, pairing an emulator to isolated state, or verifying mobile behavior on macOS, Linux, or Windows.
|
||||
---
|
||||
|
||||
# Test T3 Mobile
|
||||
|
||||
Run one focused, end-to-end mobile verification pass against disposable T3 state. Use the sibling [`test-t3-app`](../test-t3-app/SKILL.md) skill as the detailed reference for pairing-token semantics and SQLite fixtures.
|
||||
|
||||
Command examples use POSIX shell syntax. On Windows, use PowerShell equivalents: set variables with `$env:NAME = "value"`, use an explicit temporary directory from `[System.IO.Path]::GetTempPath()`, and run multiline examples on one line or with PowerShell backticks. Use `$env:ANDROID_HOME\platform-tools\adb.exe` when `adb` is not already on `PATH`.
|
||||
|
||||
## Select a viable platform
|
||||
|
||||
Inspect the host and the affected code before launching processes:
|
||||
|
||||
- On macOS with Xcode, prefer one representative iOS Simulator when the change is cross-platform so the user can watch through serve-sim. Load and follow [`ios-debugger-agent`](../ios-debugger-agent/SKILL.md), and load [`ios-simulator-browser`](../ios-simulator-browser/SKILL.md) when live streaming is available.
|
||||
- On macOS, Linux, or Windows with the Android SDK, use one Android Emulator when Android is the affected surface or iOS tooling is unavailable.
|
||||
- When the change is platform-specific, test that platform. When neither platform is viable, report the missing SDK, emulator, or dev-client prerequisite rather than claiming verification.
|
||||
|
||||
Do not treat unavailable iOS tooling as a blocker when Android is a valid representative target.
|
||||
|
||||
## Choose the lightest valid launch path
|
||||
|
||||
- For JavaScript, TypeScript, or asset-only changes, reuse a compatible installed development client and start Metro. Do not rebuild native code merely to load a new bundle.
|
||||
- For native source, native dependencies, entitlements, config plugins, or generated project changes, rebuild the affected platform.
|
||||
- Use `vp run ios:dev` or `vp run android:dev` only when an Expo clean prebuild is actually required; both commands regenerate the native project.
|
||||
- If the user requested no native rebuild and no compatible app is installed, reuse an existing compatible `.app` or `.apk` artifact when available. Otherwise report the missing dev client instead of silently rebuilding.
|
||||
|
||||
The development identity on both platforms is:
|
||||
|
||||
- App: `T3 Code Dev`
|
||||
- Bundle/package identifier: `com.t3tools.t3code.dev`
|
||||
- URL scheme: `t3code-dev`
|
||||
|
||||
Bundle or package presence proves the correct variant, not native compatibility. Reuse it only when the current changes did not alter its Expo SDK, native dependencies, config plugins, entitlements, generated project, or native source.
|
||||
|
||||
## Start one disposable T3 environment
|
||||
|
||||
Run backend commands from the repository root. Use the ignored, worktree-local `.t3` directory or create a fresh directory with the host OS's temporary-directory mechanism. An explicit base directory stores state in `<base-dir>/userdata`; never point testing at shared `~/.t3` state.
|
||||
|
||||
Seed a small number of meaningful Git projects before starting the backend:
|
||||
|
||||
```bash
|
||||
node apps/server/src/bin.ts project add <git-workspace> \
|
||||
--base-dir <base-dir> \
|
||||
--title <project-title>
|
||||
```
|
||||
|
||||
Running `project add` before the backend starts gives it exclusive offline database access. If a backend is already running, wait until it is ready so the CLI dispatches through the live server; never run offline mutations concurrently with the server.
|
||||
|
||||
Use direct SQLite mutation only for disposable projection fixtures. Follow `test-t3-app` and stop the backend before writing.
|
||||
|
||||
Start a headless backend after seeding:
|
||||
|
||||
```bash
|
||||
node apps/server/src/bin.ts serve \
|
||||
--host 127.0.0.1 \
|
||||
--port <server-port> \
|
||||
--base-dir <base-dir> \
|
||||
--no-browser
|
||||
```
|
||||
|
||||
Use these client origins:
|
||||
|
||||
- iOS Simulator: `http://127.0.0.1:<server-port>`
|
||||
- Android Emulator: `http://10.0.2.2:<server-port>`
|
||||
- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
|
||||
|
||||
Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
|
||||
|
||||
## Start or reuse Metro safely
|
||||
|
||||
Run Metro from `apps/mobile`.
|
||||
|
||||
1. Inspect any process on the intended Metro port and its `/status` response. Reuse it only when it is healthy, belongs to this worktree, and matches `APP_VARIANT=development`, `--dev-client`, and scheme `t3code-dev`.
|
||||
2. Never kill another worktree's Metro. Use a free explicit port when necessary.
|
||||
3. Run `vp run dev:client` on the standard port. For another port, retain the complete development identity:
|
||||
|
||||
```bash
|
||||
APP_VARIANT=development vp exec expo start \
|
||||
--dev-client \
|
||||
--scheme t3code-dev \
|
||||
--clear \
|
||||
--lan \
|
||||
--port <metro-port>
|
||||
```
|
||||
|
||||
In PowerShell, set `$env:APP_VARIANT = "development"` first and then run the `vp exec expo start ...` command without the leading assignment.
|
||||
|
||||
4. Open the exact development-client URL for the selected device and confirm the loaded bundle belongs to this worktree and Metro port.
|
||||
|
||||
### iOS launch
|
||||
|
||||
Use `ios-debugger-agent` to select one UDID and set these XcodeBuildMCP session defaults:
|
||||
|
||||
- Workspace: `<repo>/apps/mobile/ios/T3CodeDev.xcworkspace`
|
||||
- Scheme: `T3CodeDev`
|
||||
- Configuration: `Debug`
|
||||
- Simulator ID: the selected UDID
|
||||
- Bundle ID: `com.t3tools.t3code.dev`
|
||||
|
||||
Check the installed client with:
|
||||
|
||||
```bash
|
||||
xcrun simctl get_app_container <simulator-udid> com.t3tools.t3code.dev app
|
||||
xcrun simctl openurl <simulator-udid> <printed-dev-client-url>
|
||||
```
|
||||
|
||||
Accept the iOS confirmation prompt and dismiss the developer menu when it obscures the app.
|
||||
|
||||
### Android launch
|
||||
|
||||
Select one running emulator serial from `adb devices` and check the installed client:
|
||||
|
||||
```bash
|
||||
adb -s <emulator-serial> shell pm path com.t3tools.t3code.dev
|
||||
adb -s <emulator-serial> reverse tcp:<metro-port> tcp:<metro-port>
|
||||
adb -s <emulator-serial> shell am start -W \
|
||||
-a android.intent.action.VIEW \
|
||||
-d '<printed-dev-client-url>' \
|
||||
com.t3tools.t3code.dev
|
||||
```
|
||||
|
||||
Do not start, stop, erase, or reconfigure an emulator owned by another task. Track and later stop only processes owned by this test.
|
||||
|
||||
## Pair each client once
|
||||
|
||||
Issue a fresh credential against the running backend's exact base directory:
|
||||
|
||||
```bash
|
||||
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir <base-dir> \
|
||||
--base-url <mobile-origin> \
|
||||
--ttl 15m \
|
||||
--label agent-mobile-<short-device-id>
|
||||
```
|
||||
|
||||
In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.
|
||||
|
||||
If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:
|
||||
|
||||
```bash
|
||||
xcrun simctl openurl <simulator-udid> 't3code-dev://connections/new'
|
||||
adb -s <emulator-serial> shell am start -W \
|
||||
-a android.intent.action.VIEW \
|
||||
-d 't3code-dev://connections/new' \
|
||||
com.t3tools.t3code.dev
|
||||
```
|
||||
|
||||
Run only the command for the selected platform.
|
||||
|
||||
In T3 Code Dev, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.
|
||||
|
||||
Pairing credentials are secret, short-lived, and single-use. Create a different credential for every simulator, emulator, physical device, or browser. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.
|
||||
|
||||
## Drive and observe the affected flow
|
||||
|
||||
### iOS
|
||||
|
||||
Use `snapshot_ui` and current element references from XcodeBuildMCP for taps and typing. Stream the same UDID through `ios-simulator-browser` so the user can watch in T3 Code when the host supports it. Use the stream as a visual feed rather than a reason to switch to fragile browser coordinates.
|
||||
|
||||
### Android
|
||||
|
||||
Prefer semantic Android automation exposed by the current agent host. Otherwise inspect the current hierarchy with `adb shell uiautomator dump`, target stable resource IDs, content descriptions, text, or bounds, and use scoped `adb shell input` actions. Refresh the hierarchy after navigation. Capture the final state with `adb exec-out screencap -p`.
|
||||
|
||||
Android does not use serve-sim. Use a browser-compatible Android mirror when the host already provides one; otherwise return focused emulator screenshots as evidence rather than installing unrelated streaming infrastructure during verification.
|
||||
|
||||
## Verify and clean up
|
||||
|
||||
Exercise only the affected flow on one representative device unless the change specifically concerns platform, OS version, or screen size. Before finishing:
|
||||
|
||||
1. Confirm the app connected to the intended disposable environment instead of merely rendering an empty disconnected state.
|
||||
2. Capture the relevant final state.
|
||||
3. Remove the disposable environment from T3 Code Dev.
|
||||
4. Remove any `adb reverse` rule created for this test with `adb -s <emulator-serial> reverse --remove tcp:<metro-port>`.
|
||||
5. Stop only the serve-sim, Metro, backend, emulator, and log processes started by this test.
|
||||
6. Remove only base directories and temporary Git repositories deliberately created for this test. Preserve them when they contain useful reproduction evidence.
|
||||
|
||||
Keep local verification focused. Do not turn this workflow into a full repository test run.
|
||||
|
||||
## Troubleshoot predictable failures
|
||||
|
||||
- **Old UI or an old error appears:** verify Metro's worktree, variant, URL, and port before diagnosing the app.
|
||||
- **The environment remains empty:** verify the platform-specific HTTP origin, use a fresh token, and confirm project seeding used the identical base directory.
|
||||
- **A second client cannot pair:** pairing tokens are single-use; issue another token.
|
||||
- **iOS semantic actions fail:** set explicit XcodeBuildMCP defaults and refresh with `snapshot_ui`.
|
||||
- **Android cannot reach Metro:** verify `adb reverse` for the exact Metro port and relaunch the development-client URL.
|
||||
- **Android cannot reach the backend:** use `10.0.2.2`, not `127.0.0.1`, for the Android Emulator.
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "Test T3 Mobile"
|
||||
short_description: "Test T3 Code on iOS or Android"
|
||||
default_prompt: "Use $test-t3-mobile to launch T3 Code against an isolated backend and verify the affected flow on an available simulator or emulator."
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../.agents/skills
|
||||
@@ -0,0 +1,9 @@
|
||||
[mcp_servers.xcodebuildmcp]
|
||||
enabled = true
|
||||
required = false
|
||||
command = "npx"
|
||||
args = ["--yes", "[email protected]", "mcp"]
|
||||
startup_timeout_sec = 20.0
|
||||
|
||||
[mcp_servers.xcodebuildmcp.env]
|
||||
XCODEBUILDMCP_ENABLED_WORKFLOWS = "simulator,ui-automation,debugging,logging"
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Cursor Cloud specific instructions
|
||||
|
||||
These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is
|
||||
developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats.
|
||||
|
||||
## Toolchain
|
||||
|
||||
Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global
|
||||
`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo
|
||||
(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter <pkg> <script>`).
|
||||
|
||||
- Node gotcha: the base image also ships an older Node on `/exec-daemon` that wins on `PATH` in
|
||||
non-login shells. Run commands in a login shell (`bash -lc '...'`) or prepend
|
||||
`$HOME/.nvm/versions/node/v24.13.1/bin` so Node 24 (`engines.node: ^24.13.1`) is used.
|
||||
- `vp check` also runs the formatter (not just lint); markdown edits must be formatter-clean. Run
|
||||
`vp check --fix` before committing.
|
||||
|
||||
## Running the web app
|
||||
|
||||
- `npm run dev` (from repo root) starts contracts (watch), web (Vite, port 5733), and the server
|
||||
(`node --watch`, port 13773) together, auto-wiring `VITE_HTTP_URL`/`VITE_WS_URL`. Use
|
||||
`npm run dev:server` / `npm run dev:web` for one side. If base ports are taken it auto-offsets to
|
||||
the next free pair, so read the actual ports from stdout. Avoid production `build`/`start` in dev.
|
||||
- Auth/pairing: the server is unauthenticated by default and prints a pairing URL to stdout on startup
|
||||
(e.g. `http://localhost:5733/pair#token=XXXX`). Open that URL in the browser to pair before the web
|
||||
UI can talk to the server. Server state (SQLite, auth, projects) lives under `~/.t3`
|
||||
(`T3CODE_HOME`); multiple `npm run dev` instances bind different ports but share that same DB.
|
||||
- Agent providers are external CLIs (`codex`, `claude`, `cursor-agent`, `opencode`) probed on `PATH`.
|
||||
Without one installed the UI loads but no agent can run. Claude Code
|
||||
(`npm i -g @anthropic-ai/claude-code`) works headlessly using `ANTHROPIC_API_KEY` from the
|
||||
environment (the server forwards `process.env` to the child; no interactive `claude auth login`
|
||||
needed). Provider probing runs at startup and refreshes roughly every 5 minutes — restart the dev
|
||||
server to pick up a newly installed provider CLI immediately.
|
||||
|
||||
## Android native builds (apps/mobile)
|
||||
|
||||
The Android toolchain is pre-installed and wired into login shells: OpenJDK 17
|
||||
(`JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64`; the base image's default `java` is 21, so builds must
|
||||
use `JAVA_HOME`), and the Android SDK at `$HOME/Android/Sdk` (`ANDROID_HOME`/`ANDROID_SDK_ROOT`) with
|
||||
platform-tools, `platforms;android-36`, `build-tools;36.0.0`, `ndk;27.1.12297006`, and `cmake;3.22.1`.
|
||||
Gradle auto-downloads any additional pinned SDK packages on demand.
|
||||
|
||||
- Generate the native project first: from `apps/mobile`,
|
||||
`EXPO_NO_GIT_STATUS=1 APP_VARIANT=development npx expo prebuild --clean --platform android`
|
||||
(the `android/` folder is generated, not committed). RN 0.85 defaults: compileSdk/targetSdk 36,
|
||||
minSdk 24, NDK `27.1.12297006` (see `react-native/gradle/libs.versions.toml`).
|
||||
- Build with Gradle from `apps/mobile/android`, e.g. `./gradlew :app:assembleDebug`. First build is
|
||||
slow (Kotlin + C++/NDK codegen). Limit ABIs to speed things up, e.g.
|
||||
`-PreactNativeArchitectures=arm64-v8a`. Verified working end-to-end on a native module:
|
||||
`./gradlew :react-native-worklets:assembleDebug` compiles Kotlin + C++ and emits an AAR + `.so`s.
|
||||
- No emulator: this VM has no `/dev/kvm` (nested virtualization), so a hardware-accelerated Android
|
||||
emulator will not run. Use a physical device (`adb`) or EAS cloud builds (`vp run eas:android:*`) to
|
||||
actually run the app. The full IDE GUI is unnecessary here — the SDK/NDK/Gradle toolchain that
|
||||
Android Studio bundles is what is installed.
|
||||
- Known blocker for the full-app `:app:assembleDebug` (pre-existing, app-level — not the environment):
|
||||
`:react-native-screens:compileDebugKotlin` fails because `patches/[email protected]`
|
||||
adds new codegen props (`subtitle`, `largeSubtitle`, `navigationItemStyle`,
|
||||
`headerCenterBarButtonItems`, `headerToolbarItems`) to the JS spec + iOS native code but includes no
|
||||
Android Kotlin setters, so the generated `ScreenStackHeaderConfigManagerInterface` is unimplemented.
|
||||
The mobile README documents only iOS for local builds and routes Android through EAS. Fixing local
|
||||
Android app builds requires an app/patch change (add the Android Kotlin setters), which is out of
|
||||
scope for environment setup.
|
||||
|
||||
## Known flaky tests (unrelated to setup)
|
||||
|
||||
- `apps/server/src/git/GitManager.test.ts` (cross-repo PR metadata, can time out at 12s).
|
||||
- `apps/server/src/provider/Layers/ProviderRegistry.test.ts` (codex binaryPath re-probe ordering).
|
||||
@@ -1,6 +0,0 @@
|
||||
# CI quality gates
|
||||
|
||||
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
|
||||
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
|
||||
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
|
||||
- See `docs/release.md` for full release/signing setup checklist.
|
||||
@@ -1,42 +0,0 @@
|
||||
# Scripts
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
|
||||
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
|
||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||
`bun run dev -- --base-dir ~/.t3-2`
|
||||
- `bun run start` — Runs the production server (serves built web app as static files).
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
|
||||
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
|
||||
|
||||
## Desktop `.dmg` packaging notes
|
||||
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
|
||||
- Windows `--signed` uses Azure Trusted Signing and expects:
|
||||
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
|
||||
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
## Running multiple dev instances
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
- Default ports: server `3773`, web `5733`
|
||||
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
||||
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
||||
|
||||
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Optional: T3 Connect source builds
|
||||
# Leave these unset to disable optional T3 Connect features in local source builds.
|
||||
# Release builds inject their public values at build time. Do not add server-side
|
||||
# secrets to this file.
|
||||
|
||||
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
|
||||
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
|
||||
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
|
||||
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
|
||||
|
||||
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
|
||||
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
|
||||
# returns a different RP ID or when multiple domains must be entitled.
|
||||
# T3CODE_APPLE_TEAM_ID=ABC1234567
|
||||
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
|
||||
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
|
||||
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
|
||||
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
|
||||
# Defaults to https://app.t3.codes; override to test against a staging deployment.
|
||||
# T3CODE_HOSTED_APP_URL=https://nightly.app.t3.codes
|
||||
|
||||
# Public, ingest-only mobile OpenTelemetry configuration.
|
||||
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
|
||||
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
|
||||
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
|
||||
+59
-57
@@ -7,72 +7,80 @@ on:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
||||
check:
|
||||
name: Check
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Cache Bun and Turbo
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
.turbo
|
||||
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Format
|
||||
run: bun run fmt:check
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
- name: Check
|
||||
run: vp check
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: |
|
||||
cd apps/web
|
||||
bunx playwright install --with-deps chromium
|
||||
|
||||
- name: Browser test
|
||||
run: bun run --cwd apps/web test:browser
|
||||
run: vpr typecheck
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: bun run build:desktop
|
||||
run: vp run build:desktop
|
||||
|
||||
- name: Verify preload bundle output
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.cjs
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
|
||||
grep -n "__clerk_internal_electron_passkeys" apps/desktop/dist-electron/preload.cjs
|
||||
|
||||
test:
|
||||
name: Test
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
mobile_native_static_analysis:
|
||||
name: Mobile Native Static Analysis
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Install mobile native static analysis tools
|
||||
run: brew bundle install --file apps/mobile/Brewfile
|
||||
|
||||
- name: Lint mobile native sources
|
||||
run: vp run lint:mobile
|
||||
|
||||
release_smoke:
|
||||
name: Release Smoke
|
||||
@@ -82,18 +90,12 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Exercise release-only workflow steps
|
||||
run: node scripts/release-smoke.ts
|
||||
@@ -0,0 +1,80 @@
|
||||
name: Deploy T3 Connect relay
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: none
|
||||
statuses: write
|
||||
|
||||
concurrency:
|
||||
group: relay-production
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy_relay:
|
||||
name: Deploy production relay
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 15
|
||||
environment:
|
||||
name: production
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }}
|
||||
AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }}
|
||||
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
|
||||
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
|
||||
RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}
|
||||
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
|
||||
CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}
|
||||
APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }}
|
||||
APNS_TEAM_ID: ${{ vars.APNS_TEAM_ID }}
|
||||
APNS_KEY_ID: ${{ vars.APNS_KEY_ID }}
|
||||
APNS_BUNDLE_ID: ${{ vars.APNS_BUNDLE_ID }}
|
||||
ALCHEMY_TELEMETRY_DISABLED: "1"
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Deploy production relay stage
|
||||
id: deploy
|
||||
run: vp run --filter t3code-relay deploy --stage prod --yes --github-output
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }}
|
||||
PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }}
|
||||
AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }}
|
||||
CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
|
||||
APNS_PRIVATE_KEY: ${{ secrets.APNS_PRIVATE_KEY }}
|
||||
|
||||
- name: Publish relay deploy commit status
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const result = "${{ steps.deploy.outputs.result }}";
|
||||
const changed = "${{ steps.deploy.outputs.changed }}" === "true";
|
||||
const description = changed
|
||||
? "Relay production deploy applied infrastructure changes."
|
||||
: result === "noop"
|
||||
? "Relay production deploy was a no-op."
|
||||
: `Relay production deploy completed with result: ${result}.`;
|
||||
|
||||
await github.rest.repos.createCommitStatus({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
sha: context.sha,
|
||||
state: "success",
|
||||
context: "Relay deploy / production",
|
||||
description,
|
||||
target_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
name: Mobile EAS Preview
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize, labeled, unlabeled]
|
||||
|
||||
jobs:
|
||||
preview:
|
||||
name: EAS Preview
|
||||
if: contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
env:
|
||||
APP_VARIANT: preview
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
MOBILE_VERSION_POLICY: fingerprint
|
||||
steps:
|
||||
- id: expo-token
|
||||
name: Check for EXPO_TOKEN
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
if [ -n "$EXPO_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "EXPO_TOKEN is not available; skipping EAS preview."
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup EAS
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: expo/expo-github-action@v8
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
# npm, not pnpm: this only installs eas-cli into the action's own
|
||||
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
|
||||
# ignored build script (no allowBuilds config outside the repo).
|
||||
packager: npm
|
||||
|
||||
- name: Pull preview environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull preview --non-interactive
|
||||
|
||||
- name: Deploy with fingerprint check
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: expo/expo-github-action/continuous-deploy-fingerprint@main
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
with:
|
||||
profile: preview:dev
|
||||
branch: pr-${{ github.event.pull_request.number }}
|
||||
platform: all
|
||||
environment: preview
|
||||
working-directory: apps/mobile
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,113 @@
|
||||
name: Mobile EAS Production
|
||||
|
||||
# Production builds and OTA updates run from CI (Linux) — never from a laptop.
|
||||
# Under the fingerprint runtime-version policy the fingerprint must be computed
|
||||
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
|
||||
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
|
||||
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: "build (+ auto-submit to TestFlight) or update (OTA)"
|
||||
required: true
|
||||
type: choice
|
||||
default: build
|
||||
options:
|
||||
- build
|
||||
- update
|
||||
platform:
|
||||
description: "Target platform"
|
||||
required: true
|
||||
type: choice
|
||||
default: ios
|
||||
options:
|
||||
- ios
|
||||
- android
|
||||
- all
|
||||
message:
|
||||
description: "OTA update message (mode=update only)"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
production:
|
||||
name: EAS Production ${{ inputs.mode }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
APP_VARIANT: production
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
steps:
|
||||
- id: expo-token
|
||||
name: Check for EXPO_TOKEN
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
if [ -n "$EXPO_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "EXPO_TOKEN is not available; skipping EAS production job."
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup EAS
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
uses: expo/expo-github-action@v8
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
# npm, not pnpm: this only installs eas-cli into the action's own
|
||||
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
|
||||
# ignored build script (no allowBuilds config outside the repo).
|
||||
packager: npm
|
||||
|
||||
- name: Pull production environment variables
|
||||
if: steps.expo-token.outputs.present == 'true'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas env:pull production --non-interactive
|
||||
|
||||
- name: Build and submit
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
|
||||
|
||||
- name: Publish OTA update
|
||||
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
|
||||
working-directory: apps/mobile
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
run: |
|
||||
eas update \
|
||||
--channel production \
|
||||
--environment production \
|
||||
--platform ${{ inputs.platform }} \
|
||||
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
|
||||
--non-interactive
|
||||
@@ -0,0 +1,134 @@
|
||||
name: Mobile Showcase Screenshots
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
platform:
|
||||
description: Device platforms to capture
|
||||
required: true
|
||||
default: all
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- ios
|
||||
- android
|
||||
appearance:
|
||||
description: System appearances to capture
|
||||
required: true
|
||||
default: both
|
||||
type: choice
|
||||
options:
|
||||
- both
|
||||
- dark
|
||||
- light
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
|
||||
jobs:
|
||||
ios:
|
||||
name: iPhone 6.9, iPhone 6.5, and iPad 13
|
||||
if: inputs.platform == 'all' || inputs.platform == 'ios'
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Capture iOS showcase
|
||||
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}"
|
||||
|
||||
- name: Validate App Store Connect assets
|
||||
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --validate-only
|
||||
|
||||
- name: Upload iOS screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: app-store-connect-screenshots
|
||||
path: artifacts/app-store/screenshots/apple/
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
android:
|
||||
name: Android phone, 7-inch tablet, and 10-inch tablet
|
||||
if: inputs.platform == 'all' || inputs.platform == 'android'
|
||||
runs-on: blacksmith-16vcpu-ubuntu-2404
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
T3_SHOWCASE_ANDROID_ABI: x86_64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Expose pnpm
|
||||
run: |
|
||||
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
|
||||
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
|
||||
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
|
||||
"$vp_pnpm_bin/pnpm" --version
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
- name: Setup Gradle cache
|
||||
uses: gradle/actions/setup-gradle@v5
|
||||
|
||||
- name: Enable KVM
|
||||
run: |
|
||||
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS="static_node=kvm"' \
|
||||
| sudo tee /etc/udev/rules.d/99-kvm4all.rules
|
||||
sudo udevadm control --reload-rules
|
||||
sudo udevadm trigger --name-match=kvm
|
||||
|
||||
- name: Capture Android showcase
|
||||
uses: reactivecircus/android-emulator-runner@v2
|
||||
with:
|
||||
api-level: 36
|
||||
target: google_apis
|
||||
arch: x86_64
|
||||
profile: pixel_7_pro
|
||||
avd-name: Pixel_10_Pro
|
||||
cores: 8
|
||||
ram-size: 4096M
|
||||
disable-animations: false
|
||||
script: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}"
|
||||
|
||||
- name: Validate Google Play assets
|
||||
run: pnpm screenshots:mobile --platform android --appearance "${{ inputs.appearance }}" --validate-only
|
||||
|
||||
- name: Upload Android screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: google-play-screenshots
|
||||
path: artifacts/app-store/screenshots/google-play/
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -124,6 +124,9 @@ jobs:
|
||||
group: pr-size-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
# This pull_request_target job may fetch untrusted PR commits only as passive
|
||||
# git data. Do not add dependency installs, build/test scripts, or cache
|
||||
# actions here; use pull_request plus workflow_run for that pattern instead.
|
||||
- name: Checkout base repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
|
||||
+464
-87
@@ -23,8 +23,8 @@ on:
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
contents: read
|
||||
id-token: none
|
||||
|
||||
jobs:
|
||||
check_changes:
|
||||
@@ -85,18 +85,15 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
@@ -152,14 +149,14 @@ jobs:
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
- name: Check
|
||||
run: vp check
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
run: vp run typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
run: vp run test
|
||||
|
||||
- id: previous_tag
|
||||
name: Resolve previous release tag
|
||||
@@ -169,12 +166,157 @@ jobs:
|
||||
--current-tag "${{ steps.release_meta.outputs.tag }}" \
|
||||
--github-output
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
relay_public_config:
|
||||
name: Resolve T3 Connect public config
|
||||
needs: preflight
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 5
|
||||
environment:
|
||||
name: production
|
||||
outputs:
|
||||
clerk_publishable_key: ${{ steps.public_config.outputs.clerk_publishable_key }}
|
||||
clerk_jwt_template: ${{ steps.public_config.outputs.clerk_jwt_template }}
|
||||
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
relay_url: ${{ steps.public_config.outputs.relay_url }}
|
||||
env:
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
|
||||
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
|
||||
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
|
||||
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
|
||||
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=t3code-relay...
|
||||
|
||||
- id: relay_state
|
||||
name: Read production relay tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
vp run --filter t3code-relay deploy \
|
||||
--stage prod \
|
||||
--read-state \
|
||||
--github-output \
|
||||
--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"
|
||||
|
||||
- name: Upload relay client tracing config
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing.env
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
- id: public_config
|
||||
name: Resolve production relay public config
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
relay_domain="${RELAY_DOMAIN:-}"
|
||||
if [[ -z "$relay_domain" && -n "${RELAY_API_ZONE_NAME:-}" ]]; then
|
||||
relay_domain="relay.$RELAY_API_ZONE_NAME"
|
||||
fi
|
||||
required=(
|
||||
relay_domain
|
||||
CLERK_PUBLISHABLE_KEY
|
||||
CLERK_JWT_TEMPLATE
|
||||
CLERK_CLI_OAUTH_CLIENT_ID
|
||||
)
|
||||
missing=()
|
||||
for name in "${required[@]}"; do
|
||||
if [[ -z "${!name:-}" ]]; then
|
||||
missing+=("$name")
|
||||
fi
|
||||
done
|
||||
if (( ${#missing[@]} > 0 )); then
|
||||
printf 'Missing required relay deployment configuration: %s\n' "${missing[*]}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "clerk_publishable_key=$CLERK_PUBLISHABLE_KEY" >> "$GITHUB_OUTPUT"
|
||||
echo "clerk_jwt_template=$CLERK_JWT_TEMPLATE" >> "$GITHUB_OUTPUT"
|
||||
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# node-pty publishes no Linux prebuilt and the WSL backend runs under the
|
||||
# distro's own (Linux) Node, which can't load the Windows/Electron binary. We
|
||||
# build the Linux pty.node here, on Linux, and hand it to the Windows packaging
|
||||
# job — the Windows artifact then ships a ready WSL backend binary with no
|
||||
# cross-compiling and no first-launch compiler/node-gyp/network on the user's
|
||||
# machine. node-pty is N-API, so one binary works across all WSL Node versions.
|
||||
build_wsl_node_pty:
|
||||
name: Build WSL node-pty (linux-x64)
|
||||
needs: [preflight]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Build node-pty linux-x64 prebuild
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Resolve node-pty from apps/server (where it's a dependency) and build
|
||||
# its native binary from source for Linux. node-addon-api resolves from
|
||||
# node-pty's own dependency tree, so node-gyp has everything it needs.
|
||||
pty_pkg="$(node -e "console.log(require.resolve('node-pty/package.json', { paths: ['$GITHUB_WORKSPACE/apps/server'] }))")"
|
||||
pty_dir="$(dirname "$pty_pkg")"
|
||||
( cd "$pty_dir" && npx --yes node-gyp rebuild )
|
||||
mkdir -p wsl-prebuild
|
||||
cp "$pty_dir/build/Release/pty.node" wsl-prebuild/pty.node
|
||||
file wsl-prebuild/pty.node
|
||||
|
||||
- name: Upload node-pty linux-x64 prebuild
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: wsl-node-pty-x64
|
||||
path: wsl-prebuild/pty.node
|
||||
if-no-files-found: error
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
# build_wsl_node_pty stays in `needs` so it runs first and its artifact is
|
||||
# available to download, but only the Windows matrix entry consumes it. We
|
||||
# therefore gate the job on preflight + relay (must succeed) WITHOUT requiring
|
||||
# build_wsl_node_pty, so a failed Linux prebuild doesn't skip the macOS/Linux
|
||||
# builds. `!cancelled()` (not `!failure()`) lets the job run even when
|
||||
# build_wsl_node_pty failed; the Windows-only download step below then fails
|
||||
# that single platform if the prebuild is missing.
|
||||
needs: [preflight, relay_public_config, build_wsl_node_pty]
|
||||
if: ${{ !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
|
||||
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -211,38 +353,130 @@ jobs:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Download WSL node-pty prebuild
|
||||
if: matrix.platform == 'win'
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: wsl-node-pty-x64
|
||||
path: wsl-prebuild
|
||||
|
||||
- name: Install Spectre-mitigated MSVC libs
|
||||
if: matrix.platform == 'win'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
|
||||
$installPath = & $vswhere -products * -latest -property installationPath
|
||||
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
|
||||
$proc = Start-Process -FilePath $setupExe `
|
||||
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
|
||||
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
|
||||
-Wait -PassThru -NoNewWindow
|
||||
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
|
||||
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
|
||||
Write-Error "Visual Studio Installer failed with exit code $code"
|
||||
exit $code
|
||||
}
|
||||
$installPath = & $vswhere -products * -latest -property installationPath
|
||||
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
|
||||
$proc = Start-Process -FilePath $setupExe `
|
||||
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
|
||||
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
|
||||
-Wait -PassThru -NoNewWindow
|
||||
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
|
||||
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
|
||||
Write-Error "Visual Studio Installer failed with exit code $code"
|
||||
exit $code
|
||||
}
|
||||
|
||||
- name: Install ImageMagick
|
||||
if: matrix.platform == 'linux'
|
||||
shell: bash
|
||||
run: |
|
||||
if ! command -v magick >/dev/null 2>&1 && ! command -v convert >/dev/null 2>&1; then
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y imagemagick
|
||||
fi
|
||||
|
||||
if command -v magick >/dev/null 2>&1; then
|
||||
magick -version
|
||||
else
|
||||
convert -version
|
||||
fi
|
||||
|
||||
- name: Prepare Azure Trusted Signing
|
||||
if: matrix.platform == 'win'
|
||||
shell: pwsh
|
||||
env:
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
|
||||
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
|
||||
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
|
||||
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$requiredSecrets = @(
|
||||
$env:AZURE_TENANT_ID,
|
||||
$env:AZURE_CLIENT_ID,
|
||||
$env:AZURE_CLIENT_SECRET,
|
||||
$env:AZURE_TRUSTED_SIGNING_ENDPOINT,
|
||||
$env:AZURE_TRUSTED_SIGNING_ACCOUNT_NAME,
|
||||
$env:AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME,
|
||||
$env:AZURE_TRUSTED_SIGNING_PUBLISHER_NAME
|
||||
)
|
||||
if ($requiredSecrets | Where-Object { [string]::IsNullOrWhiteSpace($_) }) {
|
||||
Write-Host "Azure Trusted Signing disabled; skipping TrustedSigning module preparation."
|
||||
exit 0
|
||||
}
|
||||
|
||||
try {
|
||||
Install-PackageProvider `
|
||||
-Name NuGet `
|
||||
-MinimumVersion 2.8.5.201 `
|
||||
-Force `
|
||||
-Scope CurrentUser `
|
||||
-ErrorAction Stop
|
||||
} catch {
|
||||
Write-Warning "Could not bootstrap NuGet package provider. Continuing because the runner may already have a usable provider. $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
Install-Module `
|
||||
-Name TrustedSigning `
|
||||
-MinimumVersion 0.5.0 `
|
||||
-Force `
|
||||
-AllowClobber `
|
||||
-Repository PSGallery `
|
||||
-Scope CurrentUser `
|
||||
-ErrorAction Stop
|
||||
|
||||
Import-Module TrustedSigning -MinimumVersion 0.5.0 -Force
|
||||
Get-Command Invoke-TrustedSigning -ErrorAction Stop
|
||||
|
||||
$moduleRoots = @(
|
||||
[System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "PowerShell", "Modules"),
|
||||
[System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "WindowsPowerShell", "Modules"),
|
||||
[System.IO.Path]::Combine($env:ProgramFiles, "PowerShell", "Modules"),
|
||||
[System.IO.Path]::Combine($env:ProgramFiles, "WindowsPowerShell", "Modules")
|
||||
)
|
||||
$modulePathEntries = @($moduleRoots + ($env:PSModulePath -split ";")) |
|
||||
Where-Object { $_ -and (Test-Path $_) } |
|
||||
Select-Object -Unique
|
||||
"PSModulePath=$($modulePathEntries -join ';')" >> $env:GITHUB_ENV
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
@@ -252,6 +486,9 @@ jobs:
|
||||
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
APPLE_TEAM_ID: ${{ vars.APPLE_TEAM_ID }}
|
||||
MACOS_PROVISIONING_PROFILE: ${{ secrets.MACOS_PROVISIONING_PROFILE }}
|
||||
T3CODE_CLERK_PASSKEY_RP_DOMAINS: ${{ vars.CLERK_PASSKEY_RP_DOMAINS }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
@@ -279,15 +516,31 @@ jobs:
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" ]]; then
|
||||
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
|
||||
if ! has_all "$APPLE_TEAM_ID" "$MACOS_PROVISIONING_PROFILE"; then
|
||||
echo "macOS signing is configured, but APPLE_TEAM_ID or MACOS_PROVISIONING_PROFILE is missing." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
|
||||
printf '%s' "$APPLE_API_KEY" > "$key_path"
|
||||
export APPLE_API_KEY="$key_path"
|
||||
|
||||
profile_path="$RUNNER_TEMP/t3code.provisionprofile"
|
||||
printf '%s' "$MACOS_PROVISIONING_PROFILE" | base64 -D > "$profile_path"
|
||||
security cms -D -i "$profile_path" >/dev/null
|
||||
export T3CODE_APPLE_TEAM_ID="$APPLE_TEAM_ID"
|
||||
export T3CODE_MACOS_PROVISIONING_PROFILE="$profile_path"
|
||||
|
||||
echo "macOS signing enabled."
|
||||
args+=(--signed)
|
||||
else
|
||||
echo "macOS signing disabled (missing one or more Apple signing secrets)."
|
||||
fi
|
||||
elif [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
# Bundle the Linux node-pty binary built by the build_wsl_node_pty job
|
||||
# so the packaged WSL backend ships a ready binary (no first-launch
|
||||
# compile). Required for a working WSL backend on Windows.
|
||||
args+=(--wsl-prebuild "$GITHUB_WORKSPACE/wsl-prebuild/pty.node")
|
||||
if has_all \
|
||||
"$AZURE_TENANT_ID" \
|
||||
"$AZURE_CLIENT_ID" \
|
||||
@@ -305,7 +558,7 @@ jobs:
|
||||
echo "Signing disabled for ${{ matrix.platform }}."
|
||||
fi
|
||||
|
||||
bun run dist:desktop:artifact -- "${args[@]}"
|
||||
vp run dist:desktop:artifact "${args[@]}"
|
||||
|
||||
- name: Collect release assets
|
||||
shell: bash
|
||||
@@ -354,38 +607,57 @@ jobs:
|
||||
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
|
||||
needs: [preflight, relay_public_config, build]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.build.result == 'success' }}
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
env:
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
|
||||
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
registry-url: https://registry.npmjs.org
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=t3...
|
||||
- --filter=@t3tools/web...
|
||||
- --filter=@t3tools/scripts...
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Build web package
|
||||
run: bun --filter=@t3tools/web run build
|
||||
run: vp run --filter @t3tools/web build
|
||||
|
||||
- name: Build CLI package
|
||||
run: bun --filter=t3 run build
|
||||
run: vp run --filter t3 build
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
@@ -410,18 +682,14 @@ jobs:
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
@@ -511,6 +779,120 @@ jobs:
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
deploy_web:
|
||||
name: Deploy hosted web app
|
||||
needs: [preflight, relay_public_config, release]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.release.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
env:
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }}
|
||||
T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }}
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }}
|
||||
T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }}
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
|
||||
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
|
||||
T3CODE_WEB_ROUTER_URL: ${{ vars.T3CODE_WEB_ROUTER_URL }}
|
||||
T3CODE_WEB_LATEST_DOMAIN: ${{ vars.T3CODE_WEB_LATEST_DOMAIN }}
|
||||
T3CODE_WEB_NIGHTLY_DOMAIN: ${{ vars.T3CODE_WEB_NIGHTLY_DOMAIN }}
|
||||
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=@t3tools/web...
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: relay-client-tracing-config
|
||||
path: ${{ runner.temp }}/relay-client-tracing
|
||||
|
||||
- name: Load relay client tracing config
|
||||
shell: bash
|
||||
run: |
|
||||
config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
|
||||
tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
|
||||
echo "::add-mask::$tracing_token"
|
||||
cat "$config_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Refresh release lockfile
|
||||
run: vp install --lockfile-only --ignore-scripts
|
||||
|
||||
- name: Deploy and alias channel
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" || -z "${VERCEL_PROJECT_ID:-}" ]]; then
|
||||
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
router_url="${T3CODE_WEB_ROUTER_URL:-https://app.t3.codes}"
|
||||
latest_domain="${T3CODE_WEB_LATEST_DOMAIN:-latest.app.t3.codes}"
|
||||
nightly_domain="${T3CODE_WEB_NIGHTLY_DOMAIN:-nightly.app.t3.codes}"
|
||||
router_domain="${router_url#http://}"
|
||||
router_domain="${router_domain#https://}"
|
||||
router_domain="${router_domain%%/*}"
|
||||
|
||||
if [[ "${{ needs.preflight.outputs.release_channel }}" == "stable" ]]; then
|
||||
channel_domain="$latest_domain"
|
||||
channel_name="latest"
|
||||
else
|
||||
channel_domain="$nightly_domain"
|
||||
channel_name="nightly"
|
||||
fi
|
||||
|
||||
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
|
||||
vercel_scope_args=(--scope "$vercel_scope")
|
||||
|
||||
echo "Deploying hosted web app for $channel_name channel."
|
||||
deployment_url="$(
|
||||
vp dlx [email protected] deploy \
|
||||
--prod \
|
||||
--skip-domain \
|
||||
--yes \
|
||||
--token "$VERCEL_TOKEN" \
|
||||
"${vercel_scope_args[@]}" \
|
||||
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
|
||||
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
|
||||
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
|
||||
--build-env "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=${T3CODE_CLERK_CLI_OAUTH_CLIENT_ID:-}" \
|
||||
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
|
||||
--build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=${T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN:-}" \
|
||||
--build-env "VITE_HOSTED_APP_URL=$router_url" \
|
||||
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
|
||||
)"
|
||||
|
||||
echo "Aliasing $deployment_url to $channel_domain."
|
||||
vp dlx [email protected] alias set "$deployment_url" "$channel_domain" \
|
||||
--token "$VERCEL_TOKEN" \
|
||||
"${vercel_scope_args[@]}"
|
||||
|
||||
if [[ "$channel_name" == "latest" && -n "$router_domain" && "$router_domain" != "$channel_domain" ]]; then
|
||||
echo "Aliasing $deployment_url to router domain $router_domain."
|
||||
vp dlx [email protected] alias set "$deployment_url" "$router_domain" \
|
||||
--token "$VERCEL_TOKEN" \
|
||||
"${vercel_scope_args[@]}"
|
||||
fi
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
|
||||
@@ -544,18 +926,15 @@ jobs:
|
||||
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
|
||||
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
- --filter=@t3tools/oxlint-plugin-t3code...
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
@@ -565,11 +944,11 @@ jobs:
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bunx [email protected] apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
run: vp fmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bun install --lockfile-only --ignore-scripts
|
||||
run: vp install --lockfile-only --ignore-scripts
|
||||
|
||||
- name: Commit and push version bump
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
@@ -577,7 +956,7 @@ jobs:
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
|
||||
run: |
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json pnpm-lock.yaml; then
|
||||
echo "No version changes to commit."
|
||||
exit 0
|
||||
fi
|
||||
@@ -585,7 +964,7 @@ jobs:
|
||||
git config user.name "${{ steps.app_bot.outputs.name }}"
|
||||
git config user.email "${{ steps.app_bot.outputs.email }}"
|
||||
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json pnpm-lock.yaml
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
git push origin HEAD:main
|
||||
|
||||
@@ -594,9 +973,11 @@ jobs:
|
||||
if: |
|
||||
always() && !cancelled() &&
|
||||
needs.preflight.result == 'success' &&
|
||||
needs.relay_public_config.result == 'success' &&
|
||||
needs.release.result == 'success' &&
|
||||
needs.deploy_web.result == 'success' &&
|
||||
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
|
||||
needs: [preflight, release, finalize]
|
||||
needs: [preflight, relay_public_config, release, deploy_web, finalize]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
@@ -605,18 +986,14 @@ jobs:
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
cache: true
|
||||
run-install: |
|
||||
args:
|
||||
- --filter=@t3tools/scripts...
|
||||
|
||||
- name: Announce prerelease on Discord
|
||||
if: needs.preflight.outputs.is_prerelease == 'true'
|
||||
|
||||
+10
@@ -5,6 +5,7 @@ node_modules
|
||||
*.log
|
||||
*.tsbuildinfo
|
||||
apps/*/dist
|
||||
infra/*/dist
|
||||
.astro
|
||||
packages/*/dist
|
||||
.env
|
||||
@@ -23,5 +24,14 @@ __screenshots__/
|
||||
.tanstack
|
||||
squashfs-root/
|
||||
.vercel
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
.showcase/
|
||||
apps/mobile/.showcase/
|
||||
artifacts/app-store/screenshots/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
.env*
|
||||
!.env.example
|
||||
@@ -0,0 +1,92 @@
|
||||
---
|
||||
title: Effect Service Conventions
|
||||
model: claude-opus-4-8
|
||||
effort: high
|
||||
input: full_diff
|
||||
tools:
|
||||
- browse_code
|
||||
- git_tools
|
||||
- github_api_read_only
|
||||
- modify_pr
|
||||
include:
|
||||
- "apps/**/*.ts"
|
||||
- "apps/**/*.tsx"
|
||||
- "packages/**/*.ts"
|
||||
- "packages/**/*.tsx"
|
||||
- "infra/**/*.ts"
|
||||
- "infra/**/*.tsx"
|
||||
conclusion: failure
|
||||
showToolCalls: true
|
||||
---
|
||||
|
||||
# Effect service review
|
||||
|
||||
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
|
||||
|
||||
## Imports and module namespaces
|
||||
|
||||
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
|
||||
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
|
||||
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
|
||||
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
|
||||
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
|
||||
|
||||
## Service definition
|
||||
|
||||
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
|
||||
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
|
||||
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
|
||||
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
|
||||
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
|
||||
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
|
||||
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
|
||||
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
|
||||
- `infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
|
||||
|
||||
## Dependency acquisition and runtime boundaries
|
||||
|
||||
- Production service construction must acquire Effect service dependencies from the environment with `yield* Foo.Foo`, and its `make`/`layer` types must expose those requirements. Flag factories or constructors that accept `Foo["Service"]` (or a plain object whose methods return `Effect`) when that value is an implementation dependency owned by the service. Passing service instances explicitly is acceptable in tests and integration harnesses; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection.
|
||||
- Do not hide dependencies in module globals, closures over singleton services, or `Layer.succeed` implementations that call runtime-backed or imperative APIs. Trace helpers used by a supposedly synchronous layer far enough to verify that asynchronous services are represented in the Effect environment.
|
||||
- `ManagedRuntime.make`, `runPromise`, and `runPromiseExit` belong at explicit application/framework boundaries such as React, native callback, CLI, or HTTP adapters. Flag their use in domain services, repositories, persistence implementations, and service constructors. A clearly named imperative adapter may bridge an Effect service into a Promise API, but it must not become a dependency of another Effect service.
|
||||
- Do not create per-feature managed runtimes or Atom runtimes to smuggle the same owned resource into multiple consumers. Compose the resource once in an application-owned layer/runtime and provide its context to integration runtimes.
|
||||
- When acquisition can fail but a caller must retain fallback behavior, keep the failure typed in Effect rather than bypassing the layer through an imperative runtime. Model unavailability in service operations or with an explicit optional-service layer so downstream recovery remains visible and testable.
|
||||
- During review, search touched code and affected call sites for service-instance parameters, `Layer.succeed`, `ManagedRuntime.make`, and `.runPromise`/`.runPromiseExit`. Verify that each occurrence is a legitimate test seam, pure value injection, or application boundary—not fake dependency injection or a hidden runtime.
|
||||
|
||||
## Errors and predicates
|
||||
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
|
||||
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
|
||||
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
|
||||
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
|
||||
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
|
||||
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
|
||||
|
||||
## Change discipline
|
||||
|
||||
- Preserve useful comments, invariants, and specification documentation while moving code.
|
||||
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
|
||||
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
|
||||
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"xcodebuildmcp": {
|
||||
"command": "npx",
|
||||
"args": ["--yes", "[email protected]", "mcp"],
|
||||
"env": {
|
||||
"XCODEBUILDMCP_ENABLED_WORKFLOWS": "simulator,ui-automation,debugging,logging"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
[tools]
|
||||
node = "24.13.1"
|
||||
bun = "1.3.9"
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
".reference",
|
||||
".plans",
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/web/public/mockServiceWorker.js",
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts",
|
||||
"*.icon/**"
|
||||
],
|
||||
"sortPackageJson": {},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [".devcontainer/devcontainer.json"],
|
||||
"options": {
|
||||
"trailingComma": "none"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts"
|
||||
],
|
||||
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
|
||||
"categories": {
|
||||
"correctness": "warn",
|
||||
"suspicious": "warn",
|
||||
"perf": "warn"
|
||||
},
|
||||
"rules": {
|
||||
"react-in-jsx-scope": "off",
|
||||
"eslint/no-shadow": "off",
|
||||
"eslint/no-await-in-loop": "off"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Plan: seamless `npx t3 connect` for remote boxes</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #000;
|
||||
--fg: #fff;
|
||||
--muted: #a3a3a3;
|
||||
--surface: #121212;
|
||||
--surface2: #1a1a1a;
|
||||
--border: #2a2a2a;
|
||||
--accent: #7c9cff;
|
||||
--green: #4ade80;
|
||||
--amber: #fbbf24;
|
||||
--red: #f87171;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
}
|
||||
main { max-width: 880px; margin: 0 auto; padding: 48px 24px 96px; }
|
||||
h1 { font-size: 30px; line-height: 1.25; margin: 0 0 8px; }
|
||||
h2 { font-size: 21px; margin: 48px 0 12px; padding-top: 24px; border-top: 1px solid var(--border); }
|
||||
h3 { font-size: 16px; margin: 24px 0 8px; }
|
||||
p, li { color: #e5e5e5; }
|
||||
.sub { color: var(--muted); margin: 0 0 24px; }
|
||||
code, pre {
|
||||
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
code { background: var(--surface2); border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px; }
|
||||
pre {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
overflow-x: auto;
|
||||
line-height: 1.5;
|
||||
}
|
||||
pre code { background: none; border: none; padding: 0; }
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 18px 20px;
|
||||
margin: 16px 0;
|
||||
}
|
||||
.card h3 { margin-top: 0; }
|
||||
table { border-collapse: collapse; width: 100%; margin: 16px 0; font-size: 14.5px; }
|
||||
th, td { text-align: left; padding: 8px 12px; border: 1px solid var(--border); vertical-align: top; }
|
||||
th { background: var(--surface2); font-weight: 600; }
|
||||
td code { white-space: nowrap; }
|
||||
.pill {
|
||||
display: inline-block; font-size: 12px; font-weight: 600; border-radius: 999px;
|
||||
padding: 2px 10px; margin-right: 6px; vertical-align: 2px;
|
||||
}
|
||||
.pill.core { background: #1e2a4a; color: var(--accent); }
|
||||
.pill.new { background: #14301e; color: var(--green); }
|
||||
.pill.later { background: #33270e; color: var(--amber); }
|
||||
.ok { color: var(--green); }
|
||||
.warn { color: var(--amber); }
|
||||
.no { color: var(--red); }
|
||||
ul { padding-left: 22px; }
|
||||
li { margin: 4px 0; }
|
||||
.terminal {
|
||||
background: #0a0a0a; border: 1px solid var(--border); border-radius: 8px;
|
||||
padding: 16px; font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
||||
font-size: 13.5px; line-height: 1.65; color: #d4d4d4; overflow-x: auto;
|
||||
}
|
||||
.terminal .dim { color: #737373; }
|
||||
.terminal .g { color: var(--green); }
|
||||
.terminal .b { color: var(--accent); }
|
||||
figure { margin: 24px 0; }
|
||||
figcaption { color: var(--muted); font-size: 13px; margin-top: 8px; text-align: center; }
|
||||
svg text { font-family: -apple-system, "Segoe UI", sans-serif; }
|
||||
a { color: var(--accent); }
|
||||
.kv { color: var(--muted); font-size: 13.5px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
|
||||
<h1>Seamless <code>npx t3 connect</code> for remote boxes</h1>
|
||||
<p class="sub">Design principle: <strong>the smallest diff that ships the UX.</strong> No relay/infra changes, no new backend surface, no new auth primitives — every step reuses code that already exists. One PR, built as four phases with clear commit boundaries — each phase compiles, passes tests, and leaves the product working, so the PR reviews commit-by-commit. (Phase 4, web-triggered update, is an optional follow-up PR.)</p>
|
||||
|
||||
<div class="terminal">
|
||||
$ npx t3 connect<br><br>
|
||||
To set up T3 Connect, open this URL and sign in:<br>
|
||||
<span class="b">https://app.t3.codes/connect#B64URL_STATE_AND_CHALLENGE</span><br><br>
|
||||
Enter your authentication code: <span class="dim">[code]</span><br><br>
|
||||
<span class="g">Connected as [email protected]!</span><br><br>
|
||||
Run T3 Code in the background whenever this machine boots? (y/n): y<br><br>
|
||||
<span class="g">T3 Code is set up and ready to go.</span>
|
||||
</div>
|
||||
|
||||
<h2>Why this is a small change</h2>
|
||||
<p>The entire <code>t3 connect</code> data plane already works: Clerk PKCE token exchange, encrypted secret store, cloudflared relay-client install, relay environment linking, DPoP tokens. The <em>only</em> broken piece on an SSH box is the redirect: <code>CliTokenManager.login()</code> hardcodes a loopback callback (<code>http://127.0.0.1:34338/callback</code>) that requires a browser on the same machine.</p>
|
||||
<p>We swap that one leg for a hosted out-of-band authorization page and keep everything else. Because PKCE's <code>code_verifier</code> never leaves the box, the displayed one-time code is useless to anyone who sees it — no new token-minting or storage is needed anywhere.</p>
|
||||
|
||||
<div class="card">
|
||||
<h3>Reused as-is (zero changes)</h3>
|
||||
<ul>
|
||||
<li><code>exchangeToken()</code> PKCE exchange — <code>apps/server/src/cloud/CliTokenManager.ts:147</code></li>
|
||||
<li>Token persistence in <code>ServerSecretStore</code> (<code>cloud-cli-oauth-token</code>)</li>
|
||||
<li><code>acquireRelayClientForLink()</code> cloudflared install + progress — <code>cli/connect.ts:146</code></li>
|
||||
<li><code>CliState.setCliDesiredCloudLink()</code> + server-side provisioning on start</li>
|
||||
<li>All relay endpoints (<code>infra/relay</code>) and contracts — <strong>untouched</strong></li>
|
||||
<li>Existing subcommands <code>login/link/status/unlink/logout</code> — semantics unchanged</li>
|
||||
<li>Web app Clerk session + hosted-page precedent (<code>routes/pair.tsx</code>, <code>hostedPairing.ts</code>)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>Auth flow (hosted out-of-band OAuth, Clerk PKCE)</h2>
|
||||
|
||||
<figure>
|
||||
<svg viewBox="0 0 820 470" width="100%" role="img" aria-label="Sequence diagram of the out-of-band OAuth flow">
|
||||
<!-- lanes -->
|
||||
<rect x="20" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
|
||||
<rect x="300" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
|
||||
<rect x="580" y="16" width="220" height="44" rx="8" fill="#121212" stroke="#2a2a2a"/>
|
||||
<text x="130" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Remote box — t3 CLI</text>
|
||||
<text x="410" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Laptop — app.t3.codes</text>
|
||||
<text x="690" y="43" fill="#fff" font-size="14" font-weight="600" text-anchor="middle">Clerk</text>
|
||||
<line x1="130" y1="60" x2="130" y2="450" stroke="#2a2a2a"/>
|
||||
<line x1="410" y1="60" x2="410" y2="450" stroke="#2a2a2a"/>
|
||||
<line x1="690" y1="60" x2="690" y2="450" stroke="#2a2a2a"/>
|
||||
|
||||
<!-- 1: generate + print -->
|
||||
<rect x="30" y="80" width="200" height="34" rx="6" fill="#1e2a4a"/>
|
||||
<text x="130" y="101" fill="#7c9cff" font-size="12.5" text-anchor="middle">1. gen verifier + challenge + state</text>
|
||||
|
||||
<!-- 2: user opens URL -->
|
||||
<line x1="130" y1="140" x2="404" y2="140" stroke="#7c9cff" stroke-dasharray="5 4"/>
|
||||
<polygon points="404,140 394,135 394,145" fill="#7c9cff"/>
|
||||
<text x="267" y="132" fill="#a3a3a3" font-size="12.5" text-anchor="middle">2. user opens /connect#{state,challenge}</text>
|
||||
|
||||
<!-- 3: redirect to clerk -->
|
||||
<line x1="410" y1="185" x2="684" y2="185" stroke="#e5e5e5"/>
|
||||
<polygon points="684,185 674,180 674,190" fill="#e5e5e5"/>
|
||||
<text x="547" y="177" fill="#a3a3a3" font-size="12.5" text-anchor="middle">3. sign in → /oauth/authorize (PKCE)</text>
|
||||
|
||||
<!-- 4: redirect back with code -->
|
||||
<line x1="690" y1="230" x2="416" y2="230" stroke="#e5e5e5"/>
|
||||
<polygon points="416,230 426,225 426,235" fill="#e5e5e5"/>
|
||||
<text x="553" y="222" fill="#a3a3a3" font-size="12.5" text-anchor="middle">4. redirect /connect/callback?code&state</text>
|
||||
|
||||
<!-- 5: page shows code -->
|
||||
<rect x="310" y="252" width="200" height="34" rx="6" fill="#14301e"/>
|
||||
<text x="410" y="273" fill="#4ade80" font-size="12.5" text-anchor="middle">5. shows account + authorization code</text>
|
||||
|
||||
<!-- 6: user enters code -->
|
||||
<line x1="410" y1="316" x2="136" y2="316" stroke="#7c9cff" stroke-dasharray="5 4"/>
|
||||
<polygon points="136,316 146,311 146,321" fill="#7c9cff"/>
|
||||
<text x="273" y="308" fill="#a3a3a3" font-size="12.5" text-anchor="middle">6. user enters code in terminal</text>
|
||||
|
||||
<!-- 7: token exchange -->
|
||||
<line x1="130" y1="360" x2="684" y2="360" stroke="#e5e5e5"/>
|
||||
<polygon points="684,360 674,355 674,365" fill="#e5e5e5"/>
|
||||
<text x="407" y="352" fill="#a3a3a3" font-size="12.5" text-anchor="middle">7. POST /oauth/token {code + verifier} → access/refresh tokens</text>
|
||||
|
||||
<!-- 8: done -->
|
||||
<rect x="30" y="392" width="200" height="46" rx="6" fill="#14301e"/>
|
||||
<text x="130" y="411" fill="#4ade80" font-size="12.5" text-anchor="middle">8. store token, set desired link,</text>
|
||||
<text x="130" y="427" fill="#4ade80" font-size="12.5" text-anchor="middle">install relay client → Connected!</text>
|
||||
</svg>
|
||||
<figcaption>The verifier never leaves the box (steps 1→7), so the authorization code is worthless if observed. state/challenge ride the URL fragment — they are not secrets.</figcaption>
|
||||
</figure>
|
||||
|
||||
<div class="card">
|
||||
<h3>Details that keep it simple</h3>
|
||||
<ul>
|
||||
<li><strong>Stateless URL, no short-link service.</strong> The <code>/connect</code> page reads <code>state</code> + <code>code_challenge</code> from the URL fragment and builds the Clerk authorize URL client-side. ~100-char URL — fine to transfer into an SSH session.</li>
|
||||
<li><strong>State check without a backend:</strong> the callback page displays one authorization blob of <code>code.state</code>; the CLI splits it and verifies <code>state</code> matches what it generated. One line on each side, preserves the loopback flow's CSRF check.</li>
|
||||
<li><strong>Phishing is addressed with copy, not code:</strong> the callback page shows <em>which account</em> is being connected ("Connecting as theo@…") and warns: <em>"Only enter this code in a terminal session you started yourself."</em> No mechanism needed.</li>
|
||||
<li><strong>Code expiry is a non-issue:</strong> Clerk auth codes live 10 minutes — the same timeout the existing loopback flow already uses. Wrong/expired code → friendly retry that reprints the URL.</li>
|
||||
<li><strong>One external config step:</strong> register <code>https://app.t3.codes/connect/callback</code> as an allowed redirect URI on the existing Clerk CLI OAuth client. No new client, no new scopes.</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<h2>The phases (one PR, one commit each)</h2>
|
||||
<p class="kv">Ordering is dependency order: each phase is independently revertable and the tree is green at every boundary. Phases 1–3 are the PR; phase 4 ships separately later.</p>
|
||||
|
||||
<table>
|
||||
<tr><th style="width:1%">Phase</th><th>Scope</th><th>Files</th><th style="width:1%">~LOC</th></tr>
|
||||
<tr>
|
||||
<td><span class="pill core">1</span></td>
|
||||
<td><strong>Hosted code page</strong> (web-only, purely additive, zero risk). Two static routes modeled on <code>pair.tsx</code>: <code>/connect</code> (ensure Clerk session, then client-side redirect to authorize — it's a static SPA, no server 302) and <code>/connect/callback</code> (validate params, show account + copyable code + safety warning). Both routes guard against non-hosted deployments — redirect to <code>/</code> unless <code>isHostedStaticApp()</code>, same pattern as <code>pair.tsx</code>, since this bundle also ships in local instances. Plus the Clerk dashboard redirect-URI entry.</td>
|
||||
<td><code>apps/web/src/routes/connect.tsx</code><br><code>apps/web/src/routes/connect.callback.tsx</code></td>
|
||||
<td>~200</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="pill core">2</span></td>
|
||||
<td><strong>CLI out-of-band OAuth flow + single command.</strong> Add an out-of-band OAuth login path to <code>CliTokenManager</code> (print URL, <code>Prompt.text</code> for the code, reuse <code>exchangeToken</code>). Make bare <code>t3 connect</code> a handler = login + link (subcommands untouched). Auto-pick headless mode inside SSH sessions (<code>SSH_CONNECTION</code>/<code>SSH_TTY</code> — nothing else); <code>--headless</code> flag as manual override. Loopback stays the default on desktop — no regression.</td>
|
||||
<td><code>cloud/CliTokenManager.ts</code> (+60)<br><code>cloud/publicConfig.ts</code> (+10)<br><code>cli/connect.ts</code> (+60)</td>
|
||||
<td>~150</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="pill new">3</span></td>
|
||||
<td><strong>Background on boot — Linux first</strong> (the SSH case). One new module: pinned runtime install to <code>~/.t3/runtime/versions/<v></code> + <code>current</code> symlink, systemd <em>user</em> unit with absolute node/t3 paths, <code>enable-linger</code>. y/n prompt at the end of <code>connect</code>; teardown in <code>logout</code>. Install and service-start failures must land in a log file (under <code>~/.t3/userdata/logs/</code>) whose path is printed at connect time — systemd user units fail invisibly otherwise. Unit-file generation is pure string-building → trivially testable. macOS launchd / Windows follow as 3b/3c only if wanted.</td>
|
||||
<td><code>cloud/bootService.ts</code> (new)<br><code>cli/connect.ts</code> (+prompt/teardown)</td>
|
||||
<td>~250</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><span class="pill later">4</span></td>
|
||||
<td><strong>Web-triggered update</strong> (optional follow-up PR; not part of this one, not needed for the core UX). Web detects <code>daemon version < latest-on-channel</code> using the existing version-skew surface + hosted manifest; one authenticated "update" command — client says <em>update</em>, daemon resolves/verifies the version itself (never client-specified — that would be RCE). Stage install → verify → atomic symlink swap → <code>systemctl --user restart</code>. Progress streams reuse the <code>RelayClientInstallProgressEvent</code> pattern.</td>
|
||||
<td>web banner + one control command + daemon update routine</td>
|
||||
<td>later</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h3>Runtime layout (phase 3)</h3>
|
||||
<pre><code>~/.t3/runtime/
|
||||
├── versions/0.0.27/ ← npm install --prefix (gets native deps right: node-pty etc.)
|
||||
└── current -> versions/0.0.27
|
||||
|
||||
~/.config/systemd/user/t3code.service ← ExecStart=/abs/path/node .../current/.../t3 serve
|
||||
loginctl enable-linger $USER ← survives SSH logout / reboot</code></pre>
|
||||
<p class="kv">Why a real <code>npm install</code> and not "reuse the npx binary": the npx cache is ephemeral and <code>t3</code> ships native deps (<code>node-pty</code>, <code>@ff-labs/fff-node</code>) that need per-platform prebuilds. Why pinned and not <code>npx t3@latest</code> in the unit: a boot-time registry fetch means the box may simply not come up (network down, PATH-less systemd env, nvm). Deterministic boot; updates happen out-of-band (phase 4 follow-up) or by re-running <code>npx t3 connect</code>.</p>
|
||||
|
||||
<h2>Explicitly not doing</h2>
|
||||
<ul>
|
||||
<li><span class="no">✗</span> Relay / <code>infra</code> / contracts changes — none, in any phase</li>
|
||||
<li><span class="no">✗</span> Short-link service (<code>app.t3.codes/c/AB7K</code>) — only matters for hand-typing; revisit if ever needed</li>
|
||||
<li><span class="no">✗</span> RFC 8628 device grant — wrong UX direction, unverified Clerk support</li>
|
||||
<li><span class="no">✗</span> Auto-update loop in the daemon — web-triggered only (phase 4 follow-up), user stays in control</li>
|
||||
<li><span class="no">✗</span> Project auto-registration — workspace assumed set up; the web UI handles the rest</li>
|
||||
<li><span class="no">✗</span> Changing existing loopback flow, subcommands, or desktop behavior</li>
|
||||
</ul>
|
||||
|
||||
<h2>Risks & checks</h2>
|
||||
<ul>
|
||||
<li><span class="warn">⚠</span> <strong>Clerk redirect URI:</strong> confirm the CLI OAuth client accepts the hosted redirect and that the token endpoint honors PKCE exchange for codes issued to it. Verify in staging before the phase 2 commit. <em>(Only external dependency in the plan.)</em></li>
|
||||
<li><span class="warn">⚠</span> <strong>systemd user env is minimal:</strong> always write absolute paths for node + t3 into the unit; never rely on PATH. Service failures are invisible by default — hence the phase 3 requirement to log to a printed file path.</li>
|
||||
<li><span class="warn">⚠</span> <strong>Linger prompt honesty:</strong> the y/n prompt should say the machine becomes reachable via T3 Connect whenever powered on — that's the feature, but say it.</li>
|
||||
<li><span class="ok">✓</span> Re-running <code>connect</code> when linked → idempotent: refresh token, re-confirm service, done.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Decision log</h2>
|
||||
<ul class="kv">
|
||||
<li>Auth: hosted out-of-band OAuth redirect on Clerk PKCE (not relay-brokered pairing, not device grant) — chosen for minimal new surface.</li>
|
||||
<li>URL: stateless static page, no backend short-link.</li>
|
||||
<li>Service: real per-user login service (systemd user + linger first); detect + offer install, never silent.</li>
|
||||
<li>Binary: pinned managed runtime under <code>~/.t3</code>; interactive <code>npx</code> usage untouched.</li>
|
||||
<li>Updates: not always-latest; web UI surfaces available updates with one-click trigger (phase 4 follow-up).</li>
|
||||
<li>Delivery: one PR with a commit per phase (green tree at every boundary), not separate PRs.</li>
|
||||
<li>Workspace: assumed already set up; no auto-registration.</li>
|
||||
</ul>
|
||||
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
alchemy/test/**
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
name: Deploy Website
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "website/**"
|
||||
- "packages/alchemy/**"
|
||||
- "bun.lock"
|
||||
- ".github/workflows/deploy.yml"
|
||||
pull_request:
|
||||
types:
|
||||
- opened
|
||||
- reopened
|
||||
- synchronize
|
||||
- closed
|
||||
paths:
|
||||
- "website/**"
|
||||
- "packages/alchemy/**"
|
||||
- "bun.lock"
|
||||
- ".github/workflows/deploy.yml"
|
||||
|
||||
concurrency:
|
||||
group: deploy-website-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
STAGE: ${{ github.event_name == 'pull_request' && format('pr-{0}',
|
||||
github.event.number) || (github.ref == 'refs/heads/main' && 'prod' ||
|
||||
github.ref_name) }}
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
if: ${{ github.event.action != 'closed' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
# Mint a token for the alchemy-version-bot GitHub App so the PR
|
||||
# preview comment (created via GitHub.Comment in alchemy.run.ts)
|
||||
# posts under the bot's identity instead of `github-actions[bot]`.
|
||||
# Same App as release.yml — its installation scopes already cover
|
||||
# PR comments.
|
||||
- name: Generate bot token
|
||||
id: bot-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
||||
with:
|
||||
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
|
||||
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
# Build the website ahead of `alchemy deploy`. The
|
||||
# Cloudflare.StaticSite resource declares the same `bun run build`
|
||||
# in its config and runs it as part of the create lifecycle, but
|
||||
# on update plans alchemy reads `dist/` during plan.diff before
|
||||
# the embedded Build resource gets a chance to (re)run, causing
|
||||
# a NotFound on a fresh CI checkout. Building here makes the
|
||||
# workflow correct under both create and update plans.
|
||||
- name: Build website
|
||||
working-directory: website
|
||||
run: bun run build
|
||||
|
||||
- name: Deploy
|
||||
working-directory: website
|
||||
run: bun alchemy deploy --stage ${{ env.STAGE }} --yes
|
||||
env:
|
||||
# Alchemy's Cloudflare auth provider accepts either a scoped
|
||||
# API token (CLOUDFLARE_API_TOKEN) or the legacy global API
|
||||
# key paired with email (CLOUDFLARE_API_KEY +
|
||||
# CLOUDFLARE_EMAIL). We use the latter here so CI matches
|
||||
# the credentials in Doppler / .env, where only the admin
|
||||
# global key is provisioned.
|
||||
CLOUDFLARE_API_KEY: ${{ secrets.ADMIN_CLOUDFLARE_API_KEY }}
|
||||
CLOUDFLARE_EMAIL: ${{ secrets.ADMIN_CLOUDFLARE_EMAIL }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ env.STAGE == 'prod' &&
|
||||
secrets.PROD_CLOUDFLARE_ACCOUNT_ID ||
|
||||
secrets.TEST_CLOUDFLARE_ACCOUNT_ID }}
|
||||
PULL_REQUEST: ${{ github.event.number }}
|
||||
# On `pull_request` events GitHub Actions' built-in
|
||||
# `GITHUB_SHA` is the synthetic merge commit (PR head merged
|
||||
# into base) — that SHA never shows up in the PR's git log.
|
||||
# `GITHUB_SHA` is also a reserved env var, so a step-level
|
||||
# override is silently ignored. Pass the PR head SHA under
|
||||
# a non-reserved name and read it from alchemy.run.ts.
|
||||
BUILD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
GITHUB_TOKEN: ${{ steps.bot-token.outputs.token }}
|
||||
|
||||
cleanup:
|
||||
runs-on: ubuntu-latest
|
||||
if:
|
||||
${{ github.event_name == 'pull_request' && github.event.action == 'closed'
|
||||
}}
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Generate bot token
|
||||
id: bot-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
||||
with:
|
||||
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
|
||||
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
- name: Safety Check
|
||||
run: |-
|
||||
if [ "${{ env.STAGE }}" = "prod" ]; then
|
||||
echo "ERROR: Cannot destroy prod environment in cleanup job"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Destroy Preview Environment
|
||||
working-directory: website
|
||||
run: bun alchemy destroy --stage ${{ env.STAGE }} --yes
|
||||
env:
|
||||
CLOUDFLARE_API_KEY: ${{ secrets.ADMIN_CLOUDFLARE_API_KEY }}
|
||||
CLOUDFLARE_EMAIL: ${{ secrets.ADMIN_CLOUDFLARE_EMAIL }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.TEST_CLOUDFLARE_ACCOUNT_ID }}
|
||||
PULL_REQUEST: ${{ github.event.number }}
|
||||
GITHUB_TOKEN: ${{ steps.bot-token.outputs.token }}
|
||||
@@ -0,0 +1,180 @@
|
||||
name: pr-package
|
||||
|
||||
# Publishes alchemy + better-auth + pr-package tarballs to the pr-package
|
||||
# service at pkg.ing on every push to main and every PR sync. On PR close,
|
||||
# deletes every tag we ever assigned for that PR so the underlying tarballs
|
||||
# become orphaned and the bucket cleans them up.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, closed]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
PR_PACKAGE_HOST: pkg.ing
|
||||
NODE_VERSION: "24"
|
||||
|
||||
jobs:
|
||||
# ── Publish on push-to-main and PR sync. ──────────────────────────────────
|
||||
publish:
|
||||
if: github.event_name == 'push' || (github.event_name == 'pull_request' &&
|
||||
github.event.action != 'closed')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
# Build everything: tsdown bundles alchemy (bin/ + cli lib) and tsc -b
|
||||
# populates lib/ for the layer packages (better-auth, pr-package).
|
||||
# Their tarballs ship both src/ and lib/, and consumers in non-bun
|
||||
# runtimes resolve via the `import` condition → ./lib/index.js.
|
||||
- run: bun run build:packages
|
||||
|
||||
- name: Compute tags
|
||||
id: tags
|
||||
env:
|
||||
EVENT: ${{ github.event_name }}
|
||||
# `head_ref` for PRs (source branch), `ref_name` for push (e.g. "main").
|
||||
BRANCH: ${{ github.event_name == 'pull_request' && github.head_ref ||
|
||||
github.ref_name }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
# PR builds run on the merge commit by default; tag the actual head sha
|
||||
# so consumers can pin to a specific PR commit.
|
||||
SHA: ${{ github.event_name == 'pull_request' &&
|
||||
github.event.pull_request.head.sha || github.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
short="${SHA:0:7}"
|
||||
long="$SHA"
|
||||
tags=("$short" "$long" "$BRANCH")
|
||||
if [ "$EVENT" = "pull_request" ]; then
|
||||
tags+=("pr-${PR_NUMBER}")
|
||||
fi
|
||||
json=$(printf '%s\n' "${tags[@]}" | jq -R . | jq -s -c .)
|
||||
echo "tags=$json" >> "$GITHUB_OUTPUT"
|
||||
echo "short=$short" >> "$GITHUB_OUTPUT"
|
||||
echo "Tags: $json"
|
||||
|
||||
# PR builds expire after 1 week; pushes to main omit the header and
|
||||
# fall back to the worker's defaultTtl (3 weeks).
|
||||
- name: Publish alchemy
|
||||
env:
|
||||
TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
|
||||
TAGS: ${{ steps.tags.outputs.tags }}
|
||||
TTL: ${{ github.event_name == 'pull_request' && '1 week' || '' }}
|
||||
working-directory: packages/alchemy
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rm -f *.tgz
|
||||
bun pm pack --destination .
|
||||
tgz=$(ls *.tgz)
|
||||
echo "Publishing $tgz with tags $TAGS ttl=${TTL:-default}"
|
||||
curl -fsSL --show-error -X PUT \
|
||||
"https://${PR_PACKAGE_HOST}/projects/alchemy/packages" \
|
||||
-H "Authorization: Bearer ${TOKEN}" \
|
||||
-H "X-Tags: ${TAGS}" \
|
||||
${TTL:+-H "X-TTL: ${TTL}"} \
|
||||
-H "Content-Type: application/gzip" \
|
||||
--data-binary "@${tgz}"
|
||||
|
||||
- name: Publish better-auth
|
||||
env:
|
||||
TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
|
||||
TAGS: ${{ steps.tags.outputs.tags }}
|
||||
TTL: ${{ github.event_name == 'pull_request' && '1 week' || '' }}
|
||||
working-directory: packages/better-auth
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rm -f *.tgz
|
||||
bun pm pack --destination .
|
||||
tgz=$(ls *.tgz)
|
||||
echo "Publishing $tgz with tags $TAGS ttl=${TTL:-default}"
|
||||
curl -fsSL --show-error -X PUT \
|
||||
"https://${PR_PACKAGE_HOST}/projects/@alchemy.run/better-auth/packages" \
|
||||
-H "Authorization: Bearer ${TOKEN}" \
|
||||
-H "X-Tags: ${TAGS}" \
|
||||
${TTL:+-H "X-TTL: ${TTL}"} \
|
||||
-H "Content-Type: application/gzip" \
|
||||
--data-binary "@${tgz}"
|
||||
|
||||
- name: Publish pr-package
|
||||
env:
|
||||
TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
|
||||
TAGS: ${{ steps.tags.outputs.tags }}
|
||||
TTL: ${{ github.event_name == 'pull_request' && '1 week' || '' }}
|
||||
working-directory: packages/pr-package
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rm -f *.tgz
|
||||
bun pm pack --destination .
|
||||
tgz=$(ls *.tgz)
|
||||
echo "Publishing $tgz with tags $TAGS ttl=${TTL:-default}"
|
||||
curl -fsSL --show-error -X PUT \
|
||||
"https://${PR_PACKAGE_HOST}/projects/@alchemy.run/pr-package/packages" \
|
||||
-H "Authorization: Bearer ${TOKEN}" \
|
||||
-H "X-Tags: ${TAGS}" \
|
||||
${TTL:+-H "X-TTL: ${TTL}"} \
|
||||
-H "Content-Type: application/gzip" \
|
||||
--data-binary "@${tgz}"
|
||||
|
||||
# PR-only: leave a sticky comment with the install URLs pinned to this
|
||||
# commit. Uses pkg.ing (the canonical short host), which serves both
|
||||
# the pretty alias paths and the underlying /projects/:project/tags/:tag
|
||||
# API directly.
|
||||
- name: Generate bot token
|
||||
if: github.event_name == 'pull_request'
|
||||
id: bot-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
||||
with:
|
||||
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
|
||||
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
|
||||
|
||||
- name: Comment on PR
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.bot-token.outputs.token }}
|
||||
REPO: ${{ github.repository }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
SHORT_SHA: ${{ steps.tags.outputs.short }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
MARKER="<!-- pr-package-comment -->"
|
||||
# Use `bun add <name>@<url>` instead of `bun add <url>`. Without an
|
||||
# explicit name, bun's resolver hits a DependencyLoop bug when the
|
||||
# consumer already has the same package name resolved from npm
|
||||
# (oven-sh/bun#5789, oven-sh/bun#17946). The aliased form bypasses
|
||||
# the buggy reconciliation path and works on fresh and existing
|
||||
# projects alike.
|
||||
BODY=$(printf '%s\n\nInstall the packages built from this commit:\n\n**alchemy**\n```sh\nbun add alchemy@https://pkg.ing/alchemy/%s\n```\n\n**@alchemy.run/better-auth**\n```sh\nbun add @alchemy.run/better-auth@https://pkg.ing/@alchemy.run/better-auth/%s\n```\n\n**@alchemy.run/pr-package**\n```sh\nbun add @alchemy.run/pr-package@https://pkg.ing/@alchemy.run/pr-package/%s\n```\n' "$MARKER" "$SHORT_SHA" "$SHORT_SHA" "$SHORT_SHA")
|
||||
|
||||
existing=$(gh api --paginate \
|
||||
"repos/${REPO}/issues/${PR_NUMBER}/comments" \
|
||||
--jq ".[] | select(.user.login == \"alchemy-version-bot[bot]\") | select(.body | startswith(\"${MARKER}\")) | .id" \
|
||||
| head -1)
|
||||
|
||||
if [ -n "$existing" ]; then
|
||||
gh api -X PATCH "repos/${REPO}/issues/comments/${existing}" -f body="$BODY"
|
||||
else
|
||||
gh api -X POST "repos/${REPO}/issues/${PR_NUMBER}/comments" -f body="$BODY"
|
||||
fi
|
||||
+432
@@ -0,0 +1,432 @@
|
||||
name: Release NPM Package
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
description: "Release channel"
|
||||
required: true
|
||||
type: choice
|
||||
default: beta
|
||||
options:
|
||||
- release
|
||||
- beta
|
||||
- alpha
|
||||
- tag
|
||||
spec:
|
||||
description: >-
|
||||
Channel-specific value. tag: REQUIRED, the explicit full version (e.g.
|
||||
2.0.0-experimental.1). release: REQUIRED, patch|minor|major or an
|
||||
explicit x.y.z. beta|alpha: optional, an integer N to force
|
||||
2.0.0-<channel>.N; leave blank to auto-increment.
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
|
||||
env:
|
||||
NODE_VERSION: "24"
|
||||
# Files produced by the bump job and consumed by every publish job + the
|
||||
# final commit job. Listed once here so additions stay in sync.
|
||||
BUMP_ARTIFACT_PATHS: |
|
||||
packages/alchemy/lib
|
||||
packages/alchemy/bin
|
||||
packages/alchemy/package.json
|
||||
packages/better-auth/package.json
|
||||
packages/better-auth/lib
|
||||
packages/pr-package/package.json
|
||||
packages/pr-package/lib
|
||||
bun.lock
|
||||
jobs:
|
||||
# ── Step 1: Compute the next version and stage the bump in-memory. ──
|
||||
# No git commit: we want a failed publish to leave no orphan commit
|
||||
# behind. The staged files ride to the publish jobs (and the final commit
|
||||
# job) as an artifact.
|
||||
bump:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.bump.outputs.version }}
|
||||
channel: ${{ inputs.channel }}
|
||||
sha: ${{ steps.sha.outputs.sha }}
|
||||
steps:
|
||||
- name: Validate inputs
|
||||
env:
|
||||
CHANNEL: ${{ inputs.channel }}
|
||||
SPEC: ${{ inputs.spec }}
|
||||
run: |
|
||||
case "$CHANNEL" in
|
||||
tag)
|
||||
if [ -z "$SPEC" ]; then
|
||||
echo "::error::'tag' channel requires an explicit version in 'spec' (e.g. 2.0.0-experimental.1)"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
release)
|
||||
if [ -z "$SPEC" ]; then
|
||||
echo "::error::'release' channel requires a 'spec' (patch|minor|major|x.y.z)"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- id: sha
|
||||
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
registry-url: https://registry.npmjs.org/
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- id: bump
|
||||
env:
|
||||
CHANNEL: ${{ inputs.channel }}
|
||||
SPEC: ${{ inputs.spec }}
|
||||
run: |
|
||||
if [ -n "$SPEC" ]; then
|
||||
VERSION=$(bun ./scripts/release/bump.ts "$CHANNEL" "$SPEC")
|
||||
else
|
||||
VERSION=$(bun ./scripts/release/bump.ts "$CHANNEL")
|
||||
fi
|
||||
echo "Resolved version: $VERSION (channel: $CHANNEL)"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Build everything once, up front, against the bumped versions. Outputs
|
||||
# ride to every publish job as the `build-output` artifact so we don't
|
||||
# rebuild three times in parallel.
|
||||
- run: bun run build:packages
|
||||
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: bump-files
|
||||
path: ${{ env.BUMP_ARTIFACT_PATHS }}
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: build-output
|
||||
path: |
|
||||
packages/*/lib
|
||||
packages/*/bin
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
include-hidden-files: true
|
||||
|
||||
# ── Step 2: Commit (bump + changelog) and tag BEFORE publishing.
|
||||
# Committing first means the publishable source of truth is the tagged
|
||||
# commit; publish jobs check it out by SHA. Durability: if a previous
|
||||
# attempt already committed and tagged but failed during npm publish, the
|
||||
# bump job's HEAD-tag detection reuses the existing version, and this job
|
||||
# detects HEAD is already at the tag and skips the commit/push.
|
||||
# Skipped for `tag` channel — those releases are intentionally uncommitted.
|
||||
commit-and-tag:
|
||||
needs: bump
|
||||
if: inputs.channel != 'tag'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
sha: ${{ steps.commit.outputs.sha }}
|
||||
steps:
|
||||
- name: Generate bot token
|
||||
id: bot-token
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
||||
with:
|
||||
app-id: ${{ secrets.ALCHEMY_VERSION_BOT_ID }}
|
||||
private-key: ${{ secrets.ALCHEMY_VERSION_BOT_PRIVATE_KEY }}
|
||||
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.bot-token.outputs.token }}
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: bump-files
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- name: Configure git
|
||||
run: |
|
||||
git config user.email "alchemy-version-bot[bot]@users.noreply.github.com"
|
||||
git config user.name "alchemy-version-bot[bot]"
|
||||
|
||||
- id: commit
|
||||
name: Commit bump + changelog, tag, push
|
||||
env:
|
||||
VERSION: ${{ needs.bump.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG="v${VERSION}"
|
||||
|
||||
# Durability: if HEAD already points at the release tag (resumed
|
||||
# run after a previous attempt committed+tagged but publish
|
||||
# failed), there is nothing to do. Use HEAD as the publish SHA.
|
||||
HEAD_TAG=$(git describe --exact-match --tags HEAD 2>/dev/null || true)
|
||||
if [ "$HEAD_TAG" = "$TAG" ]; then
|
||||
echo "HEAD is already at ${TAG}; skipping commit/tag/push"
|
||||
SHA=$(git rev-parse HEAD)
|
||||
echo "sha=${SHA}" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Generate release notes; release-notes.ts is idempotent and
|
||||
# bails out if the tag heading is already present in CHANGELOG.md.
|
||||
bun scripts/release/release-notes.ts "${TAG}"
|
||||
|
||||
# Stage bump files (overwritten by the downloaded artifact) and
|
||||
# the new changelog entry as a single commit.
|
||||
git add packages/alchemy/package.json \
|
||||
packages/better-auth/package.json \
|
||||
packages/pr-package/package.json \
|
||||
bun.lock \
|
||||
CHANGELOG.md
|
||||
|
||||
if git diff --cached --quiet; then
|
||||
echo "No changes to commit (already on a release commit?)"
|
||||
else
|
||||
git commit -m "chore(release): ${VERSION}"
|
||||
fi
|
||||
|
||||
if ! git rev-parse --verify "refs/tags/${TAG}" >/dev/null 2>&1; then
|
||||
git tag -a "${TAG}" -m "Release ${TAG}"
|
||||
fi
|
||||
|
||||
git push origin HEAD
|
||||
if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
|
||||
echo "Tag ${TAG} already on remote, skipping tag push"
|
||||
else
|
||||
git push origin "refs/tags/${TAG}"
|
||||
fi
|
||||
|
||||
SHA=$(git rev-parse HEAD)
|
||||
echo "sha=${SHA}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# ── Step 3a: Build and publish `alchemy`. ──
|
||||
# For non-tag channels, checkout the just-committed tagged SHA; for the
|
||||
# `tag` channel (no commit), checkout the bump's pre-bump SHA and rely
|
||||
# on the bump-files artifact instead.
|
||||
publish-alchemy:
|
||||
needs: [bump, commit-and-tag]
|
||||
if:
|
||||
always() && needs.bump.result == 'success' && (needs.commit-and-tag.result
|
||||
== 'success' || needs.commit-and-tag.result == 'skipped')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ needs.commit-and-tag.outputs.sha || needs.bump.outputs.sha }}
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
registry-url: https://registry.npmjs.org/
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Upgrade npm for OIDC trusted publishing
|
||||
run: |
|
||||
npm install -g npm@latest && npm --version
|
||||
sed -i '/always-auth/d' ~/.npmrc 2>/dev/null || true
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: bump-files
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: build-output
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- run: bun scripts/release/publish-package.ts packages/alchemy ${{
|
||||
needs.bump.outputs.channel }}
|
||||
|
||||
# ── Step 3b: Build and publish `@alchemy.run/better-auth`. ──
|
||||
publish-better-auth:
|
||||
needs: [bump, commit-and-tag, publish-alchemy]
|
||||
if:
|
||||
always() && needs.bump.result == 'success' && (needs.commit-and-tag.result
|
||||
== 'success' || needs.commit-and-tag.result == 'skipped') &&
|
||||
needs.publish-alchemy.result == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ needs.commit-and-tag.outputs.sha || needs.bump.outputs.sha }}
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
registry-url: https://registry.npmjs.org/
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Upgrade npm for OIDC trusted publishing
|
||||
run: |
|
||||
npm install -g npm@latest && npm --version
|
||||
sed -i '/always-auth/d' ~/.npmrc 2>/dev/null || true
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: bump-files
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: build-output
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- run: bun scripts/release/publish-package.ts packages/better-auth ${{
|
||||
needs.bump.outputs.channel }}
|
||||
|
||||
# ── Step 3c: Build and publish `@alchemy.run/pr-package`. ──
|
||||
publish-pr-package:
|
||||
needs: [bump, commit-and-tag, publish-alchemy]
|
||||
if:
|
||||
always() && needs.bump.result == 'success' && (needs.commit-and-tag.result
|
||||
== 'success' || needs.commit-and-tag.result == 'skipped') &&
|
||||
needs.publish-alchemy.result == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ needs.commit-and-tag.outputs.sha || needs.bump.outputs.sha }}
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
registry-url: https://registry.npmjs.org/
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Upgrade npm for OIDC trusted publishing
|
||||
run: |
|
||||
npm install -g npm@latest && npm --version
|
||||
sed -i '/always-auth/d' ~/.npmrc 2>/dev/null || true
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: bump-files
|
||||
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: build-output
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- run: bun scripts/release/publish-package.ts packages/pr-package ${{
|
||||
needs.bump.outputs.channel }}
|
||||
|
||||
# ── Step 4: Create GitHub Release and notify Discord. ──
|
||||
# Runs only after every publish job succeeded. The bump+changelog commit
|
||||
# and tag were already pushed by `commit-and-tag` before publishing.
|
||||
finalize:
|
||||
needs:
|
||||
[
|
||||
bump,
|
||||
commit-and-tag,
|
||||
publish-alchemy,
|
||||
publish-better-auth,
|
||||
publish-pr-package,
|
||||
]
|
||||
if: inputs.channel != 'tag'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
ref: ${{ needs.commit-and-tag.outputs.sha }}
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
bun-${{ runner.os }}-
|
||||
|
||||
- run: bun install
|
||||
|
||||
- name: Create GitHub Release
|
||||
env:
|
||||
VERSION: ${{ needs.bump.outputs.version }}
|
||||
CHANNEL: ${{ needs.bump.outputs.channel }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: bun scripts/release/github-release.ts "v${VERSION}" "${CHANNEL}"
|
||||
|
||||
- name: Notify Discord
|
||||
if: success() && env.DISCORD_WEBHOOK != ''
|
||||
env:
|
||||
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
VERSION: ${{ needs.bump.outputs.version }}
|
||||
CHANNEL: ${{ needs.bump.outputs.channel }}
|
||||
run: bun scripts/release/discord-notify.ts "v${VERSION}" "${CHANNEL}"
|
||||
@@ -0,0 +1,93 @@
|
||||
name: test
|
||||
|
||||
# Smoke-tests `alchemy destroy → deploy → destroy` against each example.
|
||||
# `bun test:canary` drives the whole suite — it iterates both bun and pnpm
|
||||
# runtimes itself and publishes canary tarballs to pkg.ing before deploying.
|
||||
|
||||
on:
|
||||
# TODO(sam): re-enable these when they are running reliably and not polluting our account
|
||||
# push:
|
||||
# branches: [main]
|
||||
# pull_request:
|
||||
# types: [opened, reopened, synchronize]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
# Required for aws-actions/configure-aws-credentials to mint a session
|
||||
# via OIDC instead of long-lived AWS_ACCESS_KEY_ID secrets.
|
||||
id-token: write
|
||||
|
||||
env:
|
||||
PKGING_HOST: pkg.ing
|
||||
NODE_VERSION: "24"
|
||||
# PR runs use `pr-<n>` so each PR has its own isolated cloud namespace;
|
||||
# main pushes use `main`; manual `workflow_dispatch` runs use the branch
|
||||
# name. Forwarded to the smoke test as $SMOKE_STAGE.
|
||||
SMOKE_STAGE: ${{ github.event_name == 'pull_request' && format('pr-{0}',
|
||||
github.event.number) || (github.ref == 'refs/heads/main' && 'main' ||
|
||||
github.ref_name) }}
|
||||
|
||||
concurrency:
|
||||
# Cancel an in-progress run for the same PR (or branch) when a new push
|
||||
# arrives — the smoke suite mutates real cloud state, so two parallel
|
||||
# runs against the same SMOKE_STAGE would race.
|
||||
group: test-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
smoke:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093 # v6.0.8
|
||||
with:
|
||||
version: latest
|
||||
|
||||
- uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
with:
|
||||
path: ~/.bun/install/cache
|
||||
key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: bun-${{ runner.os }}-
|
||||
|
||||
# Bootstrap install so `bun test:canary` itself can resolve. The
|
||||
# test then runs its own `bun install` + `pnpm install` in canary
|
||||
# `beforeAll` after rewriting the catalog to pkg.ing tarballs, so
|
||||
# there's nothing pnpm-specific to wire up here.
|
||||
- run: bun install
|
||||
|
||||
# OIDC → short-lived AWS session. Exports AWS_ACCESS_KEY_ID,
|
||||
# AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_REGION; the
|
||||
# `output-credentials: true` flag also surfaces aws-account-id as a
|
||||
# step output (which we forward as `AWS_ACCOUNT_ID` below — the
|
||||
# action does NOT set it as an env var on its own).
|
||||
- id: aws-creds
|
||||
uses: aws-actions/configure-aws-credentials@d979d5b3a71173a29b74b5b88418bfda9437d885 # v6.1.1
|
||||
with:
|
||||
role-to-assume: ${{ vars.AWS_ROLE_ARN }}
|
||||
aws-region: ${{ vars.AWS_REGION }}
|
||||
output-credentials: true
|
||||
|
||||
- name: Smoke
|
||||
env:
|
||||
# AWS — `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`,
|
||||
# `AWS_SESSION_TOKEN`, `AWS_REGION` are already exported by
|
||||
# configure-aws-credentials; we only need to forward the account
|
||||
# id, which Alchemy's `loadFromEnv` requires when CI=true.
|
||||
AWS_ACCOUNT_ID: ${{ steps.aws-creds.outputs.aws-account-id }}
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.TEST_CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.TEST_CLOUDFLARE_ACCOUNT_ID }}
|
||||
NEON_API_KEY: ${{ secrets.NEON_API_KEY }}
|
||||
PR_PACKAGE_TOKEN: ${{ secrets.PR_PACKAGE_TOKEN }}
|
||||
PKGING_HOST: ${{ env.PKGING_HOST }}
|
||||
SMOKE_STAGE: ${{ env.SMOKE_STAGE }}
|
||||
run: bun test:canary
|
||||
@@ -0,0 +1,48 @@
|
||||
node_modules/
|
||||
dist/
|
||||
/lib/
|
||||
/alchemy/lib/
|
||||
.out/
|
||||
.test/
|
||||
.DS_Store
|
||||
.env
|
||||
*.tsbuildinfo
|
||||
.claude/
|
||||
.alchemy/
|
||||
# !.alchemy/github:alchemy/
|
||||
# examples/*/.alchemy
|
||||
|
||||
.repomix-output.txt
|
||||
wrangler.jsonc
|
||||
|
||||
# Husky - ignore generated files but keep hooks
|
||||
.husky/_
|
||||
!.husky/pre-commit
|
||||
|
||||
.smoke
|
||||
.smoke.logs
|
||||
smoke
|
||||
# Generated by test/smoke.test.ts to make pnpm 11's deps-status check
|
||||
# resolve the bun catalog. Cleaned up at end of suite.
|
||||
pnpm-workspace.yaml
|
||||
.svelte-kit
|
||||
.astro
|
||||
.wrangler
|
||||
|
||||
*.tgz
|
||||
*.js
|
||||
*.d.ts
|
||||
*.map
|
||||
|
||||
.attest
|
||||
.cache
|
||||
.external
|
||||
.bundle-benchmark
|
||||
packages/alchemy/docs
|
||||
.sonda
|
||||
examples/cloudflare-worker/src/scratch.ts
|
||||
|
||||
!/packages/alchemy/bin/cli.js
|
||||
.vendor/*
|
||||
.tmp
|
||||
pnpm-lock.yaml
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "vendor/alchemy"]
|
||||
path = .vendor/alchemy
|
||||
url = [email protected]:alchemy-run/alchemy.git
|
||||
@@ -0,0 +1,2 @@
|
||||
bun format
|
||||
git update-index --again
|
||||
@@ -0,0 +1 @@
|
||||
# see: https://opencode.ai/docs/tools/#ignore-patterns
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": false,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"printWidth": 80,
|
||||
"endOfLine": "lf",
|
||||
"ternaries": true,
|
||||
"experimental_sort_imports": {
|
||||
"order": "asc"
|
||||
},
|
||||
"ignorePatterns": [
|
||||
"dist/**",
|
||||
"*.min.js",
|
||||
"**/lib/**",
|
||||
"**/mdx/**",
|
||||
"**/*.mdx",
|
||||
"**/*.md",
|
||||
"**/.vendor/**",
|
||||
"**/package.json"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"rules": {
|
||||
"no-misused-new": "off",
|
||||
"require-yield": "off",
|
||||
"no-non-null-asserted-optional-chain": "off"
|
||||
}
|
||||
}
|
||||
Submodule
+1
Submodule .repos/alchemy-effect/.vendor/alchemy added at c9f5e549cf.
+65
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"diffEditor.renderSideBySide": false,
|
||||
"js/ts.experimental.useTsgo": true,
|
||||
"typescript.experimental.useTsgo": true,
|
||||
"typescript.tsdk": "node_modules/@typescript/native-preview/lib",
|
||||
"typescript.native-preview.tsdk": "node_modules/@typescript/native-preview/lib",
|
||||
"typescript.enablePromptUseWorkspaceTsdk": true,
|
||||
"typescript.preferences.importModuleSpecifier": "relative",
|
||||
"typescript.preferences.importModuleSpecifierEnding": "js",
|
||||
"oxc.enable": true,
|
||||
"oxc.lint.run": "onSave",
|
||||
"json.schemaDownload.enable": true,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode",
|
||||
"editor.codeLens": false,
|
||||
"editor.formatOnSave": true,
|
||||
"editor.formatOnSaveMode": "file",
|
||||
"editor.inlayHints.enabled": "offUnlessPressed",
|
||||
"editor.tabSize": 2,
|
||||
"editor.indentSize": 2,
|
||||
"editor.insertSpaces": true,
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll": "explicit",
|
||||
"source.organizeImports": "explicit"
|
||||
},
|
||||
"[toml]": {
|
||||
"editor.defaultFormatter": "tamasfe.even-better-toml"
|
||||
},
|
||||
"[json]": {
|
||||
"editor.defaultFormatter": "vscode.json-language-features"
|
||||
},
|
||||
"[jsonc]": {
|
||||
"editor.defaultFormatter": "vscode.json-language-features"
|
||||
},
|
||||
"[markdown]": {
|
||||
"editor.formatOnSave": false,
|
||||
"editor.defaultFormatter": null
|
||||
},
|
||||
"[mdx]": {
|
||||
"editor.defaultFormatter": null,
|
||||
"editor.formatOnSave": false
|
||||
},
|
||||
"files.exclude": {
|
||||
"**/__pycache__": true,
|
||||
"**/*.pyc": true,
|
||||
"packages/alchemy/bin/**/*.js*": true,
|
||||
"packages/alchemy/bin/**/*.d*": true
|
||||
},
|
||||
"[typescript]": {
|
||||
"editor.indentSize": 2,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode"
|
||||
},
|
||||
"[javascript]": {
|
||||
"editor.indentSize": 2,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode"
|
||||
},
|
||||
"[typescriptreact]": {
|
||||
"editor.indentSize": 2,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode"
|
||||
},
|
||||
"[javascriptreact]": {
|
||||
"editor.indentSize": 2,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode"
|
||||
},
|
||||
"oxc.enable.oxfmt": true
|
||||
}
|
||||
@@ -0,0 +1,854 @@
|
||||
# alchemy
|
||||
|
||||
Alchemy Effect is an Infrastructure-as-Effects (IaE) framework that extends Infrastructure-as-Code (IaC) by combining business logic and infrastructure config into a single, type-safe program expressed as Effects.
|
||||
|
||||
It includes a core IaC engine built with Effect. Effect provides the foundation for type-safe, composable, and testable infrastructure programs. It brings errors into the type-system and provides declarative/composable retry logic that ensure proper and reliable handling of failures.
|
||||
|
||||
# Concepts
|
||||
|
||||
- **Cloud Provider** - a cloud provider that offers a set of Services, e.g. AWS, Azure, GCP, Cloudflare, Stripe, Planetscale, Neon, etc.
|
||||
- **Service** - a collection of Resources, Functions, and Bindings offered by a Cloud Provider.
|
||||
- **Resource** - a named entity that is configuted with "Input Properties" and produces "Output Attributes". May or may not have Binding Contract.
|
||||
- **Input Properties** - the properties passed as input to configure a Resource. Otherwise known as the "desired state" of the Resource.
|
||||
- **Output Attributes** - the attributes produced by a Resource. Otherwise known as the "current state" of the Resource.
|
||||
- **Stable Properties** - properties that are not affected by an Update, e.g. the ID or ARN of a Resource.
|
||||
- **Function** (aka. **Runtime**) - a special kind of Resource that includes a runtime implementation expressed as a Function producing an `Effect<A, Err, Req>`. The `Req` type captures runtime dependencies, from which Infrastructure Dependencies are inferred.
|
||||
- **Resource Provider** (see [Provider](./packages/alchemy/src/Provider.ts))
|
||||
|
||||
A Resource Provider implements the following Lifecycle Operations:
|
||||
|
||||
- **Diff** - compares new props with old props and determines if the Resource needs to be updated or replaced. For updates, it can also specify a list of Stable Properties that will not be changed by the update.
|
||||
- **Read** - reads the current state of a Resource and returns the current Output Attributes. May return `Unowned(attrs)` to signal an existing-but-foreign resource that the engine should refuse to take over unless `--adopt` is set.
|
||||
- **Pre-Create** - an optional operation that creates a stub of a Resource before reconcile runs. Used to resolve circular dependencies — e.g. Function A and B depend on each other, so we create a stub of Function A first and then `reconcile` later wires up the real dependency.
|
||||
- **Reconcile** - converges a Resource's actual cloud state to the desired state described by the new Input Properties. Called for both first-time provisioning and subsequent updates. The provider receives `output` (current Attributes) and `olds` (previous Props) which may both be `undefined` on a greenfield create, both defined on an update, or `output !== undefined && olds === undefined` on an adoption. See the **Reconciler doctrine** section below for the required shape.
|
||||
- **Delete** - deletes an existing Resource. It must be designed as idempotent because it is always possible for state persistence to fail after the delete operation is called. If the resource doesn't exist during deletion, it should not be considered an error.
|
||||
- **Capability** - a runtime requirement of a Function (e.g. require `SQS.SendMessage` on a `SQS.Queue`). Each Capability is split into two parts: a `Binding.Service` (runtime SDK wrapper) and a `Binding.Policy` (deploy-time IAM/binding attachment).
|
||||
- **Binding.Service** - an Effect Service that wraps an SDK client and exposes a `.bind(resource)` method returning a typed callable for runtime use. Provided as a Layer on the **Function** Effect so it gets bundled into the Lambda/Worker. See [Binding](./packages/alchemy/src/Binding.ts).
|
||||
- **Binding.Policy** - an Effect Service that runs only at deploy time to attach IAM policies (AWS) or bindings (Cloudflare) to a Function's role/config. At runtime, `Binding.Policy` uses `Effect.serviceOption` so it gracefully becomes a no-op when the layer is not provided. Policy layers are provided on the **Stack** via `AWS.providers()()`, not on the Function.
|
||||
- **Binding** - data attached to a Resource via `resource.bind(data)`. A Binding is a `{ context: PolicyContext, data: BindingData }` tuple that is collected on the Stack during plan/deploy. Bindings enable circular references between Resources — the `Binding.Policy` calls `ctx.bind({ policyStatements: [...] })` on the target Function, which records the binding data on the Stack. The Resource Provider then receives the resolved binding data in its `reconcile` lifecycle operation via the `bindings` parameter.
|
||||
- **Binding Contract** - the shape of data a Resource accepts from Bindings. For example, a Lambda Function accepts `{ env?: Record<string, any>, policyStatements?: PolicyStatement[] }` because it needs environment variables and IAM policies. A Cloudflare Worker accepts `{ bindings: Worker.Binding[] }` for its native binding system. The Binding Contract is declared as the fourth type parameter on the `Resource` interface. See [Lambda Function](./packages/alchemy/src/AWS/Lambda/Function.ts) and [Cloudflare Worker](./packages/alchemy/src/Cloudflare/Workers/Worker.ts).
|
||||
- **Dependency** - Resources depend on other Resources through two mechanisms:
|
||||
- Output Properties of one Resource passed as Input Properties to another Resource (non-circular, directed acyclic graph)
|
||||
- Bindings that attach data (IAM policies, env vars, Cloudflare bindings) from one Resource to another, enabling circular references between Resources.
|
||||
- **Output** - a reference to (or derived from) a Resource's "Output Attributes". E.g. Bucket.bucketArn
|
||||
- **Stack** - a collection of Resources, Functions, and Bindings that are deployed together.
|
||||
- **Stack Name** - the name of a Stack, e.g. `my-stack`
|
||||
- **Stage** - the stage of a Stack, e.g. `dev`, `prod`, `dev-sam`
|
||||
- **Stack Instance** - a deployed instance of a Stack+Stage
|
||||
- **Resource Type** - the type of a Resource, e.g. `Bucket`, `Instance`
|
||||
- **Physical Name** - a unique name for a Resource, e.g. `my-bucket-1234567890`. It is usually best to generate them using the built-in createPhysicalName utility function which generates
|
||||
- **Logical ID** - the logical ID identifying a resource within a Stack, e.g. `my-bucket`. It is stable across creates, updates, deletes and replaces.
|
||||
- **Instance ID** - a unique identifier for an instance of a Resource. It is stable across creates, updates and deletes. It changes when a resource is replaced. It is truncated and used as the suffix of the Physical Name.
|
||||
- **Event Source** - a special kind of Binding between a Function and a Resource that produces events that invoke the Function, e.g. `SQS.QueueEventSource`. Event Sources are implemented as Binding.Service + Binding.Policy pairs, where the attach logic creates/updates the event source mapping via the cloud provider API.
|
||||
- **Replacement** - the process of replacing a Resource with a new one. A new one is created, downstream dependencies are updated with the new reference, and then the old one is deleted. Or, the old one is deleted first and then the new one is created.
|
||||
- **Dependency Violation** - an error that some APIs call when an operation cannot be performed because a dependency is not met. E.g. you cannot delete an EIP until the NAT Gateway it is attached to is deleted. Lifecycle operations typically retry Dependency Violations.
|
||||
- **Eventual Consistency** - create/update/delete operations can be eventually consistent leading to a variety of failure modes. For example, a Resource may be created but not yet available for use, or a Resource may be deleted but still appear in the console. Errors caused by eventual consistency should be retried, and lifecycle operations/tests should be carefully designed to wait for consistency before proceeding.
|
||||
- **Retryable Error** - an error that can be retried. E.g. a Dependency Violation, Eventual Consistency Error, Transient Failure, etc.
|
||||
- **Non-Retryable Error** - an error that cannot be retried. E.g. a Validation Error, Authorization Error, etc.
|
||||
- **Retry Policy** - a policy for retrying errors. E.g. a fixed delay, exponential backoff, max retries, while some condition is true, or until some condition is true/false, etc.
|
||||
|
||||
# File System Conventions
|
||||
|
||||
Each Service's Resources follow the same pattern. Resource contract and provider are co-located in the same file. Capabilities (Binding.Service + Binding.Policy) are in separate files named after the capability.
|
||||
|
||||
```sh
|
||||
# source files
|
||||
packages/alchemy/src/{Cloud}/{Service}/index.ts # re-exports all resources and capabilities
|
||||
packages/alchemy/src/{Cloud}/{Service}/{Resource}.ts # resource contract + resource provider
|
||||
packages/alchemy/src/{Cloud}/{Service}/{Capability}.ts # Binding.Service + Binding.Policy for a capability
|
||||
# test files
|
||||
packages/alchemy/test/{Cloud}/{Service}/{Resource}.test.ts
|
||||
# docs (auto-generated from source-code JSDoc - DO NOT manually edit)
|
||||
website/src/content/docs/providers/{Cloud}/{Resource}.md # API reference, generated by `bun generate:api-reference`
|
||||
```
|
||||
|
||||
Examples of actual paths:
|
||||
|
||||
```sh
|
||||
packages/alchemy/src/AWS/S3/Bucket.ts # S3 Bucket resource + provider
|
||||
packages/alchemy/src/AWS/S3/GetObject.ts # S3 GetObject Binding.Service + Binding.Policy
|
||||
packages/alchemy/src/AWS/S3/PutObject.ts # S3 PutObject Binding.Service + Binding.Policy
|
||||
packages/alchemy/src/AWS/SQS/Queue.ts # SQS Queue resource + provider
|
||||
packages/alchemy/src/AWS/SQS/SendMessage.ts # SQS SendMessage capability
|
||||
packages/alchemy/src/AWS/Kinesis/Stream.ts # Kinesis Stream resource + provider
|
||||
packages/alchemy/src/AWS/Kinesis/PutRecord.ts # Kinesis PutRecord capability
|
||||
packages/alchemy/src/AWS/Lambda/Function.ts # Lambda Function resource + provider
|
||||
packages/alchemy/src/AWS/DynamoDB/Table.ts # DynamoDB Table resource + provider
|
||||
packages/alchemy/src/AWS/DynamoDB/GetItem.ts # DynamoDB GetItem capability
|
||||
packages/alchemy/src/AWS/EC2/Vpc.ts # VPC resource + provider
|
||||
packages/alchemy/src/AWS/EC2/Subnet.ts # Subnet resource + provider
|
||||
```
|
||||
|
||||
# Documentation Generation
|
||||
|
||||
**Source of truth:** The source code is the single source of truth for all API documentation. JSDoc comments in `packages/alchemy/src/**/*.ts` are extracted and used to generate the public API reference markdown.
|
||||
|
||||
:::warning
|
||||
**Never edit the generated markdown files** under `website/src/content/docs/providers/{Cloud}/`. They are overwritten on every regeneration.
|
||||
|
||||
To "update the docs", edit the JSDoc on the source `.ts` file (resource-level JSDoc on the exported `const`, plus field-level JSDoc on each prop/attribute) and re-run the generator. There is no separate doc file to update.
|
||||
:::
|
||||
|
||||
**How to generate docs:**
|
||||
|
||||
```sh
|
||||
bun generate:api-reference # -> website/src/content/docs/providers/{Cloud}/{Resource}.md
|
||||
```
|
||||
|
||||
This is the only doc generator that produces user-facing output. ([scripts/generate-api-reference.ts](./scripts/generate-api-reference.ts)) does the following:
|
||||
|
||||
1. Discovers resource files in `packages/alchemy/src/{Cloud}/{Service}/`
|
||||
2. Parses TypeScript with `ts-morph`
|
||||
3. Extracts the resource-level summary plus `@section` / `@example` blocks from JSDoc
|
||||
4. Writes one markdown file per resource at `website/src/content/docs/providers/{Cloud}/{Resource}.md`
|
||||
|
||||
After editing JSDoc on a resource, run `bun generate:api-reference` to refresh the website docs.
|
||||
|
||||
**Writing good documentation:** When adding or updating a resource, ensure all Props and Attrs have JSDoc comments:
|
||||
|
||||
```typescript
|
||||
export interface BucketProps {
|
||||
/**
|
||||
* Name of the bucket. If omitted, a unique name will be generated.
|
||||
* Must be lowercase and between 3-63 characters.
|
||||
*/
|
||||
bucketName?: string;
|
||||
|
||||
/**
|
||||
* Whether to delete all objects when the bucket is destroyed.
|
||||
* @default false
|
||||
*/
|
||||
forceDestroy?: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
The `@default` tag is used to document default values and will appear in the generated documentation.
|
||||
|
||||
### Examples and Sections (IMPORTANT)
|
||||
|
||||
**Examples are critical for documentation.** Every resource should have examples demonstrating common use cases. Use `@section` and `@example` JSDoc tags on the main Resource export to organize examples into a navigable table of contents.
|
||||
|
||||
**Format:**
|
||||
|
||||
- `@section <Section Title>` - Creates a heading in the Examples section and adds an entry to the Quick Reference table of contents
|
||||
- `@example <Example Title>` - Creates a subheading for a specific code example (must follow a `@section`)
|
||||
- Code blocks inside examples use standard markdown fenced code blocks (` `)
|
||||
|
||||
**Example:**
|
||||
|
||||
````typescript
|
||||
/**
|
||||
* An S3 bucket for storing objects.
|
||||
*
|
||||
* @section Creating a Bucket
|
||||
* @example Basic Bucket
|
||||
* ```typescript
|
||||
* const bucket = yield* Bucket("my-bucket", {});
|
||||
* ```
|
||||
*
|
||||
* @example Bucket with Force Destroy
|
||||
* ```typescript
|
||||
* const bucket = yield* Bucket("my-bucket", {
|
||||
* forceDestroy: true,
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @section Reading Objects
|
||||
* @example Get Object from Bucket
|
||||
* ```typescript
|
||||
* const response = yield* getObject(bucket, { key: "my-key" });
|
||||
* const body = yield* Effect.tryPromise(() => response.Body?.transformToString());
|
||||
* ```
|
||||
*
|
||||
* @section Writing Objects
|
||||
* @example Put Object to Bucket
|
||||
* ```typescript
|
||||
* yield* putObject(bucket, {
|
||||
* key: "hello.txt",
|
||||
* body: "Hello, World!",
|
||||
* contentType: "text/plain",
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export const Bucket = Resource<...>("AWS.S3.Bucket");
|
||||
````
|
||||
|
||||
This generates:
|
||||
|
||||
1. A "Quick Reference" section with links to each `@section`
|
||||
2. An "Examples" section with organized code examples under each section heading
|
||||
|
||||
**Best practices for examples:**
|
||||
|
||||
- Start with the simplest use case and progress to more complex ones
|
||||
- Include examples for all major capabilities (GetObject, PutObject, etc.)
|
||||
- Show real-world patterns like error handling, combining with other resources
|
||||
- Use descriptive titles that explain what the example demonstrates
|
||||
|
||||
# Workflow
|
||||
|
||||
Development of Alchemy-Effect Resources is heavily pattern based. Each Service has many Resources that each have 0 oor more Capabilities and Event Sources. When working on a new Service, the following steps should be followed.
|
||||
|
||||
1. Research the AWS Service and identify its Resources, Identifier Types, Structs, Capabilities, and Event Sources. Refer to the corresponding Terraform Provider, Pulumi Provider, and CloudFormation docs for that service (use the provided tools specifically for searching these docs for services and resources).
|
||||
|
||||
Example (abbreviated):
|
||||
|
||||
Service: S3
|
||||
|
||||
Resources:
|
||||
|
||||
- Bucket
|
||||
- BucketPolicy
|
||||
- etc.
|
||||
|
||||
Bucket Capabilities:
|
||||
|
||||
- GetObject
|
||||
- PutObject
|
||||
- DeleteObject
|
||||
|
||||
Identifier Types:
|
||||
|
||||
- Bucket Name
|
||||
- Bucket ARN
|
||||
|
||||
Structs:
|
||||
|
||||
- CorsRule
|
||||
- LifecycleConfiguration
|
||||
|
||||
2. Document each of the Resource interfaces
|
||||
|
||||
Include the following information:
|
||||
|
||||
- ResourceName, e.g. Bucket, Instance, Queue
|
||||
- Input Properties (for each property: Name, Type, Description, Default Value, Required, Constraints, Replaces: true/false)
|
||||
- Output Attributes (for each attribute: Name, Type, Description)
|
||||
|
||||
3. Document each of the Capabilities and Bindings
|
||||
|
||||
Include the following information:
|
||||
|
||||
- Capability Name, e.g. `GetObject`, `PutObject` (it maps 1:1 with an AWS API)
|
||||
- Constraints (e.g. `Key`)
|
||||
- IAM Policies (how the capability maps to an IAM Policy, e.g. Effect: Allow, Action: s3:GetObject, Resource: `arn:aws:s3:::${bucketName}/${Key}`)
|
||||
- Environment Variables (what environment variables should be added to a Lambda Function so that it can access the capability, e.g. `BUCKET_NAME`, `BUCKET_ARN`, `QUEUE_URL`, `QUEUE_ARN`, etc.)
|
||||
|
||||
4. Research and design each of the Lifecycle Operations
|
||||
|
||||
- **Diff** - identify which properties are always stable across any update, which properties change conditionally depending on new and old values, which properties trigger a replacement. This is usually just a distinct list, but can sometimes require if-this-then-that logic. Document it explicitly and exhaustively. Cross-reference with AWS CloudFormation, Terraform Provider and Pulumi Provider docs.
|
||||
|
||||
:::warning
|
||||
You should almost never use `no-op` in the Diff. No-op should be explicitly designed as a way to say "i know this property changed, but i don't want it to trigger an update". This is an edge-case and not the norm. Usually you want diff to return `undefined` or `void` to let the engine apply the default update logic. Diff is usually just use as an optimization or to identify replacement instead of update.
|
||||
:::
|
||||
|
||||
- **Read** - determine which API calls are required to read the Output Attributes of a Resource from the Cloud Provider state (otherwise known as refresh or synchronize resource state). This is usually a single Get{Resource} API call, but can be a complex set of calls depending on the Service. Read can also be called without the current Output Attributes because of past state persistence failures. These cases are handled by computing the deterministic Physical Name and looking it up or by searching for Resources using tags (if the Cloud Provider supports it). Read may return `Unowned(attrs)` when the resource exists but lacks our ownership tags, signalling the engine to gate adoption behind `--adopt` or `adopt(true)`.
|
||||
- **Pre-Create** - determine if the Resource needs a pre-create operation. This is usually only the case for the special Function/Runtime Resources like AWS Lambda Functions. If it is required, then document which API call(s) should be called and what the empty (unit) input properties are. E.g. a Lambda Function takes a simple script that exports a no-op handler function.
|
||||
- **Reconcile** - determine the API calls needed to converge the cloud's actual state to the desired state described by the new Input Properties. Reconcile must be a single flow that works whether the resource is missing (greenfield create), pre-existing under our ownership (update), or freshly adopted (`output` defined but `olds` absent). See the **Reconciler doctrine** section below.
|
||||
- **Delete** - determine which APIs should be called and in what order to delete an existing Resource. Delete should be idempotent so that if the resource has already been deleted, it is not considered an error. It is common for deletions to fail because of Dependency Violations or Eventual Consistency Errors. These are not always called Dependency Violations in the API docs, so attention should be paid to investigating each API's possible error codes and how they should be handled by the Delete operation. Should we retry for a period of time, indefinitely, or fail immediately?
|
||||
|
||||
# Reconciler doctrine
|
||||
|
||||
The provider's `reconcile` function replaces the legacy `create` + `update` pair. It runs every time the engine wants to make the cloud match the desired state — whether that's the first time the resource is being provisioned, a routine update, or a takeover after `read` returned an existing cloud resource.
|
||||
|
||||
It receives `output: Attributes | undefined` and `olds: Props | undefined`:
|
||||
|
||||
| `output` | `olds` | Meaning |
|
||||
| ------------ | ------------ | ------------------------------------------------- |
|
||||
| `undefined` | `undefined` | Greenfield — no prior physical resource |
|
||||
| defined | defined | Routine update — engine-owned resource |
|
||||
| defined | `undefined` | Adoption — engine adopted via `read` |
|
||||
|
||||
A reconciler MUST work correctly for all three combinations. It MUST NOT branch the body on `output === undefined` and run different code paths for "create" vs "update". That pattern is just rename-and-branch and re-introduces every assumption the old `create`/`update` split made. Instead, write one flow:
|
||||
|
||||
```
|
||||
1. Observe — derive the physical identifier; read live cloud state via getX/describeX
|
||||
2. Ensure — if the resource is missing, call createX. Catch AlreadyExists/ConflictException
|
||||
as a race and continue. Wait for active state if applicable.
|
||||
3. Sync — for each mutable aspect (settings, sub-resources, tags, policy):
|
||||
- read OBSERVED cloud state (not olds)
|
||||
- compute desired state from news + bindings
|
||||
- diff observed against desired
|
||||
- apply only the delta API call (skip the API entirely on no-op)
|
||||
4. Return — re-read final state if needed; return the fresh Attributes shape
|
||||
```
|
||||
|
||||
Key invariants:
|
||||
|
||||
- **Observation > assumption.** Cloud state is authoritative. `olds` is at most a hint to skip a no-op API call; it is never the source of truth for what's actually deployed.
|
||||
- **Each sync step is independently idempotent.** Crash mid-reconcile, re-run, you converge.
|
||||
- **`output` is treated as a cache** for stable identifiers (physical name, ARN, immutable id). It is NOT a guarantee that the resource still exists. If it doesn't, observation falls through to "missing" and ensure recreates.
|
||||
- **`AlreadyExists`/`NotFoundException`/`ResourceInUseException`-style errors are caught**, not propagated — they're races or eventual-consistency, not failures.
|
||||
- **Tags use observed cloud tags as the diff baseline**, not `olds.tags` or `output.tags`. Adoption may bring you a resource with foreign tags that need to be reconciled.
|
||||
|
||||
:::warning
|
||||
**Do not write `if (output === undefined) { /* create body */ } else { /* update body */ }`.** That is rename-and-branch, not reconciliation. The reconciler's body is one observe-ensure-sync flow that produces correct cloud state regardless of starting point.
|
||||
:::
|
||||
|
||||
The canonical reference reconcilers cover the common shapes:
|
||||
|
||||
- [S3 Bucket](./packages/alchemy/src/AWS/S3/Bucket.ts) — uses `ensureBucketExists` + `syncBucketTags` + `syncBucketPolicy` helpers; each helper is itself a tiny reconciler.
|
||||
- [SQS Queue](./packages/alchemy/src/AWS/SQS/Queue.ts) — observe via `getQueueUrl`, ensure via `createQueue` (tolerates `QueueNameExists` race), sync attributes by diffing `getQueueAttributes` against desired, sync tags.
|
||||
- [Kinesis Stream](./packages/alchemy/src/AWS/Kinesis/Stream.ts) — many mutable aspects (mode, shards, retention, encryption, metrics), each its own observed-vs-desired sync block.
|
||||
- [DynamoDB Table](./packages/alchemy/src/AWS/DynamoDB/Table.ts) — multi-API observation (table + tags + PITR + TTL), per-aspect diffing, GSI delta application.
|
||||
- [EC2 Vpc](./packages/alchemy/src/AWS/EC2/Vpc.ts) — auto-assigned id, observe via `describeVpcs([output.vpcId])` with NotFound fallback to create, sync DNS attrs by reading `describeVpcAttribute`, sync tags from observed `vpc.Tags`.
|
||||
- [Lambda Function](./packages/alchemy/src/AWS/Lambda/Function.ts) — uses `createOrUpdateFunction` / `createOrUpdateFunctionUrl` / `attachBindings` helpers, each idempotent.
|
||||
- [Cloudflare Worker](./packages/alchemy/src/Cloudflare/Workers/Worker.ts) — non-AWS API; the underlying `putWorker` is a true upsert, so reconcile observes existing settings and delegates.
|
||||
|
||||
Existence-only resources (Lambda Permission, EC2 Route, EC2 RouteTableAssociation, IAM AccessKey, etc.) have nothing mutable beyond their identity. Their reconciler is just observe → if missing, create. There is no sync step.
|
||||
|
||||
5. Research and design the test cases for each resource. Test cases can be single or multi-step. Single-step test cases are just testing a single create success or failure mode. Multi-step cases are testing a sequence of operations, starting with create and then updating or replacing the resource multiple times. Test cases should be designed to be exhaustive and cover all possible success and failure modes, starting from simple happy paths to long, complicated aggregate (including other resources) smoke tests.
|
||||
6. Implement the Resource contract and Provider in `packages/alchemy/src/{Cloud}/{Service}/{Resource}.ts`.
|
||||
|
||||
The Resource contract (Props, Attributes, Binding Contract) and the Resource Provider (lifecycle operations) are co-located in the same file.
|
||||
|
||||
Read through the established examples to understand the pattern:
|
||||
|
||||
- [S3 Bucket](./packages/alchemy/src/AWS/S3/Bucket.ts)
|
||||
- [SQS Queue](./packages/alchemy/src/AWS/SQS/Queue.ts)
|
||||
- [DynamoDB Table](./packages/alchemy/src/AWS/DynamoDB/Table.ts)
|
||||
- [Kinesis Stream](./packages/alchemy/src/AWS/Kinesis/Stream.ts)
|
||||
- [Lambda Function](./packages/alchemy/src/AWS/Lambda/Function.ts)
|
||||
- [VPC](./packages/alchemy/src/AWS/EC2/Vpc.ts)
|
||||
- [Subnet](./packages/alchemy/src/AWS/EC2/Subnet.ts)
|
||||
|
||||
The Resource interface takes four type parameters: `Resource<Type, Props, Attributes, BindingContract>`.
|
||||
|
||||
```ts
|
||||
export interface Stream extends Resource<
|
||||
"AWS.Kinesis.Stream",
|
||||
StreamProps,
|
||||
{
|
||||
streamName: string;
|
||||
streamArn: string;
|
||||
streamStatus: StreamStatus;
|
||||
}
|
||||
> {}
|
||||
|
||||
export const Stream = Resource<Stream>("AWS.Kinesis.Stream");
|
||||
```
|
||||
|
||||
For Resources that accept Bindings (like Lambda Function), include a fourth type parameter for the Binding Contract:
|
||||
|
||||
```ts
|
||||
export interface Function extends Resource<
|
||||
"AWS.Lambda.Function",
|
||||
FunctionProps,
|
||||
{
|
||||
functionArn: string;
|
||||
functionName: string;
|
||||
functionUrl: string | undefined;
|
||||
roleName: string;
|
||||
roleArn: string;
|
||||
},
|
||||
{
|
||||
env?: Record<string, any>;
|
||||
policyStatements?: PolicyStatement[];
|
||||
}
|
||||
> {}
|
||||
```
|
||||
|
||||
:::tip
|
||||
Some Input Property types are wrapped in an `Input<T>`, but not all are. Only properties that may need to be references to another resource's Output Attribute. E.g. common use-cases are `Input<VpcId>`, `Input<QueueUrl>`, `Tags: Record<string, Input<string>>`.
|
||||
:::
|
||||
|
||||
:::warning
|
||||
For fields like `name: string`, `bucketName: string`, `bucketPrefix: string`, you should not use `Input<string>` because these properties need to be statically knowable in the `diff` function.
|
||||
:::
|
||||
|
||||
7. Implement the Capabilities as `Binding.Service` + `Binding.Policy` pairs in `packages/alchemy/src/{Cloud}/{Service}/{Capability}.ts`.
|
||||
|
||||
Each capability has two parts:
|
||||
|
||||
- **`Binding.Service`** — runtime SDK wrapper, provided on the Function Effect (bundled into Lambda/Worker)
|
||||
- **`Binding.Policy`** — deploy-time IAM policy attachment, provided on the Stack via `AWS.providers()()` (never bundled)
|
||||
|
||||
Read through the established capabilities to understand the pattern:
|
||||
|
||||
- [S3 GetObject](./packages/alchemy/src/AWS/S3/GetObject.ts) — `Binding.Service` + `Binding.Policy`
|
||||
- [S3 PutObject](./packages/alchemy/src/AWS/S3/PutObject.ts) — `Binding.Service` + `Binding.Policy`
|
||||
- [SQS SendMessage](./packages/alchemy/src/AWS/SQS/SendMessage.ts) — `Binding.Service` + `Binding.Policy`
|
||||
- [DynamoDB GetItem](./packages/alchemy/src/AWS/DynamoDB/GetItem.ts) — `Binding.Service` + `Binding.Policy`
|
||||
- [Kinesis PutRecord](./packages/alchemy/src/AWS/Kinesis/PutRecord.ts) — `Binding.Service` + `Binding.Policy`
|
||||
- [Lambda InvokeFunction](./packages/alchemy/src/AWS/Lambda/InvokeFunction.ts) — `Binding.Service` + `Binding.Policy`
|
||||
|
||||
For Event Sources, see:
|
||||
|
||||
- [SQS QueueEventSource](./packages/alchemy/src/AWS/SQS/QueueEventSource.ts)
|
||||
- [S3 BucketEventSource](./packages/alchemy/src/AWS/S3/BucketEventSource.ts)
|
||||
|
||||
The `Binding.Policy` implementation calls `ctx.bind({ policyStatements: [...] })` on the target Function, which records binding data on the Stack. The `Binding.Service` implementation resolves the Policy via `yield* Policy(resource)`, then returns a typed callable that wraps the SDK client. At runtime, the Policy is not provided and becomes a no-op.
|
||||
|
||||
Each capability exports four things:
|
||||
|
||||
```ts
|
||||
// 1. The Binding.Service class
|
||||
export class PutRecord extends Binding.Service<...>()("AWS.Kinesis.PutRecord") {}
|
||||
|
||||
// 2. The Binding.Service Live layer (provided on Function Effect)
|
||||
export const PutRecordLive = Layer.effect(PutRecord, ...);
|
||||
|
||||
// 3. The Binding.Policy class
|
||||
export class PutRecordPolicy extends Binding.Policy<...>()("AWS.Kinesis.PutRecord") {}
|
||||
|
||||
// 4. The Binding.Policy Live layer (provided on Stack via AWS.providers()())
|
||||
export const PutRecordPolicyLive = Layer.effect(PutRecordPolicy, ...);
|
||||
```
|
||||
|
||||
### Runtime-only methods: color with `Alchemy.RuntimeContext`
|
||||
|
||||
The runtime callable returned by a `Binding.Service` (the inner Effect inside `.bind(resource)`'s return) **must** declare `Alchemy.RuntimeContext` as a requirement. This is how Alchemy models "this code can only run inside a deployed Function/Worker" at the type level — analogous to a colored function.
|
||||
|
||||
```ts
|
||||
import type { RuntimeContext } from "../../RuntimeContext.ts";
|
||||
|
||||
export class GetItem extends Binding.Service<
|
||||
GetItem,
|
||||
<T extends Table>(
|
||||
table: T,
|
||||
) => Effect.Effect<
|
||||
(
|
||||
request: GetItemRequest,
|
||||
) => Effect.Effect<
|
||||
DynamoDB.GetItemOutput,
|
||||
DynamoDB.GetItemError,
|
||||
RuntimeContext // ← runtime-only
|
||||
>
|
||||
>
|
||||
>()("AWS.DynamoDB.GetItem") {}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- **Outer Effect** (the `bind(resource)` setup) runs at the Function's init phase. It does NOT require `RuntimeContext`.
|
||||
- **Inner Effect** (the actual SDK invocation) only makes sense inside a running Function. It MUST require `RuntimeContext`.
|
||||
- Resolve cloud-environment services (`WorkerEnvironment`, AWS SDK clients, etc.) once during Layer construction and close over them. Do NOT leak `WorkerEnvironment` / `Lambda.FunctionEnvironment` onto the runtime callable — that couples downstream service code to a specific cloud and breaks Layer encapsulation. The Function/Worker runtime satisfies `RuntimeContext` automatically.
|
||||
- The implementation can return `Effect.Effect<A, E>` without explicitly providing `RuntimeContext` (it's contravariant in `R`); just declare it on the interface.
|
||||
|
||||
Why this matters: consumers can build cloud-agnostic services on top of bindings using `Layer.effect(Tag, ...)` without polluting their service interface with `WorkerEnvironment`. See [Layers concept](./website/src/content/docs/concepts/layers.mdx).
|
||||
|
||||
After implementing, register the Policy in `AWS.providers()()`:
|
||||
|
||||
- Add the `*PolicyLive` layer to `bindings()` in [Providers.ts](./packages/alchemy/src/AWS/Providers.ts)
|
||||
- Re-export from the service's `index.ts`
|
||||
|
||||
:::tip
|
||||
If you need to know what AWS region or account ID the resource is being created/updated in, you can use this inside any of the lifecycle operations.
|
||||
|
||||
```ts
|
||||
const region = yield * Region;
|
||||
const account = yield * Account;
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
:::warning
|
||||
You should favor getting the region/account INSIDE the lifecycle operations instead of inside the Layer effect like this because then it's scoped to the resource isntead of the resource provider:
|
||||
|
||||
```ts
|
||||
reconcile: Effect.fn(function* ({ id, news, output, session }) {
|
||||
const region = yield* Region;
|
||||
const accountId = yield* Account;
|
||||
});
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
:::warning
|
||||
Do not use `Effect.orDie` in the lifecycle operations since this will crash the whole IaC engine.
|
||||
:::
|
||||
|
||||
:::warning
|
||||
**Never use `async`/`await`, raw `Promise`, `node:fs/promises`, `node:fs`, `node:os`, or `pathe` directly in resource code.** Always use the Effect platform services so that effects remain composable, traceable, retryable, and testable:
|
||||
|
||||
| Don't | Do |
|
||||
| ---------------------------------------------------- | ----------------------------------------------------------- |
|
||||
| `import fs from "node:fs/promises"` | `const fs = yield* FileSystem.FileSystem` |
|
||||
| `await fs.readFile(p, "utf8")` | `yield* fs.readFileString(p)` |
|
||||
| `await fs.mkdtemp(...)` | `yield* fs.makeTempDirectory({ prefix: ... })` |
|
||||
| `import path from "pathe"` / `node:path` | `const path = yield* Path.Path` |
|
||||
| `await fetch(...)` | `yield* HttpClient.HttpClient` + `HttpClientRequest` |
|
||||
| `Effect.promise(() => listSqlFiles(dir))` | Make `listSqlFiles` itself return `Effect` and `yield*` it |
|
||||
| `new Promise((res) => setTimeout(res, ms))` | `yield* Effect.sleep(Duration.millis(ms))` |
|
||||
|
||||
Sync, CPU-only Node APIs (e.g. `crypto.createHash().update().digest()`, `process.cwd()`, `Buffer`, `TextEncoder`) must still be wrapped in `Effect.sync(() => ...)` (or `Effect.try` if they can throw) so the call participates in the Effect runtime — tracing, interruption, and error channels. Don't call them as bare expressions inside `Effect.gen`.
|
||||
|
||||
```ts
|
||||
const hash = yield* Effect.sync(() =>
|
||||
crypto.createHash("sha256").update(input).digest("hex"),
|
||||
);
|
||||
const cwd = yield* Effect.sync(() => process.cwd());
|
||||
```
|
||||
|
||||
This applies to **lifecycle operations, helpers, AND tests**. Tests must use `FileSystem.FileSystem`/`Path.Path` for any file/path access (see [Database.test.ts](./packages/alchemy/test/Cloudflare/D1/Database.test.ts) for the pattern).
|
||||
:::
|
||||
|
||||
:::tip
|
||||
If a Resource supports tags, you should always include the internal Alchemy tags to brand the resource with the app, stage and logical ID so that we can "know" that we created it and are responsible for it.
|
||||
|
||||
```ts
|
||||
reconcile: Effect.fn(function* ({ id, news, output, session }) {
|
||||
const internalTags = yield* createInternalTags(id);
|
||||
const userTags = news.tags ?? {};
|
||||
const allTags = { ...internalTags, ...userTags };
|
||||
});
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
:::warning
|
||||
Do not roll your own tag diffing logic, always use `diffTags` from [Tags.ts](./packages/alchemy/src/Tags.ts), and diff against **observed cloud tags** (not `olds.tags` or `output.tags`). Adoption can hand you a resource whose tags don't match what we last persisted.
|
||||
|
||||
```ts
|
||||
reconcile: Effect.fn(function* ({ id, news, output, session }) {
|
||||
const internalTags = yield* createInternalTags(id);
|
||||
const newTags = { ...news.tags, ...internalTags };
|
||||
// Read tags fresh from the cloud so adoption (where tags may not match
|
||||
// what we last persisted) converges correctly.
|
||||
const oldTags = yield* fetchObservedTags(/* … */);
|
||||
// Option 1. use `upsert` if the API expects you to create/update tags in one call
|
||||
const { removed, upsert } = diffTags(oldTags, newTags);
|
||||
// Option 2. use `added` and `updated` if the API expects you to create/update tags in separate calls
|
||||
const { removed, added, updated } = diffTags(oldTags, newTags);
|
||||
// Option 3. use `upsert` only if the API doesn't expect you to remove tags (only PUT/UPDATe)
|
||||
const { upsert } = diffTags(oldTags, newTags);
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
9. Implement the test cases in `packages/alchemy/test/{Cloud}/{Service}/{Resource}.test.ts`.
|
||||
|
||||
Read through the established test cases before continuing so that you understand the pattern and structure of the test cases.
|
||||
|
||||
- [S3 Bucket Test Cases](./test/AWS/S3/Bucket.test.ts)
|
||||
- [SQS Queue Test Cases](./test/AWS/SQS/Queue.test.ts)
|
||||
- [Lambda Function Test Cases](./test/AWS/Lambda/Function.test.ts)
|
||||
- [Kinesis Stream Test Cases](./test/AWS/Kinesis/Stream.test.ts)
|
||||
- [DynamoDB Table Test Cases](./test/AWS/DynamoDB/Table.test.ts)
|
||||
- [VPC Test Cases](./test/AWS/EC2/Vpc.test.ts)
|
||||
- [Subnet Test Cases](./test/AWS/EC2/Subnet.test.ts)
|
||||
|
||||
:::warning
|
||||
Never use `Date.now()` when constructing the physical name of a resource. You should either:
|
||||
|
||||
1. Do not proide a name and rely on the resource provider to generate a unique name for you from the app, stage and logical ID.
|
||||
2. Construct a deterministic one unique to each test case. But it should be the same on each subsequent run of the test case.
|
||||
:::
|
||||
|
||||
3. Consider implementing an aggregate Smoke test that brings together multiple resources that are often used together.
|
||||
|
||||
See the [VPC Smoke Test](./test/AWS/EC2/Vpc.smoke.test.ts) for an example.
|
||||
|
||||
11. Add the resource-level JSDoc (`@section` + `@example` blocks) and field-level JSDoc on each prop/attribute on the source `.ts` file. Then run `bun generate:api-reference` to refresh `website/src/content/docs/providers/{Cloud}/{Resource}.md`. Do NOT manually edit the generated markdown.
|
||||
|
||||
# Test Fixtures for Effect-Native Workers / Functions
|
||||
|
||||
To test runtime behavior of an Effect-native Worker, Workflow, Lambda, etc., write a **fixture** that defines the Worker/Function with the bindings under test and exposes one HTTP route per behavior, then write a **test** that deploys the fixture once via `beforeAll` and drives it over HTTP.
|
||||
|
||||
## File system layout
|
||||
|
||||
Put fixtures in a `fixtures/` directory next to the test file. Each test suite owns its own fixtures — never reach across suites:
|
||||
|
||||
```sh
|
||||
packages/alchemy/test/{Cloud}/{Service}/{Resource}.test.ts
|
||||
packages/alchemy/test/{Cloud}/{Service}/fixtures/{worker|workflow|handler}.ts
|
||||
```
|
||||
|
||||
## Fixture shape
|
||||
|
||||
Resolve the bindings, expose one route per behavior, default-export the class so the test can deploy it directly:
|
||||
|
||||
```ts
|
||||
// fixtures/worker.ts
|
||||
import * as Cloudflare from "@/Cloudflare/index.ts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { HttpServerRequest } from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { Gateway } from "./gateway.ts";
|
||||
|
||||
export default class TestWorker extends Cloudflare.Worker<TestWorker>()(
|
||||
"TestWorker",
|
||||
{
|
||||
main: import.meta.filename,
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const aiGateway = yield* Cloudflare.AiGateway.bind(Gateway);
|
||||
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest;
|
||||
if (request.url.startsWith("/url")) {
|
||||
const url = yield* aiGateway.getUrl().pipe(Effect.orDie);
|
||||
return yield* HttpServerResponse.json({ url });
|
||||
}
|
||||
return HttpServerResponse.text("ok");
|
||||
}),
|
||||
};
|
||||
}).pipe(Effect.provide(Cloudflare.AiGatewayBindingLive)),
|
||||
) {}
|
||||
```
|
||||
|
||||
## Test shape
|
||||
|
||||
Compose a `Stack` that deploys the fixture, share one deploy across the file with `beforeAll`/`afterAll`, drive it via `HttpClient`, and retry the first request through edge propagation:
|
||||
|
||||
```ts
|
||||
// Service.test.ts
|
||||
import * as Alchemy from "@/index.ts";
|
||||
import * as Cloudflare from "@/Cloudflare";
|
||||
import * as Test from "@/Test/Vitest";
|
||||
import { expect } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import TestWorker from "./fixtures/worker.ts";
|
||||
|
||||
const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
|
||||
providers: Cloudflare.providers(),
|
||||
});
|
||||
|
||||
const Stack = Alchemy.Stack(
|
||||
"ServiceTestStack",
|
||||
{ providers: Cloudflare.providers(), state: Cloudflare.state() },
|
||||
Effect.gen(function* () {
|
||||
const worker = yield* TestWorker;
|
||||
return { url: worker.url.as<string>() };
|
||||
}),
|
||||
);
|
||||
|
||||
const stack = beforeAll(deploy(Stack));
|
||||
afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
|
||||
|
||||
test(
|
||||
"deployed worker exercises the binding",
|
||||
Effect.gen(function* () {
|
||||
const { url } = yield* stack;
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
|
||||
const res = yield* client.get(`${url}/url`).pipe(
|
||||
Effect.retry({ schedule: Schedule.exponential("500 millis"), times: 10 }),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (yield* res.json) as { url: string };
|
||||
expect(body.url).toContain("gateway.ai.cloudflare.com");
|
||||
}),
|
||||
{ timeout: 180_000 },
|
||||
);
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `Test.make({ providers: Cloudflare.providers() })` gives you `test`, `beforeAll`, `afterAll`, `deploy`, `destroy`.
|
||||
- `beforeAll(deploy(Stack))` returns a handle (`stack` above) that every `test` body can `yield*` to get the stack outputs.
|
||||
- `afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack))` is the standard cleanup — set `NO_DESTROY=1` locally to keep the deployment around between runs while iterating.
|
||||
- Always retry the first request (`Schedule.exponential("500 millis")`) — fresh workers.dev URLs and Lambda function URLs take a few seconds to start serving 200s.
|
||||
- For POST: use `client.post(url)` for empty bodies, or `HttpClient.execute(HttpClientRequest.post(url).pipe(HttpClientRequest.bodyJsonUnsafe(body)))` for typed bodies.
|
||||
- **Never use `while (Date.now() < deadline)` loops to poll** for an async side effect (a workflow status, a cron fire, a queue drain, eventual-consistency read, etc.). Use `Effect.repeat` with a `Schedule` and an `until` predicate so the polling participates in the Effect runtime — tracing, interruption, and error propagation work correctly, and the intent is declarative. Cap iterations with `times: N` (or a bounded schedule) so the test fails fast instead of running until the vitest timeout:
|
||||
|
||||
```ts
|
||||
// good — declarative, bounded, interruption-safe
|
||||
const value = yield* fetchValue.pipe(
|
||||
Effect.repeat({
|
||||
schedule: Schedule.spaced("5 seconds"),
|
||||
until: (v) => v.ready,
|
||||
times: 36,
|
||||
}),
|
||||
);
|
||||
|
||||
// bad — opaque loop, ignores interruption, leaks into vitest timeout
|
||||
let value: Value | undefined;
|
||||
const deadline = Date.now() + 180_000;
|
||||
while (Date.now() < deadline) {
|
||||
value = yield* fetchValue;
|
||||
if (value.ready) break;
|
||||
yield* Effect.sleep("5 seconds");
|
||||
}
|
||||
```
|
||||
|
||||
See [CronEventSource.test.ts](./packages/alchemy/test/Cloudflare/Workers/CronEventSource.test.ts) for a real-world example (polling a DO via the worker's `/times` route until the cron handler fires).
|
||||
|
||||
## Reference implementations
|
||||
|
||||
- Cloudflare AiGateway — [worker fixture](./packages/alchemy/test/Cloudflare/AiGateway/worker.ts) + [test](./packages/alchemy/test/Cloudflare/AiGateway/AiGateway.test.ts) (the deploy+fetch case lives at the bottom of the file)
|
||||
- Cloudflare D1Connection — [worker fixture](./packages/alchemy/test/Cloudflare/D1/d1-worker.ts) + [test](./packages/alchemy/test/Cloudflare/D1/D1Binding.test.ts)
|
||||
- Cloudflare Workflow — [workflow fixture](./packages/alchemy/test/Cloudflare/Workers/fixtures/test-workflow.ts) + [worker fixture](./packages/alchemy/test/Cloudflare/Workers/fixtures/workflow-worker.ts) + [test](./packages/alchemy/test/Cloudflare/Workers/Workflow.test.ts)
|
||||
- Cloudflare Cron Trigger — [worker + DO fixture](./packages/alchemy/test/Cloudflare/Workers/fixtures/cron-worker.ts) + [test](./packages/alchemy/test/Cloudflare/Workers/CronEventSource.test.ts) (cron handler writes to a DO; test polls a fetch route with `Effect.repeat` until the scheduled handler fires)
|
||||
- Cloudflare Images — [effect fixture](./packages/alchemy/test/Cloudflare/Images/fixtures/effect-worker.ts) + [async fixture](./packages/alchemy/test/Cloudflare/Images/fixtures/async-worker.ts) + [test](./packages/alchemy/test/Cloudflare/Images/Images.test.ts)
|
||||
- AWS Lambda (DynamoDB bindings) — [Lambda fixture](./packages/alchemy/test/AWS/DynamoDB/handler.ts) + [test](./packages/alchemy/test/AWS/DynamoDB/Bindings.test.ts) (one `describe("<BindingName>")` per binding, all driving the same deployed Lambda)
|
||||
|
||||
# Spec-Driven Service Bring-Up
|
||||
|
||||
Use @processes/AWS.md as the source of truth for bringing a single AWS service from zero to full coverage.
|
||||
|
||||
That process covers:
|
||||
|
||||
- deriving resources, bindings, event sources, and helpers from distilled
|
||||
- the audit-driven implementation loop
|
||||
- deterministic checks for registration and binding test coverage
|
||||
- Lambda fixture testing conventions
|
||||
- learned conventions like no auto-marshalling and one `describe("<BindingName>")` block per binding
|
||||
|
||||
Keep `AGENTS.md` high-level and update @processes/AWS.md when the process evolves.
|
||||
|
||||
When a canonical resource needs mutable event-source configuration and there is any chance of circularity, prefer a resource binding contract over a plain input prop. DynamoDB Streams is the reference case: `Table` owns the actual stream state, while `streams(table)` injects that state via bindings and the runtime-specific layer handles the subscription mechanics. See @processes/AWS.md for the DynamoDB Streams case study.
|
||||
|
||||
# Build and Type Checking
|
||||
|
||||
Always run type checking before committing changes:
|
||||
|
||||
```bash
|
||||
bun tsc -b
|
||||
```
|
||||
|
||||
This runs the TypeScript compiler in build mode, which checks all projects in the workspace. This is critical because CI will fail if there are type errors.
|
||||
|
||||
## Build Commands
|
||||
|
||||
| Command | Description |
|
||||
| ----------------- | -------------------------------------------------------------------------------------------- |
|
||||
| `bun tsc -b` | Type check all projects (always run before committing) |
|
||||
| `bun run build` | Clean, type check, and build the alchemy package |
|
||||
| `bun build:clean` | Full clean rebuild: cleans all artifacts, reinstalls dependencies, builds, and downloads env |
|
||||
|
||||
Use `bun build:clean` when you encounter stale build artifacts or dependency issues. It runs:
|
||||
|
||||
1. `bun clean .` - Removes all untracked files except .env
|
||||
2. `bun i` - Reinstalls dependencies
|
||||
3. `bun run build` - Builds the project
|
||||
4. `bun download:env` - Downloads environment files
|
||||
|
||||
# Tutorial Documentation Standard
|
||||
|
||||
Tutorials under `website/src/content/docs/tutorial/` are **step-by-step and granular**: every code snippet introduces exactly **one** new thing, followed by a short prose explanation of just that thing. Each step gets its own `##` heading.
|
||||
|
||||
**Anti-pattern** — one snippet that adds multiple distinct changes, followed by a numbered list or bullet list explaining each:
|
||||
|
||||
````md
|
||||
## Bind the DO to the Worker
|
||||
|
||||
```diff lang="typescript"
|
||||
+import Counter from "./counter.ts";
|
||||
+import { HttpServerRequest } from "...";
|
||||
|
||||
Effect.gen(function* () {
|
||||
+ const counters = yield* Counter;
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
+ const request = yield* HttpServerRequest;
|
||||
+ if (request.url.startsWith("/counter/") && ...) {
|
||||
+ const next = yield* counters.getByName(name).increment();
|
||||
+ return HttpServerResponse.text(String(next));
|
||||
+ }
|
||||
return HttpServerResponse.text("Hello!");
|
||||
}),
|
||||
};
|
||||
})
|
||||
```
|
||||
|
||||
Two things just happened:
|
||||
1. `yield* Counter` registers the DO ...
|
||||
2. `counters.getByName(name)` returns a typed stub ...
|
||||
````
|
||||
|
||||
**Correct** — split into one heading per step, each with one snippet and one explanation:
|
||||
|
||||
````md
|
||||
## Bind the DO to the Worker
|
||||
|
||||
```diff lang="typescript"
|
||||
+import Counter from "./counter.ts";
|
||||
|
||||
Effect.gen(function* () {
|
||||
+ const counters = yield* Counter;
|
||||
...
|
||||
})
|
||||
```
|
||||
|
||||
`yield* Counter` registers the DO with the Worker (binding + class-migration metadata) and hands you the namespace.
|
||||
|
||||
## Call the DO from `fetch`
|
||||
|
||||
```diff lang="typescript"
|
||||
+import { HttpServerRequest } from "...";
|
||||
|
||||
fetch: Effect.gen(function* () {
|
||||
+ const request = yield* HttpServerRequest;
|
||||
+ if (request.url.startsWith("/counter/") && ...) {
|
||||
+ const next = yield* counters.getByName(name).increment();
|
||||
+ return HttpServerResponse.text(String(next));
|
||||
+ }
|
||||
return HttpServerResponse.text("Hello!");
|
||||
})
|
||||
```
|
||||
|
||||
`counters.getByName(name)` returns a typed stub — `increment()` and `get()` round-trip through Cloudflare's RPC machinery.
|
||||
````
|
||||
|
||||
Rules of thumb:
|
||||
|
||||
- If you find yourself writing "Two/three things just happened", "A few things are happening here", or a numbered/bulleted list explaining separate parts of a single snippet — **split the snippet**.
|
||||
- One concept ⇒ one heading ⇒ one diff snippet ⇒ one explanation paragraph (no bullets).
|
||||
- Bullet/numbered lists are fine when they describe a recap, prerequisites, or genuinely list-shaped content (e.g. "the Worker now handles two routes: PUT and GET" at the end). They are **not** fine as a substitute for splitting a compound snippet.
|
||||
- A single API call that internally does several things (e.g. `Cloudflare.upgrade()`) doesn't need splitting — describe its behavior in prose.
|
||||
- Use `diff lang="typescript"` blocks so each step shows what's added on top of the previous step.
|
||||
|
||||
# Pull Request Conventions
|
||||
|
||||
When you automatically open a PR, it MUST follow this structure:
|
||||
|
||||
- **Title**: Use conventional commit format (e.g. `fix(website): mobile theme metas`, `feat(aws/s3): add bucket lifecycle rules`).
|
||||
- **Description heading levels**: NEVER use `#` or `##` in the PR description. The smallest heading allowed is `###`. The PR description must NOT begin with its own title heading — GitHub already renders the PR title above it.
|
||||
- **Content**: Aim for the minimal content needed to convey the idea.
|
||||
- Use simple sentences. If there are multiple discrete changes, use bullet points.
|
||||
- **Prefer code snippets over prose.** A short ` ```ts ` or ` ```diff ` block showing the new/changed shape is worth more than a paragraph explaining it. Reach for code first; only add prose to fill in the "why" the snippet can't show on its own.
|
||||
- Be direct and succinct. Cut adjectives, justifications, and anything that reads like marketing copy. If a sentence is restating what the diff already shows, delete it.
|
||||
- **Never include a "Test plan", "Testing", or checklist of TODOs.** PR descriptions document the change, not the verification process. If something needs manual verification, follow the draft-PR rule below.
|
||||
- Skip examples for trivial fixes, internal refactors, or doc-only changes.
|
||||
|
||||
Example PR description (good — code snippet does the talking):
|
||||
|
||||
````
|
||||
Track which state-store backend each project uses by emitting a `state_store.init` span tagged with `alchemy.state_store.kind`.
|
||||
|
||||
```ts
|
||||
// every Layer.effect(State, …) site now wraps construction:
|
||||
makeLocalState().pipe(recordStateStoreInit("local"))
|
||||
```
|
||||
|
||||
Dashboard groups projects by kind from these spans (Axiom can't APL-query metric datasets).
|
||||
````
|
||||
- **Outstanding work / testing / review needed**: If there are outstanding steps, manual testing required, or review items, DO NOT leave a comment on the PR and DO NOT include them in the PR description. Instead:
|
||||
1. Mark the PR as **draft**.
|
||||
2. Tell the user (in the chat that initiated the PR creation) what is outstanding.
|
||||
|
||||
:::warning
|
||||
**Markdown content must reach GitHub verbatim** — un-escaped backticks, fenced code blocks, etc. The reliable shape is to write the description to a file and pass `--body-file <path>` to `gh pr create` / `gh pr edit`:
|
||||
|
||||
```sh
|
||||
# write the body to a temp file (use Write tool, not echo/cat heredoc)
|
||||
gh pr edit 179 --body-file /tmp/pr-body.md
|
||||
```
|
||||
|
||||
Do **not** inline the body via `--body "$(cat <<'EOF' ... EOF)"`. Even with a single-quoted heredoc some shells / `gh` versions still mangle backticks and backslashes; the resulting PR body ends up with literal `\`` sequences instead of inline code spans. `--body-file` sidesteps shell quoting entirely.
|
||||
|
||||
If you need to update an already-created PR's body, prefer `gh pr edit --body-file ...`. If that silently no-ops (older `gh` versions), fall back to `gh api -X PATCH repos/<owner>/<repo>/pulls/<n> -F body=@/tmp/pr-body.md`.
|
||||
:::
|
||||
|
||||
The summary goes at the very top of the description as plain prose — NO heading above it, no `### Summary`, nothing. The PR title already serves as the title; do not repeat or re-title it. Only add `###` subheadings further down if the description genuinely has multiple sections worth separating.
|
||||
|
||||
Example PR description (good):
|
||||
|
||||
```
|
||||
Persist the user's selected theme across reloads and fix a hero scroll glitch on mobile.
|
||||
|
||||
- Read theme from `localStorage` on mount before first paint
|
||||
- Add `<meta name="theme-color">` per theme so mobile chrome matches
|
||||
```
|
||||
|
||||
Example PR description (BAD — do not do this):
|
||||
|
||||
```
|
||||
## Theme persistence fix ← no, the PR title already exists
|
||||
### Summary ← no, summary needs no heading
|
||||
Persist the user's theme...
|
||||
```
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,85 @@
|
||||
<div align="center">
|
||||
|
||||
<a href="https://v2.alchemy.run">
|
||||
<img src="./images/readme-hero.png" alt="Alchemy — Infrastructure as Effects" width="360" />
|
||||
</a>
|
||||
|
||||
<br />
|
||||
|
||||
[](https://www.npmjs.com/package/alchemy)
|
||||
[](./LICENSE)
|
||||
[](https://discord.gg/jwKw8dBJdN)
|
||||
|
||||
**Infrastructure-as-Effects** — cloud infrastructure and application logic as a single, type-safe [Effect](https://effect.website) program.
|
||||
|
||||
[Docs](https://v2.alchemy.run) · [Tutorial](https://v2.alchemy.run/tutorial/part-1) · [Examples](./examples) · [Discord](https://discord.gg/jwKw8dBJdN)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
A Worker bound to a R2 bucket and serving objects from it:
|
||||
|
||||
```typescript
|
||||
const Bucket = Cloudflare.R2Bucket("bucket");
|
||||
|
||||
export default Cloudflare.Worker(
|
||||
"api",
|
||||
{ main: import.meta.path },
|
||||
Effect.gen(function* () {
|
||||
const bucket = yield* Cloudflare.R2Bucket.bind(Bucket);
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest;
|
||||
const object = yield* bucket.get(request.url);
|
||||
return HttpServerResponse.stream(object!.body);
|
||||
})
|
||||
};
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
One `bind()` wires the binding, env var, and typed connection — at deploy time and at runtime.
|
||||
|
||||
---
|
||||
|
||||
- **One program, one language.** Resources, Lambdas/Workers, IAM, and SDKs live in the same Effect program — no YAML, no second runtime.
|
||||
- **Bindings, not glue code.** `S3.GetObject.bind(bucket)` wires the IAM policy, env var, and a typed SDK call in a single line.
|
||||
- **Errors in the type system.** Every cloud API failure is a tagged Effect error you handle — or don't — on purpose.
|
||||
- **AWS + Cloudflare today.** S3, SQS, DynamoDB, Kinesis, Lambda, EC2 / Workers, R2, D1, Durable Objects, Containers.
|
||||
- **Same code, every stage.** Local dev, `plan` / `deploy`, smoke tests, and CI all share one mental model.
|
||||
|
||||
```sh
|
||||
bun add alchemy effect
|
||||
```
|
||||
|
||||
## Bootstrap with an AI coding agent
|
||||
|
||||
Paste this into Claude Code, Cursor, or any agent that can fetch a URL:
|
||||
|
||||
```
|
||||
You are an Alchemy expert. Read https://v2.alchemy.run/llms.txt to load the
|
||||
full documentation index, then act as my pair on this project.
|
||||
|
||||
Goal: help me set up, build, test, and deploy a cloud application with
|
||||
`alchemy` (Infrastructure-as-Effects, powered by Effect).
|
||||
|
||||
Follow the patterns from the docs and the /examples folder. Stay idiomatic
|
||||
to Effect: use Layers for wiring, return Effects from lifecycle code, and
|
||||
keep infra and runtime in the same program. Ask before introducing new
|
||||
dependencies or breaking conventions.
|
||||
```
|
||||
|
||||
## Learn more
|
||||
|
||||
- [What is Alchemy?](https://v2.alchemy.run/what-is-alchemy) — the framework in 2 minutes
|
||||
- [Getting Started](https://v2.alchemy.run/getting-started) — your first Stack
|
||||
- [Tutorial](https://v2.alchemy.run/tutorial/part-1) — five-part walkthrough to a tested, CI-deployed app
|
||||
- [Examples](./examples) — runnable projects on AWS and Cloudflare
|
||||
- [llms.txt](https://v2.alchemy.run/llms.txt) — agent-ready documentation index
|
||||
|
||||
> **alchemy** is in alpha. Expect breaking changes. Come hang in our [Discord](https://discord.gg/jwKw8dBJdN).
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { NetworkLive } from "./src/Network.ts";
|
||||
import Server from "./src/Server.ts";
|
||||
|
||||
const aws = AWS.providers();
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"AwsEc2Example",
|
||||
{ providers: aws, state: Alchemy.localState() },
|
||||
Effect.gen(function* () {
|
||||
const instance = yield* Server;
|
||||
|
||||
return {
|
||||
instanceId: instance.instanceId,
|
||||
publicIpAddress: instance.publicIpAddress,
|
||||
instanceUrl: Output.interpolate`http://${instance.publicIpAddress}:3000`,
|
||||
enqueueExample: Output.interpolate`http://${instance.publicIpAddress}:3000/enqueue?message=hello`,
|
||||
};
|
||||
}).pipe(Effect.provide(NetworkLive)),
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "aws-ec2-example",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-ec2"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import type { Output } from "alchemy/Output";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export interface ExampleNetwork {
|
||||
network: AWS.EC2.Network;
|
||||
publicSubnetIds: Output<AWS.EC2.SubnetId>[];
|
||||
appSecurityGroupId: Output<AWS.EC2.SecurityGroupId>;
|
||||
}
|
||||
|
||||
export class Network extends Context.Service<Network, ExampleNetwork>()(
|
||||
"Network",
|
||||
) {}
|
||||
|
||||
export const NetworkLive = Layer.effect(
|
||||
Network,
|
||||
Effect.gen(function* () {
|
||||
const network = yield* AWS.EC2.Network("Network", {
|
||||
cidrBlock: "10.42.0.0/16",
|
||||
availabilityZones: 2,
|
||||
nat: "single",
|
||||
});
|
||||
|
||||
const appSecurityGroup = yield* AWS.EC2.SecurityGroup("AppSecurityGroup", {
|
||||
vpcId: network.vpcId,
|
||||
description: "Security group for the EC2 application instance",
|
||||
ingress: [
|
||||
{
|
||||
ipProtocol: "tcp",
|
||||
fromPort: 3000,
|
||||
toPort: 3000,
|
||||
cidrIpv4: "0.0.0.0/0",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return {
|
||||
network,
|
||||
publicSubnetIds: network.publicSubnetIds,
|
||||
appSecurityGroupId: appSecurityGroup.groupId,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import { SQSQueueEventSource } from "alchemy/Server/SQSQueueEventSource";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { Network, NetworkLive } from "./Network.ts";
|
||||
|
||||
export default class Server extends AWS.EC2.Instance<Server>()(
|
||||
"ServerInstance",
|
||||
Effect.gen(function* () {
|
||||
const imageId = yield* AWS.EC2.amazonLinux();
|
||||
const network = yield* Network;
|
||||
|
||||
return {
|
||||
main: import.meta.filename,
|
||||
imageId,
|
||||
instanceType: "t3.small",
|
||||
subnetId: network.publicSubnetIds[0],
|
||||
securityGroupIds: [network.appSecurityGroupId],
|
||||
associatePublicIpAddress: true,
|
||||
port: 3000,
|
||||
};
|
||||
}),
|
||||
Effect.gen(function* () {
|
||||
const queue = yield* AWS.SQS.Queue("JobsQueue", {
|
||||
receiveMessageWaitTimeSeconds: 20,
|
||||
visibilityTimeout: 60,
|
||||
});
|
||||
|
||||
yield* AWS.SQS.messages(queue).subscribe((stream) =>
|
||||
stream.pipe(Stream.mapEffect(Effect.logInfo), Stream.runDrain),
|
||||
);
|
||||
|
||||
const sendMessage = yield* AWS.SQS.SendMessage.bind(queue);
|
||||
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = new URL(request.originalUrl);
|
||||
|
||||
if (request.method === "GET" && url.pathname === "/") {
|
||||
return yield* HttpServerResponse.json({
|
||||
ok: true,
|
||||
routes: ["GET /", "GET /enqueue?message=hello"],
|
||||
});
|
||||
}
|
||||
|
||||
if (request.method === "GET" && url.pathname === "/enqueue") {
|
||||
const message = url.searchParams.get("message") ?? "hello from EC2";
|
||||
const body = JSON.stringify({
|
||||
message,
|
||||
enqueuedAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const result = yield* sendMessage({
|
||||
MessageBody: body,
|
||||
});
|
||||
|
||||
return yield* HttpServerResponse.json({
|
||||
ok: true,
|
||||
message,
|
||||
messageId: result.MessageId,
|
||||
});
|
||||
}
|
||||
|
||||
return HttpServerResponse.text("Not found", { status: 404 });
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(
|
||||
HttpServerResponse.text("Internal server error", { status: 500 }),
|
||||
),
|
||||
),
|
||||
),
|
||||
};
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(NetworkLive, SQSQueueEventSource),
|
||||
Layer.mergeAll(
|
||||
AWS.SQS.DeleteMessageBatchLive,
|
||||
AWS.SQS.ReceiveMessageLive,
|
||||
AWS.SQS.SendMessageLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts", "src/**/*.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"target": "ESNext"
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
import QueueConsumerTask from "./src/QueueConsumerTask.ts";
|
||||
import ApiTask from "./src/Task.ts";
|
||||
|
||||
const aws = AWS.providers();
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"AwsEcsExample",
|
||||
{
|
||||
providers: aws,
|
||||
state: Alchemy.localState(),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const network = yield* AWS.EC2.Network("ExampleNetwork", {
|
||||
cidrBlock: "10.42.0.0/16",
|
||||
availabilityZones: 2,
|
||||
});
|
||||
|
||||
const serviceSecurityGroup = yield* AWS.EC2.SecurityGroup(
|
||||
"ExampleServiceSecurityGroup",
|
||||
{
|
||||
vpcId: network.vpcId,
|
||||
description: "Security group for the ECS example services",
|
||||
ingress: [
|
||||
{
|
||||
ipProtocol: "tcp",
|
||||
fromPort: 80,
|
||||
toPort: 80,
|
||||
cidrIpv4: "0.0.0.0/0",
|
||||
},
|
||||
{
|
||||
ipProtocol: "tcp",
|
||||
fromPort: 3000,
|
||||
toPort: 3000,
|
||||
cidrIpv4: "0.0.0.0/0",
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
const queue = yield* AWS.SQS.Queue("ExampleJobsQueue", {
|
||||
receiveMessageWaitTimeSeconds: 20,
|
||||
visibilityTimeout: 60,
|
||||
});
|
||||
|
||||
const cluster = yield* AWS.ECS.Cluster("ExampleCluster", {});
|
||||
const apiTask = yield* ApiTask;
|
||||
const queuePollerTask = yield* QueueConsumerTask;
|
||||
|
||||
const apiService = yield* AWS.ECS.Service("ExampleApiService", {
|
||||
cluster,
|
||||
task: apiTask,
|
||||
vpcId: network.vpcId,
|
||||
subnets: network.publicSubnetIds,
|
||||
securityGroups: [serviceSecurityGroup.groupId],
|
||||
assignPublicIp: true,
|
||||
public: true,
|
||||
healthCheckPath: "/",
|
||||
});
|
||||
|
||||
yield* AWS.ECS.Service("ExampleQueuePollerService", {
|
||||
cluster,
|
||||
task: queuePollerTask,
|
||||
vpcId: network.vpcId,
|
||||
subnets: network.publicSubnetIds,
|
||||
securityGroups: [serviceSecurityGroup.groupId],
|
||||
assignPublicIp: true,
|
||||
desiredCount: 1,
|
||||
});
|
||||
|
||||
return {
|
||||
url: apiService.url,
|
||||
queueUrl: queue.queueUrl,
|
||||
enqueueExample: Output.interpolate`${apiService.url}/enqueue?message=hello`,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "aws-ecs-example",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-ecs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
/**
|
||||
* Deploy-time binding for the ECS example’s jobs queue. Provide with
|
||||
* `Layer.succeed(ExampleJobsQueue, queue)` from the stack after the queue exists.
|
||||
*/
|
||||
export class JobsQueue extends Context.Service<JobsQueue, AWS.SQS.Queue>()(
|
||||
"JobsQueue",
|
||||
) {}
|
||||
|
||||
export const JobsQueueLive = Layer.effect(
|
||||
JobsQueue,
|
||||
AWS.SQS.Queue("JobsQueue"),
|
||||
);
|
||||
@@ -0,0 +1,41 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Server from "alchemy/Server";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { JobsQueue, JobsQueueLive } from "./JobsQueue.ts";
|
||||
|
||||
export default class QueueConsumerTask extends AWS.ECS.Task<QueueConsumerTask>()(
|
||||
"QueueConsumerTask",
|
||||
{
|
||||
main: import.meta.filename,
|
||||
cpu: 256,
|
||||
memory: 512,
|
||||
taskRoleManagedPolicyArns: ["arn:aws:iam::aws:policy/AmazonSQSFullAccess"],
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const queue = yield* JobsQueue;
|
||||
yield* AWS.SQS.messages(queue, {
|
||||
batchSize: 10,
|
||||
maximumBatchingWindowInSeconds: 20,
|
||||
}).subscribe((stream) =>
|
||||
stream.pipe(
|
||||
Stream.runForEach((record) =>
|
||||
Effect.logInfo(
|
||||
`processed SQS message ${record.messageId}: ${record.body ?? ""}`,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(Server.SQSQueueEventSource, JobsQueueLive),
|
||||
Layer.mergeAll(
|
||||
AWS.SQS.ReceiveMessageLive,
|
||||
AWS.SQS.DeleteMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,67 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { JobsQueue, JobsQueueLive } from "./JobsQueue.ts";
|
||||
|
||||
export default class ApiTask extends AWS.ECS.Task<ApiTask>()(
|
||||
"ApiTask",
|
||||
{
|
||||
main: import.meta.filename,
|
||||
cpu: 512,
|
||||
memory: 1024,
|
||||
port: 3000,
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const queue = yield* JobsQueue;
|
||||
const sendMessage = yield* AWS.SQS.SendMessage.bind(queue);
|
||||
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = new URL(request.originalUrl);
|
||||
if (request.method === "GET" && url.pathname === "/") {
|
||||
return yield* HttpServerResponse.json({
|
||||
ok: true,
|
||||
routes: ["GET /", "GET /enqueue?message=hello"],
|
||||
});
|
||||
}
|
||||
|
||||
if (request.method === "GET" && url.pathname === "/enqueue") {
|
||||
const message = url.searchParams.get("message") ?? "hello from ECS";
|
||||
const body = JSON.stringify({
|
||||
message,
|
||||
enqueuedAt: new Date().toISOString(),
|
||||
});
|
||||
|
||||
const result = yield* sendMessage({
|
||||
MessageBody: body,
|
||||
});
|
||||
|
||||
return yield* HttpServerResponse.json({
|
||||
ok: true,
|
||||
message,
|
||||
messageId: result.MessageId,
|
||||
});
|
||||
}
|
||||
|
||||
return HttpServerResponse.text("Not found", { status: 404 });
|
||||
}).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.succeed(
|
||||
HttpServerResponse.text("Internal server error", { status: 500 }),
|
||||
),
|
||||
),
|
||||
),
|
||||
};
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
JobsQueueLive,
|
||||
AWS.SQS.SendMessageLive,
|
||||
AWS.SQS.DeleteMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts", "src/**/*.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"target": "ESNext"
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
# AWS EKS Auto Mode Example
|
||||
|
||||
This example is fully TypeScript-driven. It provisions:
|
||||
|
||||
- `AWS.EC2.Network`
|
||||
- `AWS.EKS.AutoCluster`
|
||||
- `AWS.EKS.AccessEntry` for cluster-admin access
|
||||
- `AWS.EKS.Addon` for `metrics-server` and `snapshot-controller`
|
||||
- `AWS.EKS.LoadBalancedWorkload` for deployment + public service composition
|
||||
- `AWS.EKS.PodIdentityWorkload` for workload identity + deployment composition
|
||||
- `Kubernetes.Namespace`
|
||||
- `Kubernetes.Job`
|
||||
|
||||
There is no YAML or `kubectl apply` step. The workloads are declared in
|
||||
[`alchemy.run.ts`](./alchemy.run.ts) and reconciled by the EKS cluster resource.
|
||||
|
||||
## Commands
|
||||
|
||||
```sh
|
||||
bun install
|
||||
bun run --filter aws-eks-example deploy
|
||||
bun run --filter aws-eks-example destroy
|
||||
```
|
||||
|
||||
## Cluster Access
|
||||
|
||||
By default, the example grants cluster-admin access to the IAM principal that is
|
||||
running the deploy. If your current caller is not a normal IAM user or IAM role,
|
||||
set this before deploy:
|
||||
|
||||
```sh
|
||||
export EKS_ADMIN_PRINCIPAL_ARN=arn:aws:iam::123456789012:role/YourAdminRole
|
||||
```
|
||||
|
||||
## What Gets Deployed
|
||||
|
||||
The example creates these in-cluster workloads in code:
|
||||
|
||||
- a `demo` namespace
|
||||
- an `echo-server` workload created with `AWS.EKS.LoadBalancedWorkload`
|
||||
- a `pod-identity-demo` workload created with `AWS.EKS.PodIdentityWorkload`
|
||||
- a `cluster-info` job
|
||||
|
||||
The pod identity workload creates the Kubernetes service account, IAM role,
|
||||
`AWS.EKS.PodIdentityAssociation`, and deployment together.
|
||||
|
||||
## Optional Inspection
|
||||
|
||||
If you want to inspect the cluster manually after deploy, you can still use your
|
||||
normal kubeconfig flow, for example:
|
||||
|
||||
```sh
|
||||
aws eks update-kubeconfig --name alchemy-eks-auto-example --region "$AWS_REGION"
|
||||
kubectl get pods -n demo
|
||||
```
|
||||
@@ -0,0 +1,251 @@
|
||||
import * as STS from "@distilled.cloud/aws/sts";
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as EC2 from "alchemy/AWS/EC2";
|
||||
import * as EKS from "alchemy/AWS/EKS";
|
||||
import * as Kubernetes from "alchemy/Kubernetes";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
const aws = AWS.providers();
|
||||
|
||||
const EKS_ADMIN_PRINCIPAL_ARN = Config.string("EKS_ADMIN_PRINCIPAL_ARN").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
);
|
||||
|
||||
const clusterName = "alchemy-eks-auto-example";
|
||||
const namespace = "demo";
|
||||
const serviceAccount = "pod-identity-demo";
|
||||
|
||||
const toIamPrincipalArn = (arn: string): string | undefined => {
|
||||
const assumedRole = arn.match(
|
||||
/^arn:([^:]+):sts::([0-9]{12}):assumed-role\/(.+)\/[^/]+$/,
|
||||
);
|
||||
if (assumedRole) {
|
||||
const [, partition, accountId, rolePath] = assumedRole;
|
||||
return `arn:${partition}:iam::${accountId}:role/${rolePath}`;
|
||||
}
|
||||
|
||||
if (arn.includes(":role/") || arn.includes(":user/")) {
|
||||
return arn;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const resolveClusterAdminPrincipalArn = Effect.gen(function* () {
|
||||
const configured = yield* EKS_ADMIN_PRINCIPAL_ARN;
|
||||
if (configured) {
|
||||
return configured;
|
||||
}
|
||||
|
||||
const caller = yield* STS.getCallerIdentity({});
|
||||
const principalArn =
|
||||
typeof caller.Arn === "string" ? toIamPrincipalArn(caller.Arn) : undefined;
|
||||
|
||||
if (!principalArn) {
|
||||
return yield* Effect.fail(
|
||||
new Error(
|
||||
"Unable to infer an IAM principal ARN for cluster access. Set EKS_ADMIN_PRINCIPAL_ARN before deploy.",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return principalArn;
|
||||
});
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"AwsEksExample",
|
||||
{
|
||||
providers: aws,
|
||||
state: Alchemy.localState(),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const tags = {
|
||||
Example: "aws-eks",
|
||||
Surface: "eks",
|
||||
Mode: "auto",
|
||||
};
|
||||
|
||||
const clusterAdminPrincipalArn = yield* resolveClusterAdminPrincipalArn;
|
||||
|
||||
const network = yield* EC2.Network("Network", {
|
||||
cidrBlock: "10.42.0.0/16",
|
||||
availabilityZones: 2,
|
||||
nat: "single",
|
||||
tags,
|
||||
});
|
||||
|
||||
const cluster = yield* EKS.AutoCluster("Cluster", {
|
||||
clusterName,
|
||||
network,
|
||||
tags,
|
||||
});
|
||||
|
||||
const clusterAdmin = yield* EKS.AccessEntry("ClusterAdmin", {
|
||||
clusterName: cluster.cluster.clusterName,
|
||||
principalArn: clusterAdminPrincipalArn,
|
||||
accessPolicies: [
|
||||
{
|
||||
policyArn:
|
||||
"arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy",
|
||||
accessScope: {
|
||||
type: "cluster",
|
||||
},
|
||||
},
|
||||
],
|
||||
tags,
|
||||
});
|
||||
|
||||
const metricsServer = yield* EKS.Addon("MetricsServer", {
|
||||
clusterName: cluster.cluster.clusterName,
|
||||
addonName: "metrics-server",
|
||||
tags,
|
||||
});
|
||||
|
||||
const snapshotController = yield* EKS.Addon("SnapshotController", {
|
||||
clusterName: cluster.cluster.clusterName,
|
||||
addonName: "snapshot-controller",
|
||||
tags,
|
||||
});
|
||||
|
||||
const demoNamespace = yield* Kubernetes.Namespace("DemoNamespace", {
|
||||
cluster: cluster.cluster,
|
||||
name: namespace,
|
||||
labels: {
|
||||
"app.kubernetes.io/part-of": "aws-eks-example",
|
||||
},
|
||||
});
|
||||
|
||||
const echoServer = yield* EKS.LoadBalancedWorkload("EchoServer", {
|
||||
cluster: cluster.cluster,
|
||||
namespace: demoNamespace,
|
||||
name: "echo-server",
|
||||
labels: {
|
||||
"app.kubernetes.io/name": "echo-server",
|
||||
"app.kubernetes.io/part-of": "aws-eks-example",
|
||||
},
|
||||
replicas: 2,
|
||||
containers: [
|
||||
{
|
||||
name: "echo-server",
|
||||
image: "registry.k8s.io/echoserver:1.10",
|
||||
ports: [
|
||||
{
|
||||
containerPort: 8080,
|
||||
name: "http",
|
||||
},
|
||||
],
|
||||
resources: {
|
||||
requests: {
|
||||
cpu: "50m",
|
||||
memory: "64Mi",
|
||||
},
|
||||
limits: {
|
||||
cpu: "250m",
|
||||
memory: "128Mi",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
ports: [
|
||||
{
|
||||
name: "http",
|
||||
port: 80,
|
||||
targetPort: 8080,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const podIdentityWorkload = yield* EKS.PodIdentityWorkload(
|
||||
"PodIdentityDemo",
|
||||
{
|
||||
cluster: cluster.cluster,
|
||||
namespace: demoNamespace,
|
||||
name: "pod-identity-demo",
|
||||
serviceAccountName: serviceAccount,
|
||||
tags,
|
||||
serviceAccountLabels: {
|
||||
"app.kubernetes.io/name": serviceAccount,
|
||||
"app.kubernetes.io/part-of": "aws-eks-example",
|
||||
},
|
||||
labels: {
|
||||
"app.kubernetes.io/name": "pod-identity-demo",
|
||||
"app.kubernetes.io/part-of": "aws-eks-example",
|
||||
},
|
||||
containers: [
|
||||
{
|
||||
name: "aws-cli",
|
||||
image: "public.ecr.aws/aws-cli/aws-cli:2.17.37",
|
||||
command: ["/bin/sh", "-lc"],
|
||||
args: [
|
||||
[
|
||||
"while true; do",
|
||||
" date;",
|
||||
" aws sts get-caller-identity;",
|
||||
" sleep 60;",
|
||||
"done",
|
||||
].join(" "),
|
||||
],
|
||||
resources: {
|
||||
requests: {
|
||||
cpu: "50m",
|
||||
memory: "64Mi",
|
||||
},
|
||||
limits: {
|
||||
cpu: "250m",
|
||||
memory: "128Mi",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
const clusterInfoJob = yield* Kubernetes.Job("ClusterInfoJob", {
|
||||
cluster: cluster.cluster,
|
||||
namespace: demoNamespace,
|
||||
name: "cluster-info",
|
||||
labels: {
|
||||
"app.kubernetes.io/name": "cluster-info",
|
||||
"app.kubernetes.io/part-of": "aws-eks-example",
|
||||
},
|
||||
containers: [
|
||||
{
|
||||
name: "cluster-info",
|
||||
image: "public.ecr.aws/docker/library/busybox:1.36",
|
||||
command: ["/bin/sh", "-lc"],
|
||||
args: [
|
||||
[
|
||||
'echo "demo workload is running on EKS Auto Mode";',
|
||||
"nslookup echo-server.demo.svc.cluster.local || true;",
|
||||
].join(" "),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return {
|
||||
clusterName: cluster.cluster.clusterName,
|
||||
clusterArn: cluster.cluster.clusterArn,
|
||||
endpoint: cluster.cluster.endpoint,
|
||||
adminPrincipalArn: clusterAdmin.principalArn,
|
||||
namespace: demoNamespace.name,
|
||||
serviceAccount: podIdentityWorkload.serviceAccount.name,
|
||||
podIdentityAssociationArn:
|
||||
podIdentityWorkload.podIdentityAssociation.associationArn,
|
||||
workloadRoleArn: podIdentityWorkload.roleArn,
|
||||
metricsServerAddonArn: metricsServer.addonArn,
|
||||
snapshotControllerAddonArn: snapshotController.addonArn,
|
||||
echoDeploymentName: echoServer.deployment.name,
|
||||
echoServiceName: echoServer.service?.name,
|
||||
podIdentityDeploymentName: podIdentityWorkload.deployment.name,
|
||||
clusterInfoJobName: clusterInfoJob.name,
|
||||
accessSummary: Output.interpolate`Granted cluster-admin access on ${cluster.cluster.clusterName} to ${clusterAdmin.principalArn}.`,
|
||||
workloadSummary: Output.interpolate`Demo workloads are declared in TypeScript and reconciled into namespace ${demoNamespace.name} on ${cluster.cluster.clusterName}.`,
|
||||
};
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "aws-eks-example",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-eks"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": "../..",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"target": "ESNext",
|
||||
"paths": {
|
||||
"alchemy": ["../../packages/alchemy/src/index.ts"],
|
||||
"alchemy/*": ["../../packages/alchemy/src/*"]
|
||||
}
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import JobFunction from "./src/JobFunction.ts";
|
||||
|
||||
const aws = AWS.providers();
|
||||
const dashboardRegion = process.env.AWS_REGION ?? "us-west-2";
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"JobLambdaHttpApi",
|
||||
{
|
||||
providers: Layer.mergeAll(
|
||||
// Fully configured cloud provider Layers go here:
|
||||
aws,
|
||||
),
|
||||
state: Alchemy.localState(),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const func = yield* JobFunction;
|
||||
const dashboard = yield* AWS.CloudWatch.Dashboard("JobDashboard", {
|
||||
DashboardBody: func.functionName.pipe(
|
||||
Output.map((functionName) => ({
|
||||
widgets: [
|
||||
{
|
||||
type: "metric",
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 12,
|
||||
height: 6,
|
||||
properties: {
|
||||
title: "Lambda Invocations and Errors",
|
||||
region: dashboardRegion,
|
||||
stat: "Sum",
|
||||
period: 300,
|
||||
metrics: [
|
||||
["AWS/Lambda", "Invocations", "FunctionName", functionName],
|
||||
["AWS/Lambda", "Errors", "FunctionName", functionName],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "metric",
|
||||
x: 12,
|
||||
y: 0,
|
||||
width: 12,
|
||||
height: 6,
|
||||
properties: {
|
||||
title: "Lambda Duration",
|
||||
region: dashboardRegion,
|
||||
stat: "Average",
|
||||
period: 300,
|
||||
metrics: [
|
||||
["AWS/Lambda", "Duration", "FunctionName", functionName],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
})),
|
||||
),
|
||||
});
|
||||
const alarm = yield* AWS.CloudWatch.Alarm("JobFunctionErrorsAlarm", {
|
||||
AlarmDescription:
|
||||
"Alerts when the example Lambda function reports errors.",
|
||||
MetricName: "Errors",
|
||||
Namespace: "AWS/Lambda",
|
||||
Statistic: "Sum",
|
||||
Period: 300,
|
||||
EvaluationPeriods: 1,
|
||||
Threshold: 1,
|
||||
ComparisonOperator: "GreaterThanOrEqualToThreshold",
|
||||
TreatMissingData: "notBreaching",
|
||||
Dimensions: [
|
||||
{
|
||||
Name: "FunctionName",
|
||||
Value: func.functionName,
|
||||
},
|
||||
],
|
||||
});
|
||||
return {
|
||||
url: Output.interpolate`${func.functionUrl}?jobId=foo`,
|
||||
dashboardName: dashboard.dashboardName,
|
||||
alarmName: alarm.alarmName,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "aws-lambda-httpapi",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-lambda-httpapi"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import * as S from "effect/Schema";
|
||||
|
||||
export type JobId = S.Schema.Type<typeof JobId>;
|
||||
export const JobId = S.String.annotate({
|
||||
description: "The ID of the job",
|
||||
});
|
||||
|
||||
export class Job extends S.Class<Job>("Job")({
|
||||
id: JobId,
|
||||
content: S.String,
|
||||
}) {}
|
||||
|
||||
export const decodeJob = S.decodeEffect(Job);
|
||||
@@ -0,0 +1,106 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import * as HttpApi from "effect/unstable/httpapi/HttpApi";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import * as HttpApiEndpoint from "effect/unstable/httpapi/HttpApiEndpoint";
|
||||
import * as HttpApiGroup from "effect/unstable/httpapi/HttpApiGroup";
|
||||
import { Job, JobId } from "./Job.ts";
|
||||
import { JobNotifications, NotifyJobError } from "./JobNotifications.ts";
|
||||
import { GetJobError, JobStorage, PutJobError } from "./JobStorage.ts";
|
||||
|
||||
export const getJob = HttpApiEndpoint.get("getJob", "/", {
|
||||
success: Job,
|
||||
query: {
|
||||
jobId: JobId.pipe(Schema.optional),
|
||||
},
|
||||
});
|
||||
|
||||
export const createJob = HttpApiEndpoint.post("createJob", "/", {
|
||||
success: JobId,
|
||||
payload: Schema.Struct({
|
||||
content: Schema.String,
|
||||
}),
|
||||
});
|
||||
|
||||
export const JobApi = HttpApi.make("JobApi").add(
|
||||
HttpApiGroup.make("Jobs").add(getJob, createJob),
|
||||
);
|
||||
|
||||
export const JobApiLive = HttpApiBuilder.layer(JobApi).pipe(
|
||||
Layer.provide(
|
||||
HttpApiBuilder.group(JobApi, "Jobs", (handlers) =>
|
||||
Effect.gen(function* () {
|
||||
const jobService = yield* JobStorage;
|
||||
const notifications = yield* JobNotifications;
|
||||
|
||||
return handlers
|
||||
.handle(
|
||||
"getJob",
|
||||
Effect.fn(function* (req) {
|
||||
if (!req.query.jobId) {
|
||||
return HttpServerResponse.text("Job ID is required", {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
const job = yield* jobService.getJob(req.query.jobId).pipe(
|
||||
Effect.catchTag("GetJobError", (error) =>
|
||||
Effect.succeed(
|
||||
HttpServerResponse.text(error.message, {
|
||||
status: 500,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (job instanceof GetJobError) {
|
||||
return HttpServerResponse.text(job.message, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
if (!job) {
|
||||
return HttpServerResponse.text("Job not found", {
|
||||
status: 404,
|
||||
});
|
||||
}
|
||||
return job!;
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"createJob",
|
||||
Effect.fn(function* (req) {
|
||||
const jobId = crypto.randomUUID();
|
||||
const job = yield* jobService
|
||||
.putJob({
|
||||
id: jobId,
|
||||
content: req.payload.content,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchTag("PutJobError", (error) =>
|
||||
Effect.succeed(error),
|
||||
),
|
||||
);
|
||||
if (job instanceof PutJobError) {
|
||||
return HttpServerResponse.text(job.message, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
const notificationResult = yield* notifications
|
||||
.notifyJobCreated(job)
|
||||
.pipe(
|
||||
Effect.catchTag("NotifyJobError", (error) =>
|
||||
Effect.succeed(error),
|
||||
),
|
||||
);
|
||||
if (notificationResult instanceof NotifyJobError) {
|
||||
return HttpServerResponse.text(notificationResult.message, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
return job.id;
|
||||
}),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,29 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Etag from "effect/unstable/http/Etag";
|
||||
import * as HttpPlatform from "effect/unstable/http/HttpPlatform";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import { JobApiLive } from "./JobApi.ts";
|
||||
import { JobNotificationsSNS } from "./JobNotifications.ts";
|
||||
import { JobStorageDynamoDB } from "./JobStorage.ts";
|
||||
|
||||
export default class JobFunction extends AWS.Lambda.Function<JobFunction>()(
|
||||
"JobFunction",
|
||||
{
|
||||
main: import.meta.filename,
|
||||
url: true,
|
||||
},
|
||||
HttpRouter.toHttpEffect(JobApiLive).pipe(
|
||||
Effect.map((fetch) => ({ fetch })),
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
JobStorageDynamoDB,
|
||||
JobNotificationsSNS,
|
||||
// TODO(sam): these should be provided to us automatically
|
||||
HttpPlatform.layer,
|
||||
Etag.layer,
|
||||
),
|
||||
),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { Job } from "./Job.ts";
|
||||
|
||||
export class NotifyJobError extends Data.TaggedError("NotifyJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
type JobNotification = {
|
||||
type: "job.created";
|
||||
job: Job;
|
||||
};
|
||||
|
||||
export class JobNotifications extends Context.Service<
|
||||
JobNotifications,
|
||||
{
|
||||
notifyJobCreated(job: Job): Effect.Effect<void, NotifyJobError>;
|
||||
}
|
||||
>()("JobNotifications") {}
|
||||
|
||||
export const JobNotificationsSNS = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobNotifications,
|
||||
Effect.gen(function* () {
|
||||
const topic = yield* AWS.SNS.Topic("JobNotificationsTopic", {
|
||||
attributes: {
|
||||
DisplayName: "job-notifications",
|
||||
},
|
||||
});
|
||||
|
||||
const publish = yield* AWS.SNS.Publish.bind(topic);
|
||||
|
||||
yield* AWS.SNS.notifications(topic).subscribe((stream) =>
|
||||
stream.pipe(
|
||||
Stream.mapEffect((notification) =>
|
||||
Effect.try({
|
||||
try: () => JSON.parse(notification.Message) as JobNotification,
|
||||
catch: (cause) =>
|
||||
new NotifyJobError({
|
||||
message: "Failed to parse SNS job notification",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((payload) =>
|
||||
Effect.logInfo(
|
||||
`Job notification received: ${payload.type} (${payload.job.id})`,
|
||||
),
|
||||
),
|
||||
// Keep the example resilient to malformed demo messages.
|
||||
Effect.catchTag("NotifyJobError", (error) =>
|
||||
Effect.logWarning(error.message),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.runDrain,
|
||||
),
|
||||
);
|
||||
|
||||
const notifyJobCreated = (job: Job) =>
|
||||
publish({
|
||||
Subject: "JobCreated",
|
||||
Message: JSON.stringify({
|
||||
type: "job.created",
|
||||
job,
|
||||
} satisfies JobNotification),
|
||||
}).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NotifyJobError({
|
||||
message: `Failed to publish job notification for "${job.id}"`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return JobNotifications.of({
|
||||
notifyJobCreated,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(AWS.Lambda.TopicEventSource, AWS.SNS.PublishLive),
|
||||
);
|
||||
@@ -0,0 +1,230 @@
|
||||
import * as DynamoDB from "alchemy/AWS/DynamoDB";
|
||||
import * as Lambda from "alchemy/AWS/Lambda";
|
||||
import * as S3 from "alchemy/AWS/S3";
|
||||
import * as SQS from "alchemy/AWS/SQS";
|
||||
import * as RemovalPolicy from "alchemy/RemovalPolicy";
|
||||
import { Stack } from "alchemy/Stack";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { Job } from "./Job.ts";
|
||||
|
||||
export class PutJobError extends Data.TaggedError("PutJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class GetJobError extends Data.TaggedError("GetJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class JobStorage extends Context.Service<
|
||||
JobStorage,
|
||||
{
|
||||
putJob(job: Job): Effect.Effect<Job, PutJobError>;
|
||||
getJob(jobId: string): Effect.Effect<Job | undefined, GetJobError>;
|
||||
}
|
||||
>()("JobStorage") {}
|
||||
|
||||
export const JobStorageDynamoDB = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobStorage,
|
||||
Effect.gen(function* () {
|
||||
const stack = yield* Stack;
|
||||
const table = yield* DynamoDB.Table("JobsTable", {
|
||||
partitionKey: "id",
|
||||
attributes: {
|
||||
id: "S",
|
||||
},
|
||||
});
|
||||
const queue = yield* SQS.Queue("JobsQueue").pipe(
|
||||
RemovalPolicy.retain(stack.stage === "prod"),
|
||||
);
|
||||
|
||||
const getItem = yield* DynamoDB.GetItem.bind(table);
|
||||
const putItem = yield* DynamoDB.PutItem.bind(table);
|
||||
const sink = yield* SQS.QueueSink.bind(queue);
|
||||
|
||||
yield* DynamoDB.stream(table, {
|
||||
streamViewType: "NEW_AND_OLD_IMAGES",
|
||||
startingPosition: "LATEST",
|
||||
batchSize: 10,
|
||||
}).process((stream) =>
|
||||
stream.pipe(
|
||||
Stream.map((record) =>
|
||||
JSON.stringify({
|
||||
eventName: record.eventName,
|
||||
keys: record.dynamodb.Keys,
|
||||
newImage: record.dynamodb.NewImage,
|
||||
oldImage: record.dynamodb.OldImage,
|
||||
}),
|
||||
),
|
||||
Stream.run(sink),
|
||||
),
|
||||
);
|
||||
|
||||
const putJob = (job: Job) =>
|
||||
putItem({
|
||||
Item: {
|
||||
id: { S: job.id },
|
||||
content: { S: job.content },
|
||||
},
|
||||
}).pipe(
|
||||
Effect.map(() => job),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new PutJobError({
|
||||
message: `Failed to store job "${job.id}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getJob = (jobId: string) =>
|
||||
getItem({
|
||||
Key: {
|
||||
id: { S: jobId },
|
||||
},
|
||||
}).pipe(
|
||||
Effect.flatMap((item) =>
|
||||
item.Item
|
||||
? Effect.try({
|
||||
try: () =>
|
||||
({
|
||||
id: item.Item?.id?.S ?? jobId,
|
||||
content: item.Item?.content?.S ?? "",
|
||||
}) as Job,
|
||||
catch: (cause) =>
|
||||
new GetJobError({
|
||||
message: `Failed to parse job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
: Effect.succeed(undefined),
|
||||
),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new GetJobError({
|
||||
message: `Failed to load job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return JobStorage.of({
|
||||
putJob,
|
||||
getJob,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(Lambda.TableEventSource, SQS.QueueSinkLive).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
DynamoDB.GetItemLive,
|
||||
DynamoDB.PutItemLive,
|
||||
SQS.SendMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const JobStorageS3 = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobStorage,
|
||||
Effect.gen(function* () {
|
||||
const stack = yield* Stack;
|
||||
const bucket = yield* S3.Bucket("JobsBucket");
|
||||
const queue = yield* SQS.Queue("JobsQueue").pipe(
|
||||
RemovalPolicy.retain(stack.stage === "prod"),
|
||||
);
|
||||
|
||||
const getObject = yield* S3.GetObject.bind(bucket);
|
||||
const putObject = yield* S3.PutObject.bind(bucket);
|
||||
const sink = yield* SQS.QueueSink.bind(queue);
|
||||
|
||||
const putJob = (job: Job) =>
|
||||
putObject({
|
||||
Key: job.id,
|
||||
Body: JSON.stringify(job),
|
||||
}).pipe(
|
||||
Effect.map(() => job),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new PutJobError({
|
||||
message: `Failed to store job "${job.id}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getJob = (jobId: string) =>
|
||||
getObject({
|
||||
Key: jobId,
|
||||
}).pipe(
|
||||
Effect.catchTag("NoSuchKey", () => Effect.succeed(undefined)),
|
||||
Effect.flatMap(
|
||||
(item) =>
|
||||
item?.Body?.pipe(
|
||||
Stream.decodeText,
|
||||
Stream.mkString,
|
||||
Effect.flatMap((body) =>
|
||||
Effect.try({
|
||||
try: () => JSON.parse(body) as Job,
|
||||
catch: (cause) =>
|
||||
new GetJobError({
|
||||
message: `Failed to parse job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
) ?? Effect.succeed(undefined),
|
||||
),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new GetJobError({
|
||||
message: `Failed to load job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* S3.notifications(bucket).subscribe((stream) =>
|
||||
stream.pipe(
|
||||
Stream.flatMap((item) =>
|
||||
Stream.fromEffect(getJob(item.key).pipe(Effect.orDie)),
|
||||
),
|
||||
Stream.filter((job): job is Job => job !== undefined),
|
||||
Stream.map((job) => JSON.stringify(job)),
|
||||
Stream.run(sink),
|
||||
),
|
||||
);
|
||||
|
||||
return JobStorage.of({
|
||||
putJob,
|
||||
getJob,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(Lambda.BucketEventSource, SQS.QueueSinkLive).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
S3.GetObjectLive,
|
||||
S3.PutObjectLive,
|
||||
SQS.SendMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts", "src/**/*.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"target": "ESNext"
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import JobFunction from "./src/JobFunction.ts";
|
||||
|
||||
const aws = AWS.providers();
|
||||
const dashboardRegion = process.env.AWS_REGION ?? "us-west-2";
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"JobLambdaRpc",
|
||||
{
|
||||
providers: Layer.mergeAll(
|
||||
// Fully configured cloud provider Layers go here:
|
||||
aws,
|
||||
),
|
||||
state: Alchemy.localState(),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const func = yield* JobFunction;
|
||||
const dashboard = yield* AWS.CloudWatch.Dashboard("JobDashboard", {
|
||||
DashboardBody: func.functionName.pipe(
|
||||
Output.map((functionName) => ({
|
||||
widgets: [
|
||||
{
|
||||
type: "metric",
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 12,
|
||||
height: 6,
|
||||
properties: {
|
||||
title: "Lambda Invocations and Errors",
|
||||
region: dashboardRegion,
|
||||
stat: "Sum",
|
||||
period: 300,
|
||||
metrics: [
|
||||
["AWS/Lambda", "Invocations", "FunctionName", functionName],
|
||||
["AWS/Lambda", "Errors", "FunctionName", functionName],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "metric",
|
||||
x: 12,
|
||||
y: 0,
|
||||
width: 12,
|
||||
height: 6,
|
||||
properties: {
|
||||
title: "Lambda Duration",
|
||||
region: dashboardRegion,
|
||||
stat: "Average",
|
||||
period: 300,
|
||||
metrics: [
|
||||
["AWS/Lambda", "Duration", "FunctionName", functionName],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
})),
|
||||
),
|
||||
});
|
||||
const alarm = yield* AWS.CloudWatch.Alarm("JobFunctionErrorsAlarm", {
|
||||
AlarmDescription:
|
||||
"Alerts when the example Lambda function reports errors.",
|
||||
MetricName: "Errors",
|
||||
Namespace: "AWS/Lambda",
|
||||
Statistic: "Sum",
|
||||
Period: 300,
|
||||
EvaluationPeriods: 1,
|
||||
Threshold: 1,
|
||||
ComparisonOperator: "GreaterThanOrEqualToThreshold",
|
||||
TreatMissingData: "notBreaching",
|
||||
Dimensions: [
|
||||
{
|
||||
Name: "FunctionName",
|
||||
Value: func.functionName,
|
||||
},
|
||||
],
|
||||
});
|
||||
return {
|
||||
url: func.functionUrl,
|
||||
dashboardName: dashboard.dashboardName,
|
||||
alarmName: alarm.alarmName,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "aws-lambda-rpc",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-lambda-rpc"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import * as S from "effect/Schema";
|
||||
|
||||
export type JobId = S.Schema.Type<typeof JobId>;
|
||||
export const JobId = S.String.annotate({
|
||||
description: "The ID of the job",
|
||||
});
|
||||
|
||||
export class Job extends S.Class<Job>("Job")({
|
||||
id: JobId,
|
||||
content: S.String,
|
||||
}) {}
|
||||
|
||||
export const decodeJob = S.decodeEffect(Job);
|
||||
@@ -0,0 +1,18 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { JobNotificationsSNS } from "./JobNotifications.ts";
|
||||
import { JobRpcHttpEffect } from "./JobRpcApi.ts";
|
||||
import { JobStorageDynamoDB } from "./JobStorage.ts";
|
||||
|
||||
export default class JobFunction extends AWS.Lambda.Function<JobFunction>()(
|
||||
"JobFunction",
|
||||
{
|
||||
main: import.meta.filename,
|
||||
url: true,
|
||||
},
|
||||
JobRpcHttpEffect.pipe(
|
||||
Effect.map((fetch) => ({ fetch })),
|
||||
Effect.provide(Layer.mergeAll(JobStorageDynamoDB, JobNotificationsSNS)),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { Job } from "./Job.ts";
|
||||
|
||||
export class NotifyJobError extends Data.TaggedError("NotifyJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
type JobNotification = {
|
||||
type: "job.created";
|
||||
job: Job;
|
||||
};
|
||||
|
||||
export class JobNotifications extends Context.Service<
|
||||
JobNotifications,
|
||||
{
|
||||
notifyJobCreated(job: Job): Effect.Effect<void, NotifyJobError>;
|
||||
}
|
||||
>()("JobNotifications") {}
|
||||
|
||||
export const JobNotificationsSNS = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobNotifications,
|
||||
Effect.gen(function* () {
|
||||
const topic = yield* AWS.SNS.Topic("JobNotificationsTopic", {
|
||||
attributes: {
|
||||
DisplayName: "job-notifications",
|
||||
},
|
||||
});
|
||||
|
||||
const publish = yield* AWS.SNS.Publish.bind(topic);
|
||||
|
||||
yield* AWS.SNS.notifications(topic).subscribe((stream) =>
|
||||
stream.pipe(
|
||||
Stream.mapEffect((notification) =>
|
||||
Effect.try({
|
||||
try: () => JSON.parse(notification.Message) as JobNotification,
|
||||
catch: (cause) =>
|
||||
new NotifyJobError({
|
||||
message: "Failed to parse SNS job notification",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((payload) =>
|
||||
Effect.logInfo(
|
||||
`Job notification received: ${payload.type} (${payload.job.id})`,
|
||||
),
|
||||
),
|
||||
// Keep the example resilient to malformed demo messages.
|
||||
Effect.catchTag("NotifyJobError", (error) =>
|
||||
Effect.logWarning(error.message),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.runDrain,
|
||||
),
|
||||
);
|
||||
|
||||
const notifyJobCreated = (job: Job) =>
|
||||
publish({
|
||||
Subject: "JobCreated",
|
||||
Message: JSON.stringify({
|
||||
type: "job.created",
|
||||
job,
|
||||
} satisfies JobNotification),
|
||||
}).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NotifyJobError({
|
||||
message: `Failed to publish job notification for "${job.id}"`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return JobNotifications.of({
|
||||
notifyJobCreated,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(AWS.Lambda.TopicEventSource, AWS.SNS.PublishLive),
|
||||
);
|
||||
@@ -0,0 +1,86 @@
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import {
|
||||
Rpc,
|
||||
RpcGroup,
|
||||
RpcSerialization,
|
||||
RpcServer,
|
||||
} from "effect/unstable/rpc";
|
||||
import { Job, JobId } from "./Job.ts";
|
||||
import { JobNotifications } from "./JobNotifications.ts";
|
||||
import { JobStorage } from "./JobStorage.ts";
|
||||
|
||||
export class JobNotFound extends Schema.TaggedClass<JobNotFound>()(
|
||||
"JobNotFound",
|
||||
{ jobId: JobId },
|
||||
) {}
|
||||
|
||||
export class GetJobFailed extends Schema.TaggedClass<GetJobFailed>()(
|
||||
"GetJobFailed",
|
||||
{ message: Schema.String },
|
||||
) {}
|
||||
|
||||
export class PutJobFailed extends Schema.TaggedClass<PutJobFailed>()(
|
||||
"PutJobFailed",
|
||||
{ message: Schema.String },
|
||||
) {}
|
||||
|
||||
const getJob = Rpc.make("getJob", {
|
||||
success: Job,
|
||||
error: Schema.Union([JobNotFound, GetJobFailed]),
|
||||
payload: {
|
||||
jobId: JobId,
|
||||
},
|
||||
});
|
||||
|
||||
const createJob = Rpc.make("createJob", {
|
||||
success: JobId,
|
||||
error: PutJobFailed,
|
||||
payload: {
|
||||
content: Schema.String,
|
||||
},
|
||||
});
|
||||
|
||||
export class JobRpcs extends RpcGroup.make(getJob, createJob) {}
|
||||
|
||||
export const JobRpcsLive = JobRpcs.toLayer(
|
||||
Effect.gen(function* () {
|
||||
const jobService = yield* JobStorage;
|
||||
const notifications = yield* JobNotifications;
|
||||
|
||||
return {
|
||||
getJob: ({ jobId }) =>
|
||||
jobService.getJob(jobId).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new GetJobFailed({
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((job) =>
|
||||
job ? Effect.succeed(job) : Effect.fail(new JobNotFound({ jobId })),
|
||||
),
|
||||
),
|
||||
createJob: ({ content }) =>
|
||||
Effect.gen(function* () {
|
||||
const jobId = crypto.randomUUID();
|
||||
const job = yield* jobService.putJob({
|
||||
id: jobId,
|
||||
content,
|
||||
});
|
||||
yield* notifications.notifyJobCreated(job);
|
||||
return job.id;
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new PutJobFailed({
|
||||
message: error.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
export const JobRpcHttpEffect = RpcServer.toHttpEffect(JobRpcs).pipe(
|
||||
Effect.provide(Layer.mergeAll(JobRpcsLive, RpcSerialization.layerJson)),
|
||||
);
|
||||
@@ -0,0 +1,230 @@
|
||||
import * as DynamoDB from "alchemy/AWS/DynamoDB";
|
||||
import * as Lambda from "alchemy/AWS/Lambda";
|
||||
import * as S3 from "alchemy/AWS/S3";
|
||||
import * as SQS from "alchemy/AWS/SQS";
|
||||
import * as RemovalPolicy from "alchemy/RemovalPolicy";
|
||||
import { Stack } from "alchemy/Stack";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { Job } from "./Job.ts";
|
||||
|
||||
export class PutJobError extends Data.TaggedError("PutJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class GetJobError extends Data.TaggedError("GetJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class JobStorage extends Context.Service<
|
||||
JobStorage,
|
||||
{
|
||||
putJob(job: Job): Effect.Effect<Job, PutJobError>;
|
||||
getJob(jobId: string): Effect.Effect<Job | undefined, GetJobError>;
|
||||
}
|
||||
>()("JobStorage") {}
|
||||
|
||||
export const JobStorageDynamoDB = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobStorage,
|
||||
Effect.gen(function* () {
|
||||
const stack = yield* Stack;
|
||||
const table = yield* DynamoDB.Table("JobsTable", {
|
||||
partitionKey: "id",
|
||||
attributes: {
|
||||
id: "S",
|
||||
},
|
||||
});
|
||||
const queue = yield* SQS.Queue("JobsQueue").pipe(
|
||||
RemovalPolicy.retain(stack.stage === "prod"),
|
||||
);
|
||||
|
||||
const getItem = yield* DynamoDB.GetItem.bind(table);
|
||||
const putItem = yield* DynamoDB.PutItem.bind(table);
|
||||
const sink = yield* SQS.QueueSink.bind(queue);
|
||||
|
||||
yield* DynamoDB.stream(table, {
|
||||
streamViewType: "NEW_AND_OLD_IMAGES",
|
||||
startingPosition: "LATEST",
|
||||
batchSize: 10,
|
||||
}).process((stream) =>
|
||||
stream.pipe(
|
||||
Stream.map((record) =>
|
||||
JSON.stringify({
|
||||
eventName: record.eventName,
|
||||
keys: record.dynamodb.Keys,
|
||||
newImage: record.dynamodb.NewImage,
|
||||
oldImage: record.dynamodb.OldImage,
|
||||
}),
|
||||
),
|
||||
Stream.run(sink),
|
||||
),
|
||||
);
|
||||
|
||||
const putJob = (job: Job) =>
|
||||
putItem({
|
||||
Item: {
|
||||
id: { S: job.id },
|
||||
content: { S: job.content },
|
||||
},
|
||||
}).pipe(
|
||||
Effect.map(() => job),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new PutJobError({
|
||||
message: `Failed to store job "${job.id}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getJob = (jobId: string) =>
|
||||
getItem({
|
||||
Key: {
|
||||
id: { S: jobId },
|
||||
},
|
||||
}).pipe(
|
||||
Effect.flatMap((item) =>
|
||||
item.Item
|
||||
? Effect.try({
|
||||
try: () =>
|
||||
({
|
||||
id: item.Item?.id?.S ?? jobId,
|
||||
content: item.Item?.content?.S ?? "",
|
||||
}) as Job,
|
||||
catch: (cause) =>
|
||||
new GetJobError({
|
||||
message: `Failed to parse job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
: Effect.succeed(undefined),
|
||||
),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new GetJobError({
|
||||
message: `Failed to load job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return JobStorage.of({
|
||||
putJob,
|
||||
getJob,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(Lambda.TableEventSource, SQS.QueueSinkLive).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
DynamoDB.GetItemLive,
|
||||
DynamoDB.PutItemLive,
|
||||
SQS.SendMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const JobStorageS3 = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobStorage,
|
||||
Effect.gen(function* () {
|
||||
const stack = yield* Stack;
|
||||
const bucket = yield* S3.Bucket("JobsBucket");
|
||||
const queue = yield* SQS.Queue("JobsQueue").pipe(
|
||||
RemovalPolicy.retain(stack.stage === "prod"),
|
||||
);
|
||||
|
||||
const getObject = yield* S3.GetObject.bind(bucket);
|
||||
const putObject = yield* S3.PutObject.bind(bucket);
|
||||
const sink = yield* SQS.QueueSink.bind(queue);
|
||||
|
||||
const putJob = (job: Job) =>
|
||||
putObject({
|
||||
Key: job.id,
|
||||
Body: JSON.stringify(job),
|
||||
}).pipe(
|
||||
Effect.map(() => job),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new PutJobError({
|
||||
message: `Failed to store job "${job.id}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getJob = (jobId: string) =>
|
||||
getObject({
|
||||
Key: jobId,
|
||||
}).pipe(
|
||||
Effect.catchTag("NoSuchKey", () => Effect.succeed(undefined)),
|
||||
Effect.flatMap(
|
||||
(item) =>
|
||||
item?.Body?.pipe(
|
||||
Stream.decodeText,
|
||||
Stream.mkString,
|
||||
Effect.flatMap((body) =>
|
||||
Effect.try({
|
||||
try: () => JSON.parse(body) as Job,
|
||||
catch: (cause) =>
|
||||
new GetJobError({
|
||||
message: `Failed to parse job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
) ?? Effect.succeed(undefined),
|
||||
),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new GetJobError({
|
||||
message: `Failed to load job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* S3.notifications(bucket).subscribe((stream) =>
|
||||
stream.pipe(
|
||||
Stream.flatMap((item) =>
|
||||
Stream.fromEffect(getJob(item.key).pipe(Effect.orDie)),
|
||||
),
|
||||
Stream.filter((job): job is Job => job !== undefined),
|
||||
Stream.map((job) => JSON.stringify(job)),
|
||||
Stream.run(sink),
|
||||
),
|
||||
);
|
||||
|
||||
return JobStorage.of({
|
||||
putJob,
|
||||
getJob,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(Lambda.BucketEventSource, SQS.QueueSinkLive).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
S3.GetObjectLive,
|
||||
S3.PutObjectLive,
|
||||
SQS.SendMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts", "src/**/*.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"target": "ESNext"
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
import JobFunction from "./src/JobFunction.ts";
|
||||
|
||||
// AWS.providers() already provides AWSEnvironment from the SSO profile
|
||||
// named by $AWS_PROFILE (defaults to "default"). To pin a different
|
||||
// profile per stage, wrap with `Layer.provide(AWS.makeEnvironment({...}))`.
|
||||
const aws = AWS.providers();
|
||||
const dashboardRegion = process.env.AWS_REGION ?? "us-west-2";
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"JobLambda",
|
||||
{
|
||||
providers: aws,
|
||||
state: Alchemy.localState(),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const func = yield* JobFunction;
|
||||
const dashboard = yield* AWS.CloudWatch.Dashboard("JobDashboard", {
|
||||
DashboardBody: func.functionName.pipe(
|
||||
Output.map((functionName) => ({
|
||||
widgets: [
|
||||
{
|
||||
type: "metric",
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 12,
|
||||
height: 6,
|
||||
properties: {
|
||||
title: "Lambda Invocations and Errors",
|
||||
region: dashboardRegion,
|
||||
stat: "Sum",
|
||||
period: 300,
|
||||
metrics: [
|
||||
["AWS/Lambda", "Invocations", "FunctionName", functionName],
|
||||
["AWS/Lambda", "Errors", "FunctionName", functionName],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "metric",
|
||||
x: 12,
|
||||
y: 0,
|
||||
width: 12,
|
||||
height: 6,
|
||||
properties: {
|
||||
title: "Lambda Duration",
|
||||
region: dashboardRegion,
|
||||
stat: "Average",
|
||||
period: 300,
|
||||
metrics: [
|
||||
["AWS/Lambda", "Duration", "FunctionName", functionName],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
})),
|
||||
),
|
||||
});
|
||||
const alarm = yield* AWS.CloudWatch.Alarm("JobFunctionErrorsAlarm", {
|
||||
AlarmDescription:
|
||||
"Alerts when the example Lambda function reports errors.",
|
||||
MetricName: "Errors",
|
||||
Namespace: "AWS/Lambda",
|
||||
Statistic: "Sum",
|
||||
Period: 300,
|
||||
EvaluationPeriods: 1,
|
||||
Threshold: 1,
|
||||
ComparisonOperator: "GreaterThanOrEqualToThreshold",
|
||||
TreatMissingData: "notBreaching",
|
||||
Dimensions: [
|
||||
{
|
||||
Name: "FunctionName",
|
||||
Value: func.functionName,
|
||||
},
|
||||
],
|
||||
});
|
||||
return {
|
||||
url: Output.interpolate`${func.functionUrl}?jobId=foo`,
|
||||
dashboardName: dashboard.dashboardName,
|
||||
alarmName: alarm.alarmName,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "aws-lambda",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-lambda"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy",
|
||||
"test": "bun test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import * as S from "effect/Schema";
|
||||
|
||||
export type JobId = S.Schema.Type<typeof JobId>;
|
||||
export const JobId = S.String.annotate({
|
||||
description: "The ID of the job",
|
||||
});
|
||||
|
||||
export class Job extends S.Class<Job>("Job")({
|
||||
id: JobId,
|
||||
content: S.String,
|
||||
}) {}
|
||||
|
||||
export const decodeJob = S.decodeEffect(Job);
|
||||
@@ -0,0 +1,119 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import { Stack } from "alchemy/Stack";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HttpServerRequest } from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import {
|
||||
JobNotifications,
|
||||
JobNotificationsSNS,
|
||||
NotifyJobError,
|
||||
} from "./JobNotifications.ts";
|
||||
import {
|
||||
GetJobError,
|
||||
JobStorage,
|
||||
JobStorageDynamoDB,
|
||||
PutJobError,
|
||||
} from "./JobStorage.ts";
|
||||
|
||||
export default class JobFunction extends AWS.Lambda.Function<JobFunction>()(
|
||||
"JobFunction",
|
||||
Stack.useSync((stack) => ({
|
||||
main: import.meta.filename,
|
||||
memory: stack.stage === "prod" ? 1024 : 512,
|
||||
url: true,
|
||||
})),
|
||||
Effect.gen(function* () {
|
||||
const jobStorage = yield* JobStorage;
|
||||
const notifications = yield* JobNotifications;
|
||||
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest;
|
||||
const url = new URL(request.originalUrl);
|
||||
|
||||
if (request.method === "GET" && url.pathname === "/") {
|
||||
const jobId = url.searchParams.get("jobId");
|
||||
if (!jobId) {
|
||||
return HttpServerResponse.text("Job ID is required", {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
const job = yield* jobStorage.getJob(jobId).pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => error,
|
||||
onSuccess: (job) => job,
|
||||
}),
|
||||
);
|
||||
|
||||
if (job instanceof GetJobError) {
|
||||
return HttpServerResponse.text(job.message, { status: 500 });
|
||||
}
|
||||
|
||||
if (!job) {
|
||||
return HttpServerResponse.text("Job not found", { status: 404 });
|
||||
}
|
||||
|
||||
return yield* HttpServerResponse.json(job);
|
||||
}
|
||||
|
||||
if (request.method === "POST" && url.pathname === "/") {
|
||||
const content = yield* request.text;
|
||||
if (!content) {
|
||||
return HttpServerResponse.text("Job content is required", {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
const job = yield* jobStorage
|
||||
.putJob({
|
||||
id: crypto.randomUUID(),
|
||||
content,
|
||||
})
|
||||
.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => error,
|
||||
onSuccess: (job) => job,
|
||||
}),
|
||||
);
|
||||
|
||||
if (job instanceof PutJobError) {
|
||||
return HttpServerResponse.text(job.message, { status: 500 });
|
||||
}
|
||||
|
||||
const notificationResult = yield* notifications
|
||||
.notifyJobCreated(job)
|
||||
.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => error,
|
||||
onSuccess: () => undefined,
|
||||
}),
|
||||
);
|
||||
|
||||
if (notificationResult instanceof NotifyJobError) {
|
||||
return HttpServerResponse.text(notificationResult.message, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
|
||||
return yield* HttpServerResponse.json(
|
||||
{ jobId: job.id },
|
||||
{ status: 201 },
|
||||
);
|
||||
}
|
||||
|
||||
return HttpServerResponse.text("Not found", { status: 404 });
|
||||
}),
|
||||
};
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
// Services go here
|
||||
JobStorageDynamoDB,
|
||||
JobNotificationsSNS,
|
||||
// JobStorageS3,
|
||||
),
|
||||
),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,90 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { Job } from "./Job.ts";
|
||||
|
||||
export class NotifyJobError extends Data.TaggedError("NotifyJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
type JobNotification = {
|
||||
type: "job.created";
|
||||
job: Job;
|
||||
};
|
||||
|
||||
export class JobNotifications extends Context.Service<
|
||||
JobNotifications,
|
||||
{
|
||||
notifyJobCreated(job: Job): Effect.Effect<void, NotifyJobError>;
|
||||
}
|
||||
>()("JobNotifications") {}
|
||||
|
||||
export const JobNotificationsSNS = Layer.effect(
|
||||
JobNotifications,
|
||||
Effect.gen(function* () {
|
||||
const topic = yield* AWS.SNS.Topic("JobNotificationsTopic", {
|
||||
attributes: {
|
||||
DisplayName: "job-notifications",
|
||||
},
|
||||
});
|
||||
|
||||
const publish = yield* AWS.SNS.Publish.bind(topic);
|
||||
|
||||
yield* AWS.SNS.notifications(topic).subscribe((stream) =>
|
||||
stream.pipe(
|
||||
Stream.mapEffect((notification) =>
|
||||
Effect.try({
|
||||
try: () => JSON.parse(notification.Message) as JobNotification,
|
||||
catch: (cause) =>
|
||||
new NotifyJobError({
|
||||
message: "Failed to parse SNS job notification",
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((payload) =>
|
||||
Effect.logInfo(
|
||||
`Job notification received: ${payload.type} (${payload.job.id})`,
|
||||
),
|
||||
),
|
||||
// Keep the example resilient to malformed demo messages.
|
||||
Effect.catchTag("NotifyJobError", (error) =>
|
||||
Effect.logWarning(error.message),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.runDrain,
|
||||
),
|
||||
);
|
||||
|
||||
const notifyJobCreated = (job: Job) =>
|
||||
publish({
|
||||
Subject: "JobCreated",
|
||||
Message: JSON.stringify({
|
||||
type: "job.created",
|
||||
job,
|
||||
} satisfies JobNotification),
|
||||
}).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new NotifyJobError({
|
||||
message: `Failed to publish job notification for "${job.id}"`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return JobNotifications.of({
|
||||
notifyJobCreated,
|
||||
});
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(AWS.Lambda.TopicEventSource, AWS.SNS.PublishLive),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,230 @@
|
||||
import * as DynamoDB from "alchemy/AWS/DynamoDB";
|
||||
import * as Lambda from "alchemy/AWS/Lambda";
|
||||
import * as S3 from "alchemy/AWS/S3";
|
||||
import * as SQS from "alchemy/AWS/SQS";
|
||||
import * as RemovalPolicy from "alchemy/RemovalPolicy";
|
||||
import { Stack } from "alchemy/Stack";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { Job } from "./Job.ts";
|
||||
|
||||
export class PutJobError extends Data.TaggedError("PutJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class GetJobError extends Data.TaggedError("GetJobError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class JobStorage extends Context.Service<
|
||||
JobStorage,
|
||||
{
|
||||
putJob(job: Job): Effect.Effect<Job, PutJobError>;
|
||||
getJob(jobId: string): Effect.Effect<Job | undefined, GetJobError>;
|
||||
}
|
||||
>()("JobStorage") {}
|
||||
|
||||
export const JobStorageDynamoDB = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobStorage,
|
||||
Effect.gen(function* () {
|
||||
const stack = yield* Stack;
|
||||
const table = yield* DynamoDB.Table("JobsTable", {
|
||||
partitionKey: "id",
|
||||
attributes: {
|
||||
id: "S",
|
||||
},
|
||||
});
|
||||
const queue = yield* SQS.Queue("JobsQueue").pipe(
|
||||
RemovalPolicy.retain(stack.stage === "prod"),
|
||||
);
|
||||
|
||||
const getItem = yield* DynamoDB.GetItem.bind(table);
|
||||
const putItem = yield* DynamoDB.PutItem.bind(table);
|
||||
const sink = yield* SQS.QueueSink.bind(queue);
|
||||
|
||||
yield* DynamoDB.stream(table, {
|
||||
streamViewType: "NEW_AND_OLD_IMAGES",
|
||||
startingPosition: "LATEST",
|
||||
batchSize: 10,
|
||||
}).process((stream) =>
|
||||
stream.pipe(
|
||||
Stream.map((record) =>
|
||||
JSON.stringify({
|
||||
eventName: record.eventName,
|
||||
keys: record.dynamodb.Keys,
|
||||
newImage: record.dynamodb.NewImage,
|
||||
oldImage: record.dynamodb.OldImage,
|
||||
}),
|
||||
),
|
||||
Stream.run(sink),
|
||||
),
|
||||
);
|
||||
|
||||
const putJob = (job: Job) =>
|
||||
putItem({
|
||||
Item: {
|
||||
id: { S: job.id },
|
||||
content: { S: job.content },
|
||||
},
|
||||
}).pipe(
|
||||
Effect.map(() => job),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new PutJobError({
|
||||
message: `Failed to store job "${job.id}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getJob = (jobId: string) =>
|
||||
getItem({
|
||||
Key: {
|
||||
id: { S: jobId },
|
||||
},
|
||||
}).pipe(
|
||||
Effect.flatMap((item) =>
|
||||
item.Item
|
||||
? Effect.try({
|
||||
try: () =>
|
||||
({
|
||||
id: item.Item?.id?.S ?? jobId,
|
||||
content: item.Item?.content?.S ?? "",
|
||||
}) as Job,
|
||||
catch: (cause) =>
|
||||
new GetJobError({
|
||||
message: `Failed to parse job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
: Effect.succeed(undefined),
|
||||
),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new GetJobError({
|
||||
message: `Failed to load job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return JobStorage.of({
|
||||
putJob,
|
||||
getJob,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(Lambda.TableEventSource, SQS.QueueSinkLive).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
DynamoDB.GetItemLive,
|
||||
DynamoDB.PutItemLive,
|
||||
SQS.SendMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const JobStorageS3 = Layer.provideMerge(
|
||||
Layer.effect(
|
||||
JobStorage,
|
||||
Effect.gen(function* () {
|
||||
const stack = yield* Stack;
|
||||
const bucket = yield* S3.Bucket("JobsBucket");
|
||||
const queue = yield* SQS.Queue("JobsQueue").pipe(
|
||||
RemovalPolicy.retain(stack.stage === "prod"),
|
||||
);
|
||||
|
||||
const getObject = yield* S3.GetObject.bind(bucket);
|
||||
const putObject = yield* S3.PutObject.bind(bucket);
|
||||
const sink = yield* SQS.QueueSink.bind(queue);
|
||||
|
||||
const putJob = (job: Job) =>
|
||||
putObject({
|
||||
Key: job.id,
|
||||
Body: JSON.stringify(job),
|
||||
}).pipe(
|
||||
Effect.map(() => job),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new PutJobError({
|
||||
message: `Failed to store job "${job.id}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getJob = (jobId: string) =>
|
||||
getObject({
|
||||
Key: jobId,
|
||||
}).pipe(
|
||||
Effect.catchTag("NoSuchKey", () => Effect.succeed(undefined)),
|
||||
Effect.flatMap(
|
||||
(item) =>
|
||||
item?.Body?.pipe(
|
||||
Stream.decodeText,
|
||||
Stream.mkString,
|
||||
Effect.flatMap((body) =>
|
||||
Effect.try({
|
||||
try: () => JSON.parse(body) as Job,
|
||||
catch: (cause) =>
|
||||
new GetJobError({
|
||||
message: `Failed to parse job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
) ?? Effect.succeed(undefined),
|
||||
),
|
||||
Effect.tapError(Console.log),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.fail(
|
||||
new GetJobError({
|
||||
message: `Failed to load job "${jobId}": ${cause}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* S3.notifications(bucket).subscribe((stream) =>
|
||||
stream.pipe(
|
||||
Stream.flatMap((item) =>
|
||||
Stream.fromEffect(getJob(item.key).pipe(Effect.orDie)),
|
||||
),
|
||||
Stream.filter((job): job is Job => job !== undefined),
|
||||
Stream.map((job) => JSON.stringify(job)),
|
||||
Stream.run(sink),
|
||||
),
|
||||
);
|
||||
|
||||
return JobStorage.of({
|
||||
putJob,
|
||||
getJob,
|
||||
});
|
||||
}),
|
||||
),
|
||||
Layer.mergeAll(Lambda.BucketEventSource, SQS.QueueSinkLive).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(
|
||||
S3.GetObjectLive,
|
||||
S3.PutObjectLive,
|
||||
SQS.SendMessageBatchLive,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as Test from "alchemy/Test/Bun";
|
||||
import { expect } from "bun:test";
|
||||
import * as Effect from "effect/Effect";
|
||||
import Stack from "../alchemy.run.ts";
|
||||
|
||||
const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
|
||||
providers: AWS.providers(),
|
||||
state: Alchemy.localState(),
|
||||
});
|
||||
|
||||
const stack = beforeAll(deploy(Stack));
|
||||
afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
|
||||
|
||||
test(
|
||||
"deploys and exposes a url",
|
||||
Effect.gen(function* () {
|
||||
const out = (yield* stack) as unknown;
|
||||
const url = typeof out === "string" ? out : (out as { url: string }).url;
|
||||
expect(url).toBeString();
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts", "src/**/*.ts", "test/**/*.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"target": "ESNext"
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Effect from "effect/Effect";
|
||||
import ServiceFunction from "./src/ServiceFunction.ts";
|
||||
|
||||
const aws = AWS.providers();
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"AwsRdsExample",
|
||||
{ providers: aws, state: Alchemy.localState() },
|
||||
Effect.gen(function* () {
|
||||
const service = yield* ServiceFunction;
|
||||
return {
|
||||
url: service.functionUrl,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "aws-rds-example",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-rds"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@types/pg": "^8.18.0",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:",
|
||||
"pg": "^8.20.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Client } from "pg";
|
||||
import { Network } from "./Network.ts";
|
||||
|
||||
export class SqlError extends Data.TaggedError("SqlError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class Database extends Context.Service<
|
||||
Database,
|
||||
{
|
||||
query<Row extends Record<string, unknown> = Record<string, unknown>>(
|
||||
statement: string,
|
||||
values?: ReadonlyArray<unknown>,
|
||||
): Effect.Effect<ReadonlyArray<Row>, SqlError>;
|
||||
}
|
||||
>()("Sql") {}
|
||||
|
||||
export const DatabaseAurora = Layer.effect(
|
||||
Database,
|
||||
Effect.gen(function* () {
|
||||
const { vpc, databaseSecurityGroup } = yield* Network;
|
||||
const database = yield* AWS.RDS.Aurora("Database", {
|
||||
subnetIds: vpc.privateSubnetIds,
|
||||
securityGroupIds: [databaseSecurityGroup.groupId],
|
||||
});
|
||||
|
||||
const connect = yield* AWS.RDS.Connect.bind(database.cluster, {
|
||||
secret: database.secret,
|
||||
subnetIds: vpc.privateSubnetIds,
|
||||
securityGroupIds: [databaseSecurityGroup.groupId],
|
||||
});
|
||||
|
||||
return Database.of({
|
||||
query: <Row extends Record<string, unknown>>(
|
||||
statement: string,
|
||||
values: ReadonlyArray<unknown> = [],
|
||||
): Effect.Effect<ReadonlyArray<Row>, SqlError> =>
|
||||
connect.pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.fail(
|
||||
new SqlError({
|
||||
message: "Failed to resolve Aurora connection settings",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flatMap((connection: AWS.RDS.ConnectionInfo) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const client = new Client({
|
||||
host: connection.host,
|
||||
port: connection.port,
|
||||
database: connection.database,
|
||||
user: connection.username,
|
||||
password: connection.password,
|
||||
// Example-only SSL posture for private Aurora connections.
|
||||
ssl: connection.ssl
|
||||
? { rejectUnauthorized: false }
|
||||
: undefined,
|
||||
});
|
||||
|
||||
await client.connect();
|
||||
try {
|
||||
const result = await client.query<Row>({
|
||||
text: statement,
|
||||
values: [...values],
|
||||
});
|
||||
return result.rows as ReadonlyArray<Row>;
|
||||
} finally {
|
||||
await client.end();
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
message: `Failed to execute SQL statement: ${statement}`,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,58 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export interface ExampleNetwork {
|
||||
vpc: AWS.EC2.Network;
|
||||
functionSecurityGroup: AWS.EC2.SecurityGroup;
|
||||
databaseSecurityGroup: AWS.EC2.SecurityGroup;
|
||||
privateSecurityGroups: AWS.EC2.SecurityGroup[];
|
||||
}
|
||||
|
||||
export class Network extends Context.Service<Network, ExampleNetwork>()(
|
||||
"Network",
|
||||
) {}
|
||||
|
||||
export const NetworkLive = Layer.effect(
|
||||
Network,
|
||||
Effect.gen(function* () {
|
||||
const network = yield* AWS.EC2.Network("Network", {
|
||||
cidrBlock: "10.0.0.0/16",
|
||||
availabilityZones: 2,
|
||||
nat: "single",
|
||||
});
|
||||
|
||||
const functionSecurityGroup = yield* AWS.EC2.SecurityGroup(
|
||||
"FunctionSecurityGroup",
|
||||
{
|
||||
vpcId: network.vpcId,
|
||||
description: "Security group for the RDS example Lambda function",
|
||||
},
|
||||
);
|
||||
|
||||
const databaseSecurityGroup = yield* AWS.EC2.SecurityGroup(
|
||||
"DatabaseSecurityGroup",
|
||||
{
|
||||
vpcId: network.vpcId,
|
||||
description: "Security group for the RDS example Aurora cluster",
|
||||
ingress: [
|
||||
{
|
||||
ipProtocol: "tcp",
|
||||
fromPort: 5432,
|
||||
toPort: 5432,
|
||||
referencedGroupId: functionSecurityGroup.groupId,
|
||||
description: "Allow Lambda to reach Aurora PostgreSQL",
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
vpc: network,
|
||||
functionSecurityGroup,
|
||||
databaseSecurityGroup,
|
||||
privateSecurityGroups: [functionSecurityGroup],
|
||||
} satisfies ExampleNetwork;
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,71 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import { Stack } from "alchemy/Stack";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HttpServerRequest } from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { Database, DatabaseAurora } from "./Database.ts";
|
||||
import { NetworkLive } from "./Network.ts";
|
||||
|
||||
export default class ServiceFunction extends AWS.Lambda.Function<ServiceFunction>()(
|
||||
"ServiceFunction",
|
||||
Stack.useSync((stack) => ({
|
||||
main: import.meta.filename,
|
||||
memory: stack.stage === "prod" ? 1024 : 512,
|
||||
runtime: "nodejs24.x",
|
||||
})),
|
||||
Effect.gen(function* () {
|
||||
const db = yield* Database;
|
||||
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest;
|
||||
|
||||
if (
|
||||
request.method === "GET" &&
|
||||
new URL(request.originalUrl).pathname === "/"
|
||||
) {
|
||||
const response = yield* db
|
||||
.query<{
|
||||
database: string;
|
||||
current_time: string;
|
||||
current_user: string;
|
||||
}>(
|
||||
"select current_database() as database, now()::text as current_time, current_user::text as current_user",
|
||||
)
|
||||
.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({
|
||||
status: 500 as const,
|
||||
body: {
|
||||
ok: false,
|
||||
error: error.message,
|
||||
},
|
||||
}),
|
||||
onSuccess: (rows) => ({
|
||||
status: 200 as const,
|
||||
body: {
|
||||
ok: true,
|
||||
connection: rows[0] ?? null,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
return yield* HttpServerResponse.json(response.body, {
|
||||
status: response.status,
|
||||
});
|
||||
}
|
||||
|
||||
return HttpServerResponse.text("Not found", { status: 404 });
|
||||
}),
|
||||
};
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.provideMerge(
|
||||
Layer.mergeAll(DatabaseAurora),
|
||||
Layer.mergeAll(NetworkLive, AWS.RDS.ConnectLive),
|
||||
),
|
||||
),
|
||||
),
|
||||
) {}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts", "src/**/*.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"customConditions": ["bun"],
|
||||
"target": "ESNext"
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
import JobFunction from "./src/JobFunction.ts";
|
||||
|
||||
const aws = AWS.providers();
|
||||
|
||||
export default Alchemy.Stack(
|
||||
"AwsRestApiProxy",
|
||||
{
|
||||
providers: aws,
|
||||
state: Alchemy.localState(),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const { region, accountId } = yield* AWS.AWSEnvironment;
|
||||
|
||||
const fn = yield* JobFunction;
|
||||
|
||||
const api = yield* AWS.ApiGateway.RestApi("PublicApi", {
|
||||
name: "alchemy-example-rest-api",
|
||||
endpointConfiguration: { types: ["REGIONAL"] },
|
||||
});
|
||||
|
||||
const proxyResource = yield* AWS.ApiGateway.Resource("Proxy", {
|
||||
restApiId: api.restApiId,
|
||||
parentId: api.rootResourceId,
|
||||
pathPart: "{proxy+}",
|
||||
});
|
||||
|
||||
const invokeUri = Output.interpolate`arn:aws:apigateway:${region}:lambda:path/2015-03-31/functions/${fn.functionArn}/invocations`;
|
||||
|
||||
yield* AWS.ApiGateway.Method("RootAny", {
|
||||
restApiId: api.restApiId,
|
||||
resourceId: api.rootResourceId,
|
||||
httpMethod: "ANY",
|
||||
authorizationType: "NONE",
|
||||
integration: {
|
||||
type: "AWS_PROXY",
|
||||
integrationHttpMethod: "POST",
|
||||
uri: invokeUri,
|
||||
},
|
||||
});
|
||||
|
||||
yield* AWS.ApiGateway.Method("ProxyAny", {
|
||||
restApiId: api.restApiId,
|
||||
resourceId: proxyResource.resourceId,
|
||||
httpMethod: "ANY",
|
||||
authorizationType: "NONE",
|
||||
integration: {
|
||||
type: "AWS_PROXY",
|
||||
integrationHttpMethod: "POST",
|
||||
uri: invokeUri,
|
||||
},
|
||||
});
|
||||
|
||||
const deployment = yield* AWS.ApiGateway.Deployment("Release", {
|
||||
restApiId: api.restApiId,
|
||||
description: "initial",
|
||||
triggers: {
|
||||
rootMethod: "ANY",
|
||||
proxyMethod: "ANY",
|
||||
},
|
||||
});
|
||||
|
||||
const stage = yield* AWS.ApiGateway.Stage("ProdStage", {
|
||||
restApiId: api.restApiId,
|
||||
stageName: "prod",
|
||||
deploymentId: deployment.deploymentId,
|
||||
});
|
||||
|
||||
yield* AWS.Lambda.Permission("ApiGatewayInvoke", {
|
||||
action: "lambda:InvokeFunction",
|
||||
functionName: fn.functionName,
|
||||
principal: "apigateway.amazonaws.com",
|
||||
sourceArn: Output.interpolate`arn:aws:execute-api:${region}:${accountId}:${api.restApiId}/*/*/*`,
|
||||
});
|
||||
|
||||
return {
|
||||
invokeUrl: Output.interpolate`https://${api.restApiId}.execute-api.${region}.amazonaws.com/${stage.stageName}/`,
|
||||
restApiId: api.restApiId,
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "aws-rest-api",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alchemy-run/alchemy-effect.git",
|
||||
"directory": "examples/aws-rest-api"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -b",
|
||||
"deploy": "alchemy deploy",
|
||||
"dev": "alchemy dev",
|
||||
"destroy": "alchemy destroy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@distilled.cloud/aws": "catalog:",
|
||||
"alchemy": "workspace:*",
|
||||
"effect": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import * as AWS from "alchemy/AWS";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
|
||||
const main = import.meta.filename;
|
||||
|
||||
/**
|
||||
* Minimal Lambda for API Gateway `AWS_PROXY` — returns plain text.
|
||||
*/
|
||||
export default class JobFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
|
||||
"JobFunction",
|
||||
{
|
||||
main,
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
return {
|
||||
fetch: Effect.gen(function* () {
|
||||
return HttpServerResponse.text("Hello from REST API + Lambda");
|
||||
}),
|
||||
};
|
||||
}),
|
||||
) {}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["alchemy.run.ts", "src/**/*.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"rootDir": ".",
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "Bundler",
|
||||
"target": "ESNext"
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../packages/alchemy/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
# AWS Static Site Example
|
||||
|
||||
This example deploys a static website from the local `site/` directory using:
|
||||
|
||||
- `AWS.Website.StaticSite`
|
||||
- private S3 origin
|
||||
- CloudFront distribution
|
||||
- optional ACM certificate in `us-east-1`
|
||||
- optional Route 53 alias records
|
||||
|
||||
## Commands
|
||||
|
||||
```sh
|
||||
bun install
|
||||
bun run --filter aws-static-site-example deploy
|
||||
```
|
||||
|
||||
## Optional Custom Domain
|
||||
|
||||
Set these environment variables before deploy:
|
||||
|
||||
```sh
|
||||
export WEBSITE_DOMAIN=www.example.com
|
||||
export WEBSITE_ZONE_ID=Z1234567890
|
||||
export WEBSITE_ALIASES=example.com,static.example.com
|
||||
```
|
||||
|
||||
When `WEBSITE_DOMAIN` and `WEBSITE_ZONE_ID` are provided, the example will:
|
||||
|
||||
- request an ACM certificate
|
||||
- create Route 53 validation records
|
||||
- create Route 53 alias records to CloudFront
|
||||
|
||||
Without them, the example still deploys and returns the CloudFront URL.
|
||||
Loaded 100 of 6009 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user